Format all Java files with google-java-format
Having a standard tool for formatting saves reviewers' valuable time.
google-java-format is Google's standard formatter and is somewhat
inspired by gofmt[1]. This commit formats everything using
google-java-format version 1.2.
The downside of this one-off formatting is breaking blame. This can be
somewhat hacked around with a tool like git-hyper-blame[2], but it's
definitely not optimal until/unless this kind of feature makes its way
to git core.
Not in this change:
* Tool support, e.g. Eclipse. The command must be run manually [3].
* Documentation of best practice, e.g. new 100-column default.
[1] https://talks.golang.org/2015/gofmt-en.slide#3
[2] https://commondatastorage.googleapis.com/chrome-infra-docs/flat/depot_tools/docs/html/git-hyper-blame.html
[3] git ls-files | grep java$ | xargs google-java-format -i
Change-Id: Id5f3c6de95ce0b68b41f0a478b5c99a93675aaa3
Signed-off-by: David Pursehouse <dpursehouse@collab.net>
diff --git a/gerrit-server/src/main/java/com/google/gerrit/audit/AuditEvent.java b/gerrit-server/src/main/java/com/google/gerrit/audit/AuditEvent.java
index 3184b15..f2b4eab6 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/audit/AuditEvent.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/audit/AuditEvent.java
@@ -25,8 +25,7 @@
public class AuditEvent {
public static final String UNKNOWN_SESSION_ID = "000000000000000000000000000";
- protected static final ListMultimap<String, ?> EMPTY_PARAMS =
- ImmutableListMultimap.of();
+ protected static final ListMultimap<String, ?> EMPTY_PARAMS = ImmutableListMultimap.of();
public final String sessionId;
public final CurrentUser who;
@@ -58,8 +57,13 @@
* @param params parameters of the event
* @param result result of the event
*/
- public AuditEvent(String sessionId, CurrentUser who, String what, long when,
- ListMultimap<String, ?> params, Object result) {
+ public AuditEvent(
+ String sessionId,
+ CurrentUser who,
+ String what,
+ long when,
+ ListMultimap<String, ?> params,
+ Object result) {
Preconditions.checkNotNull(what, "what is a mandatory not null param !");
this.sessionId = MoreObjects.firstNonNull(sessionId, UNKNOWN_SESSION_ID);
@@ -96,7 +100,8 @@
@Override
public String toString() {
- return String.format("AuditEvent UUID:%s, SID:%s, TS:%d, who:%s, what:%s",
+ return String.format(
+ "AuditEvent UUID:%s, SID:%s, TS:%d, who:%s, what:%s",
uuid.uuid(), sessionId, when, who, what);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/audit/AuditListener.java b/gerrit-server/src/main/java/com/google/gerrit/audit/AuditListener.java
index 0aab248..8eb8ed4 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/audit/AuditListener.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/audit/AuditListener.java
@@ -20,5 +20,4 @@
public interface AuditListener {
void onAuditableAction(AuditEvent action);
-
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/audit/AuditModule.java b/gerrit-server/src/main/java/com/google/gerrit/audit/AuditModule.java
index 89b51f8..aedb8a7 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/audit/AuditModule.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/audit/AuditModule.java
@@ -25,5 +25,4 @@
DynamicSet.setOf(binder(), GroupMemberAuditListener.class);
bind(AuditService.class);
}
-
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/audit/AuditService.java b/gerrit-server/src/main/java/com/google/gerrit/audit/AuditService.java
index 4844045..cc29559 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/audit/AuditService.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/audit/AuditService.java
@@ -20,12 +20,10 @@
import com.google.gerrit.reviewdb.client.AccountGroupMember;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
+import java.util.Collection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.util.Collection;
-
@Singleton
public class AuditService {
private static final Logger log = LoggerFactory.getLogger(AuditService.class);
@@ -34,7 +32,8 @@
private final DynamicSet<GroupMemberAuditListener> groupMemberAuditListeners;
@Inject
- public AuditService(DynamicSet<AuditListener> auditListeners,
+ public AuditService(
+ DynamicSet<AuditListener> auditListeners,
DynamicSet<GroupMemberAuditListener> groupMemberAuditListeners) {
this.auditListeners = auditListeners;
this.groupMemberAuditListeners = groupMemberAuditListeners;
@@ -46,8 +45,7 @@
}
}
- public void dispatchAddAccountsToGroup(Account.Id actor,
- Collection<AccountGroupMember> added) {
+ public void dispatchAddAccountsToGroup(Account.Id actor, Collection<AccountGroupMember> added) {
for (GroupMemberAuditListener auditListener : groupMemberAuditListeners) {
try {
auditListener.onAddAccountsToGroup(actor, added);
@@ -57,8 +55,8 @@
}
}
- public void dispatchDeleteAccountsFromGroup(Account.Id actor,
- Collection<AccountGroupMember> removed) {
+ public void dispatchDeleteAccountsFromGroup(
+ Account.Id actor, Collection<AccountGroupMember> removed) {
for (GroupMemberAuditListener auditListener : groupMemberAuditListeners) {
try {
auditListener.onDeleteAccountsFromGroup(actor, removed);
@@ -68,8 +66,7 @@
}
}
- public void dispatchAddGroupsToGroup(Account.Id actor,
- Collection<AccountGroupById> added) {
+ public void dispatchAddGroupsToGroup(Account.Id actor, Collection<AccountGroupById> added) {
for (GroupMemberAuditListener auditListener : groupMemberAuditListeners) {
try {
auditListener.onAddGroupsToGroup(actor, added);
@@ -79,8 +76,8 @@
}
}
- public void dispatchDeleteGroupsFromGroup(Account.Id actor,
- Collection<AccountGroupById> removed) {
+ public void dispatchDeleteGroupsFromGroup(
+ Account.Id actor, Collection<AccountGroupById> removed) {
for (GroupMemberAuditListener auditListener : groupMemberAuditListeners) {
try {
auditListener.onDeleteGroupsFromGroup(actor, removed);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/audit/ExtendedHttpAuditEvent.java b/gerrit-server/src/main/java/com/google/gerrit/audit/ExtendedHttpAuditEvent.java
index 6bd7deb..4db8a51 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/audit/ExtendedHttpAuditEvent.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/audit/ExtendedHttpAuditEvent.java
@@ -19,12 +19,9 @@
import com.google.gerrit.extensions.restapi.RestResource;
import com.google.gerrit.extensions.restapi.RestView;
import com.google.gerrit.server.CurrentUser;
-
import javax.servlet.http.HttpServletRequest;
-/**
- * Extended audit event. Adds request, resource and view data to HttpAuditEvent.
- */
+/** Extended audit event. Adds request, resource and view data to HttpAuditEvent. */
public class ExtendedHttpAuditEvent extends HttpAuditEvent {
public final HttpServletRequest httpRequest;
public final RestResource resource;
@@ -44,12 +41,27 @@
* @param resource REST resource data
* @param view view rendering object
*/
- public ExtendedHttpAuditEvent(String sessionId, CurrentUser who,
- HttpServletRequest httpRequest, long when, ListMultimap<String, ?> params,
- Object input, int status, Object result, RestResource resource,
+ public ExtendedHttpAuditEvent(
+ String sessionId,
+ CurrentUser who,
+ HttpServletRequest httpRequest,
+ long when,
+ ListMultimap<String, ?> params,
+ Object input,
+ int status,
+ Object result,
+ RestResource resource,
RestView<RestResource> view) {
- super(sessionId, who, httpRequest.getRequestURI(), when, params,
- httpRequest.getMethod(), input, status, result);
+ super(
+ sessionId,
+ who,
+ httpRequest.getRequestURI(),
+ when,
+ params,
+ httpRequest.getMethod(),
+ input,
+ status,
+ result);
this.httpRequest = Preconditions.checkNotNull(httpRequest);
this.resource = resource;
this.view = view;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/audit/GroupMemberAuditListener.java b/gerrit-server/src/main/java/com/google/gerrit/audit/GroupMemberAuditListener.java
index 1269f4a..0878499 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/audit/GroupMemberAuditListener.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/audit/GroupMemberAuditListener.java
@@ -18,20 +18,16 @@
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.reviewdb.client.AccountGroupById;
import com.google.gerrit.reviewdb.client.AccountGroupMember;
-
import java.util.Collection;
@ExtensionPoint
public interface GroupMemberAuditListener {
- void onAddAccountsToGroup(Account.Id actor,
- Collection<AccountGroupMember> added);
+ void onAddAccountsToGroup(Account.Id actor, Collection<AccountGroupMember> added);
- void onDeleteAccountsFromGroup(Account.Id actor,
- Collection<AccountGroupMember> removed);
+ void onDeleteAccountsFromGroup(Account.Id actor, Collection<AccountGroupMember> removed);
void onAddGroupsToGroup(Account.Id actor, Collection<AccountGroupById> added);
- void onDeleteGroupsFromGroup(Account.Id actor,
- Collection<AccountGroupById> deleted);
+ void onDeleteGroupsFromGroup(Account.Id actor, Collection<AccountGroupById> deleted);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/audit/HttpAuditEvent.java b/gerrit-server/src/main/java/com/google/gerrit/audit/HttpAuditEvent.java
index 300d760..cd19606 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/audit/HttpAuditEvent.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/audit/HttpAuditEvent.java
@@ -34,9 +34,16 @@
* @param status HTTP status
* @param result result of the event
*/
- public HttpAuditEvent(String sessionId, CurrentUser who, String what,
- long when, ListMultimap<String, ?> params, String httpMethod,
- Object input, int status, Object result) {
+ public HttpAuditEvent(
+ String sessionId,
+ CurrentUser who,
+ String what,
+ long when,
+ ListMultimap<String, ?> params,
+ String httpMethod,
+ Object input,
+ int status,
+ Object result) {
super(sessionId, who, what, when, params, result);
this.httpMethod = httpMethod;
this.input = input;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/audit/RpcAuditEvent.java b/gerrit-server/src/main/java/com/google/gerrit/audit/RpcAuditEvent.java
index cefc3a2..f6b955c 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/audit/RpcAuditEvent.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/audit/RpcAuditEvent.java
@@ -32,9 +32,16 @@
* @param status HTTP status
* @param result result of the event
*/
- public RpcAuditEvent(String sessionId, CurrentUser who, String what,
- long when, ListMultimap<String, ?> params, String httpMethod,
- Object input, int status, Object result) {
+ public RpcAuditEvent(
+ String sessionId,
+ CurrentUser who,
+ String what,
+ long when,
+ ListMultimap<String, ?> params,
+ String httpMethod,
+ Object input,
+ int status,
+ Object result) {
super(sessionId, who, what, when, params, httpMethod, input, status, result);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/audit/SshAuditEvent.java b/gerrit-server/src/main/java/com/google/gerrit/audit/SshAuditEvent.java
index 6823de3..98cba09 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/audit/SshAuditEvent.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/audit/SshAuditEvent.java
@@ -19,8 +19,13 @@
public class SshAuditEvent extends AuditEvent {
- public SshAuditEvent(String sessionId, CurrentUser who, String what,
- long when, ListMultimap<String, ?> params, Object result) {
+ public SshAuditEvent(
+ String sessionId,
+ CurrentUser who,
+ String what,
+ long when,
+ ListMultimap<String, ?> params,
+ Object result) {
super(sessionId, who, what, when, params, result);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/common/EventBroker.java b/gerrit-server/src/main/java/com/google/gerrit/common/EventBroker.java
index 0029768..87cfea1 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/common/EventBroker.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/common/EventBroker.java
@@ -48,10 +48,7 @@
}
}
- /**
- * Listeners to receive changes as they happen (limited by visibility of
- * user).
- */
+ /** Listeners to receive changes as they happen (limited by visibility of user). */
protected final DynamicSet<UserScopedEventListener> listeners;
/** Listeners to receive all changes as they happen. */
@@ -64,7 +61,8 @@
protected final Provider<ReviewDb> dbProvider;
@Inject
- public EventBroker(DynamicSet<UserScopedEventListener> listeners,
+ public EventBroker(
+ DynamicSet<UserScopedEventListener> listeners,
DynamicSet<EventListener> unrestrictedListeners,
ProjectCache projectCache,
ChangeNotes.Factory notesFactory,
@@ -77,8 +75,7 @@
}
@Override
- public void postEvent(Change change, ChangeEvent event)
- throws OrmException {
+ public void postEvent(Change change, ChangeEvent event) throws OrmException {
fireEvent(change, event);
}
@@ -103,8 +100,7 @@
}
}
- protected void fireEvent(Change change, ChangeEvent event)
- throws OrmException {
+ protected void fireEvent(Change change, ChangeEvent event) throws OrmException {
for (UserScopedEventListener listener : listeners) {
if (isVisibleTo(change, listener.getUser())) {
listener.onEvent(event);
@@ -148,8 +144,7 @@
return pe.controlFor(user).isVisible();
}
- protected boolean isVisibleTo(Change change, CurrentUser user)
- throws OrmException {
+ protected boolean isVisibleTo(Change change, CurrentUser user) throws OrmException {
if (change == null) {
return false;
}
@@ -171,15 +166,14 @@
return pc.controlForRef(branchName).isVisible();
}
- protected boolean isVisibleTo(Event event, CurrentUser user)
- throws OrmException {
+ protected boolean isVisibleTo(Event event, CurrentUser user) throws OrmException {
if (event instanceof RefEvent) {
RefEvent refEvent = (RefEvent) event;
String ref = refEvent.getRefName();
if (PatchSet.isChangeRef(ref)) {
Change.Id cid = PatchSet.Id.fromRef(ref).getParentKey();
- Change change = notesFactory.create(
- dbProvider.get(), refEvent.getProjectNameKey(), cid).getChange();
+ Change change =
+ notesFactory.create(dbProvider.get(), refEvent.getProjectNameKey(), cid).getChange();
return isVisibleTo(change, user);
}
return isVisibleTo(refEvent.getBranchNameKey(), user);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/common/EventDispatcher.java b/gerrit-server/src/main/java/com/google/gerrit/common/EventDispatcher.java
index 09fa581..20d55d6 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/common/EventDispatcher.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/common/EventDispatcher.java
@@ -23,7 +23,6 @@
import com.google.gerrit.server.events.RefEvent;
import com.google.gwtorm.server.OrmException;
-
/** Interface for posting (dispatching) Events */
public interface EventDispatcher {
/**
@@ -53,10 +52,9 @@
/**
* Post a stream event generically.
- * <p>
- * If you are creating a RefEvent or ChangeEvent from scratch,
- * it is more efficient to use the specific postEvent methods
- * for those use cases.
+ *
+ * <p>If you are creating a RefEvent or ChangeEvent from scratch, it is more efficient to use the
+ * specific postEvent methods for those use cases.
*
* @param event The event to post.
* @throws OrmException on failure to post the event due to DB error
diff --git a/gerrit-server/src/main/java/com/google/gerrit/common/EventListener.java b/gerrit-server/src/main/java/com/google/gerrit/common/EventListener.java
index b2d5680..6cfc5eb 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/common/EventListener.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/common/EventListener.java
@@ -18,8 +18,8 @@
import com.google.gerrit.server.events.Event;
/**
- * Allows to listen to events without user visibility restrictions. To listen to
- * events visible to a specific user, use {@link UserScopedEventListener}.
+ * Allows to listen to events without user visibility restrictions. To listen to events visible to a
+ * specific user, use {@link UserScopedEventListener}.
*/
@ExtensionPoint
public interface EventListener {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/common/UserScopedEventListener.java b/gerrit-server/src/main/java/com/google/gerrit/common/UserScopedEventListener.java
index 22435ba..3216bac 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/common/UserScopedEventListener.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/common/UserScopedEventListener.java
@@ -17,8 +17,8 @@
import com.google.gerrit.server.CurrentUser;
/**
- * Allows to listen to events visible to the specified user. To listen to events
- * without user visibility restrictions, use {@link EventListener}.
+ * Allows to listen to events visible to the specified user. To listen to events without user
+ * visibility restrictions, use {@link EventListener}.
*/
@ExtensionPoint
public interface UserScopedEventListener extends EventListener {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/common/Version.java b/gerrit-server/src/main/java/com/google/gerrit/common/Version.java
index 57a2946..f5a63af 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/common/Version.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/common/Version.java
@@ -16,13 +16,12 @@
import static java.nio.charset.StandardCharsets.UTF_8;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class Version {
private static final Logger log = LoggerFactory.getLogger(Version.class);
@@ -57,6 +56,5 @@
}
}
- private Version() {
- }
+ private Version() {}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/lifecycle/LifecycleManager.java b/gerrit-server/src/main/java/com/google/gerrit/lifecycle/LifecycleManager.java
index db6faa2..bbffd49 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/lifecycle/LifecycleManager.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/lifecycle/LifecycleManager.java
@@ -23,10 +23,8 @@
import com.google.inject.Provider;
import com.google.inject.TypeLiteral;
import com.google.inject.util.Providers;
-
-import org.slf4j.LoggerFactory;
-
import java.util.List;
+import org.slf4j.LoggerFactory;
/** Tracks and executes registered {@link LifecycleListener}s. */
public class LifecycleManager {
@@ -36,34 +34,38 @@
/** Index of the last listener to start successfully; -1 when not started. */
private int startedIndex = -1;
- /** Add a handle that must be cleared during stop.
+ /**
+ * Add a handle that must be cleared during stop.
*
* @param handle the handle to add.
- **/
+ */
public void add(RegistrationHandle handle) {
handles.add(handle);
}
- /** Add a single listener.
+ /**
+ * Add a single listener.
*
* @param listener the listener to add.
- **/
+ */
public void add(LifecycleListener listener) {
listeners.add(Providers.of(listener));
}
- /** Add a single listener.
+ /**
+ * Add a single listener.
*
* @param listener the listener to add.
- **/
+ */
public void add(Provider<LifecycleListener> listener) {
listeners.add(listener);
}
- /** Add all {@link LifecycleListener}s registered in the Injector.
+ /**
+ * Add all {@link LifecycleListener}s registered in the Injector.
*
* @param injector the injector to add.
- **/
+ */
public void add(Injector injector) {
Preconditions.checkState(startedIndex < 0, "Already started");
for (Binding<LifecycleListener> binding : get(injector)) {
@@ -71,10 +73,11 @@
}
}
- /** Add all {@link LifecycleListener}s registered in the Injectors.
+ /**
+ * Add all {@link LifecycleListener}s registered in the Injectors.
*
* @param injectors the injectors to add.
- **/
+ */
public void add(Injector... injectors) {
for (Injector i : injectors) {
add(i);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/lifecycle/LifecycleModule.java b/gerrit-server/src/main/java/com/google/gerrit/lifecycle/LifecycleModule.java
index c22f2ee..bfb61d2 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/lifecycle/LifecycleModule.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/lifecycle/LifecycleModule.java
@@ -5,22 +5,18 @@
import com.google.inject.Singleton;
import com.google.inject.binder.LinkedBindingBuilder;
import com.google.inject.internal.UniqueAnnotations;
-
import java.lang.annotation.Annotation;
/** Module to support registering a unique LifecyleListener. */
public abstract class LifecycleModule extends FactoryModule {
/**
* @return a unique listener binding.
- * <p>
- * To create a listener binding use:
- *
- * <pre>
+ * <p>To create a listener binding use:
+ * <pre>
* listener().to(MyListener.class);
* </pre>
- *
- * where {@code MyListener} is a {@link Singleton} implementing the
- * {@link LifecycleListener} interface.
+ * where {@code MyListener} is a {@link Singleton} implementing the {@link LifecycleListener}
+ * interface.
*/
protected LinkedBindingBuilder<LifecycleListener> listener() {
final Annotation id = UniqueAnnotations.create();
diff --git a/gerrit-server/src/main/java/com/google/gerrit/metrics/CallbackMetric.java b/gerrit-server/src/main/java/com/google/gerrit/metrics/CallbackMetric.java
index 1714c7a..1264645 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/metrics/CallbackMetric.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/metrics/CallbackMetric.java
@@ -16,7 +16,6 @@
import com.google.gerrit.extensions.registration.RegistrationHandle;
-
/**
* Metric whose value is supplied when the trigger is invoked.
*
diff --git a/gerrit-server/src/main/java/com/google/gerrit/metrics/CallbackMetric1.java b/gerrit-server/src/main/java/com/google/gerrit/metrics/CallbackMetric1.java
index 864a0ea..1df88a6 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/metrics/CallbackMetric1.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/metrics/CallbackMetric1.java
@@ -38,6 +38,5 @@
/** Prune any submetrics that were not assigned during this trigger. */
@Override
- public void prune() {
- }
+ public void prune() {}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/metrics/Counter0.java b/gerrit-server/src/main/java/com/google/gerrit/metrics/Counter0.java
index a2af7e4..d684cd2 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/metrics/Counter0.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/metrics/Counter0.java
@@ -18,13 +18,13 @@
/**
* Metric whose value increments during the life of the process.
- * <p>
- * Suitable uses are "total requests handled", "bytes sent", etc.
- * Use {@link Description#setRate()} to suggest the monitoring system
- * should also track the rate of increments if this is of interest.
- * <p>
- * For an instantaneous read of a value that can change over time
- * (e.g. "memory in use") use a {@link CallbackMetric}.
+ *
+ * <p>Suitable uses are "total requests handled", "bytes sent", etc. Use {@link
+ * Description#setRate()} to suggest the monitoring system should also track the rate of increments
+ * if this is of interest.
+ *
+ * <p>For an instantaneous read of a value that can change over time (e.g. "memory in use") use a
+ * {@link CallbackMetric}.
*/
public abstract class Counter0 implements RegistrationHandle {
/** Increment the counter by one event. */
diff --git a/gerrit-server/src/main/java/com/google/gerrit/metrics/Counter1.java b/gerrit-server/src/main/java/com/google/gerrit/metrics/Counter1.java
index 1b8c833..78b2496 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/metrics/Counter1.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/metrics/Counter1.java
@@ -18,13 +18,13 @@
/**
* Metric whose value increments during the life of the process.
- * <p>
- * Suitable uses are "total requests handled", "bytes sent", etc.
- * Use {@link Description#setRate()} to suggest the monitoring system
- * should also track the rate of increments if this is of interest.
- * <p>
- * For an instantaneous read of a value that can change over time
- * (e.g. "memory in use") use a {@link CallbackMetric}.
+ *
+ * <p>Suitable uses are "total requests handled", "bytes sent", etc. Use {@link
+ * Description#setRate()} to suggest the monitoring system should also track the rate of increments
+ * if this is of interest.
+ *
+ * <p>For an instantaneous read of a value that can change over time (e.g. "memory in use") use a
+ * {@link CallbackMetric}.
*
* @param <F1> type of the field.
*/
diff --git a/gerrit-server/src/main/java/com/google/gerrit/metrics/Counter2.java b/gerrit-server/src/main/java/com/google/gerrit/metrics/Counter2.java
index a24b46d..5f2ae55 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/metrics/Counter2.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/metrics/Counter2.java
@@ -18,13 +18,13 @@
/**
* Metric whose value increments during the life of the process.
- * <p>
- * Suitable uses are "total requests handled", "bytes sent", etc.
- * Use {@link Description#setRate()} to suggest the monitoring system
- * should also track the rate of increments if this is of interest.
- * <p>
- * For an instantaneous read of a value that can change over time
- * (e.g. "memory in use") use a {@link CallbackMetric}.
+ *
+ * <p>Suitable uses are "total requests handled", "bytes sent", etc. Use {@link
+ * Description#setRate()} to suggest the monitoring system should also track the rate of increments
+ * if this is of interest.
+ *
+ * <p>For an instantaneous read of a value that can change over time (e.g. "memory in use") use a
+ * {@link CallbackMetric}.
*
* @param <F1> type of the field.
* @param <F2> type of the field.
diff --git a/gerrit-server/src/main/java/com/google/gerrit/metrics/Counter3.java b/gerrit-server/src/main/java/com/google/gerrit/metrics/Counter3.java
index e0ac5be..7a51bdb 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/metrics/Counter3.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/metrics/Counter3.java
@@ -18,13 +18,13 @@
/**
* Metric whose value increments during the life of the process.
- * <p>
- * Suitable uses are "total requests handled", "bytes sent", etc.
- * Use {@link Description#setRate()} to suggest the monitoring system
- * should also track the rate of increments if this is of interest.
- * <p>
- * For an instantaneous read of a value that can change over time
- * (e.g. "memory in use") use a {@link CallbackMetric}.
+ *
+ * <p>Suitable uses are "total requests handled", "bytes sent", etc. Use {@link
+ * Description#setRate()} to suggest the monitoring system should also track the rate of increments
+ * if this is of interest.
+ *
+ * <p>For an instantaneous read of a value that can change over time (e.g. "memory in use") use a
+ * {@link CallbackMetric}.
*
* @param <F1> type of the field.
* @param <F2> type of the field.
diff --git a/gerrit-server/src/main/java/com/google/gerrit/metrics/Description.java b/gerrit-server/src/main/java/com/google/gerrit/metrics/Description.java
index b1579f8..10568bc 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/metrics/Description.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/metrics/Description.java
@@ -17,7 +17,6 @@
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
-
import java.util.Map;
import java.util.concurrent.TimeUnit;
@@ -40,8 +39,7 @@
public static final String BYTES = "bytes";
- private Units() {
- }
+ private Units() {}
}
public enum FieldOrdering {
@@ -49,10 +47,9 @@
AT_END,
/**
- * Splits the metric name by inserting field values before the last '/' in
- * the metric name. For example {@code "plugins/replication/push_latency"}
- * with a {@code Field.ofString("remote")} will create submetrics named
- * {@code "plugins/replication/some-server/push_latency"}.
+ * Splits the metric name by inserting field values before the last '/' in the metric name. For
+ * example {@code "plugins/replication/push_latency"} with a {@code Field.ofString("remote")}
+ * will create submetrics named {@code "plugins/replication/some-server/push_latency"}.
*/
PREFIX_FIELDS_BASENAME;
}
@@ -62,16 +59,16 @@
/**
* Describe a metric.
*
- * @param helpText a short one-sentence string explaining the values captured
- * by the metric. This may be made available to administrators as
- * documentation in the reporting tools.
+ * @param helpText a short one-sentence string explaining the values captured by the metric. This
+ * may be made available to administrators as documentation in the reporting tools.
*/
public Description(String helpText) {
annotations = Maps.newLinkedHashMapWithExpectedSize(4);
annotations.put(DESCRIPTION, helpText);
}
- /** Set unit used to describe the value.
+ /**
+ * Set unit used to describe the value.
*
* @param unitName name of the unit, e.g. "requests", "seconds", etc.
* @return this
@@ -82,9 +79,8 @@
}
/**
- * Mark the value as constant for the life of this process. Typically used for
- * software versions, command line arguments, etc. that cannot change without
- * a process restart.
+ * Mark the value as constant for the life of this process. Typically used for software versions,
+ * command line arguments, etc. that cannot change without a process restart.
*
* @return this
*/
@@ -94,9 +90,8 @@
}
/**
- * Indicates the metric may be usefully interpreted as a count over short
- * periods of time, such as request arrival rate. May only be applied to a
- * {@link Counter0}.
+ * Indicates the metric may be usefully interpreted as a count over short periods of time, such as
+ * request arrival rate. May only be applied to a {@link Counter0}.
*
* @return this
*/
@@ -106,8 +101,8 @@
}
/**
- * Instantaneously sampled value that may increase or decrease at a later
- * time. Memory allocated or open network connections are examples of gauges.
+ * Instantaneously sampled value that may increase or decrease at a later time. Memory allocated
+ * or open network connections are examples of gauges.
*
* @return this
*/
@@ -117,9 +112,8 @@
}
/**
- * Indicates the metric accumulates over the lifespan of the process. A
- * {@link Counter0} like total requests handled accumulates over the process
- * and should be {@code setCumulative()}.
+ * Indicates the metric accumulates over the lifespan of the process. A {@link Counter0} like
+ * total requests handled accumulates over the process and should be {@code setCumulative()}.
*
* @return this
*/
@@ -175,11 +169,12 @@
return getTimeUnit(annotations.get(UNIT));
}
- private static final ImmutableMap<String, TimeUnit> TIME_UNITS = ImmutableMap.of(
- Units.NANOSECONDS, TimeUnit.NANOSECONDS,
- Units.MICROSECONDS, TimeUnit.MICROSECONDS,
- Units.MILLISECONDS, TimeUnit.MILLISECONDS,
- Units.SECONDS, TimeUnit.SECONDS);
+ private static final ImmutableMap<String, TimeUnit> TIME_UNITS =
+ ImmutableMap.of(
+ Units.NANOSECONDS, TimeUnit.NANOSECONDS,
+ Units.MICROSECONDS, TimeUnit.MICROSECONDS,
+ Units.MILLISECONDS, TimeUnit.MILLISECONDS,
+ Units.SECONDS, TimeUnit.SECONDS);
public static TimeUnit getTimeUnit(String unit) {
if (Strings.isNullOrEmpty(unit)) {
@@ -187,8 +182,7 @@
}
TimeUnit u = TIME_UNITS.get(unit);
if (u == null) {
- throw new IllegalArgumentException(String.format(
- "unit %s not TimeUnit", unit));
+ throw new IllegalArgumentException(String.format("unit %s not TimeUnit", unit));
}
return u;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/metrics/DisabledMetricMaker.java b/gerrit-server/src/main/java/com/google/gerrit/metrics/DisabledMetricMaker.java
index 1b05e2c..ea408e2 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/metrics/DisabledMetricMaker.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/metrics/DisabledMetricMaker.java
@@ -15,7 +15,6 @@
package com.google.gerrit.metrics;
import com.google.gerrit.extensions.registration.RegistrationHandle;
-
import java.util.Set;
import java.util.concurrent.TimeUnit;
@@ -24,132 +23,173 @@
@Override
public Counter0 newCounter(String name, Description desc) {
return new Counter0() {
- @Override public void incrementBy(long value) {}
- @Override public void remove() {}
+ @Override
+ public void incrementBy(long value) {}
+
+ @Override
+ public void remove() {}
};
}
@Override
- public <F1> Counter1<F1> newCounter(String name, Description desc,
- Field<F1> field1) {
+ public <F1> Counter1<F1> newCounter(String name, Description desc, Field<F1> field1) {
return new Counter1<F1>() {
- @Override public void incrementBy(F1 field1, long value) {}
- @Override public void remove() {}
+ @Override
+ public void incrementBy(F1 field1, long value) {}
+
+ @Override
+ public void remove() {}
};
}
@Override
- public <F1, F2> Counter2<F1, F2> newCounter(String name, Description desc,
- Field<F1> field1, Field<F2> field2) {
+ public <F1, F2> Counter2<F1, F2> newCounter(
+ String name, Description desc, Field<F1> field1, Field<F2> field2) {
return new Counter2<F1, F2>() {
- @Override public void incrementBy(F1 field1, F2 field2, long value) {}
- @Override public void remove() {}
+ @Override
+ public void incrementBy(F1 field1, F2 field2, long value) {}
+
+ @Override
+ public void remove() {}
};
}
@Override
- public <F1, F2, F3> Counter3<F1, F2, F3> newCounter(String name,
- Description desc, Field<F1> field1, Field<F2> field2, Field<F3> field3) {
+ public <F1, F2, F3> Counter3<F1, F2, F3> newCounter(
+ String name, Description desc, Field<F1> field1, Field<F2> field2, Field<F3> field3) {
return new Counter3<F1, F2, F3>() {
- @Override public void incrementBy(F1 field1, F2 field2, F3 field3, long value) {}
- @Override public void remove() {}
+ @Override
+ public void incrementBy(F1 field1, F2 field2, F3 field3, long value) {}
+
+ @Override
+ public void remove() {}
};
}
@Override
public Timer0 newTimer(String name, Description desc) {
return new Timer0() {
- @Override public void record(long value, TimeUnit unit) {}
- @Override public void remove() {}
+ @Override
+ public void record(long value, TimeUnit unit) {}
+
+ @Override
+ public void remove() {}
};
}
@Override
- public <F1> Timer1<F1> newTimer(String name, Description desc,
- Field<F1> field1) {
+ public <F1> Timer1<F1> newTimer(String name, Description desc, Field<F1> field1) {
return new Timer1<F1>() {
- @Override public void record(F1 field1, long value, TimeUnit unit) {}
- @Override public void remove() {}
+ @Override
+ public void record(F1 field1, long value, TimeUnit unit) {}
+
+ @Override
+ public void remove() {}
};
}
@Override
- public <F1, F2> Timer2<F1, F2> newTimer(String name, Description desc,
- Field<F1> field1, Field<F2> field2) {
+ public <F1, F2> Timer2<F1, F2> newTimer(
+ String name, Description desc, Field<F1> field1, Field<F2> field2) {
return new Timer2<F1, F2>() {
- @Override public void record(F1 field1, F2 field2, long value, TimeUnit unit) {}
- @Override public void remove() {}
+ @Override
+ public void record(F1 field1, F2 field2, long value, TimeUnit unit) {}
+
+ @Override
+ public void remove() {}
};
}
@Override
- public <F1, F2, F3> Timer3<F1, F2, F3> newTimer(String name,
- Description desc, Field<F1> field1, Field<F2> field2, Field<F3> field3) {
+ public <F1, F2, F3> Timer3<F1, F2, F3> newTimer(
+ String name, Description desc, Field<F1> field1, Field<F2> field2, Field<F3> field3) {
return new Timer3<F1, F2, F3>() {
- @Override public void record(F1 field1, F2 field2, F3 field3, long value, TimeUnit unit) {}
- @Override public void remove() {}
+ @Override
+ public void record(F1 field1, F2 field2, F3 field3, long value, TimeUnit unit) {}
+
+ @Override
+ public void remove() {}
};
}
@Override
public Histogram0 newHistogram(String name, Description desc) {
return new Histogram0() {
- @Override public void record(long value) {}
- @Override public void remove() {}
+ @Override
+ public void record(long value) {}
+
+ @Override
+ public void remove() {}
};
}
@Override
- public <F1> Histogram1<F1> newHistogram(String name, Description desc,
- Field<F1> field1) {
+ public <F1> Histogram1<F1> newHistogram(String name, Description desc, Field<F1> field1) {
return new Histogram1<F1>() {
- @Override public void record(F1 field1, long value) {}
- @Override public void remove() {}
+ @Override
+ public void record(F1 field1, long value) {}
+
+ @Override
+ public void remove() {}
};
}
@Override
- public <F1, F2> Histogram2<F1, F2> newHistogram(String name, Description desc,
- Field<F1> field1, Field<F2> field2) {
+ public <F1, F2> Histogram2<F1, F2> newHistogram(
+ String name, Description desc, Field<F1> field1, Field<F2> field2) {
return new Histogram2<F1, F2>() {
- @Override public void record(F1 field1, F2 field2, long value) {}
- @Override public void remove() {}
+ @Override
+ public void record(F1 field1, F2 field2, long value) {}
+
+ @Override
+ public void remove() {}
};
}
@Override
- public <F1, F2, F3> Histogram3<F1, F2, F3> newHistogram(String name,
- Description desc, Field<F1> field1, Field<F2> field2, Field<F3> field3) {
+ public <F1, F2, F3> Histogram3<F1, F2, F3> newHistogram(
+ String name, Description desc, Field<F1> field1, Field<F2> field2, Field<F3> field3) {
return new Histogram3<F1, F2, F3>() {
- @Override public void record(F1 field1, F2 field2, F3 field3, long value) {}
- @Override public void remove() {}
+ @Override
+ public void record(F1 field1, F2 field2, F3 field3, long value) {}
+
+ @Override
+ public void remove() {}
};
}
@Override
- public <V> CallbackMetric0<V> newCallbackMetric(String name,
- Class<V> valueClass, Description desc) {
+ public <V> CallbackMetric0<V> newCallbackMetric(
+ String name, Class<V> valueClass, Description desc) {
return new CallbackMetric0<V>() {
- @Override public void set(V value) {}
- @Override public void remove() {}
+ @Override
+ public void set(V value) {}
+
+ @Override
+ public void remove() {}
};
}
@Override
- public <F1, V> CallbackMetric1<F1, V> newCallbackMetric(String name,
- Class<V> valueClass, Description desc, Field<F1> field1) {
+ public <F1, V> CallbackMetric1<F1, V> newCallbackMetric(
+ String name, Class<V> valueClass, Description desc, Field<F1> field1) {
return new CallbackMetric1<F1, V>() {
- @Override public void set(F1 field1, V value) {}
- @Override public void forceCreate(F1 field1) {}
- @Override public void remove() {}
+ @Override
+ public void set(F1 field1, V value) {}
+
+ @Override
+ public void forceCreate(F1 field1) {}
+
+ @Override
+ public void remove() {}
};
}
@Override
- public RegistrationHandle newTrigger(Set<CallbackMetric<?>> metrics,
- Runnable trigger) {
+ public RegistrationHandle newTrigger(Set<CallbackMetric<?>> metrics, Runnable trigger) {
return new RegistrationHandle() {
- @Override public void remove() {}
+ @Override
+ public void remove() {}
};
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/metrics/Field.java b/gerrit-server/src/main/java/com/google/gerrit/metrics/Field.java
index 95fbf04..95eb9cf 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/metrics/Field.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/metrics/Field.java
@@ -53,8 +53,7 @@
* @param name field name
* @return enum field
*/
- public static <E extends Enum<E>> Field<E> ofEnum(Class<E> enumType,
- String name) {
+ public static <E extends Enum<E>> Field<E> ofEnum(Class<E> enumType, String name) {
return ofEnum(enumType, name, null);
}
@@ -66,16 +65,16 @@
* @param description field description
* @return enum field
*/
- public static <E extends Enum<E>> Field<E> ofEnum(Class<E> enumType,
- String name, String description) {
+ public static <E extends Enum<E>> Field<E> ofEnum(
+ Class<E> enumType, String name, String description) {
return new Field<>(name, enumType, description);
}
/**
* Break down metrics by string.
- * <p>
- * Each unique string will allocate a new submetric. <b>Do not use user
- * content as a field value</b> as field values are never reclaimed.
+ *
+ * <p>Each unique string will allocate a new submetric. <b>Do not use user content as a field
+ * value</b> as field values are never reclaimed.
*
* @param name field name
* @return string field
@@ -86,9 +85,9 @@
/**
* Break down metrics by string.
- * <p>
- * Each unique string will allocate a new submetric. <b>Do not use user
- * content as a field value</b> as field values are never reclaimed.
+ *
+ * <p>Each unique string will allocate a new submetric. <b>Do not use user content as a field
+ * value</b> as field values are never reclaimed.
*
* @param name field name
* @param description field description
@@ -100,9 +99,9 @@
/**
* Break down metrics by integer.
- * <p>
- * Each unique integer will allocate a new submetric. <b>Do not use user
- * content as a field value</b> as field values are never reclaimed.
+ *
+ * <p>Each unique integer will allocate a new submetric. <b>Do not use user content as a field
+ * value</b> as field values are never reclaimed.
*
* @param name field name
* @return integer field
@@ -113,9 +112,9 @@
/**
* Break down metrics by integer.
- * <p>
- * Each unique integer will allocate a new submetric. <b>Do not use user
- * content as a field value</b> as field values are never reclaimed.
+ *
+ * <p>Each unique integer will allocate a new submetric. <b>Do not use user content as a field
+ * value</b> as field values are never reclaimed.
*
* @param name field name
* @param description field description
@@ -160,7 +159,7 @@
@SuppressWarnings("unchecked")
private static <T> Function<T, String> initFormatter(Class<T> keyType) {
if (keyType == String.class) {
- return (Function<T, String>) Functions.<String> identity();
+ return (Function<T, String>) Functions.<String>identity();
} else if (keyType == Integer.class || keyType == Boolean.class) {
return (Function<T, String>) Functions.toStringFunction();
} else if (Enum.class.isAssignableFrom(keyType)) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/metrics/Histogram0.java b/gerrit-server/src/main/java/com/google/gerrit/metrics/Histogram0.java
index fa614d5..5aad8fe 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/metrics/Histogram0.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/metrics/Histogram0.java
@@ -18,8 +18,8 @@
/**
* Measures the statistical distribution of values in a stream of data.
- * <p>
- * Suitable uses are "response size in bytes", etc.
+ *
+ * <p>Suitable uses are "response size in bytes", etc.
*/
public abstract class Histogram0 implements RegistrationHandle {
/**
diff --git a/gerrit-server/src/main/java/com/google/gerrit/metrics/Histogram1.java b/gerrit-server/src/main/java/com/google/gerrit/metrics/Histogram1.java
index dd1ed0a..3b9307f 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/metrics/Histogram1.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/metrics/Histogram1.java
@@ -18,8 +18,8 @@
/**
* Measures the statistical distribution of values in a stream of data.
- * <p>
- * Suitable uses are "response size in bytes", etc.
+ *
+ * <p>Suitable uses are "response size in bytes", etc.
*
* @param <F1> type of the field.
*/
diff --git a/gerrit-server/src/main/java/com/google/gerrit/metrics/Histogram2.java b/gerrit-server/src/main/java/com/google/gerrit/metrics/Histogram2.java
index b1c4482..939fe25 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/metrics/Histogram2.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/metrics/Histogram2.java
@@ -18,8 +18,8 @@
/**
* Measures the statistical distribution of values in a stream of data.
- * <p>
- * Suitable uses are "response size in bytes", etc.
+ *
+ * <p>Suitable uses are "response size in bytes", etc.
*
* @param <F1> type of the field.
* @param <F2> type of the field.
diff --git a/gerrit-server/src/main/java/com/google/gerrit/metrics/Histogram3.java b/gerrit-server/src/main/java/com/google/gerrit/metrics/Histogram3.java
index 0c50e118..ed709e1 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/metrics/Histogram3.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/metrics/Histogram3.java
@@ -18,8 +18,8 @@
/**
* Measures the statistical distribution of values in a stream of data.
- * <p>
- * Suitable uses are "response size in bytes", etc.
+ *
+ * <p>Suitable uses are "response size in bytes", etc.
*
* @param <F1> type of the field.
* @param <F2> type of the field.
diff --git a/gerrit-server/src/main/java/com/google/gerrit/metrics/MetricMaker.java b/gerrit-server/src/main/java/com/google/gerrit/metrics/MetricMaker.java
index 461c6b6..9773869 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/metrics/MetricMaker.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/metrics/MetricMaker.java
@@ -17,7 +17,6 @@
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableSet;
import com.google.gerrit.extensions.registration.RegistrationHandle;
-
import java.util.Set;
/** Factory to create metrics for monitoring. */
@@ -30,15 +29,14 @@
* @return counter
*/
public abstract Counter0 newCounter(String name, Description desc);
- public abstract <F1> Counter1<F1> newCounter(
- String name, Description desc,
- Field<F1> field1);
+
+ public abstract <F1> Counter1<F1> newCounter(String name, Description desc, Field<F1> field1);
+
public abstract <F1, F2> Counter2<F1, F2> newCounter(
- String name, Description desc,
- Field<F1> field1, Field<F2> field2);
+ String name, Description desc, Field<F1> field1, Field<F2> field2);
+
public abstract <F1, F2, F3> Counter3<F1, F2, F3> newCounter(
- String name, Description desc,
- Field<F1> field1, Field<F2> field2, Field<F3> field3);
+ String name, Description desc, Field<F1> field1, Field<F2> field2, Field<F3> field3);
/**
* Metric recording time spent on an operation.
@@ -48,15 +46,14 @@
* @return timer
*/
public abstract Timer0 newTimer(String name, Description desc);
- public abstract <F1> Timer1<F1> newTimer(
- String name, Description desc,
- Field<F1> field1);
+
+ public abstract <F1> Timer1<F1> newTimer(String name, Description desc, Field<F1> field1);
+
public abstract <F1, F2> Timer2<F1, F2> newTimer(
- String name, Description desc,
- Field<F1> field1, Field<F2> field2);
+ String name, Description desc, Field<F1> field1, Field<F2> field2);
+
public abstract <F1, F2, F3> Timer3<F1, F2, F3> newTimer(
- String name, Description desc,
- Field<F1> field1, Field<F2> field2, Field<F3> field3);
+ String name, Description desc, Field<F1> field1, Field<F2> field2, Field<F3> field3);
/**
* Metric recording statistical distribution of values.
@@ -66,15 +63,14 @@
* @return histogram
*/
public abstract Histogram0 newHistogram(String name, Description desc);
- public abstract <F1> Histogram1<F1> newHistogram(
- String name, Description desc,
- Field<F1> field1);
+
+ public abstract <F1> Histogram1<F1> newHistogram(String name, Description desc, Field<F1> field1);
+
public abstract <F1, F2> Histogram2<F1, F2> newHistogram(
- String name, Description desc,
- Field<F1> field1, Field<F2> field2);
+ String name, Description desc, Field<F1> field1, Field<F2> field2);
+
public abstract <F1, F2, F3> Histogram3<F1, F2, F3> newHistogram(
- String name, Description desc,
- Field<F1> field1, Field<F2> field2, Field<F3> field3);
+ String name, Description desc, Field<F1> field1, Field<F2> field2, Field<F3> field3);
/**
* Constant value that does not change.
@@ -89,12 +85,14 @@
@SuppressWarnings("unchecked")
Class<V> type = (Class<V>) value.getClass();
final CallbackMetric0<V> metric = newCallbackMetric(name, type, desc);
- newTrigger(metric, new Runnable() {
- @Override
- public void run() {
- metric.set(value);
- }
- });
+ newTrigger(
+ metric,
+ new Runnable() {
+ @Override
+ public void run() {
+ metric.set(value);
+ }
+ });
}
/**
@@ -117,19 +115,21 @@
* @param desc description of the metric.
* @param trigger function to compute the value of the metric.
*/
- public <V> void newCallbackMetric(String name,
- Class<V> valueClass, Description desc, final Supplier<V> trigger) {
+ public <V> void newCallbackMetric(
+ String name, Class<V> valueClass, Description desc, final Supplier<V> trigger) {
final CallbackMetric0<V> metric = newCallbackMetric(name, valueClass, desc);
- newTrigger(metric, new Runnable() {
- @Override
- public void run() {
- metric.set(trigger.get());
- }
- });
+ newTrigger(
+ metric,
+ new Runnable() {
+ @Override
+ public void run() {
+ metric.set(trigger.get());
+ }
+ });
}
/**
- * Instantaneous reading of a single value.
+ * Instantaneous reading of a single value.
*
* @param name field name
* @param valueClass field type
@@ -138,9 +138,9 @@
*/
public abstract <V> CallbackMetric0<V> newCallbackMetric(
String name, Class<V> valueClass, Description desc);
+
public abstract <F1, V> CallbackMetric1<F1, V> newCallbackMetric(
- String name, Class<V> valueClass, Description desc,
- Field<F1> field1);
+ String name, Class<V> valueClass, Description desc, Field<F1> field1);
/**
* Connect logic to populate a previously created {@link CallbackMetric}.
@@ -153,16 +153,18 @@
return newTrigger(ImmutableSet.<CallbackMetric<?>>of(metric1), trigger);
}
- public RegistrationHandle newTrigger(CallbackMetric<?> metric1,
- CallbackMetric<?> metric2, Runnable trigger) {
+ public RegistrationHandle newTrigger(
+ CallbackMetric<?> metric1, CallbackMetric<?> metric2, Runnable trigger) {
return newTrigger(ImmutableSet.of(metric1, metric2), trigger);
}
- public RegistrationHandle newTrigger(CallbackMetric<?> metric1,
- CallbackMetric<?> metric2, CallbackMetric<?> metric3, Runnable trigger) {
+ public RegistrationHandle newTrigger(
+ CallbackMetric<?> metric1,
+ CallbackMetric<?> metric2,
+ CallbackMetric<?> metric3,
+ Runnable trigger) {
return newTrigger(ImmutableSet.of(metric1, metric2, metric3), trigger);
}
- public abstract RegistrationHandle newTrigger(Set<CallbackMetric<?>> metrics,
- Runnable trigger);
+ public abstract RegistrationHandle newTrigger(Set<CallbackMetric<?>> metrics, Runnable trigger);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/metrics/Timer0.java b/gerrit-server/src/main/java/com/google/gerrit/metrics/Timer0.java
index d2c9a52..55d1ddf 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/metrics/Timer0.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/metrics/Timer0.java
@@ -17,13 +17,12 @@
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import com.google.gerrit.extensions.registration.RegistrationHandle;
-
import java.util.concurrent.TimeUnit;
/**
* Records elapsed time for an operation or span.
- * <p>
- * Typical usage in a try-with-resources block:
+ *
+ * <p>Typical usage in a try-with-resources block:
*
* <pre>
* try (Timer0.Context ctx = timer.start()) {
@@ -53,7 +52,8 @@
return new Context(this);
}
- /** Record a value in the distribution.
+ /**
+ * Record a value in the distribution.
*
* @param value value to record
* @param unit time unit of the value
diff --git a/gerrit-server/src/main/java/com/google/gerrit/metrics/Timer1.java b/gerrit-server/src/main/java/com/google/gerrit/metrics/Timer1.java
index be6931d..f623841 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/metrics/Timer1.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/metrics/Timer1.java
@@ -17,13 +17,12 @@
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import com.google.gerrit.extensions.registration.RegistrationHandle;
-
import java.util.concurrent.TimeUnit;
/**
* Records elapsed time for an operation or span.
- * <p>
- * Typical usage in a try-with-resources block:
+ *
+ * <p>Typical usage in a try-with-resources block:
*
* <pre>
* try (Timer1.Context ctx = timer.start(field)) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/metrics/Timer2.java b/gerrit-server/src/main/java/com/google/gerrit/metrics/Timer2.java
index 0ace4c3..b03ff83 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/metrics/Timer2.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/metrics/Timer2.java
@@ -17,13 +17,12 @@
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import com.google.gerrit.extensions.registration.RegistrationHandle;
-
import java.util.concurrent.TimeUnit;
/**
* Records elapsed time for an operation or span.
- * <p>
- * Typical usage in a try-with-resources block:
+ *
+ * <p>Typical usage in a try-with-resources block:
*
* <pre>
* try (Timer2.Context ctx = timer.start(field)) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/metrics/Timer3.java b/gerrit-server/src/main/java/com/google/gerrit/metrics/Timer3.java
index 09e899d..91af42c 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/metrics/Timer3.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/metrics/Timer3.java
@@ -17,13 +17,12 @@
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import com.google.gerrit.extensions.registration.RegistrationHandle;
-
import java.util.concurrent.TimeUnit;
/**
* Records elapsed time for an operation or span.
- * <p>
- * Typical usage in a try-with-resources block:
+ *
+ * <p>Typical usage in a try-with-resources block:
*
* <pre>
* try (Timer3.Context ctx = timer.start(field)) {
@@ -76,6 +75,5 @@
* @param value value to record
* @param unit time unit of the value
*/
- public abstract void record(F1 field1, F2 field2, F3 field3,
- long value, TimeUnit unit);
+ public abstract void record(F1 field1, F2 field2, F3 field3, long value, TimeUnit unit);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/BucketedCallback.java b/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/BucketedCallback.java
index d3fe6ed..c7a92a3 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/BucketedCallback.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/BucketedCallback.java
@@ -14,15 +14,13 @@
package com.google.gerrit.metrics.dropwizard;
+import com.codahale.metrics.Gauge;
+import com.codahale.metrics.Metric;
+import com.codahale.metrics.MetricRegistry;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Maps;
import com.google.gerrit.metrics.Description;
import com.google.gerrit.metrics.Field;
-
-import com.codahale.metrics.Gauge;
-import com.codahale.metrics.Metric;
-import com.codahale.metrics.MetricRegistry;
-
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@@ -39,8 +37,13 @@
protected volatile Runnable trigger;
private final Object lock = new Object();
- BucketedCallback(DropWizardMetricMaker metrics, MetricRegistry registry,
- String name, Class<V> valueType, Description desc, Field<?>... fields) {
+ BucketedCallback(
+ DropWizardMetricMaker metrics,
+ MetricRegistry registry,
+ String name,
+ Class<V> valueType,
+ Description desc,
+ Field<?>... fields) {
this.metrics = metrics;
this.registry = registry;
this.name = name;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/BucketedCounter.java b/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/BucketedCounter.java
index 7894a84..7706297 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/BucketedCounter.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/BucketedCounter.java
@@ -14,14 +14,12 @@
package com.google.gerrit.metrics.dropwizard;
+import com.codahale.metrics.Metric;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Maps;
import com.google.gerrit.metrics.Description;
import com.google.gerrit.metrics.Field;
import com.google.gerrit.metrics.dropwizard.DropWizardMetricMaker.CounterImpl;
-
-import com.codahale.metrics.Metric;
-
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@@ -36,8 +34,8 @@
private final Map<Object, CounterImpl> cells;
private final Object lock = new Object();
- BucketedCounter(DropWizardMetricMaker metrics,
- String name, Description desc, Field<?>... fields) {
+ BucketedCounter(
+ DropWizardMetricMaker metrics, String name, Description desc, Field<?>... fields) {
this.metrics = metrics;
this.name = name;
this.isRate = desc.isRate();
diff --git a/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/BucketedHistogram.java b/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/BucketedHistogram.java
index ff38cd4..35eb180 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/BucketedHistogram.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/BucketedHistogram.java
@@ -14,14 +14,12 @@
package com.google.gerrit.metrics.dropwizard;
+import com.codahale.metrics.Metric;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Maps;
import com.google.gerrit.metrics.Description;
import com.google.gerrit.metrics.Field;
import com.google.gerrit.metrics.dropwizard.DropWizardMetricMaker.HistogramImpl;
-
-import com.codahale.metrics.Metric;
-
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@@ -35,8 +33,8 @@
private final Map<Object, HistogramImpl> cells;
private final Object lock = new Object();
- BucketedHistogram(DropWizardMetricMaker metrics, String name,
- Description desc, Field<?>... fields) {
+ BucketedHistogram(
+ DropWizardMetricMaker metrics, String name, Description desc, Field<?>... fields) {
this.metrics = metrics;
this.name = name;
this.ordering = desc.getFieldOrdering();
diff --git a/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/BucketedMetric.java b/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/BucketedMetric.java
index 799e594..9b0b37f 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/BucketedMetric.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/BucketedMetric.java
@@ -14,16 +14,17 @@
package com.google.gerrit.metrics.dropwizard;
+import com.codahale.metrics.Metric;
import com.google.gerrit.common.Nullable;
import com.google.gerrit.metrics.Field;
-
-import com.codahale.metrics.Metric;
-
import java.util.Map;
/** Metric broken down into buckets by {@link Field} values. */
interface BucketedMetric extends Metric {
- @Nullable Metric getTotal();
+ @Nullable
+ Metric getTotal();
+
Field<?>[] getFields();
+
Map<?, Metric> getCells();
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/BucketedTimer.java b/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/BucketedTimer.java
index aff6c4a..3b19a62 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/BucketedTimer.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/BucketedTimer.java
@@ -14,14 +14,12 @@
package com.google.gerrit.metrics.dropwizard;
+import com.codahale.metrics.Metric;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Maps;
import com.google.gerrit.metrics.Description;
import com.google.gerrit.metrics.Field;
import com.google.gerrit.metrics.dropwizard.DropWizardMetricMaker.TimerImpl;
-
-import com.codahale.metrics.Metric;
-
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@@ -35,8 +33,7 @@
private final Map<Object, TimerImpl> cells;
private final Object lock = new Object();
- BucketedTimer(DropWizardMetricMaker metrics, String name,
- Description desc, Field<?>... fields) {
+ BucketedTimer(DropWizardMetricMaker metrics, String name, Description desc, Field<?>... fields) {
this.metrics = metrics;
this.name = name;
this.ordering = desc.getFieldOrdering();
diff --git a/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/CallbackGroup.java b/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/CallbackGroup.java
index 372bdcb..f153e7e 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/CallbackGroup.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/CallbackGroup.java
@@ -15,17 +15,15 @@
package com.google.gerrit.metrics.dropwizard;
import com.google.common.collect.ImmutableSet;
-
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
/**
* Run a user specified trigger only once every 2 seconds.
- * <p>
- * This allows the same Runnable trigger to be applied to several metrics. When
- * a recorder is sampling the related metrics only the first access will perform
- * recomputation. Reading other related metrics will rely on the already set
- * values for the next several seconds.
+ *
+ * <p>This allows the same Runnable trigger to be applied to several metrics. When a recorder is
+ * sampling the related metrics only the first access will perform recomputation. Reading other
+ * related metrics will rely on the already set values for the next several seconds.
*/
class CallbackGroup implements Runnable {
private static final long PERIOD = TimeUnit.SECONDS.toNanos(2);
@@ -57,7 +55,7 @@
}
private boolean reload() {
- for (;;) {
+ for (; ; ) {
long now = System.nanoTime();
long next = reloadAt.get();
if (next > now) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/CallbackMetricGlue.java b/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/CallbackMetricGlue.java
index 4f5b7ad..9fd4fc9 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/CallbackMetricGlue.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/CallbackMetricGlue.java
@@ -16,7 +16,10 @@
interface CallbackMetricGlue {
void beginSet();
+
void endSet();
+
void register(Runnable trigger);
+
void remove();
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/CallbackMetricImpl0.java b/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/CallbackMetricImpl0.java
index dcab692..6910d22 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/CallbackMetricImpl0.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/CallbackMetricImpl0.java
@@ -14,13 +14,10 @@
package com.google.gerrit.metrics.dropwizard;
+import com.codahale.metrics.MetricRegistry;
import com.google.gerrit.metrics.CallbackMetric0;
-import com.codahale.metrics.MetricRegistry;
-
-class CallbackMetricImpl0<V>
- extends CallbackMetric0<V>
- implements CallbackMetricGlue {
+class CallbackMetricImpl0<V> extends CallbackMetric0<V> implements CallbackMetricGlue {
@SuppressWarnings("unchecked")
static <V> V zeroFor(Class<V> valueClass) {
if (valueClass == Integer.class) {
@@ -36,8 +33,7 @@
} else if (valueClass == Boolean.class) {
return (V) Boolean.FALSE;
} else {
- throw new IllegalArgumentException("unsupported value type "
- + valueClass.getName());
+ throw new IllegalArgumentException("unsupported value type " + valueClass.getName());
}
}
@@ -46,8 +42,8 @@
private final String name;
private volatile V value;
- CallbackMetricImpl0(DropWizardMetricMaker metrics, MetricRegistry registry,
- String name, Class<V> valueType) {
+ CallbackMetricImpl0(
+ DropWizardMetricMaker metrics, MetricRegistry registry, String name, Class<V> valueType) {
this.metrics = metrics;
this.registry = registry;
this.name = name;
@@ -55,12 +51,10 @@
}
@Override
- public void beginSet() {
- }
+ public void beginSet() {}
@Override
- public void endSet() {
- }
+ public void endSet() {}
@Override
public void set(V value) {
@@ -75,12 +69,14 @@
@Override
public void register(final Runnable trigger) {
- registry.register(name, new com.codahale.metrics.Gauge<V>() {
- @Override
- public V getValue() {
- trigger.run();
- return value;
- }
- });
+ registry.register(
+ name,
+ new com.codahale.metrics.Gauge<V>() {
+ @Override
+ public V getValue() {
+ trigger.run();
+ return value;
+ }
+ });
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/CallbackMetricImpl1.java b/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/CallbackMetricImpl1.java
index 81d5ff5..6d1daf4 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/CallbackMetricImpl1.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/CallbackMetricImpl1.java
@@ -14,17 +14,21 @@
package com.google.gerrit.metrics.dropwizard;
+import com.codahale.metrics.MetricRegistry;
import com.google.common.base.Function;
import com.google.gerrit.metrics.CallbackMetric1;
import com.google.gerrit.metrics.Description;
import com.google.gerrit.metrics.Field;
-import com.codahale.metrics.MetricRegistry;
-
/** Optimized version of {@link BucketedCallback} for single dimension. */
class CallbackMetricImpl1<F1, V> extends BucketedCallback<V> {
- CallbackMetricImpl1(DropWizardMetricMaker metrics, MetricRegistry registry,
- String name, Class<V> valueClass, Description desc, Field<F1> field1) {
+ CallbackMetricImpl1(
+ DropWizardMetricMaker metrics,
+ MetricRegistry registry,
+ String name,
+ Class<V> valueClass,
+ Description desc,
+ Field<F1> field1) {
super(metrics, registry, name, valueClass, desc, field1);
}
@@ -32,9 +36,7 @@
return new Impl1();
}
- private final class Impl1
- extends CallbackMetric1<F1, V>
- implements CallbackMetricGlue {
+ private final class Impl1 extends CallbackMetric1<F1, V> implements CallbackMetricGlue {
@Override
public void beginSet() {
doBeginSet();
@@ -76,8 +78,7 @@
@Override
String name(Object field1) {
@SuppressWarnings("unchecked")
- Function<Object, String> fmt =
- (Function<Object, String>) fields[0].formatter();
+ Function<Object, String> fmt = (Function<Object, String>) fields[0].formatter();
return fmt.apply(field1).replace('/', '-');
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/CounterImpl1.java b/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/CounterImpl1.java
index 25647ef..46434ce 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/CounterImpl1.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/CounterImpl1.java
@@ -21,8 +21,7 @@
/** Optimized version of {@link BucketedCounter} for single dimension. */
class CounterImpl1<F1> extends BucketedCounter {
- CounterImpl1(DropWizardMetricMaker metrics, String name, Description desc,
- Field<F1> field1) {
+ CounterImpl1(DropWizardMetricMaker metrics, String name, Description desc, Field<F1> field1) {
super(metrics, name, desc, field1);
}
@@ -44,8 +43,7 @@
@Override
String name(Object field1) {
@SuppressWarnings("unchecked")
- Function<Object, String> fmt =
- (Function<Object, String>) fields[0].formatter();
+ Function<Object, String> fmt = (Function<Object, String>) fields[0].formatter();
return fmt.apply(field1).replace('/', '-');
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/CounterImplN.java b/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/CounterImplN.java
index a2f1f84..38c31a1 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/CounterImplN.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/CounterImplN.java
@@ -24,8 +24,7 @@
/** Generalized implementation of N-dimensional counter metrics. */
class CounterImplN extends BucketedCounter implements BucketedMetric {
- CounterImplN(DropWizardMetricMaker metrics, String name, Description desc,
- Field<?>... fields) {
+ CounterImplN(DropWizardMetricMaker metrics, String name, Description desc, Field<?>... fields) {
super(metrics, name, desc, fields);
}
@@ -65,8 +64,7 @@
ImmutableList<Object> keyList = (ImmutableList<Object>) key;
String[] parts = new String[fields.length];
for (int i = 0; i < fields.length; i++) {
- Function<Object, String> fmt =
- (Function<Object, String>) fields[i].formatter();
+ Function<Object, String> fmt = (Function<Object, String>) fields[i].formatter();
parts[i] = fmt.apply(keyList.get(i)).replace('/', '-');
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/DropWizardMetricMaker.java b/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/DropWizardMetricMaker.java
index ee2ce29..1127728 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/DropWizardMetricMaker.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/DropWizardMetricMaker.java
@@ -18,6 +18,8 @@
import static com.google.gerrit.metrics.dropwizard.MetricResource.METRIC_KIND;
import static com.google.gerrit.server.config.ConfigResource.CONFIG_KIND;
+import com.codahale.metrics.Metric;
+import com.codahale.metrics.MetricRegistry;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
@@ -49,10 +51,6 @@
import com.google.inject.Inject;
import com.google.inject.Scopes;
import com.google.inject.Singleton;
-
-import com.codahale.metrics.Metric;
-import com.codahale.metrics.MetricRegistry;
-
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
@@ -123,8 +121,7 @@
@Override
public synchronized <F1> Counter1<F1> newCounter(
- String name, Description desc,
- Field<F1> field1) {
+ String name, Description desc, Field<F1> field1) {
checkCounterDescription(name, desc);
CounterImpl1<F1> m = new CounterImpl1<>(this, name, desc, field1);
define(name, desc);
@@ -134,8 +131,7 @@
@Override
public synchronized <F1, F2> Counter2<F1, F2> newCounter(
- String name, Description desc,
- Field<F1> field1, Field<F2> field2) {
+ String name, Description desc, Field<F1> field1, Field<F2> field2) {
checkCounterDescription(name, desc);
CounterImplN m = new CounterImplN(this, name, desc, field1, field2);
define(name, desc);
@@ -145,8 +141,7 @@
@Override
public synchronized <F1, F2, F3> Counter3<F1, F2, F3> newCounter(
- String name, Description desc,
- Field<F1> field1, Field<F2> field2, Field<F3> field3) {
+ String name, Description desc, Field<F1> field1, Field<F2> field2, Field<F3> field3) {
checkCounterDescription(name, desc);
CounterImplN m = new CounterImplN(this, name, desc, field1, field2, field3);
define(name, desc);
@@ -198,8 +193,8 @@
}
@Override
- public synchronized <F1, F2> Timer2<F1, F2> newTimer(String name, Description desc,
- Field<F1> field1, Field<F2> field2) {
+ public synchronized <F1, F2> Timer2<F1, F2> newTimer(
+ String name, Description desc, Field<F1> field1, Field<F2> field2) {
checkTimerDescription(name, desc);
TimerImplN m = new TimerImplN(this, name, desc, field1, field2);
define(name, desc);
@@ -209,8 +204,7 @@
@Override
public synchronized <F1, F2, F3> Timer3<F1, F2, F3> newTimer(
- String name, Description desc,
- Field<F1> field1, Field<F2> field2, Field<F3> field3) {
+ String name, Description desc, Field<F1> field1, Field<F2> field2, Field<F3> field3) {
checkTimerDescription(name, desc);
TimerImplN m = new TimerImplN(this, name, desc, field1, field2, field3);
define(name, desc);
@@ -239,8 +233,8 @@
}
@Override
- public synchronized <F1> Histogram1<F1> newHistogram(String name,
- Description desc, Field<F1> field1) {
+ public synchronized <F1> Histogram1<F1> newHistogram(
+ String name, Description desc, Field<F1> field1) {
checkHistogramDescription(name, desc);
HistogramImpl1<F1> m = new HistogramImpl1<>(this, name, desc, field1);
define(name, desc);
@@ -249,8 +243,8 @@
}
@Override
- public synchronized <F1, F2> Histogram2<F1, F2> newHistogram(String name,
- Description desc, Field<F1> field1, Field<F2> field2) {
+ public synchronized <F1, F2> Histogram2<F1, F2> newHistogram(
+ String name, Description desc, Field<F1> field1, Field<F2> field2) {
checkHistogramDescription(name, desc);
HistogramImplN m = new HistogramImplN(this, name, desc, field1, field2);
define(name, desc);
@@ -260,8 +254,7 @@
@Override
public synchronized <F1, F2, F3> Histogram3<F1, F2, F3> newHistogram(
- String name, Description desc,
- Field<F1> field1, Field<F2> field2, Field<F3> field3) {
+ String name, Description desc, Field<F1> field1, Field<F2> field2, Field<F3> field3) {
checkHistogramDescription(name, desc);
HistogramImplN m = new HistogramImplN(this, name, desc, field1, field2, field3);
define(name, desc);
@@ -293,8 +286,8 @@
public <F1, V> CallbackMetric1<F1, V> newCallbackMetric(
String name, Class<V> valueClass, Description desc, Field<F1> field1) {
checkMetricName(name);
- CallbackMetricImpl1<F1, V> m = new CallbackMetricImpl1<>(this, registry,
- name, valueClass, desc, field1);
+ CallbackMetricImpl1<F1, V> m =
+ new CallbackMetricImpl1<>(this, registry, name, valueClass, desc, field1);
define(name, desc);
bucketed.put(name, m);
return m.create();
@@ -303,9 +296,8 @@
@Override
public synchronized RegistrationHandle newTrigger(
Set<CallbackMetric<?>> metrics, Runnable trigger) {
- ImmutableSet<CallbackMetricGlue> all = FluentIterable.from(metrics)
- .transform(m -> (CallbackMetricGlue) m)
- .toSet();
+ ImmutableSet<CallbackMetricGlue> all =
+ FluentIterable.from(metrics).transform(m -> (CallbackMetricGlue) m).toSet();
trigger = new CallbackGroup(trigger, all);
for (CallbackMetricGlue m : all) {
@@ -330,24 +322,22 @@
private synchronized void define(String name, Description desc) {
if (descriptions.containsKey(name)) {
- throw new IllegalStateException(String.format(
- "metric %s already defined", name));
+ throw new IllegalStateException(String.format("metric %s already defined", name));
}
descriptions.put(name, desc.getAnnotations());
}
- private static final Pattern METRIC_NAME_PATTERN = Pattern
- .compile("[a-zA-Z0-9_-]+(/[a-zA-Z0-9_-]+)*");
+ private static final Pattern METRIC_NAME_PATTERN =
+ Pattern.compile("[a-zA-Z0-9_-]+(/[a-zA-Z0-9_-]+)*");
private static void checkMetricName(String name) {
checkArgument(
METRIC_NAME_PATTERN.matcher(name).matches(),
- "metric name must match %s", METRIC_NAME_PATTERN.pattern());
+ "metric name must match %s",
+ METRIC_NAME_PATTERN.pattern());
}
- static String name(Description.FieldOrdering ordering,
- String codeName,
- String fieldValues) {
+ static String name(Description.FieldOrdering ordering, String codeName, String fieldValues) {
if (ordering == FieldOrdering.PREFIX_FIELDS_BASENAME) {
int s = codeName.lastIndexOf('/');
if (s > 0) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/GetMetric.java b/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/GetMetric.java
index 47064df..52e35c3 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/GetMetric.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/GetMetric.java
@@ -18,7 +18,6 @@
import com.google.gerrit.extensions.restapi.RestReadView;
import com.google.gerrit.server.CurrentUser;
import com.google.inject.Inject;
-
import org.kohsuke.args4j.Option;
class GetMetric implements RestReadView<MetricResource> {
@@ -40,8 +39,6 @@
throw new AuthException("restricted to viewCaches");
}
return new MetricJson(
- resource.getMetric(),
- metrics.getAnnotations(resource.getName()),
- dataOnly);
+ resource.getMetric(), metrics.getAnnotations(resource.getName()), dataOnly);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/HistogramImpl1.java b/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/HistogramImpl1.java
index e3f9e1c..3eb12fa 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/HistogramImpl1.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/HistogramImpl1.java
@@ -21,8 +21,7 @@
/** Optimized version of {@link BucketedHistogram} for single dimension. */
class HistogramImpl1<F1> extends BucketedHistogram implements BucketedMetric {
- HistogramImpl1(DropWizardMetricMaker metrics, String name,
- Description desc, Field<F1> field1) {
+ HistogramImpl1(DropWizardMetricMaker metrics, String name, Description desc, Field<F1> field1) {
super(metrics, name, desc, field1);
}
@@ -44,8 +43,7 @@
@Override
String name(Object field1) {
@SuppressWarnings("unchecked")
- Function<Object, String> fmt =
- (Function<Object, String>) fields[0].formatter();
+ Function<Object, String> fmt = (Function<Object, String>) fields[0].formatter();
return fmt.apply(field1).replace('/', '-');
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/HistogramImplN.java b/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/HistogramImplN.java
index d832c60..3561c55a 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/HistogramImplN.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/HistogramImplN.java
@@ -24,8 +24,7 @@
/** Generalized implementation of N-dimensional Histogram metrics. */
class HistogramImplN extends BucketedHistogram implements BucketedMetric {
- HistogramImplN(DropWizardMetricMaker metrics, String name,
- Description desc, Field<?>... fields) {
+ HistogramImplN(DropWizardMetricMaker metrics, String name, Description desc, Field<?>... fields) {
super(metrics, name, desc, fields);
}
@@ -65,8 +64,7 @@
ImmutableList<Object> keyList = (ImmutableList<Object>) key;
String[] parts = new String[fields.length];
for (int i = 0; i < fields.length; i++) {
- Function<Object, String> fmt =
- (Function<Object, String>) fields[i].formatter();
+ Function<Object, String> fmt = (Function<Object, String>) fields[i].formatter();
parts[i] = fmt.apply(keyList.get(i)).replace('/', '-');
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/ListMetrics.java b/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/ListMetrics.java
index 04d10a2..891f4ac 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/ListMetrics.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/ListMetrics.java
@@ -14,21 +14,18 @@
package com.google.gerrit.metrics.dropwizard;
+import com.codahale.metrics.Metric;
import com.google.gerrit.extensions.restapi.AuthException;
import com.google.gerrit.extensions.restapi.RestReadView;
import com.google.gerrit.server.CurrentUser;
import com.google.gerrit.server.config.ConfigResource;
import com.google.inject.Inject;
-
-import com.codahale.metrics.Metric;
-
-import org.kohsuke.args4j.Option;
-
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
+import org.kohsuke.args4j.Option;
class ListMetrics implements RestReadView<ConfigResource> {
private final CurrentUser user;
@@ -37,8 +34,12 @@
@Option(name = "--data-only", usage = "return only values")
boolean dataOnly;
- @Option(name = "--prefix", aliases = {"-p"}, metaVar = "PREFIX",
- usage = "match metric by exact match or prefix")
+ @Option(
+ name = "--prefix",
+ aliases = {"-p"},
+ metaVar = "PREFIX",
+ usage = "match metric by exact match or prefix"
+ )
List<String> query = new ArrayList<>();
@Inject
@@ -48,8 +49,7 @@
}
@Override
- public Map<String, MetricJson> apply(ConfigResource resource)
- throws AuthException {
+ public Map<String, MetricJson> apply(ConfigResource resource) throws AuthException {
if (!user.getCapabilities().canViewCaches()) {
throw new AuthException("restricted to viewCaches");
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/MetricJson.java b/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/MetricJson.java
index b332262..2080623 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/MetricJson.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/MetricJson.java
@@ -14,12 +14,6 @@
package com.google.gerrit.metrics.dropwizard;
-import com.google.common.base.Function;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-import com.google.gerrit.metrics.Description;
-import com.google.gerrit.metrics.Field;
-
import com.codahale.metrics.Counter;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.Histogram;
@@ -27,7 +21,11 @@
import com.codahale.metrics.Metric;
import com.codahale.metrics.Snapshot;
import com.codahale.metrics.Timer;
-
+import com.google.common.base.Function;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.gerrit.metrics.Description;
+import com.google.gerrit.metrics.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@@ -114,8 +112,7 @@
rate_5m = m.getFiveMinuteRate();
rate_15m = m.getFifteenMinuteRate();
- double div =
- Description.getTimeUnit(atts.get(Description.UNIT)).toNanos(1);
+ double div = Description.getTimeUnit(atts.get(Description.UNIT)).toNanos(1);
p50 = s.getMedian() / div;
p75 = s.get75thPercentile() / div;
p95 = s.get95thPercentile() / div;
@@ -153,17 +150,12 @@
@SuppressWarnings("unchecked")
private static Map<String, Object> makeBuckets(
- Field<?>[] fields,
- Map<?, Metric> metrics,
- ImmutableMap<String, String> atts) {
+ Field<?>[] fields, Map<?, Metric> metrics, ImmutableMap<String, String> atts) {
if (fields.length == 1) {
- Function<Object, String> fmt =
- (Function<Object, String>) fields[0].formatter();
+ Function<Object, String> fmt = (Function<Object, String>) fields[0].formatter();
Map<String, Object> out = new TreeMap<>();
for (Map.Entry<?, Metric> e : metrics.entrySet()) {
- out.put(
- fmt.apply(e.getKey()),
- new MetricJson(e.getValue(), atts, true));
+ out.put(fmt.apply(e.getKey()), new MetricJson(e.getValue(), atts, true));
}
return out;
}
@@ -174,8 +166,7 @@
Map<String, Object> dst = out;
for (int i = 0; i < fields.length - 1; i++) {
- Function<Object, String> fmt =
- (Function<Object, String>) fields[i].formatter();
+ Function<Object, String> fmt = (Function<Object, String>) fields[i].formatter();
String key = fmt.apply(keys.get(i));
Map<String, Object> t = (Map<String, Object>) dst.get(key);
if (t == null) {
@@ -187,9 +178,7 @@
Function<Object, String> fmt =
(Function<Object, String>) fields[fields.length - 1].formatter();
- dst.put(
- fmt.apply(keys.get(fields.length - 1)),
- new MetricJson(e.getValue(), atts, true));
+ dst.put(fmt.apply(keys.get(fields.length - 1)), new MetricJson(e.getValue(), atts, true));
}
return out;
}
@@ -202,9 +191,8 @@
FieldJson(Field<?> field) {
this.name = field.getName();
this.description = field.getDescription();
- this.type = Enum.class.isAssignableFrom(field.getType())
- ? field.getType().getSimpleName()
- : null;
+ this.type =
+ Enum.class.isAssignableFrom(field.getType()) ? field.getType().getSimpleName() : null;
}
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/MetricResource.java b/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/MetricResource.java
index d073f37..226edc7 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/MetricResource.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/MetricResource.java
@@ -14,12 +14,11 @@
package com.google.gerrit.metrics.dropwizard;
+import com.codahale.metrics.Metric;
import com.google.gerrit.extensions.restapi.RestView;
import com.google.gerrit.server.config.ConfigResource;
import com.google.inject.TypeLiteral;
-import com.codahale.metrics.Metric;
-
class MetricResource extends ConfigResource {
static final TypeLiteral<RestView<MetricResource>> METRIC_KIND =
new TypeLiteral<RestView<MetricResource>>() {};
diff --git a/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/MetricsCollection.java b/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/MetricsCollection.java
index 81945f1..2686f1f 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/MetricsCollection.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/MetricsCollection.java
@@ -14,6 +14,7 @@
package com.google.gerrit.metrics.dropwizard;
+import com.codahale.metrics.Metric;
import com.google.gerrit.extensions.registration.DynamicMap;
import com.google.gerrit.extensions.restapi.AuthException;
import com.google.gerrit.extensions.restapi.ChildCollection;
@@ -26,19 +27,18 @@
import com.google.inject.Provider;
import com.google.inject.Singleton;
-import com.codahale.metrics.Metric;
-
@Singleton
-class MetricsCollection implements
- ChildCollection<ConfigResource, MetricResource> {
+class MetricsCollection implements ChildCollection<ConfigResource, MetricResource> {
private final DynamicMap<RestView<MetricResource>> views;
private final Provider<ListMetrics> list;
private final Provider<CurrentUser> user;
private final DropWizardMetricMaker metrics;
@Inject
- MetricsCollection(DynamicMap<RestView<MetricResource>> views,
- Provider<ListMetrics> list, Provider<CurrentUser> user,
+ MetricsCollection(
+ DynamicMap<RestView<MetricResource>> views,
+ Provider<ListMetrics> list,
+ Provider<CurrentUser> user,
DropWizardMetricMaker metrics) {
this.views = views;
this.list = list;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/TimerImpl1.java b/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/TimerImpl1.java
index 0164f6f..fe6f70e 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/TimerImpl1.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/TimerImpl1.java
@@ -18,13 +18,11 @@
import com.google.gerrit.metrics.Description;
import com.google.gerrit.metrics.Field;
import com.google.gerrit.metrics.Timer1;
-
import java.util.concurrent.TimeUnit;
/** Optimized version of {@link BucketedTimer} for single dimension. */
class TimerImpl1<F1> extends BucketedTimer implements BucketedMetric {
- TimerImpl1(DropWizardMetricMaker metrics, String name,
- Description desc, Field<F1> field1) {
+ TimerImpl1(DropWizardMetricMaker metrics, String name, Description desc, Field<F1> field1) {
super(metrics, name, desc, field1);
}
@@ -46,8 +44,7 @@
@Override
String name(Object field1) {
@SuppressWarnings("unchecked")
- Function<Object, String> fmt =
- (Function<Object, String>) fields[0].formatter();
+ Function<Object, String> fmt = (Function<Object, String>) fields[0].formatter();
return fmt.apply(field1).replace('/', '-');
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/TimerImplN.java b/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/TimerImplN.java
index 49c9f14..43cc290 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/TimerImplN.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/metrics/dropwizard/TimerImplN.java
@@ -21,13 +21,11 @@
import com.google.gerrit.metrics.Field;
import com.google.gerrit.metrics.Timer2;
import com.google.gerrit.metrics.Timer3;
-
import java.util.concurrent.TimeUnit;
/** Generalized implementation of N-dimensional timer metrics. */
class TimerImplN extends BucketedTimer implements BucketedMetric {
- TimerImplN(DropWizardMetricMaker metrics, String name,
- Description desc, Field<?>... fields) {
+ TimerImplN(DropWizardMetricMaker metrics, String name, Description desc, Field<?>... fields) {
super(metrics, name, desc, fields);
}
@@ -49,8 +47,7 @@
<F1, F2, F3> Timer3<F1, F2, F3> timer3() {
return new Timer3<F1, F2, F3>() {
@Override
- public void record(F1 field1, F2 field2, F3 field3,
- long value, TimeUnit unit) {
+ public void record(F1 field1, F2 field2, F3 field3, long value, TimeUnit unit) {
total.record(value, unit);
forceCreate(field1, field2, field3).record(value, unit);
}
@@ -68,8 +65,7 @@
ImmutableList<Object> keyList = (ImmutableList<Object>) key;
String[] parts = new String[fields.length];
for (int i = 0; i < fields.length; i++) {
- Function<Object, String> fmt =
- (Function<Object, String>) fields[i].formatter();
+ Function<Object, String> fmt = (Function<Object, String>) fields[i].formatter();
parts[i] = fmt.apply(keyList.get(i)).replace('/', '-');
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/metrics/proc/JGitMetricModule.java b/gerrit-server/src/main/java/com/google/gerrit/metrics/proc/JGitMetricModule.java
index b5a2fcc8..c3eb39f 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/metrics/proc/JGitMetricModule.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/metrics/proc/JGitMetricModule.java
@@ -18,31 +18,28 @@
import com.google.gerrit.metrics.Description;
import com.google.gerrit.metrics.Description.Units;
import com.google.gerrit.metrics.MetricMaker;
-
import org.eclipse.jgit.internal.storage.file.WindowCacheStatAccessor;
public class JGitMetricModule extends MetricModule {
@Override
protected void configure(MetricMaker metrics) {
metrics.newCallbackMetric(
- "jgit/block_cache/cache_used",
- Long.class,
- new Description("Bytes of memory retained in JGit block cache.")
- .setGauge()
- .setUnit(Units.BYTES),
- new Supplier<Long>() {
- @Override
- public Long get() {
- return WindowCacheStatAccessor.getOpenBytes();
- }
- });
+ "jgit/block_cache/cache_used",
+ Long.class,
+ new Description("Bytes of memory retained in JGit block cache.")
+ .setGauge()
+ .setUnit(Units.BYTES),
+ new Supplier<Long>() {
+ @Override
+ public Long get() {
+ return WindowCacheStatAccessor.getOpenBytes();
+ }
+ });
metrics.newCallbackMetric(
"jgit/block_cache/open_files",
Integer.class,
- new Description("File handles held open by JGit block cache.")
- .setGauge()
- .setUnit("fds"),
+ new Description("File handles held open by JGit block cache.").setGauge().setUnit("fds"),
new Supplier<Integer>() {
@Override
public Integer get() {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/metrics/proc/MetricModule.java b/gerrit-server/src/main/java/com/google/gerrit/metrics/proc/MetricModule.java
index c556ee4..200a29d 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/metrics/proc/MetricModule.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/metrics/proc/MetricModule.java
@@ -26,18 +26,18 @@
@Override
protected void configure() {
- listener().toInstance(new LifecycleListener() {
- @Inject
- MetricMaker metrics;
+ listener()
+ .toInstance(
+ new LifecycleListener() {
+ @Inject MetricMaker metrics;
- @Override
- public void start() {
- configure(metrics);
- }
+ @Override
+ public void start() {
+ configure(metrics);
+ }
- @Override
- public void stop() {
- }
- });
+ @Override
+ public void stop() {}
+ });
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/metrics/proc/ProcMetricModule.java b/gerrit-server/src/main/java/com/google/gerrit/metrics/proc/ProcMetricModule.java
index 53b860c..64a88bb 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/metrics/proc/ProcMetricModule.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/metrics/proc/ProcMetricModule.java
@@ -25,10 +25,8 @@
import com.google.gerrit.metrics.Description.Units;
import com.google.gerrit.metrics.Field;
import com.google.gerrit.metrics.MetricMaker;
-
import com.sun.management.OperatingSystemMXBean;
import com.sun.management.UnixOperatingSystemMXBean;
-
import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
@@ -58,16 +56,13 @@
private void procUptime(MetricMaker metrics) {
metrics.newConstantMetric(
"proc/birth_timestamp",
- Long.valueOf(TimeUnit.MILLISECONDS.toMicros(
- System.currentTimeMillis())),
- new Description("Time at which the process started")
- .setUnit(Units.MICROSECONDS));
+ Long.valueOf(TimeUnit.MILLISECONDS.toMicros(System.currentTimeMillis())),
+ new Description("Time at which the process started").setUnit(Units.MICROSECONDS));
metrics.newCallbackMetric(
"proc/uptime",
Long.class,
- new Description("Uptime of this process")
- .setUnit(Units.MILLISECONDS),
+ new Description("Uptime of this process").setUnit(Units.MILLISECONDS),
new Supplier<Long>() {
@Override
public Long get() {
@@ -83,9 +78,7 @@
metrics.newCallbackMetric(
"proc/cpu/usage",
Double.class,
- new Description("CPU time used by the process")
- .setCumulative()
- .setUnit(Units.SECONDS),
+ new Description("CPU time used by the process").setCumulative().setUnit(Units.SECONDS),
new Supplier<Double>() {
@Override
public Double get() {
@@ -99,9 +92,7 @@
metrics.newCallbackMetric(
"proc/num_open_fds",
Long.class,
- new Description("Number of open file descriptors")
- .setGauge()
- .setUnit("fds"),
+ new Description("Number of open file descriptors").setGauge().setUnit("fds"),
new Supplier<Long>() {
@Override
public Long get() {
@@ -113,99 +104,105 @@
}
private void procJvmMemory(MetricMaker metrics) {
- final CallbackMetric0<Long> heapCommitted = metrics.newCallbackMetric(
- "proc/jvm/memory/heap_committed",
- Long.class,
- new Description("Amount of memory guaranteed for user objects.")
- .setGauge()
- .setUnit(Units.BYTES));
+ final CallbackMetric0<Long> heapCommitted =
+ metrics.newCallbackMetric(
+ "proc/jvm/memory/heap_committed",
+ Long.class,
+ new Description("Amount of memory guaranteed for user objects.")
+ .setGauge()
+ .setUnit(Units.BYTES));
- final CallbackMetric0<Long> heapUsed = metrics.newCallbackMetric(
- "proc/jvm/memory/heap_used",
- Long.class,
- new Description("Amount of memory holding user objects.")
- .setGauge()
- .setUnit(Units.BYTES));
+ final CallbackMetric0<Long> heapUsed =
+ metrics.newCallbackMetric(
+ "proc/jvm/memory/heap_used",
+ Long.class,
+ new Description("Amount of memory holding user objects.")
+ .setGauge()
+ .setUnit(Units.BYTES));
- final CallbackMetric0<Long> nonHeapCommitted = metrics.newCallbackMetric(
- "proc/jvm/memory/non_heap_committed",
- Long.class,
- new Description("Amount of memory guaranteed for classes, etc.")
- .setGauge()
- .setUnit(Units.BYTES));
+ final CallbackMetric0<Long> nonHeapCommitted =
+ metrics.newCallbackMetric(
+ "proc/jvm/memory/non_heap_committed",
+ Long.class,
+ new Description("Amount of memory guaranteed for classes, etc.")
+ .setGauge()
+ .setUnit(Units.BYTES));
- final CallbackMetric0<Long> nonHeapUsed = metrics.newCallbackMetric(
- "proc/jvm/memory/non_heap_used",
- Long.class,
- new Description("Amount of memory holding classes, etc.")
- .setGauge()
- .setUnit(Units.BYTES));
+ final CallbackMetric0<Long> nonHeapUsed =
+ metrics.newCallbackMetric(
+ "proc/jvm/memory/non_heap_used",
+ Long.class,
+ new Description("Amount of memory holding classes, etc.")
+ .setGauge()
+ .setUnit(Units.BYTES));
final CallbackMetric0<Integer> objectPendingFinalizationCount =
metrics.newCallbackMetric(
- "proc/jvm/memory/object_pending_finalization_count",
- Integer.class,
- new Description("Approximate number of objects needing finalization.")
- .setGauge()
- .setUnit("objects"));
+ "proc/jvm/memory/object_pending_finalization_count",
+ Integer.class,
+ new Description("Approximate number of objects needing finalization.")
+ .setGauge()
+ .setUnit("objects"));
final MemoryMXBean memory = ManagementFactory.getMemoryMXBean();
metrics.newTrigger(
- ImmutableSet.<CallbackMetric<?>> of(
- heapCommitted, heapUsed, nonHeapCommitted,
- nonHeapUsed, objectPendingFinalizationCount),
- new Runnable() {
- @Override
- public void run() {
- try {
- MemoryUsage stats = memory.getHeapMemoryUsage();
- heapCommitted.set(stats.getCommitted());
- heapUsed.set(stats.getUsed());
- } catch (IllegalArgumentException e) {
- // MXBean may throw due to a bug in Java 7; ignore.
+ ImmutableSet.<CallbackMetric<?>>of(
+ heapCommitted, heapUsed, nonHeapCommitted, nonHeapUsed, objectPendingFinalizationCount),
+ new Runnable() {
+ @Override
+ public void run() {
+ try {
+ MemoryUsage stats = memory.getHeapMemoryUsage();
+ heapCommitted.set(stats.getCommitted());
+ heapUsed.set(stats.getUsed());
+ } catch (IllegalArgumentException e) {
+ // MXBean may throw due to a bug in Java 7; ignore.
+ }
+
+ MemoryUsage stats = memory.getNonHeapMemoryUsage();
+ nonHeapCommitted.set(stats.getCommitted());
+ nonHeapUsed.set(stats.getUsed());
+
+ objectPendingFinalizationCount.set(memory.getObjectPendingFinalizationCount());
}
-
- MemoryUsage stats = memory.getNonHeapMemoryUsage();
- nonHeapCommitted.set(stats.getCommitted());
- nonHeapUsed.set(stats.getUsed());
-
- objectPendingFinalizationCount.set(
- memory.getObjectPendingFinalizationCount());
- }
- });
+ });
}
private void procJvmGc(MetricMaker metrics) {
- final CallbackMetric1<String, Long> gcCount = metrics.newCallbackMetric(
- "proc/jvm/gc/count",
- Long.class,
- new Description("Number of GCs").setCumulative(),
- Field.ofString("gc_name", "The name of the garbage collector"));
+ final CallbackMetric1<String, Long> gcCount =
+ metrics.newCallbackMetric(
+ "proc/jvm/gc/count",
+ Long.class,
+ new Description("Number of GCs").setCumulative(),
+ Field.ofString("gc_name", "The name of the garbage collector"));
- final CallbackMetric1<String, Long> gcTime = metrics.newCallbackMetric(
- "proc/jvm/gc/time",
- Long.class,
- new Description("Approximate accumulated GC elapsed time")
- .setCumulative()
- .setUnit(Units.MILLISECONDS),
- Field.ofString("gc_name", "The name of the garbage collector"));
+ final CallbackMetric1<String, Long> gcTime =
+ metrics.newCallbackMetric(
+ "proc/jvm/gc/time",
+ Long.class,
+ new Description("Approximate accumulated GC elapsed time")
+ .setCumulative()
+ .setUnit(Units.MILLISECONDS),
+ Field.ofString("gc_name", "The name of the garbage collector"));
- metrics.newTrigger(gcCount, gcTime, new Runnable() {
- @Override
- public void run() {
- for (GarbageCollectorMXBean gc : ManagementFactory
- .getGarbageCollectorMXBeans()) {
- long count = gc.getCollectionCount();
- if (count != -1) {
- gcCount.set(gc.getName(), count);
+ metrics.newTrigger(
+ gcCount,
+ gcTime,
+ new Runnable() {
+ @Override
+ public void run() {
+ for (GarbageCollectorMXBean gc : ManagementFactory.getGarbageCollectorMXBeans()) {
+ long count = gc.getCollectionCount();
+ if (count != -1) {
+ gcCount.set(gc.getName(), count);
+ }
+ long time = gc.getCollectionTime();
+ if (time != -1) {
+ gcTime.set(gc.getName(), time);
+ }
+ }
}
- long time = gc.getCollectionTime();
- if (time != -1) {
- gcTime.set(gc.getName(), time);
- }
- }
- }
- });
+ });
}
private void procJvmThread(MetricMaker metrics) {
@@ -213,9 +210,7 @@
metrics.newCallbackMetric(
"proc/jvm/thread/num_live",
Integer.class,
- new Description("Current live thread count")
- .setGauge()
- .setUnit("threads"),
+ new Description("Current live thread count").setGauge().setUnit("threads"),
new Supplier<Integer>() {
@Override
public Integer get() {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/rules/PredicateClassLoader.java b/gerrit-server/src/main/java/com/google/gerrit/rules/PredicateClassLoader.java
index 52a9363..c2643de 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/rules/PredicateClassLoader.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/rules/PredicateClassLoader.java
@@ -17,33 +17,27 @@
import com.google.common.collect.LinkedHashMultimap;
import com.google.common.collect.SetMultimap;
import com.google.gerrit.extensions.registration.DynamicSet;
-
import java.util.Collection;
-/**
- * Loads the classes for Prolog predicates.
- */
+/** Loads the classes for Prolog predicates. */
public class PredicateClassLoader extends ClassLoader {
private final SetMultimap<String, ClassLoader> packageClassLoaderMap =
LinkedHashMultimap.create();
public PredicateClassLoader(
- final DynamicSet<PredicateProvider> predicateProviders,
- final ClassLoader parent) {
+ final DynamicSet<PredicateProvider> predicateProviders, final ClassLoader parent) {
super(parent);
for (PredicateProvider predicateProvider : predicateProviders) {
for (String pkg : predicateProvider.getPackages()) {
- packageClassLoaderMap.put(pkg, predicateProvider.getClass()
- .getClassLoader());
+ packageClassLoaderMap.put(pkg, predicateProvider.getClass().getClassLoader());
}
}
}
@Override
- protected Class<?> findClass(final String className)
- throws ClassNotFoundException {
+ protected Class<?> findClass(final String className) throws ClassNotFoundException {
final Collection<ClassLoader> classLoaders =
packageClassLoaderMap.get(getPackageName(className));
for (final ClassLoader cl : classLoaders) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/rules/PredicateProvider.java b/gerrit-server/src/main/java/com/google/gerrit/rules/PredicateProvider.java
index 9d32e38..c64bc92 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/rules/PredicateProvider.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/rules/PredicateProvider.java
@@ -15,17 +15,15 @@
import com.google.common.collect.ImmutableSet;
import com.google.gerrit.extensions.annotations.ExtensionPoint;
-
import com.googlecode.prolog_cafe.lang.Predicate;
/**
- * Provides additional packages that contain Prolog predicates that should be
- * made available in the Prolog environment. The predicates can e.g. be used in
- * the project submit rules.
+ * Provides additional packages that contain Prolog predicates that should be made available in the
+ * Prolog environment. The predicates can e.g. be used in the project submit rules.
*
- * Each Java class defining a Prolog predicate must be in one of the provided
- * packages and its name must apply to the 'PRED_[functor]_[arity]' format. In
- * addition it must extend {@link Predicate}.
+ * <p>Each Java class defining a Prolog predicate must be in one of the provided packages and its
+ * name must apply to the 'PRED_[functor]_[arity]' format. In addition it must extend {@link
+ * Predicate}.
*/
@ExtensionPoint
public interface PredicateProvider {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/rules/PrologEnvironment.java b/gerrit-server/src/main/java/com/google/gerrit/rules/PrologEnvironment.java
index de54a0b..9538121a4 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/rules/PrologEnvironment.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/rules/PrologEnvironment.java
@@ -25,34 +25,30 @@
import com.google.inject.Provider;
import com.google.inject.Singleton;
import com.google.inject.assistedinject.Assisted;
-
import com.googlecode.prolog_cafe.lang.BufferingPrologControl;
import com.googlecode.prolog_cafe.lang.Predicate;
import com.googlecode.prolog_cafe.lang.PredicateEncoder;
import com.googlecode.prolog_cafe.lang.Prolog;
import com.googlecode.prolog_cafe.lang.PrologMachineCopy;
-
-import org.eclipse.jgit.lib.Config;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
+import org.eclipse.jgit.lib.Config;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* Per-thread Prolog interpreter.
- * <p>
- * This class is not thread safe.
- * <p>
- * A single copy of the Prolog interpreter, for the current thread.
+ *
+ * <p>This class is not thread safe.
+ *
+ * <p>A single copy of the Prolog interpreter, for the current thread.
*/
public class PrologEnvironment extends BufferingPrologControl {
- private static final Logger log =
- LoggerFactory.getLogger(PrologEnvironment.class);
+ private static final Logger log = LoggerFactory.getLogger(PrologEnvironment.class);
public interface Factory {
/**
@@ -112,8 +108,8 @@
}
/**
- * Copy the stored values from another interpreter to this one.
- * Also gets the cleanup from the child interpreter
+ * Copy the stored values from another interpreter to this one. Also gets the cleanup from the
+ * child interpreter
*/
public void copyStoredValues(PrologEnvironment child) {
storedValues.putAll(child.storedValues);
@@ -121,9 +117,8 @@
}
/**
- * Assign the environment a cleanup list (in order to use a centralized list)
- * If this enivronment's list is non-empty, append its cleanup tasks to the
- * assigning list.
+ * Assign the environment a cleanup list (in order to use a centralized list) If this
+ * enivronment's list is non-empty, append its cleanup tasks to the assigning list.
*/
public void setCleanup(List<Runnable> newCleanupList) {
newCleanupList.addAll(cleanup);
@@ -132,17 +127,16 @@
/**
* Adds cleanup task to run when close() is called
+ *
* @param task is run when close() is called
*/
public void addToCleanup(Runnable task) {
cleanup.add(task);
}
- /**
- * Release resources stored in interpreter's hash manager.
- */
+ /** Release resources stored in interpreter's hash manager. */
public void close() {
- for (final Iterator<Runnable> i = cleanup.iterator(); i.hasNext();) {
+ for (final Iterator<Runnable> i = cleanup.iterator(); i.hasNext(); ) {
try {
i.next().run();
} catch (Throwable err) {
@@ -155,12 +149,16 @@
@Singleton
public static class Args {
private static final Class<Predicate> CONSULT_STREAM_2;
+
static {
try {
@SuppressWarnings("unchecked")
- Class<Predicate> c = (Class<Predicate>) Class.forName(
- PredicateEncoder.encode(Prolog.BUILTIN, "consult_stream", 2),
- false, RulesCache.class.getClassLoader());
+ Class<Predicate> c =
+ (Class<Predicate>)
+ Class.forName(
+ PredicateEncoder.encode(Prolog.BUILTIN, "consult_stream", 2),
+ false,
+ RulesCache.class.getClassLoader());
CONSULT_STREAM_2 = c;
} catch (ClassNotFoundException e) {
throw new LinkageError("cannot find predicate consult_stream", e);
@@ -177,7 +175,8 @@
private final int compileLimit;
@Inject
- Args(ProjectCache projectCache,
+ Args(
+ ProjectCache projectCache,
GitRepositoryManager repositoryManager,
PatchListCache patchListCache,
PatchSetInfoFactory patchSetInfoFactory,
@@ -194,8 +193,12 @@
int limit = config.getInt("rules", null, "reductionLimit", 100000);
reductionLimit = limit <= 0 ? Integer.MAX_VALUE : limit;
- limit = config.getInt("rules", null, "compileReductionLimit",
- (int) Math.min(10L * limit, Integer.MAX_VALUE));
+ limit =
+ config.getInt(
+ "rules",
+ null,
+ "compileReductionLimit",
+ (int) Math.min(10L * limit, Integer.MAX_VALUE));
compileLimit = limit <= 0 ? Integer.MAX_VALUE : limit;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/rules/RulesCache.java b/gerrit-server/src/main/java/com/google/gerrit/rules/RulesCache.java
index 068b70d..e364f5f 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/rules/RulesCache.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/rules/RulesCache.java
@@ -26,7 +26,6 @@
import com.google.gerrit.server.git.GitRepositoryManager;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
import com.googlecode.prolog_cafe.exceptions.CompileException;
import com.googlecode.prolog_cafe.exceptions.SyntaxException;
import com.googlecode.prolog_cafe.exceptions.TermException;
@@ -39,15 +38,6 @@
import com.googlecode.prolog_cafe.lang.StructureTerm;
import com.googlecode.prolog_cafe.lang.SymbolTerm;
import com.googlecode.prolog_cafe.lang.Term;
-
-import org.eclipse.jgit.errors.LargeObjectException;
-import org.eclipse.jgit.lib.Config;
-import org.eclipse.jgit.lib.Constants;
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.lib.ObjectLoader;
-import org.eclipse.jgit.lib.Repository;
-import org.eclipse.jgit.util.RawParseUtils;
-
import java.io.IOException;
import java.io.PushbackReader;
import java.io.Reader;
@@ -65,24 +55,28 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import org.eclipse.jgit.errors.LargeObjectException;
+import org.eclipse.jgit.lib.Config;
+import org.eclipse.jgit.lib.Constants;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.lib.ObjectLoader;
+import org.eclipse.jgit.lib.Repository;
+import org.eclipse.jgit.util.RawParseUtils;
/**
* Manages a cache of compiled Prolog rules.
- * <p>
- * Rules are loaded from the {@code site_path/cache/rules/rules-SHA1.jar}, where
- * {@code SHA1} is the SHA1 of the Prolog {@code rules.pl} in a project's
- * {@link RefNames#REFS_CONFIG} branch.
+ *
+ * <p>Rules are loaded from the {@code site_path/cache/rules/rules-SHA1.jar}, where {@code SHA1} is
+ * the SHA1 of the Prolog {@code rules.pl} in a project's {@link RefNames#REFS_CONFIG} branch.
*/
@Singleton
public class RulesCache {
- private static final List<String> PACKAGE_LIST = ImmutableList.of(
- Prolog.BUILTIN, "gerrit");
+ private static final List<String> PACKAGE_LIST = ImmutableList.of(Prolog.BUILTIN, "gerrit");
private static final class MachineRef extends WeakReference<PrologMachineCopy> {
final ObjectId key;
- MachineRef(ObjectId key, PrologMachineCopy pcm,
- ReferenceQueue<PrologMachineCopy> queue) {
+ MachineRef(ObjectId key, PrologMachineCopy pcm, ReferenceQueue<PrologMachineCopy> queue) {
super(pcm, queue);
this.key = key;
}
@@ -98,16 +92,17 @@
private final ClassLoader systemLoader;
private final PrologMachineCopy defaultMachine;
private final Map<ObjectId, MachineRef> machineCache = new HashMap<>();
- private final ReferenceQueue<PrologMachineCopy> dead =
- new ReferenceQueue<>();
+ private final ReferenceQueue<PrologMachineCopy> dead = new ReferenceQueue<>();
@Inject
- protected RulesCache(@GerritServerConfig Config config, SitePaths site,
- GitRepositoryManager gm, DynamicSet<PredicateProvider> predicateProviders) {
+ protected RulesCache(
+ @GerritServerConfig Config config,
+ SitePaths site,
+ GitRepositoryManager gm,
+ DynamicSet<PredicateProvider> predicateProviders) {
maxDbSize = config.getInt("rules", null, "maxPrologDatabaseSize", 256);
maxSrcBytes = config.getInt("rules", null, "maxSourceBytes", 128 << 10);
- enableProjectRules = config.getBoolean("rules", null, "enable", true)
- && maxSrcBytes > 0;
+ enableProjectRules = config.getBoolean("rules", null, "enable", true) && maxSrcBytes > 0;
cacheDir = site.resolve(config.getString("cache", null, "directory"));
rulesDir = cacheDir != null ? cacheDir.resolve("rules") : null;
gitMgr = gm;
@@ -127,9 +122,7 @@
* @return a Prolog machine, after loading the specified rules.
* @throws CompileException the machine cannot be created.
*/
- public synchronized PrologMachineCopy loadMachine(
- Project.NameKey project,
- ObjectId rulesId)
+ public synchronized PrologMachineCopy loadMachine(Project.NameKey project, ObjectId rulesId)
throws CompileException {
if (!enableProjectRules || project == null || rulesId == null) {
return defaultMachine;
@@ -154,8 +147,7 @@
return pcm;
}
- public PrologMachineCopy loadMachine(String name, Reader in)
- throws CompileException {
+ public PrologMachineCopy loadMachine(String name, Reader in) throws CompileException {
PrologMachineCopy pmc = consultRules(name, in);
if (pmc == null) {
throw new CompileException("Cannot consult rules from the stream " + name);
@@ -173,8 +165,8 @@
}
}
- private PrologMachineCopy createMachine(Project.NameKey project,
- ObjectId rulesId) throws CompileException {
+ private PrologMachineCopy createMachine(Project.NameKey project, ObjectId rulesId)
+ throws CompileException {
// If the rules are available as a complied JAR on local disk, prefer
// that over dynamic consult as the bytecode will be faster.
//
@@ -196,29 +188,26 @@
return pmc;
}
- private PrologMachineCopy consultRules(String name, Reader rules)
- throws CompileException {
+ private PrologMachineCopy consultRules(String name, Reader rules) throws CompileException {
BufferingPrologControl ctl = newEmptyMachine(systemLoader);
PushbackReader in = new PushbackReader(rules, Prolog.PUSHBACK_SIZE);
try {
- if (!ctl.execute(Prolog.BUILTIN, "consult_stream",
- SymbolTerm.intern(name), new JavaObjectTerm(in))) {
+ if (!ctl.execute(
+ Prolog.BUILTIN, "consult_stream", SymbolTerm.intern(name), new JavaObjectTerm(in))) {
return null;
}
} catch (SyntaxException e) {
throw new CompileException(e.toString(), e);
} catch (TermException e) {
Term m = e.getMessageTerm();
- if (m instanceof StructureTerm && "syntax_error".equals(m.name())
- && m.arity() >= 1) {
+ if (m instanceof StructureTerm && "syntax_error".equals(m.name()) && m.arity() >= 1) {
StringBuilder msg = new StringBuilder();
if (m.arg(0) instanceof ListTerm) {
msg.append(Joiner.on(' ').join(((ListTerm) m.arg(0)).toJava()));
} else {
msg.append(m.arg(0).toString());
}
- if (m.arity() == 2 && m.arg(1) instanceof StructureTerm
- && "at".equals(m.arg(1).name())) {
+ if (m.arity() == 2 && m.arg(1) instanceof StructureTerm && "at".equals(m.arg(1).name())) {
Term at = m.arg(1).arg(0).dereference();
if (at instanceof ListTerm) {
msg.append(" at: ");
@@ -259,8 +248,7 @@
return b.toString().trim();
}
- private String read(Project.NameKey project, ObjectId rulesId)
- throws CompileException {
+ private String read(Project.NameKey project, ObjectId rulesId) throws CompileException {
try (Repository git = gitMgr.openRepository(project)) {
try {
ObjectLoader ldr = git.open(rulesId, Constants.OBJ_BLOB);
@@ -279,8 +267,8 @@
private BufferingPrologControl newEmptyMachine(ClassLoader cl) {
BufferingPrologControl ctl = new BufferingPrologControl();
ctl.setMaxDatabaseSize(maxDbSize);
- ctl.setPrologClassLoader(new PrologClassLoader(new PredicateClassLoader(
- predicateProviders, cl)));
+ ctl.setPrologClassLoader(
+ new PrologClassLoader(new PredicateClassLoader(predicateProviders, cl)));
ctl.setEnabled(EnumSet.allOf(Prolog.Feature.class), false);
List<String> packages = new ArrayList<>();
diff --git a/gerrit-server/src/main/java/com/google/gerrit/rules/StoredValue.java b/gerrit-server/src/main/java/com/google/gerrit/rules/StoredValue.java
index 206e840..461f3ab 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/rules/StoredValue.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/rules/StoredValue.java
@@ -38,16 +38,14 @@
/**
* Initialize a stored value key using any Java Object.
*
- * @param key unique identity of the stored value. This will be the hash key
- * in the Prolog Environments's hash map.
+ * @param key unique identity of the stored value. This will be the hash key in the Prolog
+ * Environments's hash map.
*/
public StoredValue(Object key) {
this.key = key;
}
- /**
- * Initializes a stored value key with a new unique key.
- */
+ /** Initializes a stored value key with a new unique key. */
public StoredValue() {
key = this;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/rules/StoredValues.java b/gerrit-server/src/main/java/com/google/gerrit/rules/StoredValues.java
index c493ccd..34fcb52 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/rules/StoredValues.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/rules/StoredValues.java
@@ -36,16 +36,13 @@
import com.google.gerrit.server.project.ChangeControl;
import com.google.gerrit.server.query.change.ChangeData;
import com.google.gwtorm.server.OrmException;
-
import com.googlecode.prolog_cafe.exceptions.SystemException;
import com.googlecode.prolog_cafe.lang.Prolog;
-
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.lib.Repository;
-
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.lib.Repository;
public final class StoredValues {
public static final StoredValue<ReviewDb> REVIEW_DB = create(ReviewDb.class);
@@ -76,65 +73,68 @@
}
}
- public static final StoredValue<PatchSetInfo> PATCH_SET_INFO = new StoredValue<PatchSetInfo>() {
- @Override
- public PatchSetInfo createValue(Prolog engine) {
- Change change = getChange(engine);
- PatchSet ps = getPatchSet(engine);
- PrologEnvironment env = (PrologEnvironment) engine.control;
- PatchSetInfoFactory patchInfoFactory =
- env.getArgs().getPatchSetInfoFactory();
- try {
- return patchInfoFactory.get(change.getProject(), ps);
- } catch (PatchSetInfoNotAvailableException e) {
- throw new SystemException(e.getMessage());
- }
- }
- };
-
- public static final StoredValue<PatchList> PATCH_LIST = new StoredValue<PatchList>() {
- @Override
- public PatchList createValue(Prolog engine) {
- PrologEnvironment env = (PrologEnvironment) engine.control;
- PatchSet ps = getPatchSet(engine);
- PatchListCache plCache = env.getArgs().getPatchListCache();
- Change change = getChange(engine);
- Project.NameKey project = change.getProject();
- ObjectId b = ObjectId.fromString(ps.getRevision().get());
- Whitespace ws = Whitespace.IGNORE_NONE;
- PatchListKey plKey = PatchListKey.againstDefaultBase(b, ws);
- PatchList patchList;
- try {
- patchList = plCache.get(plKey, project);
- } catch (PatchListNotAvailableException e) {
- throw new SystemException("Cannot create " + plKey);
- }
- return patchList;
- }
- };
-
- public static final StoredValue<Repository> REPOSITORY = new StoredValue<Repository>() {
- @Override
- public Repository createValue(Prolog engine) {
- PrologEnvironment env = (PrologEnvironment) engine.control;
- GitRepositoryManager gitMgr = env.getArgs().getGitRepositoryManager();
- Change change = getChange(engine);
- Project.NameKey projectKey = change.getProject();
- final Repository repo;
- try {
- repo = gitMgr.openRepository(projectKey);
- } catch (IOException e) {
- throw new SystemException(e.getMessage());
- }
- env.addToCleanup(new Runnable() {
+ public static final StoredValue<PatchSetInfo> PATCH_SET_INFO =
+ new StoredValue<PatchSetInfo>() {
@Override
- public void run() {
- repo.close();
+ public PatchSetInfo createValue(Prolog engine) {
+ Change change = getChange(engine);
+ PatchSet ps = getPatchSet(engine);
+ PrologEnvironment env = (PrologEnvironment) engine.control;
+ PatchSetInfoFactory patchInfoFactory = env.getArgs().getPatchSetInfoFactory();
+ try {
+ return patchInfoFactory.get(change.getProject(), ps);
+ } catch (PatchSetInfoNotAvailableException e) {
+ throw new SystemException(e.getMessage());
+ }
}
- });
- return repo;
- }
- };
+ };
+
+ public static final StoredValue<PatchList> PATCH_LIST =
+ new StoredValue<PatchList>() {
+ @Override
+ public PatchList createValue(Prolog engine) {
+ PrologEnvironment env = (PrologEnvironment) engine.control;
+ PatchSet ps = getPatchSet(engine);
+ PatchListCache plCache = env.getArgs().getPatchListCache();
+ Change change = getChange(engine);
+ Project.NameKey project = change.getProject();
+ ObjectId b = ObjectId.fromString(ps.getRevision().get());
+ Whitespace ws = Whitespace.IGNORE_NONE;
+ PatchListKey plKey = PatchListKey.againstDefaultBase(b, ws);
+ PatchList patchList;
+ try {
+ patchList = plCache.get(plKey, project);
+ } catch (PatchListNotAvailableException e) {
+ throw new SystemException("Cannot create " + plKey);
+ }
+ return patchList;
+ }
+ };
+
+ public static final StoredValue<Repository> REPOSITORY =
+ new StoredValue<Repository>() {
+ @Override
+ public Repository createValue(Prolog engine) {
+ PrologEnvironment env = (PrologEnvironment) engine.control;
+ GitRepositoryManager gitMgr = env.getArgs().getGitRepositoryManager();
+ Change change = getChange(engine);
+ Project.NameKey projectKey = change.getProject();
+ final Repository repo;
+ try {
+ repo = gitMgr.openRepository(projectKey);
+ } catch (IOException e) {
+ throw new SystemException(e.getMessage());
+ }
+ env.addToCleanup(
+ new Runnable() {
+ @Override
+ public void run() {
+ repo.close();
+ }
+ });
+ return repo;
+ }
+ };
public static final StoredValue<AnonymousUser> ANONYMOUS_USER =
new StoredValue<AnonymousUser>() {
@@ -153,6 +153,5 @@
}
};
- private StoredValues() {
- }
+ private StoredValues() {}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/AnonymousUser.java b/gerrit-server/src/main/java/com/google/gerrit/server/AnonymousUser.java
index 36888e3..de8e9a4 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/AnonymousUser.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/AnonymousUser.java
@@ -19,7 +19,6 @@
import com.google.gerrit.server.account.ListGroupMembership;
import com.google.gerrit.server.group.SystemGroupBackend;
import com.google.inject.Inject;
-
import java.util.Collections;
/** An anonymous user who has not yet authenticated. */
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/ApprovalCopier.java b/gerrit-server/src/main/java/com/google/gerrit/server/ApprovalCopier.java
index 1fcb5b6..cb65ed3 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/ApprovalCopier.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/ApprovalCopier.java
@@ -36,22 +36,19 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.lib.Repository;
-
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.TreeMap;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.lib.Repository;
/**
* Copies approvals between patch sets.
- * <p>
- * The result of a copy may either be stored, as when stamping approvals in the
- * database at submit time, or refreshed on demand, as when reading approvals
- * from the NoteDb.
+ *
+ * <p>The result of a copy may either be stored, as when stamping approvals in the database at
+ * submit time, or refreshed on demand, as when reading approvals from the NoteDb.
*/
@Singleton
public class ApprovalCopier {
@@ -63,7 +60,8 @@
private final PatchSetUtil psUtil;
@Inject
- ApprovalCopier(GitRepositoryManager repoManager,
+ ApprovalCopier(
+ GitRepositoryManager repoManager,
ProjectCache projectCache,
ChangeKindCache changeKindCache,
LabelNormalizer labelNormalizer,
@@ -85,8 +83,7 @@
* @param ps new PatchSet
* @throws OrmException
*/
- public void copy(ReviewDb db, ChangeControl ctl, PatchSet ps)
- throws OrmException {
+ public void copy(ReviewDb db, ChangeControl ctl, PatchSet ps) throws OrmException {
copy(db, ctl, ps, Collections.<PatchSetApproval>emptyList());
}
@@ -96,25 +93,22 @@
* @param db review database.
* @param ctl change control for user uploading PatchSet
* @param ps new PatchSet
- * @param dontCopy PatchSetApprovals indicating which (account, label) pairs
- * should not be copied
+ * @param dontCopy PatchSetApprovals indicating which (account, label) pairs should not be copied
* @throws OrmException
*/
- public void copy(ReviewDb db, ChangeControl ctl, PatchSet ps,
- Iterable<PatchSetApproval> dontCopy) throws OrmException {
- db.patchSetApprovals().insert(
- getForPatchSet(db, ctl, ps, dontCopy));
+ public void copy(ReviewDb db, ChangeControl ctl, PatchSet ps, Iterable<PatchSetApproval> dontCopy)
+ throws OrmException {
+ db.patchSetApprovals().insert(getForPatchSet(db, ctl, ps, dontCopy));
}
- Iterable<PatchSetApproval> getForPatchSet(ReviewDb db,
- ChangeControl ctl, PatchSet.Id psId) throws OrmException {
- return getForPatchSet(db, ctl, psId,
- Collections.<PatchSetApproval>emptyList());
+ Iterable<PatchSetApproval> getForPatchSet(ReviewDb db, ChangeControl ctl, PatchSet.Id psId)
+ throws OrmException {
+ return getForPatchSet(db, ctl, psId, Collections.<PatchSetApproval>emptyList());
}
- Iterable<PatchSetApproval> getForPatchSet(ReviewDb db,
- ChangeControl ctl, PatchSet.Id psId,
- Iterable<PatchSetApproval> dontCopy) throws OrmException {
+ Iterable<PatchSetApproval> getForPatchSet(
+ ReviewDb db, ChangeControl ctl, PatchSet.Id psId, Iterable<PatchSetApproval> dontCopy)
+ throws OrmException {
PatchSet ps = psUtil.get(db, ctl.getNotes(), psId);
if (ps == null) {
return Collections.emptyList();
@@ -122,25 +116,22 @@
return getForPatchSet(db, ctl, ps, dontCopy);
}
- private Iterable<PatchSetApproval> getForPatchSet(ReviewDb db,
- ChangeControl ctl, PatchSet ps,
- Iterable<PatchSetApproval> dontCopy) throws OrmException {
+ private Iterable<PatchSetApproval> getForPatchSet(
+ ReviewDb db, ChangeControl ctl, PatchSet ps, Iterable<PatchSetApproval> dontCopy)
+ throws OrmException {
checkNotNull(ps, "ps should not be null");
ChangeData cd = changeDataFactory.create(db, ctl);
try {
- ProjectState project =
- projectCache.checkedGet(cd.change().getDest().getParentKey());
+ ProjectState project = projectCache.checkedGet(cd.change().getDest().getParentKey());
ListMultimap<PatchSet.Id, PatchSetApproval> all = cd.approvals();
checkNotNull(all, "all should not be null");
- Table<String, Account.Id, PatchSetApproval> wontCopy =
- HashBasedTable.create();
+ Table<String, Account.Id, PatchSetApproval> wontCopy = HashBasedTable.create();
for (PatchSetApproval psa : dontCopy) {
wontCopy.put(psa.getLabel(), psa.getAccountId(), psa);
}
- Table<String, Account.Id, PatchSetApproval> byUser =
- HashBasedTable.create();
+ Table<String, Account.Id, PatchSetApproval> byUser = HashBasedTable.create();
for (PatchSetApproval psa : all.get(ps.getId())) {
if (!wontCopy.contains(psa.getLabel(), psa.getAccountId())) {
byUser.put(psa.getLabel(), psa.getAccountId(), psa);
@@ -149,22 +140,22 @@
TreeMap<Integer, PatchSet> patchSets = getPatchSets(cd);
- try (Repository repo =
- repoManager.openRepository(project.getProject().getNameKey())) {
+ try (Repository repo = repoManager.openRepository(project.getProject().getNameKey())) {
// Walk patch sets strictly less than current in descending order.
- Collection<PatchSet> allPrior = patchSets.descendingMap()
- .tailMap(ps.getId().get(), false)
- .values();
+ Collection<PatchSet> allPrior =
+ patchSets.descendingMap().tailMap(ps.getId().get(), false).values();
for (PatchSet priorPs : allPrior) {
List<PatchSetApproval> priorApprovals = all.get(priorPs.getId());
if (priorApprovals.isEmpty()) {
continue;
}
- ChangeKind kind = changeKindCache.getChangeKind(
- project.getProject().getNameKey(), repo,
- ObjectId.fromString(priorPs.getRevision().get()),
- ObjectId.fromString(ps.getRevision().get()));
+ ChangeKind kind =
+ changeKindCache.getChangeKind(
+ project.getProject().getNameKey(),
+ repo,
+ ObjectId.fromString(priorPs.getRevision().get()),
+ ObjectId.fromString(ps.getRevision().get()));
for (PatchSetApproval psa : priorApprovals) {
if (wontCopy.contains(psa.getLabel(), psa.getAccountId())) {
@@ -177,8 +168,7 @@
wontCopy.put(psa.getLabel(), psa.getAccountId(), psa);
continue;
}
- byUser.put(psa.getLabel(), psa.getAccountId(),
- copy(psa, ps.getId()));
+ byUser.put(psa.getLabel(), psa.getAccountId(), copy(psa, ps.getId()));
}
}
return labelNormalizer.normalize(ctl, byUser.values()).getNormalized();
@@ -188,8 +178,7 @@
}
}
- private static TreeMap<Integer, PatchSet> getPatchSets(ChangeData cd)
- throws OrmException {
+ private static TreeMap<Integer, PatchSet> getPatchSets(ChangeData cd) throws OrmException {
Collection<PatchSet> patchSets = cd.patchSets();
TreeMap<Integer, PatchSet> result = new TreeMap<>();
for (PatchSet ps : patchSets) {
@@ -198,15 +187,14 @@
return result;
}
- private static boolean canCopy(ProjectState project, PatchSetApproval psa,
- PatchSet.Id psId, ChangeKind kind) {
+ private static boolean canCopy(
+ ProjectState project, PatchSetApproval psa, PatchSet.Id psId, ChangeKind kind) {
int n = psa.getKey().getParentKey().get();
checkArgument(n != psId.get());
LabelType type = project.getLabelTypes().byLabel(psa.getLabelId());
if (type == null) {
return false;
- } else if (
- (type.isCopyMinScore() && type.isMaxNegative(psa))
+ } else if ((type.isCopyMinScore() && type.isMaxNegative(psa))
|| (type.isCopyMaxScore() && type.isMaxPositive(psa))) {
return true;
}
@@ -234,4 +222,4 @@
}
return new PatchSetApproval(psId, src);
}
-}
\ No newline at end of file
+}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/ApprovalsUtil.java b/gerrit-server/src/main/java/com/google/gerrit/server/ApprovalsUtil.java
index c61f613..87969ec 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/ApprovalsUtil.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/ApprovalsUtil.java
@@ -48,10 +48,6 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
@@ -61,49 +57,45 @@
import java.util.Map;
import java.util.Objects;
import java.util.Set;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* Utility functions to manipulate patchset approvals.
- * <p>
- * Approvals are overloaded, they represent both approvals and reviewers
- * which should be CCed on a change. To ensure that reviewers are not lost
- * there must always be an approval on each patchset for each reviewer,
- * even if the reviewer hasn't actually given a score to the change. To
- * mark the "no score" case, a dummy approval, which may live in any of
- * the available categories, with a score of 0 is used.
- * <p>
- * The methods in this class only modify the gwtorm database.
+ *
+ * <p>Approvals are overloaded, they represent both approvals and reviewers which should be CCed on
+ * a change. To ensure that reviewers are not lost there must always be an approval on each patchset
+ * for each reviewer, even if the reviewer hasn't actually given a score to the change. To mark the
+ * "no score" case, a dummy approval, which may live in any of the available categories, with a
+ * score of 0 is used.
+ *
+ * <p>The methods in this class only modify the gwtorm database.
*/
@Singleton
public class ApprovalsUtil {
- private static final Logger log =
- LoggerFactory.getLogger(ApprovalsUtil.class);
+ private static final Logger log = LoggerFactory.getLogger(ApprovalsUtil.class);
private static final Ordering<PatchSetApproval> SORT_APPROVALS =
Ordering.from(comparing(PatchSetApproval::getGranted));
- public static List<PatchSetApproval> sortApprovals(
- Iterable<PatchSetApproval> approvals) {
+ public static List<PatchSetApproval> sortApprovals(Iterable<PatchSetApproval> approvals) {
return SORT_APPROVALS.sortedCopy(approvals);
}
- public static PatchSetApproval newApproval(PatchSet.Id psId, CurrentUser user,
- LabelId labelId, int value, Date when) {
- PatchSetApproval psa = new PatchSetApproval(
- new PatchSetApproval.Key(
- psId,
- user.getAccountId(),
- labelId),
- Shorts.checkedCast(value),
- when);
+ public static PatchSetApproval newApproval(
+ PatchSet.Id psId, CurrentUser user, LabelId labelId, int value, Date when) {
+ PatchSetApproval psa =
+ new PatchSetApproval(
+ new PatchSetApproval.Key(psId, user.getAccountId(), labelId),
+ Shorts.checkedCast(value),
+ when);
user.updateRealAccountId(psa::setRealAccountId);
return psa;
}
private static Iterable<PatchSetApproval> filterApprovals(
Iterable<PatchSetApproval> psas, final Account.Id accountId) {
- return Iterables.filter(
- psas, a -> Objects.equals(a.getAccountId(), accountId));
+ return Iterables.filter(psas, a -> Objects.equals(a.getAccountId(), accountId));
}
private final NotesMigration migration;
@@ -113,7 +105,8 @@
@VisibleForTesting
@Inject
- public ApprovalsUtil(NotesMigration migration,
+ public ApprovalsUtil(
+ NotesMigration migration,
IdentifiedUser.GenericFactory userFactory,
ChangeControl.GenericFactory changeControlFactory,
ApprovalCopier copier) {
@@ -131,11 +124,9 @@
* @return reviewers for the change.
* @throws OrmException if reviewers for the change could not be read.
*/
- public ReviewerSet getReviewers(ReviewDb db, ChangeNotes notes)
- throws OrmException {
+ public ReviewerSet getReviewers(ReviewDb db, ChangeNotes notes) throws OrmException {
if (!migration.readChanges()) {
- return ReviewerSet.fromApprovals(
- db.patchSetApprovals().byChange(notes.getChangeId()));
+ return ReviewerSet.fromApprovals(db.patchSetApprovals().byChange(notes.getChangeId()));
}
return notes.load().getReviewers();
}
@@ -143,13 +134,11 @@
/**
* Get all reviewers and CCed accounts for a change.
*
- * @param allApprovals all approvals to consider; must all belong to the same
- * change.
+ * @param allApprovals all approvals to consider; must all belong to the same change.
* @return reviewers for the change.
* @throws OrmException if reviewers for the change could not be read.
*/
- public ReviewerSet getReviewers(ChangeNotes notes,
- Iterable<PatchSetApproval> allApprovals)
+ public ReviewerSet getReviewers(ChangeNotes notes, Iterable<PatchSetApproval> allApprovals)
throws OrmException {
if (!migration.readChanges()) {
return ReviewerSet.fromApprovals(allApprovals);
@@ -158,33 +147,49 @@
}
/**
- * Get updates to reviewer set.
- * Always returns empty list for ReviewDb.
+ * Get updates to reviewer set. Always returns empty list for ReviewDb.
*
* @param notes change notes.
* @return reviewer updates for the change.
* @throws OrmException if reviewer updates for the change could not be read.
*/
- public List<ReviewerStatusUpdate> getReviewerUpdates(ChangeNotes notes)
- throws OrmException {
+ public List<ReviewerStatusUpdate> getReviewerUpdates(ChangeNotes notes) throws OrmException {
if (!migration.readChanges()) {
return ImmutableList.of();
}
return notes.load().getReviewerUpdates();
}
- public List<PatchSetApproval> addReviewers(ReviewDb db,
- ChangeUpdate update, LabelTypes labelTypes, Change change, PatchSet ps,
- PatchSetInfo info, Iterable<Account.Id> wantReviewers,
- Collection<Account.Id> existingReviewers) throws OrmException {
- return addReviewers(db, update, labelTypes, change, ps.getId(),
- info.getAuthor().getAccount(), info.getCommitter().getAccount(),
- wantReviewers, existingReviewers);
+ public List<PatchSetApproval> addReviewers(
+ ReviewDb db,
+ ChangeUpdate update,
+ LabelTypes labelTypes,
+ Change change,
+ PatchSet ps,
+ PatchSetInfo info,
+ Iterable<Account.Id> wantReviewers,
+ Collection<Account.Id> existingReviewers)
+ throws OrmException {
+ return addReviewers(
+ db,
+ update,
+ labelTypes,
+ change,
+ ps.getId(),
+ info.getAuthor().getAccount(),
+ info.getCommitter().getAccount(),
+ wantReviewers,
+ existingReviewers);
}
- public List<PatchSetApproval> addReviewers(ReviewDb db, ChangeNotes notes,
- ChangeUpdate update, LabelTypes labelTypes, Change change,
- Iterable<Account.Id> wantReviewers) throws OrmException {
+ public List<PatchSetApproval> addReviewers(
+ ReviewDb db,
+ ChangeNotes notes,
+ ChangeUpdate update,
+ LabelTypes labelTypes,
+ Change change,
+ Iterable<Account.Id> wantReviewers)
+ throws OrmException {
PatchSet.Id psId = change.currentPatchSetId();
Collection<Account.Id> existingReviewers;
if (migration.readChanges()) {
@@ -197,21 +202,26 @@
// Existing reviewers should include pending additions in the REVIEWER
// state, taken from ChangeUpdate.
existingReviewers = Lists.newArrayList(existingReviewers);
- for (Map.Entry<Account.Id, ReviewerStateInternal> entry :
- update.getReviewers().entrySet()) {
+ for (Map.Entry<Account.Id, ReviewerStateInternal> entry : update.getReviewers().entrySet()) {
if (entry.getValue() == REVIEWER) {
existingReviewers.add(entry.getKey());
}
}
- return addReviewers(db, update, labelTypes, change, psId, null, null,
- wantReviewers, existingReviewers);
+ return addReviewers(
+ db, update, labelTypes, change, psId, null, null, wantReviewers, existingReviewers);
}
- private List<PatchSetApproval> addReviewers(ReviewDb db, ChangeUpdate update,
- LabelTypes labelTypes, Change change, PatchSet.Id psId,
- Account.Id authorId, Account.Id committerId,
+ private List<PatchSetApproval> addReviewers(
+ ReviewDb db,
+ ChangeUpdate update,
+ LabelTypes labelTypes,
+ Change change,
+ PatchSet.Id psId,
+ Account.Id authorId,
+ Account.Id committerId,
Iterable<Account.Id> wantReviewers,
- Collection<Account.Id> existingReviewers) throws OrmException {
+ Collection<Account.Id> existingReviewers)
+ throws OrmException {
List<LabelType> allTypes = labelTypes.getLabelTypes();
if (allTypes.isEmpty()) {
return ImmutableList.of();
@@ -234,9 +244,9 @@
List<PatchSetApproval> cells = Lists.newArrayListWithCapacity(need.size());
LabelId labelId = Iterables.getLast(allTypes).getLabelId();
for (Account.Id account : need) {
- cells.add(new PatchSetApproval(
- new PatchSetApproval.Key(psId, account, labelId),
- (short) 0, update.getWhen()));
+ cells.add(
+ new PatchSetApproval(
+ new PatchSetApproval.Key(psId, account, labelId), (short) 0, update.getWhen()));
update.putReviewer(account, REVIEWER);
}
db.patchSetApprovals().upsert(cells);
@@ -248,8 +258,11 @@
IdentifiedUser user = userFactory.create(accountId);
return changeControlFactory.controlFor(notes, user).isVisible(db);
} catch (OrmException e) {
- log.warn(String.format("Failed to check if account %d can see change %d",
- accountId.get(), notes.getChangeId().get()), e);
+ log.warn(
+ String.format(
+ "Failed to check if account %d can see change %d",
+ accountId.get(), notes.getChangeId().get()),
+ e);
return false;
}
}
@@ -263,13 +276,13 @@
* @return whether a change was made.
* @throws OrmException
*/
- public Collection<Account.Id> addCcs(ChangeNotes notes, ChangeUpdate update,
- Collection<Account.Id> wantCCs) throws OrmException {
+ public Collection<Account.Id> addCcs(
+ ChangeNotes notes, ChangeUpdate update, Collection<Account.Id> wantCCs) throws OrmException {
return addCcs(update, wantCCs, notes.load().getReviewers());
}
- private Collection<Account.Id> addCcs(ChangeUpdate update,
- Collection<Account.Id> wantCCs, ReviewerSet existingReviewers) {
+ private Collection<Account.Id> addCcs(
+ ChangeUpdate update, Collection<Account.Id> wantCCs, ReviewerSet existingReviewers) {
Set<Account.Id> need = new LinkedHashSet<>(wantCCs);
need.removeAll(existingReviewers.all());
need.removeAll(update.getReviewers().keySet());
@@ -290,14 +303,20 @@
* @param approvals approvals to add.
* @throws OrmException
*/
- public Iterable<PatchSetApproval> addApprovalsForNewPatchSet(ReviewDb db,
- ChangeUpdate update, LabelTypes labelTypes, PatchSet ps,
- ChangeControl changeCtl, Map<String, Short> approvals)
+ public Iterable<PatchSetApproval> addApprovalsForNewPatchSet(
+ ReviewDb db,
+ ChangeUpdate update,
+ LabelTypes labelTypes,
+ PatchSet ps,
+ ChangeControl changeCtl,
+ Map<String, Short> approvals)
throws OrmException {
Account.Id accountId = changeCtl.getUser().getAccountId();
- checkArgument(accountId.equals(ps.getUploader()),
+ checkArgument(
+ accountId.equals(ps.getUploader()),
"expected user %s to match patch set uploader %s",
- accountId, ps.getUploader());
+ accountId,
+ ps.getUploader());
if (approvals.isEmpty()) {
return Collections.emptyList();
}
@@ -306,9 +325,7 @@
Date ts = update.getWhen();
for (Map.Entry<String, Short> vote : approvals.entrySet()) {
LabelType lt = labelTypes.byLabel(vote.getKey());
- cells.add(
- newApproval(ps.getId(), changeCtl.getUser(), lt.getLabelId(),
- vote.getValue(), ts));
+ cells.add(newApproval(ps.getId(), changeCtl.getUser(), lt.getLabelId(), vote.getValue(), ts));
}
for (PatchSetApproval psa : cells) {
update.putApproval(psa.getLabel(), psa.getValue());
@@ -320,35 +337,33 @@
public static void checkLabel(LabelTypes labelTypes, String name, Short value) {
LabelType label = labelTypes.byLabel(name);
if (label == null) {
- throw new IllegalArgumentException(String.format(
- "label \"%s\" is not a configured label", name));
+ throw new IllegalArgumentException(
+ String.format("label \"%s\" is not a configured label", name));
}
if (label.getValue(value) == null) {
- throw new IllegalArgumentException(String.format(
- "label \"%s\": %d is not a valid value", name, value));
+ throw new IllegalArgumentException(
+ String.format("label \"%s\": %d is not a valid value", name, value));
}
}
- private static void checkApprovals(Map<String, Short> approvals,
- ChangeControl changeCtl) {
+ private static void checkApprovals(Map<String, Short> approvals, ChangeControl changeCtl) {
for (Map.Entry<String, Short> vote : approvals.entrySet()) {
String name = vote.getKey();
Short value = vote.getValue();
PermissionRange range = changeCtl.getRange(Permission.forLabel(name));
if (range == null || !range.contains(value)) {
- throw new IllegalArgumentException(String.format(
- "applying label \"%s\": %d is restricted", name, value));
+ throw new IllegalArgumentException(
+ String.format("applying label \"%s\": %d is restricted", name, value));
}
}
}
- public ListMultimap<PatchSet.Id, PatchSetApproval> byChange(ReviewDb db,
- ChangeNotes notes) throws OrmException {
+ public ListMultimap<PatchSet.Id, PatchSetApproval> byChange(ReviewDb db, ChangeNotes notes)
+ throws OrmException {
if (!migration.readChanges()) {
ImmutableListMultimap.Builder<PatchSet.Id, PatchSetApproval> result =
ImmutableListMultimap.builder();
- for (PatchSetApproval psa
- : db.patchSetApprovals().byChange(notes.getChangeId())) {
+ for (PatchSetApproval psa : db.patchSetApprovals().byChange(notes.getChangeId())) {
result.put(psa.getPatchSetId(), psa);
}
return result.build();
@@ -356,26 +371,23 @@
return notes.load().getApprovals();
}
- public Iterable<PatchSetApproval> byPatchSet(ReviewDb db, ChangeControl ctl,
- PatchSet.Id psId) throws OrmException {
+ public Iterable<PatchSetApproval> byPatchSet(ReviewDb db, ChangeControl ctl, PatchSet.Id psId)
+ throws OrmException {
if (!migration.readChanges()) {
return sortApprovals(db.patchSetApprovals().byPatchSet(psId));
}
return copier.getForPatchSet(db, ctl, psId);
}
- public Iterable<PatchSetApproval> byPatchSetUser(ReviewDb db,
- ChangeControl ctl, PatchSet.Id psId, Account.Id accountId)
- throws OrmException {
+ public Iterable<PatchSetApproval> byPatchSetUser(
+ ReviewDb db, ChangeControl ctl, PatchSet.Id psId, Account.Id accountId) throws OrmException {
if (!migration.readChanges()) {
- return sortApprovals(
- db.patchSetApprovals().byPatchSetUser(psId, accountId));
+ return sortApprovals(db.patchSetApprovals().byPatchSetUser(psId, accountId));
}
return filterApprovals(byPatchSet(db, ctl, psId), accountId);
}
- public PatchSetApproval getSubmitter(ReviewDb db, ChangeNotes notes,
- PatchSet.Id c) {
+ public PatchSetApproval getSubmitter(ReviewDb db, ChangeNotes notes, PatchSet.Id c) {
if (c == null) {
return null;
}
@@ -387,16 +399,14 @@
}
}
- public static PatchSetApproval getSubmitter(PatchSet.Id c,
- Iterable<PatchSetApproval> approvals) {
+ public static PatchSetApproval getSubmitter(PatchSet.Id c, Iterable<PatchSetApproval> approvals) {
if (c == null) {
return null;
}
PatchSetApproval submitter = null;
for (PatchSetApproval a : approvals) {
if (a.getPatchSetId().equals(c) && a.getValue() > 0 && a.isLegacySubmit()) {
- if (submitter == null
- || a.getGranted().compareTo(submitter.getGranted()) > 0) {
+ if (submitter == null || a.getGranted().compareTo(submitter.getGranted()) > 0) {
submitter = a;
}
}
@@ -404,22 +414,20 @@
return submitter;
}
- public static String renderMessageWithApprovals(int patchSetId,
- Map<String, Short> n, Map<String, PatchSetApproval> c) {
+ public static String renderMessageWithApprovals(
+ int patchSetId, Map<String, Short> n, Map<String, PatchSetApproval> c) {
StringBuilder msgs = new StringBuilder("Uploaded patch set " + patchSetId);
if (!n.isEmpty()) {
boolean first = true;
for (Map.Entry<String, Short> e : n.entrySet()) {
- if (c.containsKey(e.getKey())
- && c.get(e.getKey()).getValue() == e.getValue()) {
+ if (c.containsKey(e.getKey()) && c.get(e.getKey()).getValue() == e.getValue()) {
continue;
}
if (first) {
msgs.append(":");
first = false;
}
- msgs.append(" ")
- .append(LabelVote.create(e.getKey(), e.getValue()).format());
+ msgs.append(" ").append(LabelVote.create(e.getKey(), e.getValue()).format());
}
}
return msgs.toString();
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/ChangeFinder.java b/gerrit-server/src/main/java/com/google/gerrit/server/ChangeFinder.java
index 7dda538..2f3a76f 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/ChangeFinder.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/ChangeFinder.java
@@ -25,7 +25,6 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@@ -43,15 +42,13 @@
/**
* Find changes matching the given identifier.
*
- * @param id change identifier, either a numeric ID, a Change-Id, or
- * project~branch~id triplet.
+ * @param id change identifier, either a numeric ID, a Change-Id, or project~branch~id triplet.
* @param user user to wrap in controls.
- * @return possibly-empty list of controls for all matching changes,
- * corresponding to the given user; may or may not be visible.
+ * @return possibly-empty list of controls for all matching changes, corresponding to the given
+ * user; may or may not be visible.
* @throws OrmException if an error occurred querying the database.
*/
- public List<ChangeControl> find(String id, CurrentUser user)
- throws OrmException {
+ public List<ChangeControl> find(String id, CurrentUser user) throws OrmException {
// Use the index to search for changes, but don't return any stored fields,
// to force rereading in case the index is stale.
InternalChangeQuery query = queryProvider.get().noFields();
@@ -72,17 +69,13 @@
// Try change triplet
Optional<ChangeTriplet> triplet = ChangeTriplet.parse(id);
if (triplet.isPresent()) {
- return asChangeControls(query.byBranchKey(
- triplet.get().branch(),
- triplet.get().id()),
- user);
+ return asChangeControls(query.byBranchKey(triplet.get().branch(), triplet.get().id()), user);
}
return Collections.emptyList();
}
- public ChangeControl findOne(Change.Id id, CurrentUser user)
- throws OrmException {
+ public ChangeControl findOne(Change.Id id, CurrentUser user) throws OrmException {
List<ChangeControl> ctls = find(id, user);
if (ctls.size() != 1) {
throw new NoSuchChangeException(id);
@@ -90,16 +83,15 @@
return ctls.get(0);
}
- public List<ChangeControl> find(Change.Id id, CurrentUser user)
- throws OrmException {
+ public List<ChangeControl> find(Change.Id id, CurrentUser user) throws OrmException {
// Use the index to search for changes, but don't return any stored fields,
// to force rereading in case the index is stale.
InternalChangeQuery query = queryProvider.get().noFields();
return asChangeControls(query.byLegacyChangeId(id), user);
}
- private List<ChangeControl> asChangeControls(List<ChangeData> cds,
- CurrentUser user) throws OrmException {
+ private List<ChangeControl> asChangeControls(List<ChangeData> cds, CurrentUser user)
+ throws OrmException {
List<ChangeControl> ctls = new ArrayList<>(cds.size());
for (ChangeData cd : cds) {
ctls.add(cd.changeControl(user));
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/ChangeMessagesUtil.java b/gerrit-server/src/main/java/com/google/gerrit/server/ChangeMessagesUtil.java
index e49b617..b8bdcd5 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/ChangeMessagesUtil.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/ChangeMessagesUtil.java
@@ -30,7 +30,6 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
import java.sql.Timestamp;
import java.util.Collections;
import java.util.List;
@@ -38,64 +37,49 @@
/**
* Utility functions to manipulate ChangeMessages.
- * <p>
- * These methods either query for and update ChangeMessages in the NoteDb or
- * ReviewDb, depending on the state of the NotesMigration.
+ *
+ * <p>These methods either query for and update ChangeMessages in the NoteDb or ReviewDb, depending
+ * on the state of the NotesMigration.
*/
@Singleton
public class ChangeMessagesUtil {
- public static final String TAG_ABANDON =
- "autogenerated:gerrit:abandon";
- public static final String TAG_CHERRY_PICK_CHANGE =
- "autogenerated:gerrit:cherryPickChange";
- public static final String TAG_DELETE_ASSIGNEE =
- "autogenerated:gerrit:deleteAssignee";
- public static final String TAG_DELETE_REVIEWER =
- "autogenerated:gerrit:deleteReviewer";
- public static final String TAG_DELETE_VOTE =
- "autogenerated:gerrit:deleteVote";
- public static final String TAG_MERGED =
- "autogenerated:gerrit:merged";
- public static final String TAG_MOVE =
- "autogenerated:gerrit:move";
- public static final String TAG_RESTORE =
- "autogenerated:gerrit:restore";
- public static final String TAG_REVERT =
- "autogenerated:gerrit:revert";
- public static final String TAG_SET_ASSIGNEE =
- "autogenerated:gerrit:setAssignee";
- public static final String TAG_SET_DESCRIPTION =
- "autogenerated:gerrit:setPsDescription";
- public static final String TAG_SET_HASHTAGS =
- "autogenerated:gerrit:setHashtag";
- public static final String TAG_SET_TOPIC =
- "autogenerated:gerrit:setTopic";
- public static final String TAG_UPLOADED_PATCH_SET =
- "autogenerated:gerrit:newPatchSet";
+ public static final String TAG_ABANDON = "autogenerated:gerrit:abandon";
+ public static final String TAG_CHERRY_PICK_CHANGE = "autogenerated:gerrit:cherryPickChange";
+ public static final String TAG_DELETE_ASSIGNEE = "autogenerated:gerrit:deleteAssignee";
+ public static final String TAG_DELETE_REVIEWER = "autogenerated:gerrit:deleteReviewer";
+ public static final String TAG_DELETE_VOTE = "autogenerated:gerrit:deleteVote";
+ public static final String TAG_MERGED = "autogenerated:gerrit:merged";
+ public static final String TAG_MOVE = "autogenerated:gerrit:move";
+ public static final String TAG_RESTORE = "autogenerated:gerrit:restore";
+ public static final String TAG_REVERT = "autogenerated:gerrit:revert";
+ public static final String TAG_SET_ASSIGNEE = "autogenerated:gerrit:setAssignee";
+ public static final String TAG_SET_DESCRIPTION = "autogenerated:gerrit:setPsDescription";
+ public static final String TAG_SET_HASHTAGS = "autogenerated:gerrit:setHashtag";
+ public static final String TAG_SET_TOPIC = "autogenerated:gerrit:setTopic";
+ public static final String TAG_UPLOADED_PATCH_SET = "autogenerated:gerrit:newPatchSet";
- public static ChangeMessage newMessage(BatchUpdate.ChangeContext ctx,
- String body, @Nullable String tag) {
- return newMessage(
- ctx.getChange().currentPatchSetId(),
- ctx.getUser(), ctx.getWhen(), body, tag);
+ public static ChangeMessage newMessage(
+ BatchUpdate.ChangeContext ctx, String body, @Nullable String tag) {
+ return newMessage(ctx.getChange().currentPatchSetId(), ctx.getUser(), ctx.getWhen(), body, tag);
}
public static ChangeMessage newMessage(
- PatchSet.Id psId, CurrentUser user, Timestamp when,
- String body, @Nullable String tag) {
+ PatchSet.Id psId, CurrentUser user, Timestamp when, String body, @Nullable String tag) {
checkNotNull(psId);
Account.Id accountId = user.isInternalUser() ? null : user.getAccountId();
- ChangeMessage m = new ChangeMessage(
- new ChangeMessage.Key(psId.getParentKey(), ChangeUtil.messageUuid()),
- accountId, when, psId);
+ ChangeMessage m =
+ new ChangeMessage(
+ new ChangeMessage.Key(psId.getParentKey(), ChangeUtil.messageUuid()),
+ accountId,
+ when,
+ psId);
m.setMessage(body);
m.setTag(tag);
user.updateRealAccountId(m::setRealAuthor);
return m;
}
- private static List<ChangeMessage> sortChangeMessages(
- Iterable<ChangeMessage> changeMessage) {
+ private static List<ChangeMessage> sortChangeMessages(Iterable<ChangeMessage> changeMessage) {
return ChangeNotes.MESSAGE_BY_TIME.sortedCopy(changeMessage);
}
@@ -109,26 +93,26 @@
public List<ChangeMessage> byChange(ReviewDb db, ChangeNotes notes) throws OrmException {
if (!migration.readChanges()) {
- return
- sortChangeMessages(db.changeMessages().byChange(notes.getChangeId()));
+ return sortChangeMessages(db.changeMessages().byChange(notes.getChangeId()));
}
return notes.load().getChangeMessages();
}
- public Iterable<ChangeMessage> byPatchSet(ReviewDb db, ChangeNotes notes,
- PatchSet.Id psId) throws OrmException {
+ public Iterable<ChangeMessage> byPatchSet(ReviewDb db, ChangeNotes notes, PatchSet.Id psId)
+ throws OrmException {
if (!migration.readChanges()) {
return db.changeMessages().byPatchSet(psId);
}
return notes.load().getChangeMessagesByPatchSet().get(psId);
}
- public void addChangeMessage(ReviewDb db, ChangeUpdate update,
- ChangeMessage changeMessage) throws OrmException {
+ public void addChangeMessage(ReviewDb db, ChangeUpdate update, ChangeMessage changeMessage)
+ throws OrmException {
checkState(
Objects.equals(changeMessage.getAuthor(), update.getNullableAccountId()),
"cannot store change message by %s in update by %s",
- changeMessage.getAuthor(), update.getNullableAccountId());
+ changeMessage.getAuthor(),
+ update.getNullableAccountId());
update.setChangeMessage(changeMessage.getMessage());
update.setTag(changeMessage.getTag());
db.changeMessages().insert(Collections.singleton(changeMessage));
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/ChangeUtil.java b/gerrit-server/src/main/java/com/google/gerrit/server/ChangeUtil.java
index fbf6d03..10ae60c 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/ChangeUtil.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/ChangeUtil.java
@@ -20,21 +20,18 @@
import com.google.common.io.BaseEncoding;
import com.google.gerrit.reviewdb.client.PatchSet;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.lib.Ref;
-import org.eclipse.jgit.lib.RefDatabase;
-import org.eclipse.jgit.lib.Repository;
-
import java.io.IOException;
import java.security.SecureRandom;
import java.util.Map;
import java.util.Random;
+import org.eclipse.jgit.lib.Ref;
+import org.eclipse.jgit.lib.RefDatabase;
+import org.eclipse.jgit.lib.Repository;
@Singleton
public class ChangeUtil {
private static final Random UUID_RANDOM = new SecureRandom();
- private static final BaseEncoding UUID_ENCODING =
- BaseEncoding.base16().lowerCase();
+ private static final BaseEncoding UUID_ENCODING = BaseEncoding.base16().lowerCase();
private static final int SUBJECT_MAX_LENGTH = 80;
private static final String SUBJECT_CROP_APPENDIX = "...";
@@ -47,12 +44,10 @@
public static String messageUuid() {
byte[] buf = new byte[8];
UUID_RANDOM.nextBytes(buf);
- return UUID_ENCODING.encode(buf, 0, 4) + '_'
- + UUID_ENCODING.encode(buf, 4, 4);
+ return UUID_ENCODING.encode(buf, 0, 4) + '_' + UUID_ENCODING.encode(buf, 4, 4);
}
- public static PatchSet.Id nextPatchSetId(Map<String, Ref> allRefs,
- PatchSet.Id id) {
+ public static PatchSet.Id nextPatchSetId(Map<String, Ref> allRefs, PatchSet.Id id) {
PatchSet.Id next = nextPatchSetId(id);
while (allRefs.containsKey(next.toRefName())) {
next = nextPatchSetId(next);
@@ -64,8 +59,7 @@
return new PatchSet.Id(id.getParentKey(), id.get() + 1);
}
- public static PatchSet.Id nextPatchSetId(Repository git, PatchSet.Id id)
- throws IOException {
+ public static PatchSet.Id nextPatchSetId(Repository git, PatchSet.Id id) throws IOException {
return nextPatchSetId(git.getRefDatabase().getRefs(RefDatabase.ALL), id);
}
@@ -73,7 +67,8 @@
if (subject.length() > SUBJECT_MAX_LENGTH) {
int maxLength = SUBJECT_MAX_LENGTH - SUBJECT_CROP_APPENDIX.length();
for (int cropPosition = maxLength;
- cropPosition > maxLength - SUBJECT_CROP_RANGE; cropPosition--) {
+ cropPosition > maxLength - SUBJECT_CROP_RANGE;
+ cropPosition--) {
if (Character.isWhitespace(subject.charAt(cropPosition - 1))) {
return subject.substring(0, cropPosition) + SUBJECT_CROP_APPENDIX;
}
@@ -83,6 +78,5 @@
return subject;
}
- private ChangeUtil() {
- }
+ private ChangeUtil() {}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/CmdLineParserModule.java b/gerrit-server/src/main/java/com/google/gerrit/server/CmdLineParserModule.java
index 282d51e..63f7202 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/CmdLineParserModule.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/CmdLineParserModule.java
@@ -32,16 +32,13 @@
import com.google.gerrit.util.cli.CmdLineParser;
import com.google.gerrit.util.cli.OptionHandlerUtil;
import com.google.gerrit.util.cli.OptionHandlers;
-
+import java.net.SocketAddress;
+import java.sql.Timestamp;
import org.eclipse.jgit.lib.ObjectId;
import org.kohsuke.args4j.spi.OptionHandler;
-import java.net.SocketAddress;
-import java.sql.Timestamp;
-
public class CmdLineParserModule extends FactoryModule {
- public CmdLineParserModule() {
- }
+ public CmdLineParserModule() {}
@Override
protected void configure() {
@@ -59,8 +56,7 @@
registerOptionHandler(Timestamp.class, TimestampHandler.class);
}
- private <T> void registerOptionHandler(Class<T> type,
- Class<? extends OptionHandler<T>> impl) {
+ private <T> void registerOptionHandler(Class<T> type, Class<? extends OptionHandler<T>> impl) {
install(OptionHandlerUtil.moduleFor(type, impl));
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/CommentsUtil.java b/gerrit-server/src/main/java/com/google/gerrit/server/CommentsUtil.java
index a9af7e0..f4344d8 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/CommentsUtil.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/CommentsUtil.java
@@ -51,15 +51,6 @@
import com.google.gwtorm.server.ResultSet;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.lib.BatchRefUpdate;
-import org.eclipse.jgit.lib.NullProgressMonitor;
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.lib.Ref;
-import org.eclipse.jgit.lib.Repository;
-import org.eclipse.jgit.revwalk.RevWalk;
-import org.eclipse.jgit.transport.ReceiveCommand;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
@@ -68,28 +59,35 @@
import java.util.Optional;
import java.util.function.Predicate;
import java.util.stream.StreamSupport;
+import org.eclipse.jgit.lib.BatchRefUpdate;
+import org.eclipse.jgit.lib.NullProgressMonitor;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.lib.Ref;
+import org.eclipse.jgit.lib.Repository;
+import org.eclipse.jgit.revwalk.RevWalk;
+import org.eclipse.jgit.transport.ReceiveCommand;
/**
* Utility functions to manipulate Comments.
- * <p>
- * These methods either query for and update Comments in the NoteDb or
- * ReviewDb, depending on the state of the NotesMigration.
+ *
+ * <p>These methods either query for and update Comments in the NoteDb or ReviewDb, depending on the
+ * state of the NotesMigration.
*/
@Singleton
public class CommentsUtil {
public static final Ordering<Comment> COMMENT_ORDER =
new Ordering<Comment>() {
- @Override
- public int compare(Comment c1, Comment c2) {
- return ComparisonChain.start()
- .compare(c1.key.filename, c2.key.filename)
- .compare(c1.key.patchSetId, c2.key.patchSetId)
- .compare(c1.side, c2.side)
- .compare(c1.lineNbr, c2.lineNbr)
- .compare(c1.writtenOn, c2.writtenOn)
- .result();
- }
- };
+ @Override
+ public int compare(Comment c1, Comment c2) {
+ return ComparisonChain.start()
+ .compare(c1.key.filename, c2.key.filename)
+ .compare(c1.key.patchSetId, c2.key.patchSetId)
+ .compare(c1.side, c2.side)
+ .compare(c1.lineNbr, c2.lineNbr)
+ .compare(c1.writtenOn, c2.writtenOn)
+ .result();
+ }
+ };
public static final Ordering<CommentInfo> COMMENT_INFO_ORDER =
new Ordering<CommentInfo>() {
@@ -111,8 +109,7 @@
}
};
- public static PatchSet.Id getCommentPsId(Change.Id changeId,
- Comment comment) {
+ public static PatchSet.Id getCommentPsId(Change.Id changeId, Comment comment) {
return new PatchSet.Id(changeId, comment.key.patchSetId);
}
@@ -123,8 +120,7 @@
return tag.substring("mailMessageId=".length());
}
- private static final Ordering<Comparable<?>> NULLS_FIRST =
- Ordering.natural().nullsFirst();
+ private static final Ordering<Comparable<?>> NULLS_FIRST = Ordering.natural().nullsFirst();
private final GitRepositoryManager repoManager;
private final AllUsersName allUsers;
@@ -132,7 +128,8 @@
private final String serverId;
@Inject
- CommentsUtil(GitRepositoryManager repoManager,
+ CommentsUtil(
+ GitRepositoryManager repoManager,
AllUsersName allUsers,
NotesMigration migration,
@GerritServerId String serverId) {
@@ -142,7 +139,8 @@
this.serverId = serverId;
}
- public Comment newComment(ChangeContext ctx,
+ public Comment newComment(
+ ChangeContext ctx,
String path,
PatchSet.Id psId,
short side,
@@ -159,62 +157,73 @@
Comment.Key key = new Comment.Key(parentUuid, path, psId.patchSetId);
Optional<Comment> parent = get(ctx.getDb(), ctx.getNotes(), key);
if (!parent.isPresent()) {
- throw new UnprocessableEntityException(
- "Invalid parentUuid supplied for comment");
+ throw new UnprocessableEntityException("Invalid parentUuid supplied for comment");
}
unresolved = parent.get().unresolved;
}
}
- Comment c = new Comment(
- new Comment.Key(ChangeUtil.messageUuid(), path, psId.get()),
- ctx.getUser().getAccountId(), ctx.getWhen(), side, message, serverId,
- unresolved);
+ Comment c =
+ new Comment(
+ new Comment.Key(ChangeUtil.messageUuid(), path, psId.get()),
+ ctx.getUser().getAccountId(),
+ ctx.getWhen(),
+ side,
+ message,
+ serverId,
+ unresolved);
c.parentUuid = parentUuid;
ctx.getUser().updateRealAccountId(c::setRealAuthor);
return c;
}
- public RobotComment newRobotComment(ChangeContext ctx, String path,
- PatchSet.Id psId, short side, String message, String robotId,
+ public RobotComment newRobotComment(
+ ChangeContext ctx,
+ String path,
+ PatchSet.Id psId,
+ short side,
+ String message,
+ String robotId,
String robotRunId) {
- RobotComment c = new RobotComment(
- new Comment.Key(ChangeUtil.messageUuid(), path, psId.get()),
- ctx.getUser().getAccountId(), ctx.getWhen(), side, message, serverId,
- robotId, robotRunId);
+ RobotComment c =
+ new RobotComment(
+ new Comment.Key(ChangeUtil.messageUuid(), path, psId.get()),
+ ctx.getUser().getAccountId(),
+ ctx.getWhen(),
+ side,
+ message,
+ serverId,
+ robotId,
+ robotRunId);
ctx.getUser().updateRealAccountId(c::setRealAuthor);
return c;
}
- public Optional<Comment> get(ReviewDb db, ChangeNotes notes,
- Comment.Key key) throws OrmException {
+ public Optional<Comment> get(ReviewDb db, ChangeNotes notes, Comment.Key key)
+ throws OrmException {
if (!migration.readChanges()) {
return Optional.ofNullable(
- db.patchComments()
- .get(PatchLineComment.Key.from(notes.getChangeId(), key)))
+ db.patchComments().get(PatchLineComment.Key.from(notes.getChangeId(), key)))
.map(plc -> plc.asComment(serverId));
}
Predicate<Comment> p = c -> key.equals(c.key);
- Optional<Comment> c =
- publishedByChange(db, notes).stream().filter(p).findFirst();
+ Optional<Comment> c = publishedByChange(db, notes).stream().filter(p).findFirst();
if (c.isPresent()) {
return c;
}
return draftByChange(db, notes).stream().filter(p).findFirst();
}
- public List<Comment> publishedByChange(ReviewDb db, ChangeNotes notes)
- throws OrmException {
+ public List<Comment> publishedByChange(ReviewDb db, ChangeNotes notes) throws OrmException {
if (!migration.readChanges()) {
- return sort(byCommentStatus(
- db.patchComments().byChange(notes.getChangeId()), Status.PUBLISHED));
+ return sort(
+ byCommentStatus(db.patchComments().byChange(notes.getChangeId()), Status.PUBLISHED));
}
notes.load();
return sort(Lists.newArrayList(notes.getComments().values()));
}
- public List<RobotComment> robotCommentsByChange(ChangeNotes notes)
- throws OrmException {
+ public List<RobotComment> robotCommentsByChange(ChangeNotes notes) throws OrmException {
if (!migration.readChanges()) {
return ImmutableList.of();
}
@@ -223,11 +232,9 @@
return sort(Lists.newArrayList(notes.getRobotComments().values()));
}
- public List<Comment> draftByChange(ReviewDb db, ChangeNotes notes)
- throws OrmException {
+ public List<Comment> draftByChange(ReviewDb db, ChangeNotes notes) throws OrmException {
if (!migration.readChanges()) {
- return sort(byCommentStatus(
- db.patchComments().byChange(notes.getChangeId()), Status.DRAFT));
+ return sort(byCommentStatus(db.patchComments().byChange(notes.getChangeId()), Status.DRAFT));
}
List<Comment> comments = new ArrayList<>();
@@ -240,17 +247,16 @@
return sort(comments);
}
- private List<Comment> byCommentStatus(ResultSet<PatchLineComment> comments,
- final PatchLineComment.Status status) {
- return toComments(serverId, Lists.newArrayList(
- Iterables.filter(comments, c -> c.getStatus() == status)));
+ private List<Comment> byCommentStatus(
+ ResultSet<PatchLineComment> comments, final PatchLineComment.Status status) {
+ return toComments(
+ serverId, Lists.newArrayList(Iterables.filter(comments, c -> c.getStatus() == status)));
}
- public List<Comment> byPatchSet(ReviewDb db,
- ChangeNotes notes, PatchSet.Id psId) throws OrmException {
+ public List<Comment> byPatchSet(ReviewDb db, ChangeNotes notes, PatchSet.Id psId)
+ throws OrmException {
if (!migration.readChanges()) {
- return sort(toComments(serverId,
- db.patchComments().byPatchSet(psId).toList()));
+ return sort(toComments(serverId, db.patchComments().byPatchSet(psId).toList()));
}
List<Comment> comments = new ArrayList<>();
comments.addAll(publishedByPatchSet(db, notes, psId));
@@ -264,27 +270,27 @@
return sort(comments);
}
- public List<Comment> publishedByChangeFile(ReviewDb db, ChangeNotes notes,
- Change.Id changeId, String file) throws OrmException {
+ public List<Comment> publishedByChangeFile(
+ ReviewDb db, ChangeNotes notes, Change.Id changeId, String file) throws OrmException {
if (!migration.readChanges()) {
- return sort(toComments(serverId,
- db.patchComments().publishedByChangeFile(changeId, file).toList()));
+ return sort(
+ toComments(serverId, db.patchComments().publishedByChangeFile(changeId, file).toList()));
}
return commentsOnFile(notes.load().getComments().values(), file);
}
- public List<Comment> publishedByPatchSet(ReviewDb db,
- ChangeNotes notes, PatchSet.Id psId) throws OrmException {
+ public List<Comment> publishedByPatchSet(ReviewDb db, ChangeNotes notes, PatchSet.Id psId)
+ throws OrmException {
if (!migration.readChanges()) {
- return removeCommentsOnAncestorOfCommitMessage(sort(toComments(serverId,
- db.patchComments().publishedByPatchSet(psId).toList())));
+ return removeCommentsOnAncestorOfCommitMessage(
+ sort(toComments(serverId, db.patchComments().publishedByPatchSet(psId).toList())));
}
return removeCommentsOnAncestorOfCommitMessage(
commentsOnPatchSet(notes.load().getComments().values(), psId));
}
- public List<RobotComment> robotCommentsByPatchSet(ChangeNotes notes,
- PatchSet.Id psId) throws OrmException {
+ public List<RobotComment> robotCommentsByPatchSet(ChangeNotes notes, PatchSet.Id psId)
+ throws OrmException {
if (!migration.readChanges()) {
return ImmutableList.of();
}
@@ -292,49 +298,45 @@
}
/**
- * For the commit message the A side in a diff view is always empty when a
- * comparison against an ancestor is done, so there can't be any comments on
- * this ancestor. However earlier we showed the auto-merge commit message on
- * side A when for a merge commit a comparison against the auto-merge was
- * done. From that time there may still be comments on the auto-merge commit
+ * For the commit message the A side in a diff view is always empty when a comparison against an
+ * ancestor is done, so there can't be any comments on this ancestor. However earlier we showed
+ * the auto-merge commit message on side A when for a merge commit a comparison against the
+ * auto-merge was done. From that time there may still be comments on the auto-merge commit
* message and those we want to filter out.
*/
- private List<Comment> removeCommentsOnAncestorOfCommitMessage(
- List<Comment> list) {
+ private List<Comment> removeCommentsOnAncestorOfCommitMessage(List<Comment> list) {
return list.stream()
.filter(c -> c.side != 0 || !Patch.COMMIT_MSG.equals(c.key.filename))
.collect(toList());
}
- public List<Comment> draftByPatchSetAuthor(ReviewDb db, PatchSet.Id psId,
- Account.Id author, ChangeNotes notes) throws OrmException {
+ public List<Comment> draftByPatchSetAuthor(
+ ReviewDb db, PatchSet.Id psId, Account.Id author, ChangeNotes notes) throws OrmException {
if (!migration.readChanges()) {
- return sort(toComments(serverId,
- db.patchComments().draftByPatchSetAuthor(psId, author).toList()));
+ return sort(
+ toComments(serverId, db.patchComments().draftByPatchSetAuthor(psId, author).toList()));
}
return commentsOnPatchSet(notes.load().getDraftComments(author).values(), psId);
}
- public List<Comment> draftByChangeFileAuthor(ReviewDb db,
- ChangeNotes notes, String file, Account.Id author)
- throws OrmException {
+ public List<Comment> draftByChangeFileAuthor(
+ ReviewDb db, ChangeNotes notes, String file, Account.Id author) throws OrmException {
if (!migration.readChanges()) {
- return sort(toComments(serverId,
- db.patchComments()
- .draftByChangeFileAuthor(notes.getChangeId(), file, author)
- .toList()));
+ return sort(
+ toComments(
+ serverId,
+ db.patchComments()
+ .draftByChangeFileAuthor(notes.getChangeId(), file, author)
+ .toList()));
}
return commentsOnFile(notes.load().getDraftComments(author).values(), file);
}
- public List<Comment> draftByChangeAuthor(ReviewDb db,
- ChangeNotes notes, Account.Id author)
+ public List<Comment> draftByChangeAuthor(ReviewDb db, ChangeNotes notes, Account.Id author)
throws OrmException {
if (!migration.readChanges()) {
- return StreamSupport
- .stream(db.patchComments().draftByAuthor(author).spliterator(), false)
- .filter(c -> c.getPatchSetId().getParentKey()
- .equals(notes.getChangeId()))
+ return StreamSupport.stream(db.patchComments().draftByAuthor(author).spliterator(), false)
+ .filter(c -> c.getPatchSetId().getParentKey().equals(notes.getChangeId()))
.map(plc -> plc.asComment(serverId))
.sorted(COMMENT_ORDER)
.collect(toList());
@@ -345,17 +347,17 @@
}
@Deprecated // To be used only by HasDraftByLegacyPredicate.
- public List<Change.Id> changesWithDraftsByAuthor(ReviewDb db,
- Account.Id author) throws OrmException {
+ public List<Change.Id> changesWithDraftsByAuthor(ReviewDb db, Account.Id author)
+ throws OrmException {
if (!migration.readChanges()) {
return FluentIterable.from(db.patchComments().draftByAuthor(author))
- .transform(plc -> plc.getPatchSetId().getParentKey()).toList();
+ .transform(plc -> plc.getPatchSetId().getParentKey())
+ .toList();
}
List<Change.Id> changes = new ArrayList<>();
try (Repository repo = repoManager.openRepository(allUsers)) {
- for (String refName : repo.getRefDatabase()
- .getRefs(RefNames.REFS_DRAFT_COMMENTS).keySet()) {
+ for (String refName : repo.getRefDatabase().getRefs(RefNames.REFS_DRAFT_COMMENTS).keySet()) {
Account.Id accountId = Account.Id.fromRefSuffix(refName);
Change.Id changeId = Change.Id.fromRefPart(refName);
if (accountId == null || changeId == null) {
@@ -369,56 +371,51 @@
return changes;
}
- public void putComments(ReviewDb db, ChangeUpdate update,
- PatchLineComment.Status status, Iterable<Comment> comments)
- throws OrmException {
+ public void putComments(
+ ReviewDb db, ChangeUpdate update, PatchLineComment.Status status, Iterable<Comment> comments)
+ throws OrmException {
for (Comment c : comments) {
update.putComment(status, c);
}
- db.patchComments()
- .upsert(toPatchLineComments(update.getId(), status, comments));
+ db.patchComments().upsert(toPatchLineComments(update.getId(), status, comments));
}
- public void putRobotComments(ChangeUpdate update,
- Iterable<RobotComment> comments) {
+ public void putRobotComments(ChangeUpdate update, Iterable<RobotComment> comments) {
for (RobotComment c : comments) {
update.putRobotComment(c);
}
}
- public void deleteComments(ReviewDb db, ChangeUpdate update,
- Iterable<Comment> comments) throws OrmException {
+ public void deleteComments(ReviewDb db, ChangeUpdate update, Iterable<Comment> comments)
+ throws OrmException {
for (Comment c : comments) {
update.deleteComment(c);
}
- db.patchComments().delete(toPatchLineComments(update.getId(),
- PatchLineComment.Status.DRAFT, comments));
+ db.patchComments()
+ .delete(toPatchLineComments(update.getId(), PatchLineComment.Status.DRAFT, comments));
}
- public void deleteAllDraftsFromAllUsers(Change.Id changeId)
- throws IOException {
+ public void deleteAllDraftsFromAllUsers(Change.Id changeId) throws IOException {
try (Repository repo = repoManager.openRepository(allUsers);
RevWalk rw = new RevWalk(repo)) {
BatchRefUpdate bru = repo.getRefDatabase().newBatchUpdate();
for (Ref ref : getDraftRefs(repo, changeId)) {
- bru.addCommand(new ReceiveCommand(
- ref.getObjectId(), ObjectId.zeroId(), ref.getName()));
+ bru.addCommand(new ReceiveCommand(ref.getObjectId(), ObjectId.zeroId(), ref.getName()));
}
bru.setRefLogMessage("Delete drafts from NoteDb", false);
bru.execute(rw, NullProgressMonitor.INSTANCE);
for (ReceiveCommand cmd : bru.getCommands()) {
if (cmd.getResult() != ReceiveCommand.Result.OK) {
- throw new IOException(String.format(
- "Failed to delete draft comment ref %s at %s: %s (%s)",
- cmd.getRefName(), cmd.getOldId(), cmd.getResult(),
- cmd.getMessage()));
+ throw new IOException(
+ String.format(
+ "Failed to delete draft comment ref %s at %s: %s (%s)",
+ cmd.getRefName(), cmd.getOldId(), cmd.getResult(), cmd.getMessage()));
}
}
}
}
- private static List<Comment> commentsOnFile(Collection<Comment> allComments,
- String file) {
+ private static List<Comment> commentsOnFile(Collection<Comment> allComments, String file) {
List<Comment> result = new ArrayList<>(allComments.size());
for (Comment c : allComments) {
String currentFilename = c.key.filename;
@@ -430,8 +427,7 @@
}
private static <T extends Comment> List<T> commentsOnPatchSet(
- Collection<T> allComments,
- PatchSet.Id psId) {
+ Collection<T> allComments, PatchSet.Id psId) {
List<T> result = new ArrayList<>(allComments.size());
for (T c : allComments) {
if (c.key.patchSetId == psId.get()) {
@@ -441,10 +437,13 @@
return sort(result);
}
- public static void setCommentRevId(Comment c,
- PatchListCache cache, Change change, PatchSet ps) throws OrmException {
- checkArgument(c.key.patchSetId == ps.getId().get(),
- "cannot set RevId for patch set %s on comment %s", ps.getId(), c);
+ public static void setCommentRevId(Comment c, PatchListCache cache, Change change, PatchSet ps)
+ throws OrmException {
+ checkArgument(
+ c.key.patchSetId == ps.getId().get(),
+ "cannot set RevId for patch set %s on comment %s",
+ ps.getId(),
+ c);
if (c.revId == null) {
try {
if (Side.fromShort(c.side) == Side.PARENT) {
@@ -464,18 +463,17 @@
/**
* Get NoteDb draft refs for a change.
- * <p>
- * Works if NoteDb is not enabled, but the results are not meaningful.
- * <p>
- * This is just a simple ref scan, so the results may potentially include refs
- * for zombie draft comments. A zombie draft is one which has been published
- * but the write to delete the draft ref from All-Users failed.
+ *
+ * <p>Works if NoteDb is not enabled, but the results are not meaningful.
+ *
+ * <p>This is just a simple ref scan, so the results may potentially include refs for zombie draft
+ * comments. A zombie draft is one which has been published but the write to delete the draft ref
+ * from All-Users failed.
*
* @param changeId change ID.
* @return raw refs from All-Users repo.
*/
- public Collection<Ref> getDraftRefs(Change.Id changeId)
- throws OrmException {
+ public Collection<Ref> getDraftRefs(Change.Id changeId) throws OrmException {
try (Repository repo = repoManager.openRepository(allUsers)) {
return getDraftRefs(repo, changeId);
} catch (IOException e) {
@@ -483,10 +481,8 @@
}
}
- private Collection<Ref> getDraftRefs(Repository repo, Change.Id changeId)
- throws IOException {
- return repo.getRefDatabase().getRefs(
- RefNames.refsDraftCommentsPrefix(changeId)).values();
+ private Collection<Ref> getDraftRefs(Repository repo, Change.Id changeId) throws IOException {
+ return repo.getRefDatabase().getRefs(RefNames.refsDraftCommentsPrefix(changeId)).values();
}
private static <T extends Comment> List<T> sort(List<T> comments) {
@@ -495,15 +491,13 @@
}
public static Iterable<PatchLineComment> toPatchLineComments(
- Change.Id changeId, PatchLineComment.Status status,
- Iterable<Comment> comments) {
- return FluentIterable.from(comments)
- .transform(c -> PatchLineComment.from(changeId, status, c));
+ Change.Id changeId, PatchLineComment.Status status, Iterable<Comment> comments) {
+ return FluentIterable.from(comments).transform(c -> PatchLineComment.from(changeId, status, c));
}
- public static List<Comment> toComments(final String serverId,
- Iterable<PatchLineComment> comments) {
- return COMMENT_ORDER.sortedCopy(FluentIterable.from(comments)
- .transform(plc -> plc.asComment(serverId)));
+ public static List<Comment> toComments(
+ final String serverId, Iterable<PatchLineComment> comments) {
+ return COMMENT_ORDER.sortedCopy(
+ FluentIterable.from(comments).transform(plc -> plc.asComment(serverId)));
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/CommonConverters.java b/gerrit-server/src/main/java/com/google/gerrit/server/CommonConverters.java
index be07bde..2b48169 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/CommonConverters.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/CommonConverters.java
@@ -15,17 +15,15 @@
package com.google.gerrit.server;
import com.google.gerrit.extensions.common.GitPerson;
-
-import org.eclipse.jgit.lib.PersonIdent;
-
import java.sql.Timestamp;
+import org.eclipse.jgit.lib.PersonIdent;
/**
* Converters to classes in {@code com.google.gerrit.extensions.common}.
- * <p>
- * The server frequently needs to convert internal types to types exposed in the
- * extension API, but the converters themselves are not part of this API. This
- * class contains such converters as static utility methods.
+ *
+ * <p>The server frequently needs to convert internal types to types exposed in the extension API,
+ * but the converters themselves are not part of this API. This class contains such converters as
+ * static utility methods.
*/
public class CommonConverters {
public static GitPerson toGitPerson(PersonIdent ident) {
@@ -37,6 +35,5 @@
return result;
}
- private CommonConverters() {
- }
+ private CommonConverters() {}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/CurrentUser.java b/gerrit-server/src/main/java/com/google/gerrit/server/CurrentUser.java
index b62283a..9a294c9 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/CurrentUser.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/CurrentUser.java
@@ -20,13 +20,12 @@
import com.google.gerrit.server.account.CapabilityControl;
import com.google.gerrit.server.account.GroupMembership;
import com.google.inject.servlet.RequestScoped;
-
import java.util.function.Consumer;
/**
* Information about the currently logged in user.
- * <p>
- * This is a {@link RequestScoped} property managed by Guice.
+ *
+ * <p>This is a {@link RequestScoped} property managed by Guice.
*
* @see AnonymousUser
* @see IdentifiedUser
@@ -38,16 +37,14 @@
return new PropertyKey<>();
}
- private PropertyKey() {
- }
+ private PropertyKey() {}
}
private final CapabilityControl.Factory capabilityControlFactory;
private AccessPath accessPath = AccessPath.UNKNOWN;
private CapabilityControl capabilities;
- private PropertyKey<AccountExternalId.Key> lastLoginExternalIdPropertyKey =
- PropertyKey.create();
+ private PropertyKey<AccountExternalId.Key> lastLoginExternalIdPropertyKey = PropertyKey.create();
protected CurrentUser(CapabilityControl.Factory capabilityControlFactory) {
this.capabilityControlFactory = capabilityControlFactory;
@@ -64,21 +61,19 @@
/**
* Identity of the authenticated user.
- * <p>
- * In the normal case where a user authenticates as themselves
- * {@code getRealUser() == this}.
- * <p>
- * If {@code X-Gerrit-RunAs} or {@code suexec} was used this method returns
- * the identity of the account that has permission to act on behalf of this
- * user.
+ *
+ * <p>In the normal case where a user authenticates as themselves {@code getRealUser() == this}.
+ *
+ * <p>If {@code X-Gerrit-RunAs} or {@code suexec} was used this method returns the identity of the
+ * account that has permission to act on behalf of this user.
*/
public CurrentUser getRealUser() {
return this;
}
/**
- * If the {@link #getRealUser()} has an account ID associated with it, call
- * the given setter with that ID.
+ * If the {@link #getRealUser()} has an account ID associated with it, call the given setter with
+ * that ID.
*/
public void updateRealAccountId(Consumer<Account.Id> setter) {
if (getRealUser().isIdentifiedUser()) {
@@ -88,12 +83,11 @@
/**
* Get the set of groups the user is currently a member of.
- * <p>
- * The returned set may be a subset of the user's actual groups; if the user's
- * account is currently deemed to be untrusted then the effective group set is
- * only the anonymous and registered user groups. To enable additional groups
- * (and gain their granted permissions) the user must update their account to
- * use only trusted authentication providers.
+ *
+ * <p>The returned set may be a subset of the user's actual groups; if the user's account is
+ * currently deemed to be untrusted then the effective group set is only the anonymous and
+ * registered user groups. To enable additional groups (and gain their granted permissions) the
+ * user must update their account to use only trusted authentication providers.
*
* @return active groups for this user.
*/
@@ -151,8 +145,7 @@
* @param key unique property key.
* @param value value to store; or {@code null} to clear the value.
*/
- public <T> void put(PropertyKey<T> key, @Nullable T value) {
- }
+ public <T> void put(PropertyKey<T> key, @Nullable T value) {}
public void setLastLoginExternalIdKey(AccountExternalId.Key externalIdKey) {
put(lastLoginExternalIdPropertyKey, externalIdKey);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/EnableSignedPush.java b/gerrit-server/src/main/java/com/google/gerrit/server/EnableSignedPush.java
index 13942a67..154a783 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/EnableSignedPush.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/EnableSignedPush.java
@@ -17,13 +17,9 @@
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import com.google.inject.BindingAnnotation;
-
import java.lang.annotation.Retention;
-/**
- * Marker on a boolean indicating whether signed push is enabled on the server.
- */
+/** Marker on a boolean indicating whether signed push is enabled on the server. */
@Retention(RUNTIME)
@BindingAnnotation
-public @interface EnableSignedPush {
-}
+public @interface EnableSignedPush {}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/GerritPersonIdent.java b/gerrit-server/src/main/java/com/google/gerrit/server/GerritPersonIdent.java
index 07b49ee..5d259b3 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/GerritPersonIdent.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/GerritPersonIdent.java
@@ -17,7 +17,6 @@
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import com.google.inject.BindingAnnotation;
-
import java.lang.annotation.Retention;
/**
@@ -26,5 +25,4 @@
*/
@Retention(RUNTIME)
@BindingAnnotation
-public @interface GerritPersonIdent {
-}
+public @interface GerritPersonIdent {}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/GerritPersonIdentProvider.java b/gerrit-server/src/main/java/com/google/gerrit/server/GerritPersonIdentProvider.java
index 2d9bbb9..8c68270 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/GerritPersonIdentProvider.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/GerritPersonIdentProvider.java
@@ -18,7 +18,6 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.lib.PersonIdent;
import org.eclipse.jgit.lib.UserConfig;
@@ -43,5 +42,4 @@
public PersonIdent get() {
return new PersonIdent(name, email);
}
-
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/GpgException.java b/gerrit-server/src/main/java/com/google/gerrit/server/GpgException.java
index 5ed27b5..a34b75c 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/GpgException.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/GpgException.java
@@ -30,4 +30,3 @@
super(message, cause);
}
}
-
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/IdentifiedUser.java b/gerrit-server/src/main/java/com/google/gerrit/server/IdentifiedUser.java
index 313a3e3..026e32a 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/IdentifiedUser.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/IdentifiedUser.java
@@ -37,10 +37,6 @@
import com.google.inject.ProvisionException;
import com.google.inject.Singleton;
import com.google.inject.util.Providers;
-
-import org.eclipse.jgit.lib.PersonIdent;
-import org.eclipse.jgit.util.SystemReader;
-
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
@@ -51,6 +47,8 @@
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
+import org.eclipse.jgit.lib.PersonIdent;
+import org.eclipse.jgit.util.SystemReader;
/** An authenticated user. */
public class IdentifiedUser extends CurrentUser {
@@ -87,9 +85,17 @@
}
public IdentifiedUser create(AccountState state) {
- return new IdentifiedUser(capabilityControlFactory, authConfig, realm,
- anonymousCowardName, canonicalUrl, accountCache, groupBackend,
- disableReverseDnsLookup, Providers.of((SocketAddress) null), state,
+ return new IdentifiedUser(
+ capabilityControlFactory,
+ authConfig,
+ realm,
+ anonymousCowardName,
+ canonicalUrl,
+ accountCache,
+ groupBackend,
+ disableReverseDnsLookup,
+ Providers.of((SocketAddress) null),
+ state,
null);
}
@@ -101,19 +107,28 @@
return runAs(remotePeer, id, null);
}
- public IdentifiedUser runAs(SocketAddress remotePeer, Account.Id id,
- @Nullable CurrentUser caller) {
- return new IdentifiedUser(capabilityControlFactory, authConfig, realm,
- anonymousCowardName, canonicalUrl, accountCache, groupBackend,
- disableReverseDnsLookup, Providers.of(remotePeer), id, caller);
+ public IdentifiedUser runAs(
+ SocketAddress remotePeer, Account.Id id, @Nullable CurrentUser caller) {
+ return new IdentifiedUser(
+ capabilityControlFactory,
+ authConfig,
+ realm,
+ anonymousCowardName,
+ canonicalUrl,
+ accountCache,
+ groupBackend,
+ disableReverseDnsLookup,
+ Providers.of(remotePeer),
+ id,
+ caller);
}
}
/**
* Create an IdentifiedUser, relying on current request state.
- * <p>
- * Can only be used from within a module that has defined request scoped
- * {@code @RemotePeer SocketAddress} and {@code ReviewDb} providers.
+ *
+ * <p>Can only be used from within a module that has defined request scoped {@code @RemotePeer
+ * SocketAddress} and {@code ReviewDb} providers.
*/
@Singleton
public static class RequestFactory {
@@ -150,22 +165,39 @@
}
public IdentifiedUser create(Account.Id id) {
- return new IdentifiedUser(capabilityControlFactory, authConfig, realm,
- anonymousCowardName, canonicalUrl, accountCache, groupBackend,
- disableReverseDnsLookup, remotePeerProvider, id, null);
+ return new IdentifiedUser(
+ capabilityControlFactory,
+ authConfig,
+ realm,
+ anonymousCowardName,
+ canonicalUrl,
+ accountCache,
+ groupBackend,
+ disableReverseDnsLookup,
+ remotePeerProvider,
+ id,
+ null);
}
public IdentifiedUser runAs(Account.Id id, CurrentUser caller) {
- return new IdentifiedUser(capabilityControlFactory, authConfig, realm,
- anonymousCowardName, canonicalUrl, accountCache, groupBackend,
- disableReverseDnsLookup, remotePeerProvider, id, caller);
+ return new IdentifiedUser(
+ capabilityControlFactory,
+ authConfig,
+ realm,
+ anonymousCowardName,
+ canonicalUrl,
+ accountCache,
+ groupBackend,
+ disableReverseDnsLookup,
+ remotePeerProvider,
+ id,
+ caller);
}
}
private static final GroupMembership registeredGroups =
- new ListGroupMembership(ImmutableSet.of(
- SystemGroupBackend.ANONYMOUS_USERS,
- SystemGroupBackend.REGISTERED_USERS));
+ new ListGroupMembership(
+ ImmutableSet.of(SystemGroupBackend.ANONYMOUS_USERS, SystemGroupBackend.REGISTERED_USERS));
private final Provider<String> canonicalUrl;
private final AccountCache accountCache;
@@ -174,8 +206,7 @@
private final GroupBackend groupBackend;
private final String anonymousCowardName;
private final Boolean disableReverseDnsLookup;
- private final Set<String> validEmails =
- Sets.newTreeSet(String.CASE_INSENSITIVE_ORDER);
+ private final Set<String> validEmails = Sets.newTreeSet(String.CASE_INSENSITIVE_ORDER);
private final Provider<SocketAddress> remotePeerProvider;
private final Account.Id accountId;
@@ -199,9 +230,18 @@
@Nullable Provider<SocketAddress> remotePeerProvider,
AccountState state,
@Nullable CurrentUser realUser) {
- this(capabilityControlFactory, authConfig, realm, anonymousCowardName,
- canonicalUrl, accountCache, groupBackend, disableReverseDnsLookup,
- remotePeerProvider, state.getAccount().getId(), realUser);
+ this(
+ capabilityControlFactory,
+ authConfig,
+ realm,
+ anonymousCowardName,
+ canonicalUrl,
+ accountCache,
+ groupBackend,
+ disableReverseDnsLookup,
+ remotePeerProvider,
+ state.getAccount().getId(),
+ realUser);
this.state = state;
}
@@ -419,8 +459,8 @@
/**
* Returns a materialized copy of the user with all dependencies.
*
- * Invoke all providers and factories of dependent objects and store the
- * references to a copy of the current identified user.
+ * <p>Invoke all providers and factories of dependent objects and store the references to a copy
+ * of the current identified user.
*
* @return copy of the identified user
*/
@@ -430,22 +470,32 @@
try {
remotePeer = Providers.of(remotePeerProvider.get());
} catch (OutOfScopeException | ProvisionException e) {
- remotePeer = new Provider<SocketAddress>() {
- @Override
- public SocketAddress get() {
- throw e;
- }
- };
+ remotePeer =
+ new Provider<SocketAddress>() {
+ @Override
+ public SocketAddress get() {
+ throw e;
+ }
+ };
}
- return new IdentifiedUser(new CapabilityControl.Factory() {
+ return new IdentifiedUser(
+ new CapabilityControl.Factory() {
- @Override
- public CapabilityControl create(CurrentUser user) {
- return capabilities;
- }
- }, authConfig, realm, anonymousCowardName,
- Providers.of(canonicalUrl.get()), accountCache, groupBackend,
- disableReverseDnsLookup, remotePeer, state, realUser);
+ @Override
+ public CapabilityControl create(CurrentUser user) {
+ return capabilities;
+ }
+ },
+ authConfig,
+ realm,
+ anonymousCowardName,
+ Providers.of(canonicalUrl.get()),
+ accountCache,
+ groupBackend,
+ disableReverseDnsLookup,
+ remotePeer,
+ state,
+ realUser);
}
private String guessHost() {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/InternalUser.java b/gerrit-server/src/main/java/com/google/gerrit/server/InternalUser.java
index 02d41f4..bc99ec1 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/InternalUser.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/InternalUser.java
@@ -21,11 +21,10 @@
/**
* User identity for plugin code that needs an identity.
- * <p>
- * An InternalUser has no real identity, it acts as the server and can access
- * anything it wants, anytime it wants, given the JVM's own direct access to
- * data. Plugins may use this when they need to have a CurrentUser with read
- * permission on anything.
+ *
+ * <p>An InternalUser has no real identity, it acts as the server and can access anything it wants,
+ * anytime it wants, given the JVM's own direct access to data. Plugins may use this when they need
+ * to have a CurrentUser with read permission on anything.
*
* @see PluginUser
*/
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/LibModuleLoader.java b/gerrit-server/src/main/java/com/google/gerrit/server/LibModuleLoader.java
index abea78f..4ec7d2d 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/LibModuleLoader.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/LibModuleLoader.java
@@ -21,18 +21,15 @@
import com.google.inject.Key;
import com.google.inject.Module;
import com.google.inject.ProvisionException;
-
+import java.util.Arrays;
+import java.util.List;
import org.eclipse.jgit.lib.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.util.Arrays;
-import java.util.List;
-
/** Loads configured Guice modules from {@code gerrit.installModule}. */
public class LibModuleLoader {
- private static final Logger log =
- LoggerFactory.getLogger(LibModuleLoader.class);
+ private static final Logger log = LoggerFactory.getLogger(LibModuleLoader.class);
public static List<Module> loadModules(Injector parent) {
Config cfg = getConfig(parent);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/OptionUtil.java b/gerrit-server/src/main/java/com/google/gerrit/server/OptionUtil.java
index c050a61..7b317cb 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/OptionUtil.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/OptionUtil.java
@@ -24,11 +24,8 @@
Splitter.on(CharMatcher.anyOf(", ")).omitEmptyStrings().trimResults();
public static Iterable<String> splitOptionValue(String value) {
- return Iterables.transform(
- COMMA_OR_SPACE.split(value),
- String::toLowerCase);
+ return Iterables.transform(COMMA_OR_SPACE.split(value), String::toLowerCase);
}
- private OptionUtil() {
- }
+ private OptionUtil() {}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/OutputFormat.java b/gerrit-server/src/main/java/com/google/gerrit/server/OutputFormat.java
index 7e1ec4b..e555845 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/OutputFormat.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/OutputFormat.java
@@ -18,30 +18,28 @@
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gwtjsonrpc.server.SqlTimestampDeserializer;
-
import java.sql.Timestamp;
/** Standard output format used by an API call. */
public enum OutputFormat {
/**
- * The output is a human readable text format. It may also be regular enough
- * to be machine readable. Whether or not the text format is machine readable
- * and will be committed to as a long term format that tools can build upon is
- * specific to each API call.
+ * The output is a human readable text format. It may also be regular enough to be machine
+ * readable. Whether or not the text format is machine readable and will be committed to as a long
+ * term format that tools can build upon is specific to each API call.
*/
TEXT,
/**
- * Pretty-printed JSON format. This format uses whitespace to make the output
- * readable by a human, but is also machine readable with a JSON library. The
- * structure of the output is a long term format that tools can rely upon.
+ * Pretty-printed JSON format. This format uses whitespace to make the output readable by a human,
+ * but is also machine readable with a JSON library. The structure of the output is a long term
+ * format that tools can rely upon.
*/
JSON,
/**
- * Same as {@link #JSON}, but with unnecessary whitespace removed to save
- * generation time and copy costs. Typically JSON_COMPACT format is used by a
- * browser based HTML client running over the network.
+ * Same as {@link #JSON}, but with unnecessary whitespace removed to save generation time and copy
+ * costs. Typically JSON_COMPACT format is used by a browser based HTML client running over the
+ * network.
*/
JSON_COMPACT;
@@ -55,9 +53,10 @@
if (!isJson()) {
throw new IllegalStateException(String.format("%s is not JSON", this));
}
- GsonBuilder gb = new GsonBuilder()
- .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
- .registerTypeAdapter(Timestamp.class, new SqlTimestampDeserializer());
+ GsonBuilder gb =
+ new GsonBuilder()
+ .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
+ .registerTypeAdapter(Timestamp.class, new SqlTimestampDeserializer());
if (this == OutputFormat.JSON) {
gb.setPrettyPrinting();
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/PatchSetUtil.java b/gerrit-server/src/main/java/com/google/gerrit/server/PatchSetUtil.java
index fdc1feb..ab942ca 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/PatchSetUtil.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/PatchSetUtil.java
@@ -32,14 +32,12 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.revwalk.RevWalk;
-
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Collections;
import java.util.List;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.revwalk.RevWalk;
/** Utilities for manipulating patch sets. */
@Singleton
@@ -51,13 +49,11 @@
this.migration = migration;
}
- public PatchSet current(ReviewDb db, ChangeNotes notes)
- throws OrmException {
+ public PatchSet current(ReviewDb db, ChangeNotes notes) throws OrmException {
return get(db, notes, notes.getChange().currentPatchSetId());
}
- public PatchSet get(ReviewDb db, ChangeNotes notes, PatchSet.Id psId)
- throws OrmException {
+ public PatchSet get(ReviewDb db, ChangeNotes notes, PatchSet.Id psId) throws OrmException {
if (!migration.readChanges()) {
return db.patchSets().get(psId);
}
@@ -73,13 +69,12 @@
return notes.load().getPatchSets().values();
}
- public ImmutableMap<PatchSet.Id, PatchSet> byChangeAsMap(ReviewDb db,
- ChangeNotes notes) throws OrmException {
+ public ImmutableMap<PatchSet.Id, PatchSet> byChangeAsMap(ReviewDb db, ChangeNotes notes)
+ throws OrmException {
if (!migration.readChanges()) {
- ImmutableMap.Builder<PatchSet.Id, PatchSet> result =
- ImmutableMap.builder();
- for (PatchSet ps : ChangeUtil.PS_ID_ORDER.sortedCopy(
- db.patchSets().byChange(notes.getChangeId()))) {
+ ImmutableMap.Builder<PatchSet.Id, PatchSet> result = ImmutableMap.builder();
+ for (PatchSet ps :
+ ChangeUtil.PS_ID_ORDER.sortedCopy(db.patchSets().byChange(notes.getChangeId()))) {
result.put(ps.getId(), ps);
}
return result.build();
@@ -87,9 +82,16 @@
return notes.load().getPatchSets();
}
- public PatchSet insert(ReviewDb db, RevWalk rw, ChangeUpdate update,
- PatchSet.Id psId, ObjectId commit, boolean draft,
- List<String> groups, String pushCertificate, String description)
+ public PatchSet insert(
+ ReviewDb db,
+ RevWalk rw,
+ ChangeUpdate update,
+ PatchSet.Id psId,
+ ObjectId commit,
+ boolean draft,
+ List<String> groups,
+ String pushCertificate,
+ String description)
throws OrmException, IOException {
checkNotNull(groups, "groups may not be null");
ensurePatchSetMatches(psId, update);
@@ -114,38 +116,40 @@
return ps;
}
- public void publish(ReviewDb db, ChangeUpdate update, PatchSet ps)
- throws OrmException {
+ public void publish(ReviewDb db, ChangeUpdate update, PatchSet ps) throws OrmException {
ensurePatchSetMatches(ps.getId(), update);
ps.setDraft(false);
update.setPatchSetState(PUBLISHED);
db.patchSets().update(Collections.singleton(ps));
}
- public void delete(ReviewDb db, ChangeUpdate update, PatchSet ps)
- throws OrmException {
+ public void delete(ReviewDb db, ChangeUpdate update, PatchSet ps) throws OrmException {
ensurePatchSetMatches(ps.getId(), update);
- checkArgument(ps.isDraft(),
- "cannot delete non-draft patch set %s", ps.getId());
+ checkArgument(ps.isDraft(), "cannot delete non-draft patch set %s", ps.getId());
update.setPatchSetState(PatchSetState.DELETED);
db.patchSets().delete(Collections.singleton(ps));
}
private void ensurePatchSetMatches(PatchSet.Id psId, ChangeUpdate update) {
Change.Id changeId = update.getChange().getId();
- checkArgument(psId.getParentKey().equals(changeId),
- "cannot modify patch set %s on update for change %s", psId, changeId);
+ checkArgument(
+ psId.getParentKey().equals(changeId),
+ "cannot modify patch set %s on update for change %s",
+ psId,
+ changeId);
if (update.getPatchSetId() != null) {
- checkArgument(update.getPatchSetId().equals(psId),
+ checkArgument(
+ update.getPatchSetId().equals(psId),
"cannot modify patch set %s on update for %s",
- psId, update.getPatchSetId());
+ psId,
+ update.getPatchSetId());
} else {
update.setPatchSetId(psId);
}
}
- public void setGroups(ReviewDb db, ChangeUpdate update, PatchSet ps,
- List<String> groups) throws OrmException {
+ public void setGroups(ReviewDb db, ChangeUpdate update, PatchSet ps, List<String> groups)
+ throws OrmException {
ps.setGroups(groups);
update.setGroups(groups);
db.patchSets().update(Collections.singleton(ps));
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/PeerDaemonUser.java b/gerrit-server/src/main/java/com/google/gerrit/server/PeerDaemonUser.java
index 6616a66..263bb50 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/PeerDaemonUser.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/PeerDaemonUser.java
@@ -18,7 +18,6 @@
import com.google.gerrit.server.account.GroupMembership;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
-
import java.net.SocketAddress;
/** Identity of a peer daemon process that isn't this JVM. */
@@ -33,8 +32,8 @@
private final SocketAddress peer;
@Inject
- protected PeerDaemonUser(CapabilityControl.Factory capabilityControlFactory,
- @Assisted SocketAddress peer) {
+ protected PeerDaemonUser(
+ CapabilityControl.Factory capabilityControlFactory, @Assisted SocketAddress peer) {
super(capabilityControlFactory);
this.peer = peer;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/PluginUser.java b/gerrit-server/src/main/java/com/google/gerrit/server/PluginUser.java
index 490ab07..13e04c5 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/PluginUser.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/PluginUser.java
@@ -28,8 +28,7 @@
@Inject
protected PluginUser(
- CapabilityControl.Factory capabilityControlFactory,
- @Assisted String pluginName) {
+ CapabilityControl.Factory capabilityControlFactory, @Assisted String pluginName) {
super(capabilityControlFactory);
this.pluginName = pluginName;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/ProjectUtil.java b/gerrit-server/src/main/java/com/google/gerrit/server/ProjectUtil.java
index 40c5242..f3ab21d 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/ProjectUtil.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/ProjectUtil.java
@@ -16,12 +16,10 @@
import com.google.gerrit.reviewdb.client.Branch;
import com.google.gerrit.server.git.GitRepositoryManager;
-
+import java.io.IOException;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
import org.eclipse.jgit.lib.Repository;
-import java.io.IOException;
-
public class ProjectUtil {
/**
@@ -29,16 +27,14 @@
*
* @param repoManager Git repository manager to open the git repository
* @param branch the branch for which it should be checked if it exists
- * @return {@code true} if the specified branch exists or if
- * {@code HEAD} points to this branch, otherwise
- * {@code false}
- * @throws RepositoryNotFoundException the repository of the branch's project
- * does not exist.
+ * @return {@code true} if the specified branch exists or if {@code HEAD} points to this branch,
+ * otherwise {@code false}
+ * @throws RepositoryNotFoundException the repository of the branch's project does not exist.
* @throws IOException error while retrieving the branch from the repository.
*/
- public static boolean branchExists(final GitRepositoryManager repoManager,
- final Branch.NameKey branch) throws RepositoryNotFoundException,
- IOException {
+ public static boolean branchExists(
+ final GitRepositoryManager repoManager, final Branch.NameKey branch)
+ throws RepositoryNotFoundException, IOException {
try (Repository repo = repoManager.openRepository(branch.getParentKey())) {
boolean exists = repo.getRefDatabase().exactRef(branch.get()) != null;
if (!exists) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/RemotePeer.java b/gerrit-server/src/main/java/com/google/gerrit/server/RemotePeer.java
index 77e6d43..4e7e04a 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/RemotePeer.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/RemotePeer.java
@@ -17,12 +17,10 @@
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import com.google.inject.BindingAnnotation;
-
import java.lang.annotation.Retention;
import java.net.SocketAddress;
/** Marker on a {@link SocketAddress} pointing to the remote client. */
@Retention(RUNTIME)
@BindingAnnotation
-public @interface RemotePeer {
-}
+public @interface RemotePeer {}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/RequestCleanup.java b/gerrit-server/src/main/java/com/google/gerrit/server/RequestCleanup.java
index 6e12346..72b361c 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/RequestCleanup.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/RequestCleanup.java
@@ -15,22 +15,16 @@
package com.google.gerrit.server;
import com.google.inject.servlet.RequestScoped;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
-
-/**
- * Registers cleanup activities to be completed when a scope ends.
- */
+/** Registers cleanup activities to be completed when a scope ends. */
@RequestScoped
public class RequestCleanup implements Runnable {
- private static final Logger log =
- LoggerFactory.getLogger(RequestCleanup.class);
+ private static final Logger log = LoggerFactory.getLogger(RequestCleanup.class);
private final List<Runnable> cleanup = new LinkedList<>();
private boolean ran;
@@ -49,7 +43,7 @@
public void run() {
synchronized (cleanup) {
ran = true;
- for (final Iterator<Runnable> i = cleanup.iterator(); i.hasNext();) {
+ for (final Iterator<Runnable> i = cleanup.iterator(); i.hasNext(); ) {
try {
i.next().run();
} catch (Throwable err) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/ReviewerRecommender.java b/gerrit-server/src/main/java/com/google/gerrit/server/ReviewerRecommender.java
index 91b568c..8728a08 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/ReviewerRecommender.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/ReviewerRecommender.java
@@ -43,12 +43,6 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
-
-import org.apache.commons.lang.mutable.MutableDouble;
-import org.eclipse.jgit.lib.Config;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumSet;
@@ -65,15 +59,20 @@
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;
+import org.apache.commons.lang.mutable.MutableDouble;
+import org.eclipse.jgit.lib.Config;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class ReviewerRecommender {
- private static final Logger log =
- LoggerFactory.getLogger(ReviewersUtil.class);
+ private static final Logger log = LoggerFactory.getLogger(ReviewersUtil.class);
private static final double BASE_REVIEWER_WEIGHT = 10;
private static final double BASE_OWNER_WEIGHT = 1;
private static final double BASE_COMMENT_WEIGHT = 0.5;
- private static final double[] WEIGHTS = new double[] {
- BASE_REVIEWER_WEIGHT, BASE_OWNER_WEIGHT, BASE_COMMENT_WEIGHT,};
+ private static final double[] WEIGHTS =
+ new double[] {
+ BASE_REVIEWER_WEIGHT, BASE_OWNER_WEIGHT, BASE_COMMENT_WEIGHT,
+ };
private static final long PLUGIN_QUERY_TIMEOUT = 500; //ms
private final ChangeQueryBuilder changeQueryBuilder;
@@ -85,7 +84,8 @@
private final ApprovalsUtil approvalsUtil;
@Inject
- ReviewerRecommender(ChangeQueryBuilder changeQueryBuilder,
+ ReviewerRecommender(
+ ChangeQueryBuilder changeQueryBuilder,
DynamicMap<ReviewerSuggestion> reviewerSuggestionPluginMap,
InternalChangeQuery internalChangeQuery,
WorkQueue workQueue,
@@ -105,7 +105,8 @@
public List<Account.Id> suggestReviewers(
ChangeNotes changeNotes,
- SuggestReviewers suggestReviewers, ProjectControl projectControl,
+ SuggestReviewers suggestReviewers,
+ ProjectControl projectControl,
List<Account.Id> candidateList)
throws OrmException {
String query = suggestReviewers.getQuery();
@@ -115,8 +116,7 @@
if (Strings.isNullOrEmpty(query)) {
reviewerScores = baseRankingForEmptyQuery(baseWeight);
} else {
- reviewerScores = baseRankingForCandidateList(
- candidateList, projectControl, baseWeight);
+ reviewerScores = baseRankingForCandidateList(candidateList, projectControl, baseWeight);
}
// Send the query along with a candidate list to all plugins and merge the
@@ -124,32 +124,41 @@
// can also return non-candidate account ids.
List<Callable<Set<SuggestedReviewer>>> tasks =
new ArrayList<>(reviewerSuggestionPluginMap.plugins().size());
- List<Double> weights =
- new ArrayList<>(reviewerSuggestionPluginMap.plugins().size());
+ List<Double> weights = new ArrayList<>(reviewerSuggestionPluginMap.plugins().size());
- for (DynamicMap.Entry<ReviewerSuggestion> plugin :
- reviewerSuggestionPluginMap) {
- tasks.add(() -> plugin.getProvider().get()
- .suggestReviewers(projectControl.getProject().getNameKey(),
- changeNotes.getChangeId(), query, reviewerScores.keySet()));
- String pluginWeight = config.getString("addReviewer",
- plugin.getPluginName() + "-" + plugin.getExportName(), "weight");
+ for (DynamicMap.Entry<ReviewerSuggestion> plugin : reviewerSuggestionPluginMap) {
+ tasks.add(
+ () ->
+ plugin
+ .getProvider()
+ .get()
+ .suggestReviewers(
+ projectControl.getProject().getNameKey(),
+ changeNotes.getChangeId(),
+ query,
+ reviewerScores.keySet()));
+ String pluginWeight =
+ config.getString(
+ "addReviewer", plugin.getPluginName() + "-" + plugin.getExportName(), "weight");
if (Strings.isNullOrEmpty(pluginWeight)) {
pluginWeight = "1";
}
try {
weights.add(Double.parseDouble(pluginWeight));
} catch (NumberFormatException e) {
- log.error("Exception while parsing weight for " +
- plugin.getPluginName() + "-" + plugin.getExportName(), e);
+ log.error(
+ "Exception while parsing weight for "
+ + plugin.getPluginName()
+ + "-"
+ + plugin.getExportName(),
+ e);
weights.add(1d);
}
}
try {
- List<Future<Set<SuggestedReviewer>>> futures = workQueue
- .getDefaultQueue()
- .invokeAll(tasks, PLUGIN_QUERY_TIMEOUT, TimeUnit.MILLISECONDS);
+ List<Future<Set<SuggestedReviewer>>> futures =
+ workQueue.getDefaultQueue().invokeAll(tasks, PLUGIN_QUERY_TIMEOUT, TimeUnit.MILLISECONDS);
Iterator<Double> weightIterator = weights.iterator();
for (Future<Set<SuggestedReviewer>> f : futures) {
double weight = weightIterator.next();
@@ -171,29 +180,30 @@
reviewerScores.remove(changeNotes.getChange().getOwner());
// Remove existing reviewers
- reviewerScores.keySet().removeAll(
- approvalsUtil.getReviewers(dbProvider.get(), changeNotes)
- .byState(REVIEWER));
+ reviewerScores
+ .keySet()
+ .removeAll(approvalsUtil.getReviewers(dbProvider.get(), changeNotes).byState(REVIEWER));
}
// Sort results
Stream<Entry<Account.Id, MutableDouble>> sorted =
- reviewerScores.entrySet().stream()
+ reviewerScores
+ .entrySet()
+ .stream()
.sorted(Collections.reverseOrder(Map.Entry.comparingByValue()));
- List<Account.Id> sortedSuggestions = sorted
- .map(Map.Entry::getKey)
- .collect(Collectors.toList());
+ List<Account.Id> sortedSuggestions = sorted.map(Map.Entry::getKey).collect(Collectors.toList());
return sortedSuggestions;
}
- private Map<Account.Id, MutableDouble> baseRankingForEmptyQuery(
- double baseWeight) throws OrmException{
+ private Map<Account.Id, MutableDouble> baseRankingForEmptyQuery(double baseWeight)
+ throws OrmException {
// Get the user's last 25 changes, check approvals
try {
- List<ChangeData> result = internalChangeQuery
- .setLimit(25)
- .setRequestedFields(ImmutableSet.of(ChangeField.REVIEWER.getName()))
- .query(changeQueryBuilder.owner("self"));
+ List<ChangeData> result =
+ internalChangeQuery
+ .setLimit(25)
+ .setRequestedFields(ImmutableSet.of(ChangeField.REVIEWER.getName()))
+ .query(changeQueryBuilder.owner("self"));
Map<Account.Id, MutableDouble> suggestions = new HashMap<>();
for (ChangeData cd : result) {
for (PatchSetApproval approval : cd.currentApprovals()) {
@@ -214,9 +224,8 @@
}
private Map<Account.Id, MutableDouble> baseRankingForCandidateList(
- List<Account.Id> candidates,
- ProjectControl projectControl,
- double baseWeight) throws OrmException {
+ List<Account.Id> candidates, ProjectControl projectControl, double baseWeight)
+ throws OrmException {
// Get each reviewer's activity based on number of applied labels
// (weighted 10d), number of comments (weighted 0.5d) and number of owned
// changes (weighted 1d).
@@ -232,21 +241,18 @@
// Get all labels for this project and create a compound OR query to
// fetch all changes where users have applied one of these labels
- List<LabelType> labelTypes =
- projectControl.getLabelTypes().getLabelTypes();
- List<Predicate<ChangeData>> labelPredicates =
- new ArrayList<>(labelTypes.size());
+ List<LabelType> labelTypes = projectControl.getLabelTypes().getLabelTypes();
+ List<Predicate<ChangeData>> labelPredicates = new ArrayList<>(labelTypes.size());
for (LabelType type : labelTypes) {
- labelPredicates
- .add(changeQueryBuilder.label(type.getName() + ",user=" + id));
+ labelPredicates.add(changeQueryBuilder.label(type.getName() + ",user=" + id));
}
Predicate<ChangeData> reviewerQuery =
Predicate.and(projectQuery, Predicate.or(labelPredicates));
- Predicate<ChangeData> ownerQuery = Predicate.and(projectQuery,
- changeQueryBuilder.owner(id.toString()));
- Predicate<ChangeData> commentedByQuery = Predicate.and(projectQuery,
- changeQueryBuilder.commentby(id.toString()));
+ Predicate<ChangeData> ownerQuery =
+ Predicate.and(projectQuery, changeQueryBuilder.owner(id.toString()));
+ Predicate<ChangeData> commentedByQuery =
+ Predicate.and(projectQuery, changeQueryBuilder.commentby(id.toString()));
predicates.add(reviewerQuery);
predicates.add(ownerQuery);
@@ -259,10 +265,8 @@
}
}
- List<List<ChangeData>> result = internalChangeQuery
- .setLimit(25)
- .setRequestedFields(ImmutableSet.of())
- .query(predicates);
+ List<List<ChangeData>> result =
+ internalChangeQuery.setLimit(25).setRequestedFields(ImmutableSet.of()).query(predicates);
Iterator<List<ChangeData>> queryResultIterator = result.iterator();
Iterator<Account.Id> reviewersIterator = reviewers.keySet().iterator();
@@ -275,8 +279,7 @@
currentId = reviewersIterator.next();
}
- reviewers.get(currentId).add(WEIGHTS[i % WEIGHTS.length] *
- baseWeight * currentResult.size());
+ reviewers.get(currentId).add(WEIGHTS[i % WEIGHTS.length] * baseWeight * currentResult.size());
i++;
}
return reviewers;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/ReviewerSet.java b/gerrit-server/src/main/java/com/google/gerrit/server/ReviewerSet.java
index 5e0f77b..67b1d9d 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/ReviewerSet.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/ReviewerSet.java
@@ -25,33 +25,34 @@
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.reviewdb.client.PatchSetApproval;
import com.google.gerrit.server.notedb.ReviewerStateInternal;
-
import java.sql.Timestamp;
/**
* Set of reviewers on a change.
- * <p>
- * A given account may appear in multiple states and at different timestamps. No
- * reviewers with state {@link ReviewerStateInternal#REMOVED} are ever exposed
- * by this interface.
+ *
+ * <p>A given account may appear in multiple states and at different timestamps. No reviewers with
+ * state {@link ReviewerStateInternal#REMOVED} are ever exposed by this interface.
*/
public class ReviewerSet {
- private static final ReviewerSet EMPTY = new ReviewerSet(
- ImmutableTable.<ReviewerStateInternal, Account.Id, Timestamp>of());
+ private static final ReviewerSet EMPTY =
+ new ReviewerSet(ImmutableTable.<ReviewerStateInternal, Account.Id, Timestamp>of());
- public static ReviewerSet fromApprovals(
- Iterable<PatchSetApproval> approvals) {
+ public static ReviewerSet fromApprovals(Iterable<PatchSetApproval> approvals) {
PatchSetApproval first = null;
- Table<ReviewerStateInternal, Account.Id, Timestamp> reviewers =
- HashBasedTable.create();
+ Table<ReviewerStateInternal, Account.Id, Timestamp> reviewers = HashBasedTable.create();
for (PatchSetApproval psa : approvals) {
if (first == null) {
first = psa;
} else {
checkArgument(
- first.getKey().getParentKey().getParentKey().equals(
- psa.getKey().getParentKey().getParentKey()),
- "multiple change IDs: %s, %s", first.getKey(), psa.getKey());
+ first
+ .getKey()
+ .getParentKey()
+ .getParentKey()
+ .equals(psa.getKey().getParentKey().getParentKey()),
+ "multiple change IDs: %s, %s",
+ first.getKey(),
+ psa.getKey());
}
Account.Id id = psa.getAccountId();
reviewers.put(REVIEWER, id, psa.getGranted());
@@ -62,8 +63,7 @@
return new ReviewerSet(reviewers);
}
- public static ReviewerSet fromTable(
- Table<ReviewerStateInternal, Account.Id, Timestamp> table) {
+ public static ReviewerSet fromTable(Table<ReviewerStateInternal, Account.Id, Timestamp> table) {
return new ReviewerSet(table);
}
@@ -71,8 +71,7 @@
return EMPTY;
}
- private final ImmutableTable<ReviewerStateInternal, Account.Id, Timestamp>
- table;
+ private final ImmutableTable<ReviewerStateInternal, Account.Id, Timestamp> table;
private ImmutableSet<Account.Id> accounts;
private ReviewerSet(Table<ReviewerStateInternal, Account.Id, Timestamp> table) {
@@ -91,8 +90,7 @@
return table.row(state).keySet();
}
- public ImmutableTable<ReviewerStateInternal, Account.Id, Timestamp>
- asTable() {
+ public ImmutableTable<ReviewerStateInternal, Account.Id, Timestamp> asTable() {
return table;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/ReviewerStatusUpdate.java b/gerrit-server/src/main/java/com/google/gerrit/server/ReviewerStatusUpdate.java
index bbe4013..c4f3e2a 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/ReviewerStatusUpdate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/ReviewerStatusUpdate.java
@@ -17,20 +17,21 @@
import com.google.auto.value.AutoValue;
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.server.notedb.ReviewerStateInternal;
-
import java.sql.Timestamp;
/** Change to a reviewer's status. */
@AutoValue
public abstract class ReviewerStatusUpdate {
public static ReviewerStatusUpdate create(
- Timestamp ts, Account.Id updatedBy, Account.Id reviewer,
- ReviewerStateInternal state) {
+ Timestamp ts, Account.Id updatedBy, Account.Id reviewer, ReviewerStateInternal state) {
return new AutoValue_ReviewerStatusUpdate(ts, updatedBy, reviewer, state);
}
public abstract Timestamp date();
+
public abstract Account.Id updatedBy();
+
public abstract Account.Id reviewer();
+
public abstract ReviewerStateInternal state();
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/ReviewersUtil.java b/gerrit-server/src/main/java/com/google/gerrit/server/ReviewersUtil.java
index a848c6c..7b4777e 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/ReviewersUtil.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/ReviewersUtil.java
@@ -49,7 +49,6 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
@@ -69,30 +68,30 @@
@Inject
Metrics(MetricMaker metricMaker) {
- queryAccountsLatency = metricMaker.newTimer(
- "reviewer_suggestion/query_accounts",
- new Description(
- "Latency for querying accounts for reviewer suggestion")
- .setCumulative()
- .setUnit(Units.MILLISECONDS));
- recommendAccountsLatency = metricMaker.newTimer(
- "reviewer_suggestion/recommend_accounts",
- new Description(
- "Latency for recommending accounts for reviewer suggestion")
- .setCumulative()
- .setUnit(Units.MILLISECONDS));
- loadAccountsLatency = metricMaker.newTimer(
- "reviewer_suggestion/load_accounts",
- new Description(
- "Latency for loading accounts for reviewer suggestion")
- .setCumulative()
- .setUnit(Units.MILLISECONDS));
- queryGroupsLatency = metricMaker.newTimer(
- "reviewer_suggestion/query_groups",
- new Description(
- "Latency for querying groups for reviewer suggestion")
- .setCumulative()
- .setUnit(Units.MILLISECONDS));
+ queryAccountsLatency =
+ metricMaker.newTimer(
+ "reviewer_suggestion/query_accounts",
+ new Description("Latency for querying accounts for reviewer suggestion")
+ .setCumulative()
+ .setUnit(Units.MILLISECONDS));
+ recommendAccountsLatency =
+ metricMaker.newTimer(
+ "reviewer_suggestion/recommend_accounts",
+ new Description("Latency for recommending accounts for reviewer suggestion")
+ .setCumulative()
+ .setUnit(Units.MILLISECONDS));
+ loadAccountsLatency =
+ metricMaker.newTimer(
+ "reviewer_suggestion/load_accounts",
+ new Description("Latency for loading accounts for reviewer suggestion")
+ .setCumulative()
+ .setUnit(Units.MILLISECONDS));
+ queryGroupsLatency =
+ metricMaker.newTimer(
+ "reviewer_suggestion/query_groups",
+ new Description("Latency for querying groups for reviewer suggestion")
+ .setCumulative()
+ .setUnit(Units.MILLISECONDS));
}
}
@@ -110,7 +109,8 @@
private final Metrics metrics;
@Inject
- ReviewersUtil(AccountLoader.Factory accountLoaderFactory,
+ ReviewersUtil(
+ AccountLoader.Factory accountLoaderFactory,
AccountQueryBuilder accountQueryBuilder,
AccountQueryProcessor accountQueryProcessor,
GroupBackend groupBackend,
@@ -134,9 +134,12 @@
boolean isVisibleTo(Account.Id account) throws OrmException;
}
- public List<SuggestedReviewerInfo> suggestReviewers(ChangeNotes changeNotes,
- SuggestReviewers suggestReviewers, ProjectControl projectControl,
- VisibilityControl visibilityControl, boolean excludeGroups)
+ public List<SuggestedReviewerInfo> suggestReviewers(
+ ChangeNotes changeNotes,
+ SuggestReviewers suggestReviewers,
+ ProjectControl projectControl,
+ VisibilityControl visibilityControl,
+ boolean excludeGroups)
throws IOException, OrmException {
String query = suggestReviewers.getQuery();
int limit = suggestReviewers.getLimit();
@@ -150,17 +153,19 @@
candidateList = suggestAccounts(suggestReviewers, visibilityControl);
}
- List<Account.Id> sortedRecommendations = recommendAccounts(changeNotes,
- suggestReviewers, projectControl, candidateList);
- List<SuggestedReviewerInfo> suggestedReviewer =
- loadAccounts(sortedRecommendations);
+ List<Account.Id> sortedRecommendations =
+ recommendAccounts(changeNotes, suggestReviewers, projectControl, candidateList);
+ List<SuggestedReviewerInfo> suggestedReviewer = loadAccounts(sortedRecommendations);
- if (!excludeGroups && suggestedReviewer.size() < limit
- && !Strings.isNullOrEmpty(query)) {
+ if (!excludeGroups && suggestedReviewer.size() < limit && !Strings.isNullOrEmpty(query)) {
// Add groups at the end as individual accounts are usually more
// important.
- suggestedReviewer.addAll(suggestAccountGroups(suggestReviewers,
- projectControl, visibilityControl, limit - suggestedReviewer.size()));
+ suggestedReviewer.addAll(
+ suggestAccountGroups(
+ suggestReviewers,
+ projectControl,
+ visibilityControl,
+ limit - suggestedReviewer.size()));
}
if (suggestedReviewer.size() <= limit) {
@@ -169,14 +174,15 @@
return suggestedReviewer.subList(0, limit);
}
- private List<Account.Id> suggestAccounts(SuggestReviewers suggestReviewers,
- VisibilityControl visibilityControl) throws OrmException {
+ private List<Account.Id> suggestAccounts(
+ SuggestReviewers suggestReviewers, VisibilityControl visibilityControl) throws OrmException {
try (Timer0.Context ctx = metrics.queryAccountsLatency.start()) {
try {
Set<Account.Id> matches = new HashSet<>();
- QueryResult<AccountState> result = accountQueryProcessor
- .setLimit(suggestReviewers.getLimit() * CANDIDATE_LIST_MULTIPLIER)
- .query(accountQueryBuilder.defaultQuery(suggestReviewers.getQuery()));
+ QueryResult<AccountState> result =
+ accountQueryProcessor
+ .setLimit(suggestReviewers.getLimit() * CANDIDATE_LIST_MULTIPLIER)
+ .query(accountQueryBuilder.defaultQuery(suggestReviewers.getQuery()));
for (AccountState accountState : result.entities()) {
Account.Id id = accountState.getAccount().getId();
if (visibilityControl.isVisibleTo(id)) {
@@ -190,48 +196,56 @@
}
}
- private List<Account.Id> recommendAccounts(ChangeNotes changeNotes,
- SuggestReviewers suggestReviewers, ProjectControl projectControl,
- List<Account.Id> candidateList) throws OrmException {
+ private List<Account.Id> recommendAccounts(
+ ChangeNotes changeNotes,
+ SuggestReviewers suggestReviewers,
+ ProjectControl projectControl,
+ List<Account.Id> candidateList)
+ throws OrmException {
try (Timer0.Context ctx = metrics.recommendAccountsLatency.start()) {
- return reviewerRecommender.suggestReviewers(changeNotes, suggestReviewers,
- projectControl, candidateList);
+ return reviewerRecommender.suggestReviewers(
+ changeNotes, suggestReviewers, projectControl, candidateList);
}
}
private List<SuggestedReviewerInfo> loadAccounts(List<Account.Id> accountIds)
throws OrmException {
try (Timer0.Context ctx = metrics.loadAccountsLatency.start()) {
- List<SuggestedReviewerInfo> reviewer = accountIds.stream()
- .map(accountLoader::get)
- .filter(Objects::nonNull)
- .map(a -> {
- SuggestedReviewerInfo info = new SuggestedReviewerInfo();
- info.account = a;
- info.count = 1;
- return info;
- }).collect(toList());
+ List<SuggestedReviewerInfo> reviewer =
+ accountIds
+ .stream()
+ .map(accountLoader::get)
+ .filter(Objects::nonNull)
+ .map(
+ a -> {
+ SuggestedReviewerInfo info = new SuggestedReviewerInfo();
+ info.account = a;
+ info.count = 1;
+ return info;
+ })
+ .collect(toList());
accountLoader.fill();
return reviewer;
}
}
private List<SuggestedReviewerInfo> suggestAccountGroups(
- SuggestReviewers suggestReviewers, ProjectControl projectControl,
- VisibilityControl visibilityControl, int limit)
- throws OrmException, IOException {
+ SuggestReviewers suggestReviewers,
+ ProjectControl projectControl,
+ VisibilityControl visibilityControl,
+ int limit)
+ throws OrmException, IOException {
try (Timer0.Context ctx = metrics.queryGroupsLatency.start()) {
List<SuggestedReviewerInfo> groups = new ArrayList<>();
- for (GroupReference g : suggestAccountGroups(suggestReviewers,
- projectControl)) {
- GroupAsReviewer result = suggestGroupAsReviewer(suggestReviewers,
- projectControl.getProject(), g, visibilityControl);
+ for (GroupReference g : suggestAccountGroups(suggestReviewers, projectControl)) {
+ GroupAsReviewer result =
+ suggestGroupAsReviewer(
+ suggestReviewers, projectControl.getProject(), g, visibilityControl);
if (result.allowed || result.allowedWithConfirmation) {
GroupBaseInfo info = new GroupBaseInfo();
info.id = Url.encode(g.getUUID().get());
info.name = g.getName();
- SuggestedReviewerInfo suggestedReviewerInfo =
- new SuggestedReviewerInfo();
+ SuggestedReviewerInfo suggestedReviewerInfo = new SuggestedReviewerInfo();
suggestedReviewerInfo.group = info;
suggestedReviewerInfo.count = result.size;
if (result.allowedWithConfirmation) {
@@ -250,8 +264,8 @@
private List<GroupReference> suggestAccountGroups(
SuggestReviewers suggestReviewers, ProjectControl ctl) {
return Lists.newArrayList(
- Iterables.limit(groupBackend.suggest(suggestReviewers.getQuery(), ctl),
- suggestReviewers.getLimit()));
+ Iterables.limit(
+ groupBackend.suggest(suggestReviewers.getQuery(), ctl), suggestReviewers.getLimit()));
}
private static class GroupAsReviewer {
@@ -262,21 +276,23 @@
private GroupAsReviewer suggestGroupAsReviewer(
SuggestReviewers suggestReviewers,
- Project project, GroupReference group,
- VisibilityControl visibilityControl) throws OrmException, IOException {
+ Project project,
+ GroupReference group,
+ VisibilityControl visibilityControl)
+ throws OrmException, IOException {
GroupAsReviewer result = new GroupAsReviewer();
int maxAllowed = suggestReviewers.getMaxAllowed();
- int maxAllowedWithoutConfirmation =
- suggestReviewers.getMaxAllowedWithoutConfirmation();
+ int maxAllowedWithoutConfirmation = suggestReviewers.getMaxAllowedWithoutConfirmation();
if (!PostReviewers.isLegalReviewerGroup(group.getUUID())) {
return result;
}
try {
- Set<Account> members = groupMembersFactory
- .create(currentUser.get())
- .listAccounts(group.getUUID(), project.getNameKey());
+ Set<Account> members =
+ groupMembersFactory
+ .create(currentUser.get())
+ .listAccounts(group.getUUID(), project.getNameKey());
if (members.isEmpty()) {
return result;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/Sequences.java b/gerrit-server/src/main/java/com/google/gerrit/server/Sequences.java
index 9448ceb..6b3a58f 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/Sequences.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/Sequences.java
@@ -28,11 +28,9 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.lib.Config;
-
import java.util.ArrayList;
import java.util.List;
+import org.eclipse.jgit.lib.Config;
@SuppressWarnings("deprecation")
@Singleton
@@ -42,7 +40,8 @@
private final RepoSequence changeSeq;
@Inject
- Sequences(@GerritServerConfig Config cfg,
+ Sequences(
+ @GerritServerConfig Config cfg,
final Provider<ReviewDb> db,
NotesMigration migration,
GitRepositoryManager repoManager,
@@ -51,17 +50,18 @@
this.migration = migration;
final int gap = cfg.getInt("noteDb", "changes", "initialSequenceGap", 0);
- changeSeq = new RepoSequence(
- repoManager,
- allProjects,
- "changes",
- new RepoSequence.Seed() {
- @Override
- public int get() throws OrmException {
- return db.get().nextChangeId() + gap;
- }
- },
- cfg.getInt("noteDb", "changes", "sequenceBatchSize", 20));
+ changeSeq =
+ new RepoSequence(
+ repoManager,
+ allProjects,
+ "changes",
+ new RepoSequence.Seed() {
+ @Override
+ public int get() throws OrmException {
+ return db.get().nextChangeId() + gap;
+ }
+ },
+ cfg.getInt("noteDb", "changes", "sequenceBatchSize", 20));
}
public int nextChangeId() throws OrmException {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/StarredChangesUtil.java b/gerrit-server/src/main/java/com/google/gerrit/server/StarredChangesUtil.java
index 5d9fbd6..8c46663 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/StarredChangesUtil.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/StarredChangesUtil.java
@@ -45,7 +45,13 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
+import java.io.IOException;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.SortedSet;
+import java.util.TreeSet;
import org.eclipse.jgit.lib.BatchRefUpdate;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.NullProgressMonitor;
@@ -63,14 +69,6 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import java.util.SortedSet;
-import java.util.TreeSet;
-
@Singleton
public class StarredChangesUtil {
@AutoValue
@@ -96,6 +94,7 @@
}
public abstract Account.Id accountId();
+
public abstract String label();
@Override
@@ -111,11 +110,12 @@
private static StarRef create(Ref ref, Iterable<String> labels) {
return new AutoValue_StarredChangesUtil_StarRef(
- checkNotNull(ref),
- ImmutableSortedSet.copyOf(labels));
+ checkNotNull(ref), ImmutableSortedSet.copyOf(labels));
}
- @Nullable public abstract Ref ref();
+ @Nullable
+ public abstract Ref ref();
+
public abstract ImmutableSortedSet<String> labels();
public ObjectId objectId() {
@@ -128,15 +128,14 @@
static IllegalLabelException invalidLabels(Set<String> invalidLabels) {
return new IllegalLabelException(
- String.format("invalid labels: %s",
- Joiner.on(", ").join(invalidLabels)));
+ String.format("invalid labels: %s", Joiner.on(", ").join(invalidLabels)));
}
- static IllegalLabelException mutuallyExclusiveLabels(String label1,
- String label2) {
+ static IllegalLabelException mutuallyExclusiveLabels(String label1, String label2) {
return new IllegalLabelException(
- String.format("The labels %s and %s are mutually exclusive."
- + " Only one of them can be set.", label1, label2));
+ String.format(
+ "The labels %s and %s are mutually exclusive." + " Only one of them can be set.",
+ label1, label2));
}
IllegalLabelException(String message) {
@@ -144,8 +143,7 @@
}
}
- private static final Logger log =
- LoggerFactory.getLogger(StarredChangesUtil.class);
+ private static final Logger log = LoggerFactory.getLogger(StarredChangesUtil.class);
public static final String DEFAULT_LABEL = "star";
public static final String IGNORE_LABEL = "ignore";
@@ -160,7 +158,8 @@
private final Provider<InternalChangeQuery> queryProvider;
@Inject
- StarredChangesUtil(GitRepositoryManager repoManager,
+ StarredChangesUtil(
+ GitRepositoryManager repoManager,
AllUsersName allUsers,
Provider<ReviewDb> dbProvider,
@GerritPersonIdent PersonIdent serverIdent,
@@ -174,21 +173,26 @@
this.queryProvider = queryProvider;
}
- public ImmutableSortedSet<String> getLabels(Account.Id accountId,
- Change.Id changeId) throws OrmException {
+ public ImmutableSortedSet<String> getLabels(Account.Id accountId, Change.Id changeId)
+ throws OrmException {
try (Repository repo = repoManager.openRepository(allUsers)) {
- return readLabels(repo, RefNames.refsStarredChanges(changeId, accountId))
- .labels();
+ return readLabels(repo, RefNames.refsStarredChanges(changeId, accountId)).labels();
} catch (IOException e) {
throw new OrmException(
- String.format("Reading stars from change %d for account %d failed",
- changeId.get(), accountId.get()), e);
+ String.format(
+ "Reading stars from change %d for account %d failed",
+ changeId.get(), accountId.get()),
+ e);
}
}
- public ImmutableSortedSet<String> star(Account.Id accountId,
- Project.NameKey project, Change.Id changeId, Set<String> labelsToAdd,
- Set<String> labelsToRemove) throws OrmException {
+ public ImmutableSortedSet<String> star(
+ Account.Id accountId,
+ Project.NameKey project,
+ Change.Id changeId,
+ Set<String> labelsToAdd,
+ Set<String> labelsToRemove)
+ throws OrmException {
try (Repository repo = repoManager.openRepository(allUsers)) {
String refName = RefNames.refsStarredChanges(changeId, accountId);
StarRef old = readLabels(repo, refName);
@@ -212,13 +216,12 @@
return ImmutableSortedSet.copyOf(labels);
} catch (IOException e) {
throw new OrmException(
- String.format("Star change %d for account %d failed",
- changeId.get(), accountId.get()), e);
+ String.format("Star change %d for account %d failed", changeId.get(), accountId.get()),
+ e);
}
}
- public void unstarAll(Project.NameKey project, Change.Id changeId)
- throws OrmException {
+ public void unstarAll(Project.NameKey project, Change.Id changeId) throws OrmException {
try (Repository repo = repoManager.openRepository(allUsers);
RevWalk rw = new RevWalk(repo)) {
BatchRefUpdate batchUpdate = repo.getRefDatabase().newBatchUpdate();
@@ -228,48 +231,43 @@
for (Account.Id accountId : byChangeFromIndex(changeId).keySet()) {
String refName = RefNames.refsStarredChanges(changeId, accountId);
Ref ref = repo.getRefDatabase().getRef(refName);
- batchUpdate.addCommand(new ReceiveCommand(ref.getObjectId(),
- ObjectId.zeroId(), refName));
+ batchUpdate.addCommand(new ReceiveCommand(ref.getObjectId(), ObjectId.zeroId(), refName));
}
batchUpdate.execute(rw, NullProgressMonitor.INSTANCE);
for (ReceiveCommand command : batchUpdate.getCommands()) {
if (command.getResult() != ReceiveCommand.Result.OK) {
- throw new IOException(String.format(
- "Unstar change %d failed, ref %s could not be deleted: %s",
- changeId.get(), command.getRefName(), command.getResult()));
+ throw new IOException(
+ String.format(
+ "Unstar change %d failed, ref %s could not be deleted: %s",
+ changeId.get(), command.getRefName(), command.getResult()));
}
}
indexer.index(dbProvider.get(), project, changeId);
} catch (IOException e) {
- throw new OrmException(
- String.format("Unstar change %d failed", changeId.get()), e);
+ throw new OrmException(String.format("Unstar change %d failed", changeId.get()), e);
}
}
- public ImmutableMap<Account.Id, StarRef> byChange(Change.Id changeId)
- throws OrmException {
+ public ImmutableMap<Account.Id, StarRef> byChange(Change.Id changeId) throws OrmException {
try (Repository repo = repoManager.openRepository(allUsers)) {
- ImmutableMap.Builder<Account.Id, StarRef> builder =
- ImmutableMap.builder();
- for (String refPart : getRefNames(repo,
- RefNames.refsStarredChangesPrefix(changeId))) {
+ ImmutableMap.Builder<Account.Id, StarRef> builder = ImmutableMap.builder();
+ for (String refPart : getRefNames(repo, RefNames.refsStarredChangesPrefix(changeId))) {
Integer id = Ints.tryParse(refPart);
if (id == null) {
continue;
}
Account.Id accountId = new Account.Id(id);
- builder.put(accountId,
- readLabels(repo, RefNames.refsStarredChanges(changeId, accountId)));
+ builder.put(accountId, readLabels(repo, RefNames.refsStarredChanges(changeId, accountId)));
}
return builder.build();
} catch (IOException e) {
- throw new OrmException(String.format(
- "Get accounts that starred change %d failed", changeId.get()), e);
+ throw new OrmException(
+ String.format("Get accounts that starred change %d failed", changeId.get()), e);
}
}
- public Set<Account.Id> byChange(final Change.Id changeId,
- final String label) throws OrmException {
+ public Set<Account.Id> byChange(final Change.Id changeId, final String label)
+ throws OrmException {
try (Repository repo = repoManager.openRepository(allUsers)) {
return getRefNames(repo, RefNames.refsStarredChangesPrefix(changeId))
.stream()
@@ -278,57 +276,53 @@
.collect(toSet());
} catch (IOException e) {
throw new OrmException(
- String.format("Get accounts that starred change %d failed",
- changeId.get()), e);
+ String.format("Get accounts that starred change %d failed", changeId.get()), e);
}
}
@Deprecated
// To be used only for IsStarredByLegacyPredicate.
- public Set<Change.Id> byAccount(final Account.Id accountId,
- final String label) throws OrmException {
+ public Set<Change.Id> byAccount(final Account.Id accountId, final String label)
+ throws OrmException {
try (Repository repo = repoManager.openRepository(allUsers)) {
- return getRefNames(repo, RefNames.REFS_STARRED_CHANGES).stream()
+ return getRefNames(repo, RefNames.REFS_STARRED_CHANGES)
+ .stream()
.filter(refPart -> refPart.endsWith("/" + accountId.get()))
.map(Change.Id::fromRefPart)
.filter(changeId -> hasStar(repo, changeId, accountId, label))
.collect(toSet());
} catch (IOException e) {
throw new OrmException(
- String.format("Get changes that were starred by %d failed",
- accountId.get()), e);
+ String.format("Get changes that were starred by %d failed", accountId.get()), e);
}
}
- private boolean hasStar(Repository repo, Change.Id changeId,
- Account.Id accountId, String label) {
+ private boolean hasStar(Repository repo, Change.Id changeId, Account.Id accountId, String label) {
try {
- return readLabels(repo,
- RefNames.refsStarredChanges(changeId, accountId)).labels()
- .contains(label);
+ return readLabels(repo, RefNames.refsStarredChanges(changeId, accountId))
+ .labels()
+ .contains(label);
} catch (IOException e) {
- log.error(String.format(
- "Cannot query stars by account %d on change %d",
- accountId.get(), changeId.get()), e);
+ log.error(
+ String.format(
+ "Cannot query stars by account %d on change %d", accountId.get(), changeId.get()),
+ e);
return false;
}
}
- public ImmutableListMultimap<Account.Id, String> byChangeFromIndex(
- Change.Id changeId) throws OrmException {
- Set<String> fields = ImmutableSet.of(
- ChangeField.ID.getName(),
- ChangeField.STAR.getName());
- List<ChangeData> changeData = queryProvider.get().setRequestedFields(fields)
- .byLegacyChangeId(changeId);
+ public ImmutableListMultimap<Account.Id, String> byChangeFromIndex(Change.Id changeId)
+ throws OrmException {
+ Set<String> fields = ImmutableSet.of(ChangeField.ID.getName(), ChangeField.STAR.getName());
+ List<ChangeData> changeData =
+ queryProvider.get().setRequestedFields(fields).byLegacyChangeId(changeId);
if (changeData.size() != 1) {
throw new NoSuchChangeException(changeId);
}
return changeData.get(0).stars();
}
- private static Set<String> getRefNames(Repository repo, String prefix)
- throws IOException {
+ private static Set<String> getRefNames(Repository repo, String prefix) throws IOException {
RefDatabase refDb = repo.getRefDatabase();
return refDb.getRefs(prefix).keySet();
}
@@ -338,15 +332,16 @@
Ref ref = repo.exactRef(RefNames.refsStarredChanges(changeId, accountId));
return ref != null ? ref.getObjectId() : ObjectId.zeroId();
} catch (IOException e) {
- log.error(String.format(
- "Getting star object ID for account %d on change %d failed",
- accountId.get(), changeId.get()), e);
+ log.error(
+ String.format(
+ "Getting star object ID for account %d on change %d failed",
+ accountId.get(), changeId.get()),
+ e);
return ObjectId.zeroId();
}
}
- private static StarRef readLabels(Repository repo, String refName)
- throws IOException {
+ private static StarRef readLabels(Repository repo, String refName) throws IOException {
Ref ref = repo.exactRef(refName);
if (ref == null) {
return StarRef.MISSING;
@@ -356,7 +351,8 @@
ObjectLoader obj = reader.open(ref.getObjectId(), Constants.OBJ_BLOB);
return StarRef.create(
ref,
- Splitter.on(CharMatcher.whitespace()).omitEmptyStrings()
+ Splitter.on(CharMatcher.whitespace())
+ .omitEmptyStrings()
.split(new String(obj.getCachedBytes(Integer.MAX_VALUE), UTF_8)));
}
}
@@ -365,13 +361,10 @@
throws IOException {
validateLabels(labels);
try (ObjectInserter oi = repo.newObjectInserter()) {
- ObjectId id = oi.insert(
- Constants.OBJ_BLOB,
- labels.stream()
- .sorted()
- .distinct()
- .collect(joining("\n"))
- .getBytes(UTF_8));
+ ObjectId id =
+ oi.insert(
+ Constants.OBJ_BLOB,
+ labels.stream().sorted().distinct().collect(joining("\n")).getBytes(UTF_8));
oi.flush();
return id;
}
@@ -379,8 +372,7 @@
private static void checkMutuallyExclusiveLabels(Set<String> labels) {
if (labels.containsAll(ImmutableSet.of(DEFAULT_LABEL, IGNORE_LABEL))) {
- throw IllegalLabelException.mutuallyExclusiveLabels(DEFAULT_LABEL,
- IGNORE_LABEL);
+ throw IllegalLabelException.mutuallyExclusiveLabels(DEFAULT_LABEL, IGNORE_LABEL);
}
}
@@ -400,9 +392,9 @@
}
}
- private void updateLabels(Repository repo, String refName,
- ObjectId oldObjectId, Collection<String> labels)
- throws IOException, OrmException {
+ private void updateLabels(
+ Repository repo, String refName, ObjectId oldObjectId, Collection<String> labels)
+ throws IOException, OrmException {
try (RevWalk rw = new RevWalk(repo)) {
RefUpdate u = repo.updateRef(refName);
u.setExpectedOldObjectId(oldObjectId);
@@ -424,8 +416,7 @@
case REJECTED_CURRENT_BRANCH:
case RENAMED:
throw new OrmException(
- String.format("Update star labels on ref %s failed: %s", refName,
- result.name()));
+ String.format("Update star labels on ref %s failed: %s", refName, result.name()));
}
}
}
@@ -450,8 +441,8 @@
case REJECTED:
case REJECTED_CURRENT_BRANCH:
case RENAMED:
- throw new OrmException(String.format("Delete star ref %s failed: %s",
- refName, result.name()));
+ throw new OrmException(
+ String.format("Delete star ref %s failed: %s", refName, result.name()));
}
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/StartupCheck.java b/gerrit-server/src/main/java/com/google/gerrit/server/StartupCheck.java
index 2a7e4c9..196ca5b 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/StartupCheck.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/StartupCheck.java
@@ -16,16 +16,12 @@
import com.google.gerrit.extensions.events.LifecycleListener;
-/**
- * Check executed on Gerrit startup.
- */
+/** Check executed on Gerrit startup. */
public interface StartupCheck {
/**
- * Performs Gerrit startup check, can abort startup by throwing
- * {@link StartupException}.
- * <p>
- * Called on Gerrit startup after all {@link LifecycleListener} have been
- * invoked.
+ * Performs Gerrit startup check, can abort startup by throwing {@link StartupException}.
+ *
+ * <p>Called on Gerrit startup after all {@link LifecycleListener} have been invoked.
*
* @throws StartupException thrown if Gerrit startup should be aborted
*/
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/StartupChecks.java b/gerrit-server/src/main/java/com/google/gerrit/server/StartupChecks.java
index 0a208fe..9df2604 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/StartupChecks.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/StartupChecks.java
@@ -29,10 +29,8 @@
protected void configure() {
DynamicSet.setOf(binder(), StartupCheck.class);
listener().to(StartupChecks.class);
- DynamicSet.bind(binder(), StartupCheck.class)
- .to(UniversalGroupBackend.ConfigCheck.class);
- DynamicSet.bind(binder(), StartupCheck.class)
- .to(SystemGroupBackend.NameCheck.class);
+ DynamicSet.bind(binder(), StartupCheck.class).to(UniversalGroupBackend.ConfigCheck.class);
+ DynamicSet.bind(binder(), StartupCheck.class).to(SystemGroupBackend.NameCheck.class);
}
}
@@ -51,6 +49,5 @@
}
@Override
- public void stop() {
- }
+ public void stop() {}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/StringUtil.java b/gerrit-server/src/main/java/com/google/gerrit/server/StringUtil.java
index 0aef9e9..83b6ec6 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/StringUtil.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/StringUtil.java
@@ -16,22 +16,21 @@
public class StringUtil {
/**
- * An array of the string representations that should be used in place
- * of the non-printable characters in the beginning of the ASCII table
- * when escaping a string. The index of each element in the array
- * corresponds to its ASCII value, i.e. the string representation of
- * ASCII 0 is found in the first element of this array.
+ * An array of the string representations that should be used in place of the non-printable
+ * characters in the beginning of the ASCII table when escaping a string. The index of each
+ * element in the array corresponds to its ASCII value, i.e. the string representation of ASCII 0
+ * is found in the first element of this array.
*/
- private static final String[] NON_PRINTABLE_CHARS =
- { "\\x00", "\\x01", "\\x02", "\\x03", "\\x04", "\\x05", "\\x06", "\\a",
- "\\b", "\\t", "\\n", "\\v", "\\f", "\\r", "\\x0e", "\\x0f",
- "\\x10", "\\x11", "\\x12", "\\x13", "\\x14", "\\x15", "\\x16", "\\x17",
- "\\x18", "\\x19", "\\x1a", "\\x1b", "\\x1c", "\\x1d", "\\x1e", "\\x1f", };
+ private static final String[] NON_PRINTABLE_CHARS = {
+ "\\x00", "\\x01", "\\x02", "\\x03", "\\x04", "\\x05", "\\x06", "\\a",
+ "\\b", "\\t", "\\n", "\\v", "\\f", "\\r", "\\x0e", "\\x0f",
+ "\\x10", "\\x11", "\\x12", "\\x13", "\\x14", "\\x15", "\\x16", "\\x17",
+ "\\x18", "\\x19", "\\x1a", "\\x1b", "\\x1c", "\\x1d", "\\x1e", "\\x1f",
+ };
/**
- * Escapes the input string so that all non-printable characters
- * (0x00-0x1f) are represented as a hex escape (\x00, \x01, ...)
- * or as a C-style escape sequence (\a, \b, \t, \n, \v, \f, or \r).
+ * Escapes the input string so that all non-printable characters (0x00-0x1f) are represented as a
+ * hex escape (\x00, \x01, ...) or as a C-style escape sequence (\a, \b, \t, \n, \v, \f, or \r).
* Backslashes in the input string are doubled (\\).
*/
public static String escapeString(final String str) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/UrlEncoded.java b/gerrit-server/src/main/java/com/google/gerrit/server/UrlEncoded.java
index 3ac6c98..adad11c 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/UrlEncoded.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/UrlEncoded.java
@@ -12,11 +12,9 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-
package com.google.gerrit.server;
import com.google.gerrit.extensions.restapi.Url;
-
import java.util.LinkedHashMap;
import java.util.Map;
@@ -25,8 +23,7 @@
private String url;
- public UrlEncoded() {
- }
+ public UrlEncoded() {}
public UrlEncoded(final String url) {
this.url = url;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/WebLinks.java b/gerrit-server/src/main/java/com/google/gerrit/server/WebLinks.java
index 789d9a7..533ed9d 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/WebLinks.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/WebLinks.java
@@ -33,12 +33,10 @@
import com.google.gerrit.reviewdb.client.Project;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
+import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.util.List;
-
@Singleton
public class WebLinks {
private static final Logger log = LoggerFactory.getLogger(WebLinks.class);
@@ -47,10 +45,8 @@
link -> {
if (link == null) {
return false;
- } else if (Strings.isNullOrEmpty(link.name)
- || Strings.isNullOrEmpty(link.url)) {
- log.warn(String.format("%s is missing name and/or url",
- link.getClass().getName()));
+ } else if (Strings.isNullOrEmpty(link.name) || Strings.isNullOrEmpty(link.url)) {
+ log.warn(String.format("%s is missing name and/or url", link.getClass().getName()));
return false;
}
return true;
@@ -60,10 +56,8 @@
link -> {
if (link == null) {
return false;
- } else if (Strings.isNullOrEmpty(link.name)
- || Strings.isNullOrEmpty(link.url)) {
- log.warn(String.format("%s is missing name and/or url", link
- .getClass().getName()));
+ } else if (Strings.isNullOrEmpty(link.name) || Strings.isNullOrEmpty(link.url)) {
+ log.warn(String.format("%s is missing name and/or url", link.getClass().getName()));
return false;
}
return true;
@@ -78,7 +72,8 @@
private final DynamicSet<BranchWebLink> branchLinks;
@Inject
- public WebLinks(DynamicSet<PatchSetWebLink> patchSetLinks,
+ public WebLinks(
+ DynamicSet<PatchSetWebLink> patchSetLinks,
DynamicSet<ParentWebLink> parentLinks,
DynamicSet<FileWebLink> fileLinks,
DynamicSet<FileHistoryWebLink> fileLogLinks,
@@ -95,60 +90,44 @@
}
/**
- *
* @param project Project name.
* @param commit SHA1 of commit.
* @return Links for patch sets.
*/
- public List<WebLinkInfo> getPatchSetLinks(Project.NameKey project,
- String commit) {
- return filterLinks(
- patchSetLinks,
- webLink -> webLink.getPatchSetWebLink(project.get(), commit));
+ public List<WebLinkInfo> getPatchSetLinks(Project.NameKey project, String commit) {
+ return filterLinks(patchSetLinks, webLink -> webLink.getPatchSetWebLink(project.get(), commit));
}
/**
- *
* @param project Project name.
* @param revision SHA1 of the parent revision.
* @return Links for patch sets.
*/
- public List<WebLinkInfo> getParentLinks(Project.NameKey project,
- String revision) {
- return filterLinks(
- parentLinks,
- webLink -> webLink.getParentWebLink(project.get(), revision));
+ public List<WebLinkInfo> getParentLinks(Project.NameKey project, String revision) {
+ return filterLinks(parentLinks, webLink -> webLink.getParentWebLink(project.get(), revision));
}
/**
- *
* @param project Project name.
* @param revision SHA1 of revision.
* @param file File name.
* @return Links for files.
*/
- public List<WebLinkInfo> getFileLinks(String project,
- String revision, String file) {
- return filterLinks(
- fileLinks,
- webLink -> webLink.getFileWebLink(project, revision, file));
+ public List<WebLinkInfo> getFileLinks(String project, String revision, String file) {
+ return filterLinks(fileLinks, webLink -> webLink.getFileWebLink(project, revision, file));
}
/**
- *
* @param project Project name.
* @param revision SHA1 of revision.
* @param file File name.
* @return Links for file history
*/
- public List<WebLinkInfoCommon> getFileHistoryLinks(
- String project, String revision, String file) {
- return FluentIterable
- .from(fileHistoryLinks)
+ public List<WebLinkInfoCommon> getFileHistoryLinks(String project, String revision, String file) {
+ return FluentIterable.from(fileHistoryLinks)
.transform(
webLink -> {
- WebLinkInfo info =
- webLink.getFileHistoryWebLink(project, revision, file);
+ WebLinkInfo info = webLink.getFileHistoryWebLink(project, revision, file);
if (info == null) {
return null;
}
@@ -164,10 +143,8 @@
}
/**
- *
* @param project Project name.
- * @param patchSetIdA Patch set ID of side A, <code>null</code> if no base
- * patch set was selected.
+ * @param patchSetIdA Patch set ID of side A, <code>null</code> if no base patch set was selected.
* @param revisionA SHA1 of revision of side A.
* @param fileA File name of side A.
* @param patchSetIdB Patch set ID of side B.
@@ -175,48 +152,50 @@
* @param fileB File name of side B.
* @return Links for file diffs.
*/
- public List<DiffWebLinkInfo> getDiffLinks(final String project, final int changeId,
- final Integer patchSetIdA, final String revisionA, final String fileA,
- final int patchSetIdB, final String revisionB, final String fileB) {
- return FluentIterable
- .from(diffLinks)
- .transform(webLink ->
- webLink.getDiffLink(project, changeId,
- patchSetIdA, revisionA, fileA,
- patchSetIdB, revisionB, fileB))
- .filter(INVALID_WEBLINK)
- .toList();
- }
+ public List<DiffWebLinkInfo> getDiffLinks(
+ final String project,
+ final int changeId,
+ final Integer patchSetIdA,
+ final String revisionA,
+ final String fileA,
+ final int patchSetIdB,
+ final String revisionB,
+ final String fileB) {
+ return FluentIterable.from(diffLinks)
+ .transform(
+ webLink ->
+ webLink.getDiffLink(
+ project,
+ changeId,
+ patchSetIdA,
+ revisionA,
+ fileA,
+ patchSetIdB,
+ revisionB,
+ fileB))
+ .filter(INVALID_WEBLINK)
+ .toList();
+ }
/**
- *
* @param project Project name.
* @return Links for projects.
*/
public List<WebLinkInfo> getProjectLinks(final String project) {
- return filterLinks(
- projectLinks,
- webLink -> webLink.getProjectWeblink(project));
+ return filterLinks(projectLinks, webLink -> webLink.getProjectWeblink(project));
}
/**
- *
* @param project Project name
* @param branch Branch name
* @return Links for branches.
*/
public List<WebLinkInfo> getBranchLinks(final String project, final String branch) {
- return filterLinks(
- branchLinks,
- webLink -> webLink.getBranchWebLink(project, branch));
+ return filterLinks(branchLinks, webLink -> webLink.getBranchWebLink(project, branch));
}
- private <T extends WebLink> List<WebLinkInfo> filterLinks(DynamicSet<T> links,
- Function<T, WebLinkInfo> transformer) {
- return FluentIterable
- .from(links)
- .transform(transformer)
- .filter(INVALID_WEBLINK)
- .toList();
+ private <T extends WebLink> List<WebLinkInfo> filterLinks(
+ DynamicSet<T> links, Function<T, WebLinkInfo> transformer) {
+ return FluentIterable.from(links).transform(transformer).filter(INVALID_WEBLINK).toList();
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/access/AccessCollection.java b/gerrit-server/src/main/java/com/google/gerrit/server/access/AccessCollection.java
index aa04b33..2e90889 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/access/AccessCollection.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/access/AccessCollection.java
@@ -25,14 +25,12 @@
import com.google.inject.Singleton;
@Singleton
-public class AccessCollection implements
- RestCollection<TopLevelResource, AccessResource> {
+public class AccessCollection implements RestCollection<TopLevelResource, AccessResource> {
private final Provider<ListAccess> list;
private final DynamicMap<RestView<AccessResource>> views;
@Inject
- AccessCollection(Provider<ListAccess> list,
- DynamicMap<RestView<AccessResource>> views) {
+ AccessCollection(Provider<ListAccess> list, DynamicMap<RestView<AccessResource>> views) {
this.list = list;
this.views = views;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/access/ListAccess.java b/gerrit-server/src/main/java/com/google/gerrit/server/access/ListAccess.java
index aeff017..024c610 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/access/ListAccess.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/access/ListAccess.java
@@ -22,19 +22,21 @@
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.server.project.GetAccess;
import com.google.inject.Inject;
-
-import org.kohsuke.args4j.Option;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
+import org.kohsuke.args4j.Option;
public class ListAccess implements RestReadView<TopLevelResource> {
- @Option(name = "--project", aliases = {"-p"}, metaVar = "PROJECT",
- usage = "projects for which the access rights should be returned")
+ @Option(
+ name = "--project",
+ aliases = {"-p"},
+ metaVar = "PROJECT",
+ usage = "projects for which the access rights should be returned"
+ )
private List<String> projects = new ArrayList<>();
private final GetAccess getAccess;
@@ -54,5 +56,4 @@
}
return access;
}
-
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/AbstractRealm.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/AbstractRealm.java
index 8b4453f..3ba457c 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/AbstractRealm.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/AbstractRealm.java
@@ -21,12 +21,11 @@
import com.google.gerrit.server.IdentifiedUser;
import com.google.gerrit.server.mail.send.EmailSender;
import com.google.inject.Inject;
-
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
-/** Basic implementation of {@link Realm}. */
+/** Basic implementation of {@link Realm}. */
public abstract class AbstractRealm implements Realm {
private EmailSender emailSender;
@@ -37,7 +36,7 @@
@Override
public Set<AccountFieldName> getEditableFields() {
- Set<AccountFieldName> fields = new HashSet<>();
+ Set<AccountFieldName> fields = new HashSet<>();
for (AccountFieldName n : AccountFieldName.values()) {
if (allowsEdit(n)) {
if (n == AccountFieldName.REGISTER_NEW_EMAIL) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountByEmailCache.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountByEmailCache.java
index 9001ea5..e73d82b 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountByEmailCache.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountByEmailCache.java
@@ -15,7 +15,6 @@
package com.google.gerrit.server.account;
import com.google.gerrit.reviewdb.client.Account;
-
import java.util.Set;
/** Translates an email address to a set of matching accounts. */
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountByEmailCacheImpl.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountByEmailCacheImpl.java
index 2ddea85d..56c41e0 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountByEmailCacheImpl.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountByEmailCacheImpl.java
@@ -29,30 +29,24 @@
import com.google.inject.Singleton;
import com.google.inject.TypeLiteral;
import com.google.inject.name.Named;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ExecutionException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/** Translates an email address to a set of matching accounts. */
@Singleton
public class AccountByEmailCacheImpl implements AccountByEmailCache {
- private static final Logger log = LoggerFactory
- .getLogger(AccountByEmailCacheImpl.class);
+ private static final Logger log = LoggerFactory.getLogger(AccountByEmailCacheImpl.class);
private static final String CACHE_NAME = "accounts_byemail";
public static Module module() {
return new CacheModule() {
@Override
protected void configure() {
- cache(CACHE_NAME,
- String.class,
- new TypeLiteral<Set<Account.Id>>() {})
- .loader(Loader.class);
+ cache(CACHE_NAME, String.class, new TypeLiteral<Set<Account.Id>>() {}).loader(Loader.class);
bind(AccountByEmailCacheImpl.class);
bind(AccountByEmailCache.class).to(AccountByEmailCacheImpl.class);
}
@@ -62,8 +56,7 @@
private final LoadingCache<String, Set<Account.Id>> cache;
@Inject
- AccountByEmailCacheImpl(
- @Named(CACHE_NAME) LoadingCache<String, Set<Account.Id>> cache) {
+ AccountByEmailCacheImpl(@Named(CACHE_NAME) LoadingCache<String, Set<Account.Id>> cache) {
this.cache = cache;
}
@@ -89,8 +82,7 @@
private final Provider<InternalAccountQuery> accountQueryProvider;
@Inject
- Loader(SchemaFactory<ReviewDb> schema,
- Provider<InternalAccountQuery> accountQueryProvider) {
+ Loader(SchemaFactory<ReviewDb> schema, Provider<InternalAccountQuery> accountQueryProvider) {
this.schema = schema;
this.accountQueryProvider = accountQueryProvider;
}
@@ -102,10 +94,11 @@
for (Account a : db.accounts().byPreferredEmail(email)) {
r.add(a.getId());
}
- for (AccountState accountState : accountQueryProvider.get()
- .byExternalId(
- (new AccountExternalId.Key(AccountExternalId.SCHEME_MAILTO,
- email)).get())) {
+ for (AccountState accountState :
+ accountQueryProvider
+ .get()
+ .byExternalId(
+ (new AccountExternalId.Key(AccountExternalId.SCHEME_MAILTO, email)).get())) {
r.add(accountState.getAccount().getId());
}
return ImmutableSet.copyOf(r);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountCache.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountCache.java
index 3a4566a..c28021c 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountCache.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountCache.java
@@ -15,7 +15,6 @@
package com.google.gerrit.server.account;
import com.google.gerrit.reviewdb.client.Account;
-
import java.io.IOException;
/** Caches important (but small) account state to avoid database hits. */
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountCacheImpl.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountCacheImpl.java
index 0ba84f3..535dfcb 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountCacheImpl.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountCacheImpl.java
@@ -37,11 +37,6 @@
import com.google.inject.Singleton;
import com.google.inject.TypeLiteral;
import com.google.inject.name.Named;
-
-import org.eclipse.jgit.errors.ConfigInvalidException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
@@ -50,12 +45,14 @@
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ExecutionException;
+import org.eclipse.jgit.errors.ConfigInvalidException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/** Caches important (but small) account state to avoid database hits. */
@Singleton
public class AccountCacheImpl implements AccountCache {
- private static final Logger log = LoggerFactory
- .getLogger(AccountCacheImpl.class);
+ private static final Logger log = LoggerFactory.getLogger(AccountCacheImpl.class);
private static final String BYID_NAME = "accounts";
private static final String BYUSER_NAME = "accounts_byname";
@@ -64,13 +61,10 @@
return new CacheModule() {
@Override
protected void configure() {
- cache(BYID_NAME, Account.Id.class, AccountState.class)
- .loader(ByIdLoader.class);
+ cache(BYID_NAME, Account.Id.class, AccountState.class).loader(ByIdLoader.class);
- cache(BYUSER_NAME,
- String.class,
- new TypeLiteral<Optional<Account.Id>>() {})
- .loader(ByNameLoader.class);
+ cache(BYUSER_NAME, String.class, new TypeLiteral<Optional<Account.Id>>() {})
+ .loader(ByNameLoader.class);
bind(AccountCacheImpl.class);
bind(AccountCache.class).to(AccountCacheImpl.class);
@@ -83,7 +77,8 @@
private final Provider<AccountIndexer> indexer;
@Inject
- AccountCacheImpl(@Named(BYID_NAME) LoadingCache<Account.Id, AccountState> byId,
+ AccountCacheImpl(
+ @Named(BYID_NAME) LoadingCache<Account.Id, AccountState> byId,
@Named(BYUSER_NAME) LoadingCache<String, Optional<Account.Id>> byUsername,
Provider<AccountIndexer> indexer) {
this.byId = byId;
@@ -145,8 +140,7 @@
account.setActive(false);
Collection<AccountExternalId> ids = Collections.emptySet();
Set<AccountGroup.UUID> anon = ImmutableSet.of();
- return new AccountState(account, anon, ids,
- new HashMap<ProjectWatchKey, Set<NotifyType>>());
+ return new AccountState(account, anon, ids, new HashMap<ProjectWatchKey, Set<NotifyType>>());
}
static class ByIdLoader extends CacheLoader<Account.Id, AccountState> {
@@ -157,11 +151,11 @@
private final Provider<WatchConfig.Accessor> watchConfig;
@Inject
- ByIdLoader(SchemaFactory<ReviewDb> sf,
+ ByIdLoader(
+ SchemaFactory<ReviewDb> sf,
GroupCache groupCache,
GeneralPreferencesLoader loader,
- @Named(BYUSER_NAME) LoadingCache<String,
- Optional<Account.Id>> byUsername,
+ @Named(BYUSER_NAME) LoadingCache<String, Optional<Account.Id>> byUsername,
Provider<WatchConfig.Accessor> watchConfig) {
this.schema = sf;
this.groupCache = groupCache;
@@ -191,8 +185,7 @@
}
Collection<AccountExternalId> externalIds =
- Collections.unmodifiableCollection(
- db.accountExternalIds().byAccount(who).toList());
+ Collections.unmodifiableCollection(db.accountExternalIds().byAccount(who).toList());
Set<AccountGroup.UUID> internalGroups = new HashSet<>();
for (AccountGroupMember g : db.accountGroupMembers().byAccount(who)) {
@@ -207,13 +200,12 @@
try {
account.setGeneralPreferences(loader.load(who));
} catch (IOException | ConfigInvalidException e) {
- log.warn("Cannot load GeneralPreferences for " + who +
- " (using default)", e);
+ log.warn("Cannot load GeneralPreferences for " + who + " (using default)", e);
account.setGeneralPreferences(GeneralPreferencesInfo.defaults());
}
- return new AccountState(account, internalGroups, externalIds,
- watchConfig.get().getProjectWatches(who));
+ return new AccountState(
+ account, internalGroups, externalIds, watchConfig.get().getProjectWatches(who));
}
}
@@ -227,13 +219,12 @@
@Override
public Optional<Account.Id> load(String username) throws Exception {
- AccountExternalId.Key key = new AccountExternalId.Key( //
- AccountExternalId.SCHEME_USERNAME, //
- username);
- AccountState accountState =
- accountQueryProvider.get().oneByExternalId(key.get());
- return Optional.ofNullable(accountState)
- .map(s -> s.getAccount().getId());
+ AccountExternalId.Key key =
+ new AccountExternalId.Key( //
+ AccountExternalId.SCHEME_USERNAME, //
+ username);
+ AccountState accountState = accountQueryProvider.get().oneByExternalId(key.get());
+ return Optional.ofNullable(accountState).map(s -> s.getAccount().getId());
}
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountControl.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountControl.java
index db2a98f..88a2411 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountControl.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountControl.java
@@ -27,7 +27,6 @@
import com.google.gerrit.server.project.ProjectCache;
import com.google.inject.Inject;
import com.google.inject.Provider;
-
import java.util.Set;
/** Access control management for one account's access to other accounts. */
@@ -40,7 +39,8 @@
private final AccountVisibility accountVisibility;
@Inject
- Factory(final ProjectCache projectCache,
+ Factory(
+ final ProjectCache projectCache,
final GroupControl.Factory groupControlFactory,
final Provider<CurrentUser> user,
final IdentifiedUser.GenericFactory userFactory,
@@ -53,8 +53,8 @@
}
public AccountControl get() {
- return new AccountControl(projectCache, groupControlFactory, user.get(),
- userFactory, accountVisibility);
+ return new AccountControl(
+ projectCache, groupControlFactory, user.get(), userFactory, accountVisibility);
}
}
@@ -64,13 +64,13 @@
private final IdentifiedUser.GenericFactory userFactory;
private final AccountVisibility accountVisibility;
- AccountControl(final ProjectCache projectCache,
- final GroupControl.Factory groupControlFactory,
- final CurrentUser user,
- final IdentifiedUser.GenericFactory userFactory,
- final AccountVisibility accountVisibility) {
- this.accountsSection =
- projectCache.getAllProjects().getConfig().getAccountsSection();
+ AccountControl(
+ final ProjectCache projectCache,
+ final GroupControl.Factory groupControlFactory,
+ final CurrentUser user,
+ final IdentifiedUser.GenericFactory userFactory,
+ final AccountVisibility accountVisibility) {
+ this.accountsSection = projectCache.getAllProjects().getConfig().getAccountsSection();
this.groupControlFactory = groupControlFactory;
this.user = user;
this.userFactory = userFactory;
@@ -82,65 +82,63 @@
}
/**
- * Returns true if the current user is allowed to see the otherUser, based
- * on the account visibility policy. Depending on the group membership
- * realms supported, this may not be able to determine SAME_GROUP or
- * VISIBLE_GROUP correctly (defaulting to not being visible). This is because
- * {@link GroupMembership#getKnownGroups()} may only return a subset of the
- * effective groups.
+ * Returns true if the current user is allowed to see the otherUser, based on the account
+ * visibility policy. Depending on the group membership realms supported, this may not be able to
+ * determine SAME_GROUP or VISIBLE_GROUP correctly (defaulting to not being visible). This is
+ * because {@link GroupMembership#getKnownGroups()} may only return a subset of the effective
+ * groups.
*/
public boolean canSee(Account otherUser) {
return canSee(otherUser.getId());
}
/**
- * Returns true if the current user is allowed to see the otherUser, based
- * on the account visibility policy. Depending on the group membership
- * realms supported, this may not be able to determine SAME_GROUP or
- * VISIBLE_GROUP correctly (defaulting to not being visible). This is because
- * {@link GroupMembership#getKnownGroups()} may only return a subset of the
- * effective groups.
+ * Returns true if the current user is allowed to see the otherUser, based on the account
+ * visibility policy. Depending on the group membership realms supported, this may not be able to
+ * determine SAME_GROUP or VISIBLE_GROUP correctly (defaulting to not being visible). This is
+ * because {@link GroupMembership#getKnownGroups()} may only return a subset of the effective
+ * groups.
*/
public boolean canSee(final Account.Id otherUser) {
- return canSee(new OtherUser() {
- @Override
- Account.Id getId() {
- return otherUser;
- }
+ return canSee(
+ new OtherUser() {
+ @Override
+ Account.Id getId() {
+ return otherUser;
+ }
- @Override
- IdentifiedUser createUser() {
- return userFactory.create(otherUser);
- }
- });
+ @Override
+ IdentifiedUser createUser() {
+ return userFactory.create(otherUser);
+ }
+ });
}
/**
- * Returns true if the current user is allowed to see the otherUser, based
- * on the account visibility policy. Depending on the group membership
- * realms supported, this may not be able to determine SAME_GROUP or
- * VISIBLE_GROUP correctly (defaulting to not being visible). This is because
- * {@link GroupMembership#getKnownGroups()} may only return a subset of the
- * effective groups.
+ * Returns true if the current user is allowed to see the otherUser, based on the account
+ * visibility policy. Depending on the group membership realms supported, this may not be able to
+ * determine SAME_GROUP or VISIBLE_GROUP correctly (defaulting to not being visible). This is
+ * because {@link GroupMembership#getKnownGroups()} may only return a subset of the effective
+ * groups.
*/
public boolean canSee(final AccountState otherUser) {
- return canSee(new OtherUser() {
- @Override
- Account.Id getId() {
- return otherUser.getAccount().getId();
- }
+ return canSee(
+ new OtherUser() {
+ @Override
+ Account.Id getId() {
+ return otherUser.getAccount().getId();
+ }
- @Override
- IdentifiedUser createUser() {
- return userFactory.create(otherUser);
- }
- });
+ @Override
+ IdentifiedUser createUser() {
+ return userFactory.create(otherUser);
+ }
+ });
}
private boolean canSee(OtherUser otherUser) {
// Special case: I can always see myself.
- if (user.isIdentifiedUser()
- && user.getAccountId().equals(otherUser.getId())) {
+ if (user.isIdentifiedUser() && user.getAccountId().equals(otherUser.getId())) {
return true;
}
if (user.getCapabilities().canViewAllAccounts()) {
@@ -150,32 +148,34 @@
switch (accountVisibility) {
case ALL:
return true;
- case SAME_GROUP: {
- Set<AccountGroup.UUID> usersGroups = groupsOf(otherUser.getUser());
- for (PermissionRule rule : accountsSection.getSameGroupVisibility()) {
- if (rule.isBlock() || rule.isDeny()) {
- usersGroups.remove(rule.getGroup().getUUID());
- }
- }
-
- if (user.getEffectiveGroups().containsAnyOf(usersGroups)) {
- return true;
- }
- break;
- }
- case VISIBLE_GROUP: {
- Set<AccountGroup.UUID> usersGroups = groupsOf(otherUser.getUser());
- for (AccountGroup.UUID usersGroup : usersGroups) {
- try {
- if (groupControlFactory.controlFor(usersGroup).isVisible()) {
- return true;
+ case SAME_GROUP:
+ {
+ Set<AccountGroup.UUID> usersGroups = groupsOf(otherUser.getUser());
+ for (PermissionRule rule : accountsSection.getSameGroupVisibility()) {
+ if (rule.isBlock() || rule.isDeny()) {
+ usersGroups.remove(rule.getGroup().getUUID());
}
- } catch (NoSuchGroupException e) {
- continue;
}
+
+ if (user.getEffectiveGroups().containsAnyOf(usersGroups)) {
+ return true;
+ }
+ break;
}
- break;
- }
+ case VISIBLE_GROUP:
+ {
+ Set<AccountGroup.UUID> usersGroups = groupsOf(otherUser.getUser());
+ for (AccountGroup.UUID usersGroup : usersGroups) {
+ try {
+ if (groupControlFactory.controlFor(usersGroup).isVisible()) {
+ return true;
+ }
+ } catch (NoSuchGroupException e) {
+ continue;
+ }
+ }
+ break;
+ }
case NONE:
break;
default:
@@ -185,7 +185,9 @@
}
private Set<AccountGroup.UUID> groupsOf(IdentifiedUser user) {
- return user.getEffectiveGroups().getKnownGroups().stream()
+ return user.getEffectiveGroups()
+ .getKnownGroups()
+ .stream()
.filter(a -> !SystemGroupBackend.isSystemGroup(a))
.collect(toSet());
}
@@ -201,6 +203,7 @@
}
abstract IdentifiedUser createUser();
+
abstract Account.Id getId();
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountDirectory.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountDirectory.java
index eebf868..5c14c94 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountDirectory.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountDirectory.java
@@ -15,13 +15,12 @@
package com.google.gerrit.server.account;
import com.google.gerrit.extensions.common.AccountInfo;
-
import java.util.Set;
/**
* Directory of user account information.
*
- * Implementations supply data to Gerrit about user accounts.
+ * <p>Implementations supply data to Gerrit about user accounts.
*/
public abstract class AccountDirectory {
/** Fields to be populated for a REST API response. */
@@ -48,9 +47,7 @@
STATUS
}
- public abstract void fillAccountInfo(
- Iterable<? extends AccountInfo> in,
- Set<FillOptions> options)
+ public abstract void fillAccountInfo(Iterable<? extends AccountInfo> in, Set<FillOptions> options)
throws DirectoryException;
@SuppressWarnings("serial")
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountLoader.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountLoader.java
index 1ddc762..a137256b 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountLoader.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountLoader.java
@@ -25,7 +25,6 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
-
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
@@ -37,16 +36,18 @@
public class AccountLoader {
public static final Set<FillOptions> DETAILED_OPTIONS =
- Collections.unmodifiableSet(EnumSet.of(
- FillOptions.ID,
- FillOptions.NAME,
- FillOptions.EMAIL,
- FillOptions.USERNAME,
- FillOptions.STATUS,
- FillOptions.AVATARS));
+ Collections.unmodifiableSet(
+ EnumSet.of(
+ FillOptions.ID,
+ FillOptions.NAME,
+ FillOptions.EMAIL,
+ FillOptions.USERNAME,
+ FillOptions.STATUS,
+ FillOptions.AVATARS));
public interface Factory {
AccountLoader create(boolean detailed);
+
AccountLoader create(Set<FillOptions> options);
}
@@ -56,17 +57,12 @@
private final List<AccountInfo> provided;
@AssistedInject
- AccountLoader(InternalAccountDirectory directory,
- @Assisted boolean detailed) {
- this(directory,
- detailed
- ? DETAILED_OPTIONS
- : InternalAccountDirectory.ID_ONLY);
+ AccountLoader(InternalAccountDirectory directory, @Assisted boolean detailed) {
+ this(directory, detailed ? DETAILED_OPTIONS : InternalAccountDirectory.ID_ONLY);
}
@AssistedInject
- AccountLoader(InternalAccountDirectory directory,
- @Assisted Set<FillOptions> options) {
+ AccountLoader(InternalAccountDirectory directory, @Assisted Set<FillOptions> options) {
this.directory = directory;
this.options = options;
created = new HashMap<>();
@@ -92,16 +88,14 @@
public void fill() throws OrmException {
try {
- directory.fillAccountInfo(
- Iterables.concat(created.values(), provided), options);
+ directory.fillAccountInfo(Iterables.concat(created.values(), provided), options);
} catch (DirectoryException e) {
Throwables.throwIfInstanceOf(e.getCause(), OrmException.class);
throw new OrmException(e);
}
}
- public void fill(Collection<? extends AccountInfo> infos)
- throws OrmException {
+ public void fill(Collection<? extends AccountInfo> infos) throws OrmException {
for (AccountInfo info : infos) {
put(info);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountManager.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountManager.java
index 7236604..9bbf8ac 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountManager.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountManager.java
@@ -36,22 +36,19 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/** Tracks authentication related details for user accounts. */
@Singleton
public class AccountManager {
- private static final Logger log =
- LoggerFactory.getLogger(AccountManager.class);
+ private static final Logger log = LoggerFactory.getLogger(AccountManager.class);
private final SchemaFactory<ReviewDb> schema;
private final AccountCache byIdCache;
@@ -65,7 +62,8 @@
private final Provider<InternalAccountQuery> accountQueryProvider;
@Inject
- AccountManager(SchemaFactory<ReviewDb> schema,
+ AccountManager(
+ SchemaFactory<ReviewDb> schema,
AccountCache byIdCache,
AccountByEmailCache byEmailCache,
Realm accountMapper,
@@ -86,14 +84,10 @@
this.accountQueryProvider = accountQueryProvider;
}
- /**
- * @return user identified by this external identity string
- */
- public Optional<Account.Id> lookup(String externalId)
- throws AccountException {
+ /** @return user identified by this external identity string */
+ public Optional<Account.Id> lookup(String externalId) throws AccountException {
try {
- AccountState accountState =
- accountQueryProvider.get().oneByExternalId(externalId);
+ AccountState accountState = accountQueryProvider.get().oneByExternalId(externalId);
return accountState != null
? Optional.of(accountState.getAccount().getId())
: Optional.empty();
@@ -107,11 +101,10 @@
*
* @param who identity of the user, with any details we received about them.
* @return the result of authenticating the user.
- * @throws AccountException the account does not exist, and cannot be created,
- * or exists, but cannot be located, or is inactive.
+ * @throws AccountException the account does not exist, and cannot be created, or exists, but
+ * cannot be located, or is inactive.
*/
- public AuthResult authenticate(AuthRequest who)
- throws AccountException, IOException {
+ public AuthResult authenticate(AuthRequest who) throws AccountException, IOException {
who = realm.authenticate(who);
try {
try (ReviewDb db = schema.open()) {
@@ -138,10 +131,8 @@
}
}
- private AccountExternalId getAccountExternalId(AccountExternalId.Key key)
- throws OrmException {
- AccountState accountState =
- accountQueryProvider.get().oneByExternalId(key.get());
+ private AccountExternalId getAccountExternalId(AccountExternalId.Key key) throws OrmException {
+ AccountState accountState = accountQueryProvider.get().oneByExternalId(key.get());
if (accountState != null) {
for (AccountExternalId extId : accountState.getExternalIds()) {
if (extId.getKey().equals(key)) {
@@ -163,8 +154,7 @@
String newEmail = who.getEmailAddress();
String oldEmail = extId.getEmailAddress();
if (newEmail != null && !newEmail.equals(oldEmail)) {
- if (oldEmail != null
- && oldEmail.equals(user.getAccount().getPreferredEmail())) {
+ if (oldEmail != null && oldEmail.equals(user.getAccount().getPreferredEmail())) {
toUpdate = load(toUpdate, user.getAccountId(), db);
toUpdate.setPreferredEmail(newEmail);
}
@@ -183,8 +173,9 @@
if (!realm.allowsEdit(AccountFieldName.USER_NAME)
&& who.getUserName() != null
&& !eq(user.getUserName(), who.getUserName())) {
- log.warn(String.format("Not changing already set username %s to %s",
- user.getUserName(), who.getUserName()));
+ log.warn(
+ String.format(
+ "Not changing already set username %s to %s", user.getUserName(), who.getUserName()));
}
if (toUpdate != null) {
@@ -200,8 +191,7 @@
}
}
- private Account load(Account toUpdate, Account.Id accountId, ReviewDb db)
- throws OrmException {
+ private Account load(Account toUpdate, Account.Id accountId, ReviewDb db) throws OrmException {
if (toUpdate == null) {
toUpdate = db.accounts().get(accountId);
if (toUpdate == null) {
@@ -225,21 +215,22 @@
account.setFullName(who.getDisplayName());
account.setPreferredEmail(extId.getEmailAddress());
- boolean isFirstAccount = awaitsFirstAccountCheck.getAndSet(false)
- && db.accounts().anyAccounts().toList().isEmpty();
+ boolean isFirstAccount =
+ awaitsFirstAccountCheck.getAndSet(false) && db.accounts().anyAccounts().toList().isEmpty();
try {
db.accounts().upsert(Collections.singleton(account));
- AccountExternalId existingExtId =
- db.accountExternalIds().get(extId.getKey());
- if (existingExtId != null
- && !existingExtId.getAccountId().equals(extId.getAccountId())) {
+ AccountExternalId existingExtId = db.accountExternalIds().get(extId.getKey());
+ if (existingExtId != null && !existingExtId.getAccountId().equals(extId.getAccountId())) {
// external ID is assigned to another account, do not overwrite
db.accounts().delete(Collections.singleton(account));
throw new AccountException(
- "Cannot assign external ID \"" + extId.getExternalId()
- + "\" to account " + newId + "; external ID already in use.");
+ "Cannot assign external ID \""
+ + extId.getExternalId()
+ + "\" to account "
+ + newId
+ + "; external ID already in use.");
}
db.accountExternalIds().upsert(Collections.singleton(extId));
} finally {
@@ -254,16 +245,17 @@
// is going to be the site's administrator and just make them that
// to bootstrap the authentication database.
//
- Permission admin = projectCache.getAllProjects()
- .getConfig()
- .getAccessSection(AccessSection.GLOBAL_CAPABILITIES)
- .getPermission(GlobalCapability.ADMINISTRATE_SERVER);
+ Permission admin =
+ projectCache
+ .getAllProjects()
+ .getConfig()
+ .getAccessSection(AccessSection.GLOBAL_CAPABILITIES)
+ .getPermission(GlobalCapability.ADMINISTRATE_SERVER);
AccountGroup.UUID uuid = admin.getRules().get(0).getGroup().getUUID();
AccountGroup g = db.accountGroups().byUUID(uuid).iterator().next();
AccountGroup.Id adminId = g.getId();
- AccountGroupMember m =
- new AccountGroupMember(new AccountGroupMember.Key(newId, adminId));
+ AccountGroupMember m = new AccountGroupMember(new AccountGroupMember.Key(newId, adminId));
auditService.dispatchAddAccountsToGroup(newId, Collections.singleton(m));
db.accountGroupMembers().insert(Collections.singleton(m));
}
@@ -276,13 +268,19 @@
changeUserNameFactory.create(db, user, who.getUserName()).call();
} catch (NameAlreadyUsedException e) {
String message =
- "Cannot assign user name \"" + who.getUserName() + "\" to account "
- + newId + "; name already in use.";
+ "Cannot assign user name \""
+ + who.getUserName()
+ + "\" to account "
+ + newId
+ + "; name already in use.";
handleSettingUserNameFailure(db, account, extId, message, e, false);
} catch (InvalidUserNameException e) {
String message =
- "Cannot assign user name \"" + who.getUserName() + "\" to account "
- + newId + "; name does not conform.";
+ "Cannot assign user name \""
+ + who.getUserName()
+ + "\" to account "
+ + newId
+ + "; name does not conform.";
handleSettingUserNameFailure(db, account, extId, message, e, false);
} catch (OrmException e) {
String message = "Cannot assign user name";
@@ -297,26 +295,27 @@
}
/**
- * This method handles an exception that occurred during the setting of the
- * user name for a newly created account. If the realm does not allow the user
- * to set a user name manually this method deletes the newly created account
- * and throws an {@link AccountUserNameException}. In any case the error
- * message is logged.
+ * This method handles an exception that occurred during the setting of the user name for a newly
+ * created account. If the realm does not allow the user to set a user name manually this method
+ * deletes the newly created account and throws an {@link AccountUserNameException}. In any case
+ * the error message is logged.
*
* @param db the database
* @param account the newly created account
* @param extId the newly created external id
* @param errorMessage the error message
- * @param e the exception that occurred during the setting of the user name
- * for the new account
- * @param logException flag that decides whether the exception should be
- * included into the log
- * @throws AccountUserNameException thrown if the realm does not allow the
- * user to manually set the user name
+ * @param e the exception that occurred during the setting of the user name for the new account
+ * @param logException flag that decides whether the exception should be included into the log
+ * @throws AccountUserNameException thrown if the realm does not allow the user to manually set
+ * the user name
* @throws OrmException thrown if cleaning the database failed
*/
- private void handleSettingUserNameFailure(ReviewDb db, Account account,
- AccountExternalId extId, String errorMessage, Exception e,
+ private void handleSettingUserNameFailure(
+ ReviewDb db,
+ Account account,
+ AccountExternalId extId,
+ String errorMessage,
+ Exception e,
boolean logException)
throws AccountUserNameException, OrmException {
if (logException) {
@@ -350,8 +349,8 @@
* @param to account to link the identity onto.
* @param who the additional identity.
* @return the result of linking the identity to the user.
- * @throws AccountException the identity belongs to a different account, or it
- * cannot be linked at this time.
+ * @throws AccountException the identity belongs to a different account, or it cannot be linked at
+ * this time.
*/
public AuthResult link(Account.Id to, AuthRequest who)
throws AccountException, OrmException, IOException {
@@ -383,33 +382,30 @@
}
return new AuthResult(to, key, false);
-
}
}
/**
* Update the link to another unique authentication identity to an existing account.
*
- * Existing external identities with the same scheme will be removed and replaced
- * with the new one.
+ * <p>Existing external identities with the same scheme will be removed and replaced with the new
+ * one.
*
* @param to account to link the identity onto.
* @param who the additional identity.
* @return the result of linking the identity to the user.
* @throws OrmException
- * @throws AccountException the identity belongs to a different account, or it
- * cannot be linked at this time.
+ * @throws AccountException the identity belongs to a different account, or it cannot be linked at
+ * this time.
*/
- public AuthResult updateLink(Account.Id to, AuthRequest who) throws OrmException,
- AccountException, IOException {
+ public AuthResult updateLink(Account.Id to, AuthRequest who)
+ throws OrmException, AccountException, IOException {
try (ReviewDb db = schema.open()) {
AccountExternalId.Key key = id(who);
List<AccountExternalId.Key> filteredKeysByScheme =
- filterKeysByScheme(key.getScheme(), db.accountExternalIds()
- .byAccount(to));
+ filterKeysByScheme(key.getScheme(), db.accountExternalIds().byAccount(to));
if (!filteredKeysByScheme.isEmpty()
- && (filteredKeysByScheme.size() > 1 || !filteredKeysByScheme
- .contains(key))) {
+ && (filteredKeysByScheme.size() > 1 || !filteredKeysByScheme.contains(key))) {
db.accountExternalIds().deleteKeys(filteredKeysByScheme);
}
byIdCache.evict(to);
@@ -434,8 +430,8 @@
* @param from account to unlink the identity from.
* @param who the identity to delete
* @return the result of unlinking the identity from the user.
- * @throws AccountException the identity belongs to a different account, or it
- * cannot be unlinked at this time.
+ * @throws AccountException the identity belongs to a different account, or it cannot be unlinked
+ * at this time.
*/
public AuthResult unlink(Account.Id from, AuthRequest who)
throws AccountException, OrmException, IOException {
@@ -444,8 +440,7 @@
AccountExternalId extId = getAccountExternalId(key);
if (extId != null) {
if (!extId.getAccountId().equals(from)) {
- throw new AccountException(
- "Identity '" + key.get() + "' in use by another account");
+ throw new AccountException("Identity '" + key.get() + "' in use by another account");
}
db.accountExternalIds().delete(Collections.singleton(extId));
@@ -465,11 +460,9 @@
}
return new AuthResult(from, key, false);
-
}
}
-
private static AccountExternalId.Key id(AuthRequest who) {
return new AccountExternalId.Key(who.getExternalId());
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountResolver.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountResolver.java
index f3356e5..9803143 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountResolver.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountResolver.java
@@ -23,7 +23,6 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
@@ -39,7 +38,8 @@
private final Provider<InternalAccountQuery> accountQueryProvider;
@Inject
- AccountResolver(Realm realm,
+ AccountResolver(
+ Realm realm,
AccountByEmailCache byEmail,
AccountCache byId,
Provider<InternalAccountQuery> accountQueryProvider) {
@@ -52,12 +52,11 @@
/**
* Locate exactly one account matching the name or name/email string.
*
- * @param nameOrEmail a string of the format
- * "Full Name <email@example>", just the email address
- * ("email@example"), a full name ("Full Name"), an account id
- * ("18419") or an user name ("username").
- * @return the single account that matches; null if no account matches or
- * there are multiple candidates.
+ * @param nameOrEmail a string of the format "Full Name <email@example>", just the email
+ * address ("email@example"), a full name ("Full Name"), an account id ("18419") or an user
+ * name ("username").
+ * @return the single account that matches; null if no account matches or there are multiple
+ * candidates.
*/
public Account find(ReviewDb db, String nameOrEmail) throws OrmException {
Set<Account.Id> r = findAll(db, nameOrEmail);
@@ -83,14 +82,12 @@
* Find all accounts matching the name or name/email string.
*
* @param db open database handle.
- * @param nameOrEmail a string of the format
- * "Full Name <email@example>", just the email address
- * ("email@example"), a full name ("Full Name"), an account id
- * ("18419") or an user name ("username").
- * @return the accounts that match, empty collection if none. Never null.
+ * @param nameOrEmail a string of the format "Full Name <email@example>", just the email
+ * address ("email@example"), a full name ("Full Name"), an account id ("18419") or an user
+ * name ("username").
+ * @return the accounts that match, empty collection if none. Never null.
*/
- public Set<Account.Id> findAll(ReviewDb db, String nameOrEmail)
- throws OrmException {
+ public Set<Account.Id> findAll(ReviewDb db, String nameOrEmail) throws OrmException {
Matcher m = Pattern.compile("^.* \\(([1-9][0-9]*)\\)$").matcher(nameOrEmail);
if (m.matches()) {
Account.Id id = Account.Id.parse(m.group(1));
@@ -126,14 +123,12 @@
* Locate exactly one account matching the name or name/email string.
*
* @param db open database handle.
- * @param nameOrEmail a string of the format
- * "Full Name <email@example>", just the email address
- * ("email@example"), a full name ("Full Name").
- * @return the single account that matches; null if no account matches or
- * there are multiple candidates.
+ * @param nameOrEmail a string of the format "Full Name <email@example>", just the email
+ * address ("email@example"), a full name ("Full Name").
+ * @return the single account that matches; null if no account matches or there are multiple
+ * candidates.
*/
- public Account findByNameOrEmail(ReviewDb db, String nameOrEmail)
- throws OrmException {
+ public Account findByNameOrEmail(ReviewDb db, String nameOrEmail) throws OrmException {
Set<Account.Id> r = findAllByNameOrEmail(db, nameOrEmail);
return r.size() == 1 ? byId.get(r.iterator().next()).getAccount() : null;
}
@@ -142,13 +137,11 @@
* Locate exactly one account matching the name or name/email string.
*
* @param db open database handle.
- * @param nameOrEmail a string of the format
- * "Full Name <email@example>", just the email address
- * ("email@example"), a full name ("Full Name").
+ * @param nameOrEmail a string of the format "Full Name <email@example>", just the email
+ * address ("email@example"), a full name ("Full Name").
* @return the accounts that match, empty collection if none. Never null.
*/
- public Set<Account.Id> findAllByNameOrEmail(ReviewDb db, String nameOrEmail)
- throws OrmException {
+ public Set<Account.Id> findAllByNameOrEmail(ReviewDb db, String nameOrEmail) throws OrmException {
int lt = nameOrEmail.indexOf('<');
int gt = nameOrEmail.indexOf('>');
if (lt >= 0 && gt > lt && nameOrEmail.contains("@")) {
@@ -185,7 +178,10 @@
// At this point we have no clue. Just perform a whole bunch of suggestions
// and pray we come up with a reasonable result list.
- return accountQueryProvider.get().byDefault(nameOrEmail).stream()
+ return accountQueryProvider
+ .get()
+ .byDefault(nameOrEmail)
+ .stream()
.map(a -> a.getAccount().getId())
.collect(toSet());
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountResource.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountResource.java
index 8bebf52..a016b98 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountResource.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountResource.java
@@ -21,7 +21,6 @@
import com.google.gerrit.server.IdentifiedUser;
import com.google.gerrit.server.change.ChangeResource;
import com.google.inject.TypeLiteral;
-
import java.util.Set;
public class AccountResource implements RestResource {
@@ -119,8 +118,7 @@
private final ChangeResource change;
private final Set<String> labels;
- public Star(IdentifiedUser user, ChangeResource change,
- Set<String> labels) {
+ public Star(IdentifiedUser user, ChangeResource change, Set<String> labels) {
this.user = user;
this.change = change;
this.labels = labels;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountState.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountState.java
index 827bdee..b811c84 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountState.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountState.java
@@ -28,7 +28,6 @@
import com.google.gerrit.server.IdentifiedUser;
import com.google.gerrit.server.account.WatchConfig.NotifyType;
import com.google.gerrit.server.account.WatchConfig.ProjectWatchKey;
-
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
@@ -44,7 +43,8 @@
private final Map<ProjectWatchKey, Set<NotifyType>> projectWatches;
private Cache<IdentifiedUser.PropertyKey<Object>, Object> properties;
- public AccountState(Account account,
+ public AccountState(
+ Account account,
Set<AccountGroup.UUID> actualGroups,
Collection<AccountExternalId> externalIds,
Map<ProjectWatchKey, Set<NotifyType>> projectWatches) {
@@ -62,9 +62,9 @@
/**
* Get the username, if one has been declared for this user.
- * <p>
- * The username is the {@link AccountExternalId} using the scheme
- * {@link AccountExternalId#SCHEME_USERNAME}.
+ *
+ * <p>The username is the {@link AccountExternalId} using the scheme {@link
+ * AccountExternalId#SCHEME_USERNAME}.
*/
public String getUserName() {
return account.getUserName();
@@ -73,8 +73,7 @@
/** @return the password matching the requested username; or null. */
public String getPassword(String username) {
for (AccountExternalId id : getExternalIds()) {
- if (id.isScheme(AccountExternalId.SCHEME_USERNAME)
- && username.equals(id.getSchemeRest())) {
+ if (id.isScheme(AccountExternalId.SCHEME_USERNAME) && username.equals(id.getSchemeRest())) {
return id.getPassword();
}
}
@@ -117,9 +116,9 @@
/**
* Lookup a previously stored property.
- * <p>
- * All properties are automatically cleared when the account cache invalidates
- * the {@code AccountState}. This method is thread-safe.
+ *
+ * <p>All properties are automatically cleared when the account cache invalidates the {@code
+ * AccountState}. This method is thread-safe.
*
* @param key unique property key.
* @return previously stored value, or {@code null}.
@@ -137,8 +136,8 @@
/**
* Store a property for later retrieval.
- * <p>
- * This method is thread-safe.
+ *
+ * <p>This method is thread-safe.
*
* @param key unique property key.
* @param value value to store; or {@code null} to clear the value.
@@ -156,16 +155,16 @@
}
}
- private synchronized Cache<PropertyKey<Object>, Object> properties(
- boolean allocate) {
+ private synchronized Cache<PropertyKey<Object>, Object> properties(boolean allocate) {
if (properties == null && allocate) {
- properties = CacheBuilder.newBuilder()
- .concurrencyLevel(1)
- .initialCapacity(16)
- // Use weakKeys to ensure plugins that garbage collect will also
- // eventually release data held in any still live AccountState.
- .weakKeys()
- .build();
+ properties =
+ CacheBuilder.newBuilder()
+ .concurrencyLevel(1)
+ .initialCapacity(16)
+ // Use weakKeys to ensure plugins that garbage collect will also
+ // eventually release data held in any still live AccountState.
+ .weakKeys()
+ .build();
}
return properties;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountUserNameException.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountUserNameException.java
index 1cf8be8..19fd34d 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountUserNameException.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountUserNameException.java
@@ -15,9 +15,8 @@
package com.google.gerrit.server.account;
/**
- * Thrown by {@link AccountManager} if the user name for a newly created account
- * could not be set and the realm does not allow the user to set a user name
- * manually.
+ * Thrown by {@link AccountManager} if the user name for a newly created account could not be set
+ * and the realm does not allow the user to set a user name manually.
*/
public class AccountUserNameException extends AccountException {
private static final long serialVersionUID = 1L;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountVisibility.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountVisibility.java
index 7ee8db6..9957134 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountVisibility.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountVisibility.java
@@ -26,8 +26,8 @@
VISIBLE_GROUP,
/**
- * Other accounts are not visible to the given user unless they are explicitly
- * collaborating on a change.
+ * Other accounts are not visible to the given user unless they are explicitly collaborating on a
+ * change.
*/
NONE
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountVisibilityProvider.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountVisibilityProvider.java
index 25f0a7d..4521cd5 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountVisibilityProvider.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountVisibilityProvider.java
@@ -17,7 +17,6 @@
import com.google.gerrit.server.config.GerritServerConfig;
import com.google.inject.Inject;
import com.google.inject.Provider;
-
import org.eclipse.jgit.lib.Config;
public class AccountVisibilityProvider implements Provider<AccountVisibility> {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountsCollection.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountsCollection.java
index c7ce1b7..081ea26 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountsCollection.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountsCollection.java
@@ -35,9 +35,8 @@
import com.google.inject.Singleton;
@Singleton
-public class AccountsCollection implements
- RestCollection<TopLevelResource, AccountResource>,
- AcceptsCreate<TopLevelResource> {
+public class AccountsCollection
+ implements RestCollection<TopLevelResource, AccountResource>, AcceptsCreate<TopLevelResource> {
private final Provider<ReviewDb> db;
private final Provider<CurrentUser> self;
private final AccountResolver resolver;
@@ -48,7 +47,8 @@
private final CreateAccount.Factory createAccountFactory;
@Inject
- AccountsCollection(Provider<ReviewDb> db,
+ AccountsCollection(
+ Provider<ReviewDb> db,
Provider<CurrentUser> self,
AccountResolver resolver,
AccountControl.Factory accountControlFactory,
@@ -81,30 +81,28 @@
/**
* Parses a account ID from a request body and returns the user.
*
- * @param id ID of the account, can be a string of the format
- * "{@code Full Name <email@example.com>}", just the email address,
- * a full name if it is unique, an account ID, a user name or
- * "{@code self}" for the calling user
+ * @param id ID of the account, can be a string of the format "{@code Full Name
+ * <email@example.com>}", just the email address, a full name if it is unique, an account ID,
+ * a user name or "{@code self}" for the calling user
* @return the user, never null.
- * @throws UnprocessableEntityException thrown if the account ID cannot be
- * resolved or if the account is not visible to the calling user
+ * @throws UnprocessableEntityException thrown if the account ID cannot be resolved or if the
+ * account is not visible to the calling user
*/
- public IdentifiedUser parse(String id) throws AuthException,
- UnprocessableEntityException, OrmException {
+ public IdentifiedUser parse(String id)
+ throws AuthException, UnprocessableEntityException, OrmException {
return parseOnBehalfOf(null, id);
}
/**
- * Parses an account ID and returns the user without making any permission
- * check whether the current user can see the account.
+ * Parses an account ID and returns the user without making any permission check whether the
+ * current user can see the account.
*
- * @param id ID of the account, can be a string of the format
- * "{@code Full Name <email@example.com>}", just the email address,
- * a full name if it is unique, an account ID, a user name or
- * "{@code self}" for the calling user
+ * @param id ID of the account, can be a string of the format "{@code Full Name
+ * <email@example.com>}", just the email address, a full name if it is unique, an account ID,
+ * a user name or "{@code self}" for the calling user
* @return the user, null if no user is found for the given account ID
- * @throws AuthException thrown if 'self' is used as account ID and the
- * current user is not authenticated
+ * @throws AuthException thrown if 'self' is used as account ID and the current user is not
+ * authenticated
* @throws OrmException
*/
public IdentifiedUser parseId(String id) throws AuthException, OrmException {
@@ -112,25 +110,21 @@
}
/**
- * Like {@link #parse(String)}, but also sets the {@link
- * CurrentUser#getRealUser()} on the result.
+ * Like {@link #parse(String)}, but also sets the {@link CurrentUser#getRealUser()} on the result.
*/
- public IdentifiedUser parseOnBehalfOf(@Nullable CurrentUser caller,
- String id)
+ public IdentifiedUser parseOnBehalfOf(@Nullable CurrentUser caller, String id)
throws AuthException, UnprocessableEntityException, OrmException {
IdentifiedUser user = parseIdOnBehalfOf(caller, id);
if (user == null) {
- throw new UnprocessableEntityException(String.format(
- "Account Not Found: %s", id));
+ throw new UnprocessableEntityException(String.format("Account Not Found: %s", id));
} else if (!accountControlFactory.get().canSee(user.getAccount())) {
- throw new UnprocessableEntityException(String.format(
- "Account Not Found: %s", id));
+ throw new UnprocessableEntityException(String.format("Account Not Found: %s", id));
}
return user;
}
- private IdentifiedUser parseIdOnBehalfOf(@Nullable CurrentUser caller,
- String id) throws AuthException, OrmException {
+ private IdentifiedUser parseIdOnBehalfOf(@Nullable CurrentUser caller, String id)
+ throws AuthException, OrmException {
if (id.equals("self")) {
CurrentUser user = self.get();
if (user.isIdentifiedUser()) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/AddSshKey.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/AddSshKey.java
index 8cc392a..8c10c73 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/AddSshKey.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/AddSshKey.java
@@ -35,14 +35,12 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
+import java.io.IOException;
+import java.io.InputStream;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.io.InputStream;
-
@Singleton
public class AddSshKey implements RestModifyView<AccountResource, Input> {
private static final Logger log = LoggerFactory.getLogger(AddSshKey.class);
@@ -57,7 +55,8 @@
private final AddKeySender.Factory addKeyFactory;
@Inject
- AddSshKey(Provider<CurrentUser> self,
+ AddSshKey(
+ Provider<CurrentUser> self,
VersionedAuthorizedKeys.Accessor authorizedKeys,
SshKeyCache sshKeyCache,
AddKeySender.Factory addKeyFactory) {
@@ -69,18 +68,15 @@
@Override
public Response<SshKeyInfo> apply(AccountResource rsrc, Input input)
- throws AuthException, BadRequestException, OrmException, IOException,
- ConfigInvalidException {
- if (self.get() != rsrc.getUser()
- && !self.get().getCapabilities().canAdministrateServer()) {
+ throws AuthException, BadRequestException, OrmException, IOException, ConfigInvalidException {
+ if (self.get() != rsrc.getUser() && !self.get().getCapabilities().canAdministrateServer()) {
throw new AuthException("not allowed to add SSH keys");
}
return apply(rsrc.getUser(), input);
}
public Response<SshKeyInfo> apply(IdentifiedUser user, Input input)
- throws BadRequestException, IOException,
- ConfigInvalidException {
+ throws BadRequestException, IOException, ConfigInvalidException {
if (input == null) {
input = new Input();
}
@@ -89,22 +85,22 @@
}
final RawInput rawKey = input.raw;
- String sshPublicKey = new ByteSource() {
- @Override
- public InputStream openStream() throws IOException {
- return rawKey.getInputStream();
- }
- }.asCharSource(UTF_8).read();
+ String sshPublicKey =
+ new ByteSource() {
+ @Override
+ public InputStream openStream() throws IOException {
+ return rawKey.getInputStream();
+ }
+ }.asCharSource(UTF_8).read();
try {
- AccountSshKey sshKey =
- authorizedKeys.addKey(user.getAccountId(), sshPublicKey);
+ AccountSshKey sshKey = authorizedKeys.addKey(user.getAccountId(), sshPublicKey);
try {
addKeyFactory.create(user, sshKey).send();
} catch (EmailException e) {
- log.error("Cannot send SSH key added message to "
- + user.getAccount().getPreferredEmail(), e);
+ log.error(
+ "Cannot send SSH key added message to " + user.getAccount().getPreferredEmail(), e);
}
sshKeyCache.evict(user.getUserName());
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/AuthRequest.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/AuthRequest.java
index c585f97..1431640 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/AuthRequest.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/AuthRequest.java
@@ -22,18 +22,16 @@
/**
* Information for {@link AccountManager#authenticate(AuthRequest)}.
- * <p>
- * Callers should populate this object with as much information as possible
- * about the user account. For example, OpenID authentication might return
- * registration information including a display name for the user, and an email
- * address for them. These fields however are optional, as not all OpenID
- * providers return them, and not all non-OpenID systems can use them.
+ *
+ * <p>Callers should populate this object with as much information as possible about the user
+ * account. For example, OpenID authentication might return registration information including a
+ * display name for the user, and an email address for them. These fields however are optional, as
+ * not all OpenID providers return them, and not all non-OpenID systems can use them.
*/
public class AuthRequest {
/** Create a request for a local username, such as from LDAP. */
public static AuthRequest forUser(final String username) {
- final AccountExternalId.Key i =
- new AccountExternalId.Key(SCHEME_GERRIT, username);
+ final AccountExternalId.Key i = new AccountExternalId.Key(SCHEME_GERRIT, username);
final AuthRequest r = new AuthRequest(i.get());
r.setUserName(username);
return r;
@@ -41,8 +39,7 @@
/** Create a request for an external username. */
public static AuthRequest forExternalUser(String username) {
- AccountExternalId.Key i =
- new AccountExternalId.Key(SCHEME_EXTERNAL, username);
+ AccountExternalId.Key i = new AccountExternalId.Key(SCHEME_EXTERNAL, username);
AuthRequest r = new AuthRequest(i.get());
r.setUserName(username);
return r;
@@ -50,13 +47,12 @@
/**
* Create a request for an email address registration.
- * <p>
- * This type of request should be used only to attach a new email address to
- * an existing user account.
+ *
+ * <p>This type of request should be used only to attach a new email address to an existing user
+ * account.
*/
public static AuthRequest forEmail(final String email) {
- final AccountExternalId.Key i =
- new AccountExternalId.Key(SCHEME_MAILTO, email);
+ final AccountExternalId.Key i = new AccountExternalId.Key(SCHEME_MAILTO, email);
final AuthRequest r = new AuthRequest(i.get());
r.setEmailAddress(email);
return r;
@@ -92,8 +88,7 @@
public void setLocalUser(final String localUser) {
if (isScheme(SCHEME_GERRIT)) {
- final AccountExternalId.Key key =
- new AccountExternalId.Key(SCHEME_GERRIT, localUser);
+ final AccountExternalId.Key key = new AccountExternalId.Key(SCHEME_GERRIT, localUser);
externalId = key.get();
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/AuthResult.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/AuthResult.java
index b94e41a..1e75b63 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/AuthResult.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/AuthResult.java
@@ -23,8 +23,8 @@
private final AccountExternalId.Key externalId;
private final boolean isNew;
- public AuthResult(final Account.Id accountId,
- final AccountExternalId.Key externalId, final boolean isNew) {
+ public AuthResult(
+ final Account.Id accountId, final AccountExternalId.Key externalId, final boolean isNew) {
this.accountId = accountId;
this.externalId = externalId;
this.isNew = isNew;
@@ -42,9 +42,9 @@
/**
* True if this account was recently created for the user.
- * <p>
- * New users should be redirected to the registration screen, so they can
- * configure their new user account.
+ *
+ * <p>New users should be redirected to the registration screen, so they can configure their new
+ * user account.
*/
public boolean isNew() {
return isNew;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/AuthorizedKeys.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/AuthorizedKeys.java
index 45dbe60..4d86ab2 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/AuthorizedKeys.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/AuthorizedKeys.java
@@ -17,7 +17,6 @@
import com.google.common.annotations.VisibleForTesting;
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.reviewdb.client.AccountSshKey;
-
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@@ -26,14 +25,11 @@
public class AuthorizedKeys {
public static final String FILE_NAME = "authorized_keys";
- @VisibleForTesting
- public static final String INVALID_KEY_COMMENT_PREFIX = "# INVALID ";
+ @VisibleForTesting public static final String INVALID_KEY_COMMENT_PREFIX = "# INVALID ";
- @VisibleForTesting
- public static final String DELETED_KEY_COMMENT = "# DELETED";
+ @VisibleForTesting public static final String DELETED_KEY_COMMENT = "# DELETED";
- public static List<Optional<AccountSshKey>> parse(
- Account.Id accountId, String s) {
+ public static List<Optional<AccountSshKey>> parse(Account.Id accountId, String s) {
List<Optional<AccountSshKey>> keys = new ArrayList<>();
int seq = 1;
for (String line : s.split("\\r?\\n")) {
@@ -42,8 +38,7 @@
continue;
} else if (line.startsWith(INVALID_KEY_COMMENT_PREFIX)) {
String pub = line.substring(INVALID_KEY_COMMENT_PREFIX.length());
- AccountSshKey key =
- new AccountSshKey(new AccountSshKey.Id(accountId, seq++), pub);
+ AccountSshKey key = new AccountSshKey(new AccountSshKey.Id(accountId, seq++), pub);
key.setInvalid();
keys.add(Optional.of(key));
} else if (line.startsWith(DELETED_KEY_COMMENT)) {
@@ -52,8 +47,7 @@
} else if (line.startsWith("#")) {
continue;
} else {
- AccountSshKey key =
- new AccountSshKey(new AccountSshKey.Id(accountId, seq++), line);
+ AccountSshKey key = new AccountSshKey(new AccountSshKey.Id(accountId, seq++), line);
keys.add(Optional.of(key));
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/Capabilities.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/Capabilities.java
index 95338fe..d35656c 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/Capabilities.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/Capabilities.java
@@ -28,8 +28,7 @@
import com.google.inject.Singleton;
@Singleton
-class Capabilities implements
- ChildCollection<AccountResource, AccountResource.Capability> {
+class Capabilities implements ChildCollection<AccountResource, AccountResource.Capability> {
private final Provider<CurrentUser> self;
private final DynamicMap<RestView<AccountResource.Capability>> views;
private final Provider<GetCapabilities> get;
@@ -52,8 +51,7 @@
@Override
public Capability parse(AccountResource parent, IdString id)
throws ResourceNotFoundException, AuthException {
- if (self.get() != parent.getUser()
- && !self.get().getCapabilities().canAdministrateServer()) {
+ if (self.get() != parent.getUser() && !self.get().getCapabilities().canAdministrateServer()) {
throw new AuthException("restricted to administrator");
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/CapabilityCollection.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/CapabilityCollection.java
index 6d245a3..05d771e 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/CapabilityCollection.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/CapabilityCollection.java
@@ -28,7 +28,6 @@
import com.google.gerrit.server.group.SystemGroupBackend;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
-
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
@@ -100,8 +99,8 @@
queryLimit = getPermission(GlobalCapability.QUERY_LIMIT);
}
- private static List<PermissionRule> mergeAdmin(Set<GroupReference> admins,
- List<PermissionRule> rules) {
+ private static List<PermissionRule> mergeAdmin(
+ Set<GroupReference> admins, List<PermissionRule> rules) {
if (admins.isEmpty()) {
return rules;
}
@@ -120,17 +119,22 @@
public ImmutableList<PermissionRule> getPermission(String permissionName) {
ImmutableList<PermissionRule> r = permissions.get(permissionName);
- return r != null ? r : ImmutableList.<PermissionRule> of();
+ return r != null ? r : ImmutableList.<PermissionRule>of();
}
- private void configureDefaults(Map<String, List<PermissionRule>> out,
- AccessSection section) {
- configureDefault(out, section, GlobalCapability.QUERY_LIMIT,
+ private void configureDefaults(Map<String, List<PermissionRule>> out, AccessSection section) {
+ configureDefault(
+ out,
+ section,
+ GlobalCapability.QUERY_LIMIT,
systemGroupBackend.getGroup(SystemGroupBackend.ANONYMOUS_USERS));
}
- private static void configureDefault(Map<String, List<PermissionRule>> out,
- AccessSection section, String capName, GroupReference group) {
+ private static void configureDefault(
+ Map<String, List<PermissionRule>> out,
+ AccessSection section,
+ String capName,
+ GroupReference group) {
if (doesNotDeclare(section, capName)) {
PermissionRange.WithDefaults range = GlobalCapability.getRange(capName);
if (range != null) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/CapabilityControl.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/CapabilityControl.java
index d86d27c..66d0bf9 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/CapabilityControl.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/CapabilityControl.java
@@ -29,7 +29,6 @@
import com.google.gerrit.server.project.ProjectCache;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
-
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
@@ -68,8 +67,9 @@
if (user.getRealUser() != user) {
canAdministrateServer = false;
} else {
- canAdministrateServer = user instanceof PeerDaemonUser
- || matchAny(capabilities.administrateServer, ALLOWED_RULE);
+ canAdministrateServer =
+ user instanceof PeerDaemonUser
+ || matchAny(capabilities.administrateServer, ALLOWED_RULE);
}
}
return canAdministrateServer;
@@ -77,20 +77,17 @@
/** @return true if the user can create an account for another user. */
public boolean canCreateAccount() {
- return canPerform(GlobalCapability.CREATE_ACCOUNT)
- || canAdministrateServer();
+ return canPerform(GlobalCapability.CREATE_ACCOUNT) || canAdministrateServer();
}
/** @return true if the user can create a group. */
public boolean canCreateGroup() {
- return canPerform(GlobalCapability.CREATE_GROUP)
- || canAdministrateServer();
+ return canPerform(GlobalCapability.CREATE_GROUP) || canAdministrateServer();
}
/** @return true if the user can create a project. */
public boolean canCreateProject() {
- return canPerform(GlobalCapability.CREATE_PROJECT)
- || canAdministrateServer();
+ return canPerform(GlobalCapability.CREATE_PROJECT) || canAdministrateServer();
}
/** @return true if the user can email reviewers. */
@@ -98,64 +95,54 @@
if (canEmailReviewers == null) {
canEmailReviewers =
matchAny(capabilities.emailReviewers, ALLOWED_RULE)
- || !matchAny(capabilities.emailReviewers, not(ALLOWED_RULE));
-
+ || !matchAny(capabilities.emailReviewers, not(ALLOWED_RULE));
}
return canEmailReviewers;
}
/** @return true if the user can kill any running task. */
public boolean canKillTask() {
- return canPerform(GlobalCapability.KILL_TASK)
- || canMaintainServer();
+ return canPerform(GlobalCapability.KILL_TASK) || canMaintainServer();
}
/** @return true if the user can modify an account for another user. */
public boolean canModifyAccount() {
- return canPerform(GlobalCapability.MODIFY_ACCOUNT)
- || canAdministrateServer();
+ return canPerform(GlobalCapability.MODIFY_ACCOUNT) || canAdministrateServer();
}
/** @return true if the user can view all accounts. */
public boolean canViewAllAccounts() {
- return canPerform(GlobalCapability.VIEW_ALL_ACCOUNTS)
- || canAdministrateServer();
+ return canPerform(GlobalCapability.VIEW_ALL_ACCOUNTS) || canAdministrateServer();
}
/** @return true if the user can view the server caches. */
public boolean canViewCaches() {
- return canPerform(GlobalCapability.VIEW_CACHES)
- || canMaintainServer();
+ return canPerform(GlobalCapability.VIEW_CACHES) || canMaintainServer();
}
/** @return true if the user can flush the server's caches. */
public boolean canFlushCaches() {
- return canPerform(GlobalCapability.FLUSH_CACHES)
- || canMaintainServer();
+ return canPerform(GlobalCapability.FLUSH_CACHES) || canMaintainServer();
}
/** @return true if the user can perform basic server maintenance. */
public boolean canMaintainServer() {
- return canPerform(GlobalCapability.MAINTAIN_SERVER)
- || canAdministrateServer();
+ return canPerform(GlobalCapability.MAINTAIN_SERVER) || canAdministrateServer();
}
/** @return true if the user can view open connections. */
public boolean canViewConnections() {
- return canPerform(GlobalCapability.VIEW_CONNECTIONS)
- || canAdministrateServer();
+ return canPerform(GlobalCapability.VIEW_CONNECTIONS) || canAdministrateServer();
}
/** @return true if the user can view the installed plugins. */
public boolean canViewPlugins() {
- return canPerform(GlobalCapability.VIEW_PLUGINS)
- || canAdministrateServer();
+ return canPerform(GlobalCapability.VIEW_PLUGINS) || canAdministrateServer();
}
/** @return true if the user can view the entire queue. */
public boolean canViewQueue() {
- return canPerform(GlobalCapability.VIEW_QUEUE)
- || canMaintainServer();
+ return canPerform(GlobalCapability.VIEW_QUEUE) || canMaintainServer();
}
/** @return true if the user can access the database (with gsql). */
@@ -165,14 +152,12 @@
/** @return true if the user can stream Gerrit events. */
public boolean canStreamEvents() {
- return canPerform(GlobalCapability.STREAM_EVENTS)
- || canAdministrateServer();
+ return canPerform(GlobalCapability.STREAM_EVENTS) || canAdministrateServer();
}
/** @return true if the user can run the Git garbage collection. */
public boolean canRunGC() {
- return canPerform(GlobalCapability.RUN_GC)
- || canMaintainServer();
+ return canPerform(GlobalCapability.RUN_GC) || canMaintainServer();
}
/** @return true if the user can impersonate another user. */
@@ -235,13 +220,11 @@
return null;
}
- private static PermissionRange toRange(String permissionName,
- List<PermissionRule> ruleList) {
+ private static PermissionRange toRange(String permissionName, List<PermissionRule> ruleList) {
int min = 0;
int max = 0;
if (ruleList.isEmpty()) {
- PermissionRange.WithDefaults defaultRange =
- GlobalCapability.getRange(permissionName);
+ PermissionRange.WithDefaults defaultRange = GlobalCapability.getRange(permissionName);
if (defaultRange != null) {
min = defaultRange.getDefaultMin();
max = defaultRange.getDefaultMax();
@@ -279,20 +262,15 @@
return mine;
}
- private static final Predicate<PermissionRule> ALLOWED_RULE =
- r -> r.getAction() == Action.ALLOW;
+ private static final Predicate<PermissionRule> ALLOWED_RULE = r -> r.getAction() == Action.ALLOW;
- private boolean matchAny(Collection<PermissionRule> rules,
- Predicate<PermissionRule> predicate) {
+ private boolean matchAny(Collection<PermissionRule> rules, Predicate<PermissionRule> predicate) {
return user.getEffectiveGroups()
.containsAnyOf(
- FluentIterable.from(rules)
- .filter(predicate)
- .transform(r -> r.getGroup().getUUID()));
+ FluentIterable.from(rules).filter(predicate).transform(r -> r.getGroup().getUUID()));
}
- private static boolean match(GroupMembership groups,
- PermissionRule rule) {
+ private static boolean match(GroupMembership groups, PermissionRule rule) {
return groups.contains(rule.getGroup().getUUID());
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/CapabilityUtils.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/CapabilityUtils.java
index 2bf147d..21399f4 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/CapabilityUtils.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/CapabilityUtils.java
@@ -20,34 +20,30 @@
import com.google.gerrit.extensions.restapi.AuthException;
import com.google.gerrit.server.CurrentUser;
import com.google.inject.Provider;
-
+import java.lang.annotation.Annotation;
+import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.lang.annotation.Annotation;
-import java.util.Arrays;
-
public class CapabilityUtils {
- private static final Logger log = LoggerFactory
- .getLogger(CapabilityUtils.class);
+ private static final Logger log = LoggerFactory.getLogger(CapabilityUtils.class);
- public static void checkRequiresCapability(Provider<CurrentUser> userProvider,
- String pluginName, Class<?> clazz) throws AuthException {
+ public static void checkRequiresCapability(
+ Provider<CurrentUser> userProvider, String pluginName, Class<?> clazz) throws AuthException {
checkRequiresCapability(userProvider.get(), pluginName, clazz);
}
- public static void checkRequiresCapability(CurrentUser user,
- String pluginName, Class<?> clazz)
+ public static void checkRequiresCapability(CurrentUser user, String pluginName, Class<?> clazz)
throws AuthException {
RequiresCapability rc = getClassAnnotation(clazz, RequiresCapability.class);
- RequiresAnyCapability rac =
- getClassAnnotation(clazz, RequiresAnyCapability.class);
+ RequiresAnyCapability rac = getClassAnnotation(clazz, RequiresAnyCapability.class);
if (rc != null && rac != null) {
- log.error(String.format(
- "Class %s uses both @%s and @%s",
- clazz.getName(),
- RequiresCapability.class.getSimpleName(),
- RequiresAnyCapability.class.getSimpleName()));
+ log.error(
+ String.format(
+ "Class %s uses both @%s and @%s",
+ clazz.getName(),
+ RequiresCapability.class.getSimpleName(),
+ RequiresAnyCapability.class.getSimpleName()));
throw new AuthException("cannot check capability");
}
CapabilityControl ctl = user.getCapabilities();
@@ -58,74 +54,73 @@
checkRequiresAnyCapability(ctl, pluginName, clazz, rac);
}
- private static void checkRequiresCapability(CapabilityControl ctl,
- String pluginName, Class<?> clazz, RequiresCapability rc)
+ private static void checkRequiresCapability(
+ CapabilityControl ctl, String pluginName, Class<?> clazz, RequiresCapability rc)
throws AuthException {
if (rc == null) {
return;
}
- String capability =
- resolveCapability(pluginName, rc.value(), rc.scope(), clazz);
+ String capability = resolveCapability(pluginName, rc.value(), rc.scope(), clazz);
if (!ctl.canPerform(capability)) {
- throw new AuthException(String.format(
- "Capability %s is required to access this resource",
- capability));
+ throw new AuthException(
+ String.format("Capability %s is required to access this resource", capability));
}
}
- private static void checkRequiresAnyCapability(CapabilityControl ctl,
- String pluginName, Class<?> clazz, RequiresAnyCapability rac)
+ private static void checkRequiresAnyCapability(
+ CapabilityControl ctl, String pluginName, Class<?> clazz, RequiresAnyCapability rac)
throws AuthException {
if (rac == null) {
return;
}
if (rac.value().length == 0) {
- log.error(String.format(
- "Class %s uses @%s with no capabilities listed",
- clazz.getName(),
- RequiresAnyCapability.class.getSimpleName()));
+ log.error(
+ String.format(
+ "Class %s uses @%s with no capabilities listed",
+ clazz.getName(), RequiresAnyCapability.class.getSimpleName()));
throw new AuthException("cannot check capability");
}
for (String capability : rac.value()) {
- capability =
- resolveCapability(pluginName, capability, rac.scope(), clazz);
+ capability = resolveCapability(pluginName, capability, rac.scope(), clazz);
if (ctl.canPerform(capability)) {
return;
}
}
throw new AuthException(
"One of the following capabilities is required to access this"
- + " resource: " + Arrays.asList(rac.value()));
+ + " resource: "
+ + Arrays.asList(rac.value()));
}
- private static String resolveCapability(String pluginName, String capability,
- CapabilityScope scope, Class<?> clazz) throws AuthException {
- if (pluginName != null && !"gerrit".equals(pluginName)
- && (scope == CapabilityScope.PLUGIN
- || scope == CapabilityScope.CONTEXT)) {
+ private static String resolveCapability(
+ String pluginName, String capability, CapabilityScope scope, Class<?> clazz)
+ throws AuthException {
+ if (pluginName != null
+ && !"gerrit".equals(pluginName)
+ && (scope == CapabilityScope.PLUGIN || scope == CapabilityScope.CONTEXT)) {
capability = String.format("%s-%s", pluginName, capability);
} else if (scope == CapabilityScope.PLUGIN) {
- log.error(String.format(
- "Class %s uses @%s(scope=%s), but is not within a plugin",
- clazz.getName(),
- RequiresCapability.class.getSimpleName(),
- CapabilityScope.PLUGIN.name()));
+ log.error(
+ String.format(
+ "Class %s uses @%s(scope=%s), but is not within a plugin",
+ clazz.getName(),
+ RequiresCapability.class.getSimpleName(),
+ CapabilityScope.PLUGIN.name()));
throw new AuthException("cannot check capability");
}
return capability;
}
/**
- * Find an instance of the specified annotation, walking up the inheritance
- * tree if necessary.
+ * Find an instance of the specified annotation, walking up the inheritance tree if necessary.
*
* @param <T> Annotation type to search for
* @param clazz root class to search, may be null
* @param annotationClass class object of Annotation subclass to search for
* @return the requested annotation or null if none
*/
- private static <T extends Annotation> T getClassAnnotation(Class<?> clazz,
- Class<T> annotationClass) {
+ private static <T extends Annotation> T getClassAnnotation(
+ Class<?> clazz, Class<T> annotationClass) {
for (; clazz != null; clazz = clazz.getSuperclass()) {
T t = clazz.getAnnotation(annotationClass);
if (t != null) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/ChangeUserName.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/ChangeUserName.java
index c1ecafd..39c732e 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/ChangeUserName.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/ChangeUserName.java
@@ -28,7 +28,6 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
@@ -38,11 +37,9 @@
/** Operation to change the username of an account. */
public class ChangeUserName implements Callable<VoidResult> {
- public static final String USERNAME_CANNOT_BE_CHANGED =
- "Username cannot be changed.";
+ public static final String USERNAME_CANNOT_BE_CHANGED = "Username cannot be changed.";
- private static final Pattern USER_NAME_PATTERN =
- Pattern.compile(Account.USER_NAME_PATTERN);
+ private static final Pattern USER_NAME_PATTERN = Pattern.compile(Account.USER_NAME_PATTERN);
/** Generic factory to change any user's username. */
public interface Factory {
@@ -57,10 +54,11 @@
private final String newUsername;
@Inject
- ChangeUserName(final AccountCache accountCache,
+ ChangeUserName(
+ final AccountCache accountCache,
final SshKeyCache sshKeyCache,
-
- @Assisted final ReviewDb db, @Assisted final IdentifiedUser user,
+ @Assisted final ReviewDb db,
+ @Assisted final IdentifiedUser user,
@Nullable @Assisted final String newUsername) {
this.accountCache = accountCache;
this.sshKeyCache = sshKeyCache;
@@ -71,8 +69,8 @@
}
@Override
- public VoidResult call() throws OrmException, NameAlreadyUsedException,
- InvalidUserNameException, IOException {
+ public VoidResult call()
+ throws OrmException, NameAlreadyUsedException, InvalidUserNameException, IOException {
final Collection<AccountExternalId> old = old();
if (!old.isEmpty()) {
throw new IllegalStateException(USERNAME_CANNOT_BE_CHANGED);
@@ -83,11 +81,9 @@
throw new InvalidUserNameException();
}
- final AccountExternalId.Key key =
- new AccountExternalId.Key(SCHEME_USERNAME, newUsername);
+ final AccountExternalId.Key key = new AccountExternalId.Key(SCHEME_USERNAME, newUsername);
try {
- final AccountExternalId id =
- new AccountExternalId(user.getAccountId(), key);
+ final AccountExternalId id = new AccountExternalId(user.getAccountId(), key);
for (AccountExternalId i : old) {
if (i.getPassword() != null) {
@@ -126,8 +122,7 @@
private Collection<AccountExternalId> old() throws OrmException {
final Collection<AccountExternalId> r = new ArrayList<>(1);
- for (AccountExternalId i : db.accountExternalIds().byAccount(
- user.getAccountId())) {
+ for (AccountExternalId i : db.accountExternalIds().byAccount(user.getAccountId())) {
if (i.isScheme(SCHEME_USERNAME)) {
r.add(i);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/CreateAccount.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/CreateAccount.java
index b0dea00..cf253ff 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/CreateAccount.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/CreateAccount.java
@@ -45,19 +45,16 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.assistedinject.Assisted;
-
-import org.eclipse.jgit.errors.ConfigInvalidException;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
+import org.eclipse.jgit.errors.ConfigInvalidException;
@RequiresCapability(GlobalCapability.CREATE_ACCOUNT)
-public class CreateAccount
- implements RestModifyView<TopLevelResource, AccountInput> {
+public class CreateAccount implements RestModifyView<TopLevelResource, AccountInput> {
public interface Factory {
CreateAccount create(String username);
}
@@ -76,7 +73,8 @@
private final String username;
@Inject
- CreateAccount(ReviewDb db,
+ CreateAccount(
+ ReviewDb db,
Provider<IdentifiedUser> currentUser,
GroupsCollection groupsCollection,
VersionedAuthorizedKeys.Accessor authorizedKeys,
@@ -104,9 +102,8 @@
@Override
public Response<AccountInfo> apply(TopLevelResource rsrc, AccountInput input)
- throws BadRequestException, ResourceConflictException,
- UnprocessableEntityException, OrmException, IOException,
- ConfigInvalidException {
+ throws BadRequestException, ResourceConflictException, UnprocessableEntityException,
+ OrmException, IOException, ConfigInvalidException {
if (input == null) {
input = new AccountInput();
}
@@ -115,8 +112,8 @@
}
if (!username.matches(Account.USER_NAME_PATTERN)) {
- throw new BadRequestException("Username '" + username + "'"
- + " must contain only letters, numbers, _, - or .");
+ throw new BadRequestException(
+ "Username '" + username + "'" + " must contain only letters, numbers, _, - or .");
}
Set<AccountGroup.Id> groups = parseGroups(input.groups);
@@ -124,21 +121,19 @@
Account.Id id = new Account.Id(db.nextAccountId());
AccountExternalId extUser =
- new AccountExternalId(id, new AccountExternalId.Key(
- AccountExternalId.SCHEME_USERNAME, username));
+ new AccountExternalId(
+ id, new AccountExternalId.Key(AccountExternalId.SCHEME_USERNAME, username));
if (input.httpPassword != null) {
extUser.setPassword(input.httpPassword);
}
if (db.accountExternalIds().get(extUser.getKey()) != null) {
- throw new ResourceConflictException(
- "username '" + username + "' already exists");
+ throw new ResourceConflictException("username '" + username + "' already exists");
}
if (input.email != null) {
if (db.accountExternalIds().get(getEmailKey(input.email)) != null) {
- throw new UnprocessableEntityException(
- "email '" + input.email + "' already exists");
+ throw new UnprocessableEntityException("email '" + input.email + "' already exists");
}
if (!OutgoingEmailValidator.isValid(input.email)) {
throw new BadRequestException("invalid email address");
@@ -154,13 +149,11 @@
try {
db.accountExternalIds().insert(externalIds);
} catch (OrmDuplicateKeyException duplicateKey) {
- throw new ResourceConflictException(
- "username '" + username + "' already exists");
+ throw new ResourceConflictException("username '" + username + "' already exists");
}
if (input.email != null) {
- AccountExternalId extMailto =
- new AccountExternalId(id, getEmailKey(input.email));
+ AccountExternalId extMailto = new AccountExternalId(id, getEmailKey(input.email));
extMailto.setEmailAddress(input.email);
try {
db.accountExternalIds().insert(Collections.singleton(extMailto));
@@ -170,8 +163,7 @@
} catch (OrmException cleanupError) {
// Ignored
}
- throw new UnprocessableEntityException(
- "email '" + input.email + "' already exists");
+ throw new UnprocessableEntityException("email '" + input.email + "' already exists");
}
}
@@ -181,10 +173,9 @@
db.accounts().insert(Collections.singleton(a));
for (AccountGroup.Id groupId : groups) {
- AccountGroupMember m =
- new AccountGroupMember(new AccountGroupMember.Key(id, groupId));
- auditService.dispatchAddAccountsToGroup(currentUser.get().getAccountId(),
- Collections.singleton(m));
+ AccountGroupMember m = new AccountGroupMember(new AccountGroupMember.Key(id, groupId));
+ auditService.dispatchAddAccountsToGroup(
+ currentUser.get().getAccountId(), Collections.singleton(m));
db.accountGroupMembers().insert(Collections.singleton(m));
}
@@ -212,8 +203,7 @@
Set<AccountGroup.Id> groupIds = new HashSet<>();
if (groups != null) {
for (String g : groups) {
- groupIds.add(GroupDescriptions.toAccountGroup(
- groupsCollection.parseInternal(g)).getId());
+ groupIds.add(GroupDescriptions.toAccountGroup(groupsCollection.parseInternal(g)).getId());
}
}
return groupIds;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/CreateEmail.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/CreateEmail.java
index ecee4b8..8aa356f 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/CreateEmail.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/CreateEmail.java
@@ -36,12 +36,10 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.assistedinject.Assisted;
-
+import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-
public class CreateEmail implements RestModifyView<AccountResource, EmailInput> {
private static final Logger log = LoggerFactory.getLogger(CreateEmail.class);
@@ -58,7 +56,8 @@
private final boolean isDevMode;
@Inject
- CreateEmail(Provider<CurrentUser> self,
+ CreateEmail(
+ Provider<CurrentUser> self,
Realm realm,
AuthConfig authConfig,
AccountManager accountManager,
@@ -77,10 +76,9 @@
@Override
public Response<EmailInfo> apply(AccountResource rsrc, EmailInput input)
throws AuthException, BadRequestException, ResourceConflictException,
- ResourceNotFoundException, OrmException, EmailException,
- MethodNotAllowedException, IOException {
- if (self.get() != rsrc.getUser()
- && !self.get().getCapabilities().canModifyAccount()) {
+ ResourceNotFoundException, OrmException, EmailException, MethodNotAllowedException,
+ IOException {
+ if (self.get() != rsrc.getUser() && !self.get().getCapabilities().canModifyAccount()) {
throw new AuthException("not allowed to add email address");
}
@@ -92,8 +90,7 @@
throw new BadRequestException("invalid email address");
}
- if (input.noConfirmation
- && !self.get().getCapabilities().canModifyAccount()) {
+ if (input.noConfirmation && !self.get().getCapabilities().canModifyAccount()) {
throw new AuthException("not allowed to use no_confirmation");
}
@@ -106,8 +103,8 @@
public Response<EmailInfo> apply(IdentifiedUser user, EmailInput input)
throws AuthException, BadRequestException, ResourceConflictException,
- ResourceNotFoundException, OrmException, EmailException,
- MethodNotAllowedException, IOException {
+ ResourceNotFoundException, OrmException, EmailException, MethodNotAllowedException,
+ IOException {
if (input.email != null && !email.equals(input.email)) {
throw new BadRequestException("email address must match URL");
}
@@ -119,15 +116,12 @@
log.warn("skipping email validation in developer mode");
}
try {
- accountManager.link(user.getAccountId(),
- AuthRequest.forEmail(email));
+ accountManager.link(user.getAccountId(), AuthRequest.forEmail(email));
} catch (AccountException e) {
throw new ResourceConflictException(e.getMessage());
}
if (input.preferred) {
- putPreferred.apply(
- new AccountResource.Email(user, email),
- null);
+ putPreferred.apply(new AccountResource.Email(user, email), null);
info.preferred = true;
}
} else {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/CreateGroupArgs.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/CreateGroupArgs.java
index 9ddef3a..0c0778c 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/CreateGroupArgs.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/CreateGroupArgs.java
@@ -16,7 +16,6 @@
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.reviewdb.client.AccountGroup;
-
import java.util.Collection;
public class CreateGroupArgs {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/DefaultRealm.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/DefaultRealm.java
index 57af333..795f1c5 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/DefaultRealm.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/DefaultRealm.java
@@ -21,7 +21,6 @@
import com.google.gerrit.server.config.AuthConfig;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
import java.util.Set;
@Singleton
@@ -31,9 +30,7 @@
private final AuthConfig authConfig;
@Inject
- DefaultRealm(EmailExpander emailExpander,
- AccountByEmailCache byEmail,
- AuthConfig authConfig) {
+ DefaultRealm(EmailExpander emailExpander, AccountByEmailCache byEmail, AuthConfig authConfig) {
this.emailExpander = emailExpander;
this.byEmail = byEmail;
this.authConfig = authConfig;
@@ -66,7 +63,8 @@
@Override
public AuthRequest authenticate(final AuthRequest who) {
- if (who.getEmailAddress() == null && who.getLocalUser() != null
+ if (who.getEmailAddress() == null
+ && who.getLocalUser() != null
&& emailExpander.canExpand(who.getLocalUser())) {
who.setEmailAddress(emailExpander.expand(who.getLocalUser()));
}
@@ -74,8 +72,7 @@
}
@Override
- public void onCreateAccount(final AuthRequest who, final Account account) {
- }
+ public void onCreateAccount(final AuthRequest who, final Account account) {}
@Override
public Account.Id lookup(final String accountName) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/DeleteActive.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/DeleteActive.java
index 94c099e..8710e91 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/DeleteActive.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/DeleteActive.java
@@ -29,23 +29,21 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.io.IOException;
import java.util.Collections;
@RequiresCapability(GlobalCapability.MODIFY_ACCOUNT)
@Singleton
public class DeleteActive implements RestModifyView<AccountResource, Input> {
- public static class Input {
- }
+ public static class Input {}
private final Provider<ReviewDb> dbProvider;
private final AccountCache byIdCache;
private final Provider<IdentifiedUser> self;
@Inject
- DeleteActive(Provider<ReviewDb> dbProvider, AccountCache byIdCache,
- Provider<IdentifiedUser> self) {
+ DeleteActive(
+ Provider<ReviewDb> dbProvider, AccountCache byIdCache, Provider<IdentifiedUser> self) {
this.dbProvider = dbProvider;
this.byIdCache = byIdCache;
this.self = self;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/DeleteEmail.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/DeleteEmail.java
index 1f073ae..96c4b8d 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/DeleteEmail.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/DeleteEmail.java
@@ -30,13 +30,11 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.io.IOException;
@Singleton
public class DeleteEmail implements RestModifyView<AccountResource.Email, Input> {
- public static class Input {
- }
+ public static class Input {}
private final Provider<CurrentUser> self;
private final Realm realm;
@@ -44,8 +42,11 @@
private final AccountManager accountManager;
@Inject
- DeleteEmail(Provider<CurrentUser> self, Realm realm,
- Provider<ReviewDb> dbProvider, AccountManager accountManager) {
+ DeleteEmail(
+ Provider<CurrentUser> self,
+ Realm realm,
+ Provider<ReviewDb> dbProvider,
+ AccountManager accountManager) {
this.self = self;
this.realm = realm;
this.dbProvider = dbProvider;
@@ -54,31 +55,27 @@
@Override
public Response<?> apply(AccountResource.Email rsrc, Input input)
- throws AuthException, ResourceNotFoundException,
- ResourceConflictException, MethodNotAllowedException, OrmException,
- IOException {
- if (self.get() != rsrc.getUser()
- && !self.get().getCapabilities().canModifyAccount()) {
+ throws AuthException, ResourceNotFoundException, ResourceConflictException,
+ MethodNotAllowedException, OrmException, IOException {
+ if (self.get() != rsrc.getUser() && !self.get().getCapabilities().canModifyAccount()) {
throw new AuthException("not allowed to delete email address");
}
return apply(rsrc.getUser(), rsrc.getEmail());
}
public Response<?> apply(IdentifiedUser user, String email)
- throws ResourceNotFoundException, ResourceConflictException,
- MethodNotAllowedException, OrmException, IOException {
+ throws ResourceNotFoundException, ResourceConflictException, MethodNotAllowedException,
+ OrmException, IOException {
if (!realm.allowsEdit(AccountFieldName.REGISTER_NEW_EMAIL)) {
throw new MethodNotAllowedException("realm does not allow deleting emails");
}
- AccountExternalId.Key key = new AccountExternalId.Key(
- AccountExternalId.SCHEME_MAILTO, email);
+ AccountExternalId.Key key = new AccountExternalId.Key(AccountExternalId.SCHEME_MAILTO, email);
AccountExternalId extId = dbProvider.get().accountExternalIds().get(key);
if (extId == null) {
throw new ResourceNotFoundException(email);
}
try {
- accountManager.unlink(user.getAccountId(),
- AuthRequest.forEmail(email));
+ accountManager.unlink(user.getAccountId(), AuthRequest.forEmail(email));
} catch (AccountException e) {
throw new ResourceConflictException(e.getMessage());
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/DeleteExternalIds.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/DeleteExternalIds.java
index cadb3f1..55e0581 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/DeleteExternalIds.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/DeleteExternalIds.java
@@ -31,7 +31,6 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@@ -39,8 +38,7 @@
import java.util.stream.Collectors;
@Singleton
-public class DeleteExternalIds implements
- RestModifyView<AccountResource, List<String>> {
+public class DeleteExternalIds implements RestModifyView<AccountResource, List<String>> {
private final Provider<ReviewDb> db;
private final AccountByEmailCache accountByEmailCache;
private final AccountCache accountCache;
@@ -74,27 +72,29 @@
Account.Id accountId = resource.getUser().getAccountId();
Map<AccountExternalId.Key, AccountExternalId> externalIdMap =
- db.get().accountExternalIds().byAccount(
- resource.getUser().getAccountId()).toList()
- .stream().collect(Collectors.toMap(i -> i.getKey(), i -> i));
+ db.get()
+ .accountExternalIds()
+ .byAccount(resource.getUser().getAccountId())
+ .toList()
+ .stream()
+ .collect(Collectors.toMap(i -> i.getKey(), i -> i));
List<AccountExternalId> toDelete = new ArrayList<>();
AccountExternalId.Key last = resource.getUser().getLastLoginExternalIdKey();
for (String externalIdStr : externalIds) {
- AccountExternalId id = externalIdMap.get(
- new AccountExternalId.Key(externalIdStr));
+ AccountExternalId id = externalIdMap.get(new AccountExternalId.Key(externalIdStr));
if (id == null) {
- throw new UnprocessableEntityException(String.format(
- "External id %s does not exist", externalIdStr));
+ throw new UnprocessableEntityException(
+ String.format("External id %s does not exist", externalIdStr));
}
if ((!id.isScheme(SCHEME_USERNAME))
&& ((last == null) || (!last.get().equals(id.getExternalId())))) {
toDelete.add(id);
} else {
- throw new ResourceConflictException(String.format(
- "External id %s cannot be deleted", externalIdStr));
+ throw new ResourceConflictException(
+ String.format("External id %s cannot be deleted", externalIdStr));
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/DeleteSshKey.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/DeleteSshKey.java
index 9212002..3d5d38e 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/DeleteSshKey.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/DeleteSshKey.java
@@ -24,24 +24,21 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
+import java.io.IOException;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
-import java.io.IOException;
-
@Singleton
-public class DeleteSshKey implements
- RestModifyView<AccountResource.SshKey, Input> {
- public static class Input {
- }
+public class DeleteSshKey implements RestModifyView<AccountResource.SshKey, Input> {
+ public static class Input {}
private final Provider<CurrentUser> self;
private final VersionedAuthorizedKeys.Accessor authorizedKeys;
private final SshKeyCache sshKeyCache;
@Inject
- DeleteSshKey(Provider<CurrentUser> self,
+ DeleteSshKey(
+ Provider<CurrentUser> self,
VersionedAuthorizedKeys.Accessor authorizedKeys,
SshKeyCache sshKeyCache) {
this.self = self;
@@ -51,15 +48,13 @@
@Override
public Response<?> apply(AccountResource.SshKey rsrc, Input input)
- throws AuthException, OrmException, RepositoryNotFoundException,
- IOException, ConfigInvalidException {
- if (self.get() != rsrc.getUser()
- && !self.get().getCapabilities().canAdministrateServer()) {
+ throws AuthException, OrmException, RepositoryNotFoundException, IOException,
+ ConfigInvalidException {
+ if (self.get() != rsrc.getUser() && !self.get().getCapabilities().canAdministrateServer()) {
throw new AuthException("not allowed to delete SSH keys");
}
- authorizedKeys.deleteKey(rsrc.getUser().getAccountId(),
- rsrc.getSshKey().getKey().get());
+ authorizedKeys.deleteKey(rsrc.getUser().getAccountId(), rsrc.getSshKey().getKey().get());
sshKeyCache.evict(rsrc.getUser().getUserName());
return Response.none();
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/DeleteWatchedProjects.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/DeleteWatchedProjects.java
index 990a563..b3a99eb 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/DeleteWatchedProjects.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/DeleteWatchedProjects.java
@@ -29,11 +29,9 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.errors.ConfigInvalidException;
-
import java.io.IOException;
import java.util.List;
+import org.eclipse.jgit.errors.ConfigInvalidException;
@Singleton
public class DeleteWatchedProjects
@@ -43,9 +41,8 @@
private final WatchConfig.Accessor watchConfig;
@Inject
- DeleteWatchedProjects(Provider<IdentifiedUser> self,
- AccountCache accountCache,
- WatchConfig.Accessor watchConfig) {
+ DeleteWatchedProjects(
+ Provider<IdentifiedUser> self, AccountCache accountCache, WatchConfig.Accessor watchConfig) {
this.self = self;
this.accountCache = accountCache;
this.watchConfig = watchConfig;
@@ -53,12 +50,10 @@
@Override
public Response<?> apply(AccountResource rsrc, List<ProjectWatchInfo> input)
- throws AuthException, UnprocessableEntityException, OrmException,
- IOException, ConfigInvalidException {
- if (self.get() != rsrc.getUser()
- && !self.get().getCapabilities().canAdministrateServer()) {
- throw new AuthException("It is not allowed to edit project watches "
- + "of other users");
+ throws AuthException, UnprocessableEntityException, OrmException, IOException,
+ ConfigInvalidException {
+ if (self.get() != rsrc.getUser() && !self.get().getCapabilities().canAdministrateServer()) {
+ throw new AuthException("It is not allowed to edit project watches " + "of other users");
}
if (input == null) {
return Response.none();
@@ -67,8 +62,9 @@
Account.Id accountId = rsrc.getUser().getAccountId();
watchConfig.deleteProjectWatches(
accountId,
- input.stream().map(w -> ProjectWatchKey.create(
- new Project.NameKey(w.project), w.filter))
+ input
+ .stream()
+ .map(w -> ProjectWatchKey.create(new Project.NameKey(w.project), w.filter))
.collect(toList()));
accountCache.evict(accountId);
return Response.none();
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/EmailExpander.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/EmailExpander.java
index 75408c8..3c501e9 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/EmailExpander.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/EmailExpander.java
@@ -14,10 +14,7 @@
package com.google.gerrit.server.account;
-
-/**
- * Expands user name to a local email address, usually by adding a domain.
- */
+/** Expands user name to a local email address, usually by adding a domain. */
public interface EmailExpander {
boolean canExpand(String user);
@@ -30,8 +27,7 @@
return fmt == null || fmt.isEmpty();
}
- private None() {
- }
+ private None() {}
@Override
public boolean canExpand(String user) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/Emails.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/Emails.java
index 733cf5b..b894f56 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/Emails.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/Emails.java
@@ -28,16 +28,17 @@
import com.google.inject.Singleton;
@Singleton
-public class Emails implements
- ChildCollection<AccountResource, AccountResource.Email>,
- AcceptsCreate<AccountResource> {
+public class Emails
+ implements ChildCollection<AccountResource, AccountResource.Email>,
+ AcceptsCreate<AccountResource> {
private final DynamicMap<RestView<AccountResource.Email>> views;
private final GetEmails list;
private final Provider<CurrentUser> self;
private final CreateEmail.Factory createEmailFactory;
@Inject
- Emails(DynamicMap<RestView<AccountResource.Email>> views,
+ Emails(
+ DynamicMap<RestView<AccountResource.Email>> views,
GetEmails list,
Provider<CurrentUser> self,
CreateEmail.Factory createEmailFactory) {
@@ -55,8 +56,7 @@
@Override
public AccountResource.Email parse(AccountResource rsrc, IdString id)
throws ResourceNotFoundException {
- if (self.get() != rsrc.getUser()
- && !self.get().getCapabilities().canAdministrateServer()) {
+ if (self.get() != rsrc.getUser() && !self.get().getCapabilities().canAdministrateServer()) {
throw new ResourceNotFoundException();
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/GeneralPreferencesLoader.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/GeneralPreferencesLoader.java
index 24a0dae..1c44670 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/GeneralPreferencesLoader.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/GeneralPreferencesLoader.java
@@ -35,7 +35,12 @@
import com.google.gerrit.server.git.UserConfigSections;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
+import java.io.IOException;
+import java.lang.reflect.Field;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
import org.eclipse.jgit.lib.Config;
@@ -43,24 +48,15 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.lang.reflect.Field;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
@Singleton
public class GeneralPreferencesLoader {
- private static final Logger log =
- LoggerFactory.getLogger(GeneralPreferencesLoader.class);
+ private static final Logger log = LoggerFactory.getLogger(GeneralPreferencesLoader.class);
private final GitRepositoryManager gitMgr;
private final AllUsersName allUsersName;
@Inject
- public GeneralPreferencesLoader(GitRepositoryManager gitMgr,
- AllUsersName allUsersName) {
+ public GeneralPreferencesLoader(GitRepositoryManager gitMgr, AllUsersName allUsersName) {
this.gitMgr = gitMgr;
this.allUsersName = allUsersName;
}
@@ -70,30 +66,37 @@
return read(id, null);
}
- public GeneralPreferencesInfo merge(Account.Id id,
- GeneralPreferencesInfo in) throws IOException,
- ConfigInvalidException, RepositoryNotFoundException {
+ public GeneralPreferencesInfo merge(Account.Id id, GeneralPreferencesInfo in)
+ throws IOException, ConfigInvalidException, RepositoryNotFoundException {
return read(id, in);
}
- private GeneralPreferencesInfo read(Account.Id id,
- GeneralPreferencesInfo in) throws IOException,
- ConfigInvalidException, RepositoryNotFoundException {
+ private GeneralPreferencesInfo read(Account.Id id, GeneralPreferencesInfo in)
+ throws IOException, ConfigInvalidException, RepositoryNotFoundException {
try (Repository allUsers = gitMgr.openRepository(allUsersName)) {
// Load all users default prefs
VersionedAccountPreferences dp = VersionedAccountPreferences.forDefault();
dp.load(allUsers);
GeneralPreferencesInfo allUserPrefs = new GeneralPreferencesInfo();
- loadSection(dp.getConfig(), UserConfigSections.GENERAL, null, allUserPrefs,
- GeneralPreferencesInfo.defaults(), in);
+ loadSection(
+ dp.getConfig(),
+ UserConfigSections.GENERAL,
+ null,
+ allUserPrefs,
+ GeneralPreferencesInfo.defaults(),
+ in);
// Load user prefs
VersionedAccountPreferences p = VersionedAccountPreferences.forUser(id);
p.load(allUsers);
GeneralPreferencesInfo r =
- loadSection(p.getConfig(), UserConfigSections.GENERAL, null,
- new GeneralPreferencesInfo(),
- updateDefaults(allUserPrefs), in);
+ loadSection(
+ p.getConfig(),
+ UserConfigSections.GENERAL,
+ null,
+ new GeneralPreferencesInfo(),
+ updateDefaults(allUserPrefs),
+ in);
loadChangeTableColumns(r, p, dp);
return loadMyMenusAndUrlAliases(r, p, dp);
}
@@ -112,9 +115,7 @@
}
}
} catch (IllegalAccessException e) {
- log.error(
- "Cannot get default general preferences from " + allUsersName.get(),
- e);
+ log.error("Cannot get default general preferences from " + allUsersName.get(), e);
return GeneralPreferencesInfo.defaults();
}
return result;
@@ -131,8 +132,7 @@
r.my.add(new MenuItem("Drafts", "#/q/owner:self+is:draft", null));
r.my.add(new MenuItem("Draft Comments", "#/q/has:draft", null));
r.my.add(new MenuItem("Edits", "#/q/has:edit", null));
- r.my.add(new MenuItem("Watched Changes", "#/q/is:watched+is:open",
- null));
+ r.my.add(new MenuItem("Watched Changes", "#/q/is:watched+is:open", null));
r.my.add(new MenuItem("Starred Changes", "#/q/is:starred", null));
r.my.add(new MenuItem("Groups", "#/groups/self", null));
}
@@ -149,23 +149,19 @@
Config cfg = v.getConfig();
for (String subsection : cfg.getSubsections(UserConfigSections.MY)) {
String url = my(cfg, subsection, KEY_URL, "#/");
- String target = my(cfg, subsection, KEY_TARGET,
- url.startsWith("#") ? null : "_blank");
- my.add(new MenuItem(
- subsection, url, target,
- my(cfg, subsection, KEY_ID, null)));
+ String target = my(cfg, subsection, KEY_TARGET, url.startsWith("#") ? null : "_blank");
+ my.add(new MenuItem(subsection, url, target, my(cfg, subsection, KEY_ID, null)));
}
return my;
}
- private static String my(Config cfg, String subsection, String key,
- String defaultValue) {
+ private static String my(Config cfg, String subsection, String key, String defaultValue) {
String val = cfg.getString(UserConfigSections.MY, subsection, key);
return !Strings.isNullOrEmpty(val) ? val : defaultValue;
}
- public GeneralPreferencesInfo loadChangeTableColumns(GeneralPreferencesInfo r,
- VersionedAccountPreferences v, VersionedAccountPreferences d) {
+ public GeneralPreferencesInfo loadChangeTableColumns(
+ GeneralPreferencesInfo r, VersionedAccountPreferences v, VersionedAccountPreferences d) {
r.changeTable = changeTable(v);
if (r.changeTable.isEmpty() && !v.isDefaults()) {
@@ -175,16 +171,16 @@
}
private static List<String> changeTable(VersionedAccountPreferences v) {
- return Lists.newArrayList(v.getConfig().getStringList(
- CHANGE_TABLE, null, CHANGE_TABLE_COLUMN));
+ return Lists.newArrayList(v.getConfig().getStringList(CHANGE_TABLE, null, CHANGE_TABLE_COLUMN));
}
private static Map<String, String> urlAliases(VersionedAccountPreferences v) {
HashMap<String, String> urlAliases = new HashMap<>();
Config cfg = v.getConfig();
for (String subsection : cfg.getSubsections(URL_ALIAS)) {
- urlAliases.put(cfg.getString(URL_ALIAS, subsection, KEY_MATCH),
- cfg.getString(URL_ALIAS, subsection, KEY_TOKEN));
+ urlAliases.put(
+ cfg.getString(URL_ALIAS, subsection, KEY_MATCH),
+ cfg.getString(URL_ALIAS, subsection, KEY_TOKEN));
}
return !urlAliases.isEmpty() ? urlAliases : null;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/GetAgreements.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/GetAgreements.java
index 46d6f11..dfbde96 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/GetAgreements.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/GetAgreements.java
@@ -31,19 +31,16 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
import org.eclipse.jgit.lib.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
@Singleton
public class GetAgreements implements RestReadView<AccountResource> {
- private static final Logger log =
- LoggerFactory.getLogger(GetAgreements.class);
+ private static final Logger log = LoggerFactory.getLogger(GetAgreements.class);
private final Provider<CurrentUser> self;
private final ProjectCache projectCache;
@@ -51,20 +48,19 @@
private final boolean agreementsEnabled;
@Inject
- GetAgreements(Provider<CurrentUser> self,
+ GetAgreements(
+ Provider<CurrentUser> self,
ProjectCache projectCache,
AgreementJson agreementJson,
@GerritServerConfig Config config) {
this.self = self;
this.projectCache = projectCache;
this.agreementJson = agreementJson;
- this.agreementsEnabled =
- config.getBoolean("auth", "contributorAgreements", false);
+ this.agreementsEnabled = config.getBoolean("auth", "contributorAgreements", false);
}
@Override
- public List<AgreementInfo> apply(AccountResource resource)
- throws RestApiException {
+ public List<AgreementInfo> apply(AccountResource resource) throws RestApiException {
if (!agreementsEnabled) {
throw new MethodNotAllowedException("contributor agreements disabled");
}
@@ -88,8 +84,13 @@
if (rule.getGroup().getUUID() != null) {
groupIds.add(rule.getGroup().getUUID());
} else {
- log.warn("group \"" + rule.getGroup().getName() + "\" does not " +
- "exist, referenced in CLA \"" + ca.getName() + "\"");
+ log.warn(
+ "group \""
+ + rule.getGroup().getName()
+ + "\" does not "
+ + "exist, referenced in CLA \""
+ + ca.getName()
+ + "\"");
}
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/GetAvatar.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/GetAvatar.java
index 1953c63..0818a0e 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/GetAvatar.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/GetAvatar.java
@@ -22,18 +22,19 @@
import com.google.gerrit.extensions.restapi.RestReadView;
import com.google.gerrit.server.avatar.AvatarProvider;
import com.google.inject.Inject;
-
-import org.kohsuke.args4j.Option;
-
import java.util.concurrent.TimeUnit;
+import org.kohsuke.args4j.Option;
public class GetAvatar implements RestReadView<AccountResource> {
private final DynamicItem<AvatarProvider> avatarProvider;
private int size;
- @Option(name = "--size", aliases = {"-s"},
- usage = "recommended size in pixels, height and width")
+ @Option(
+ name = "--size",
+ aliases = {"-s"},
+ usage = "recommended size in pixels, height and width"
+ )
public void setSize(int s) {
size = s;
}
@@ -44,18 +45,15 @@
}
@Override
- public Response.Redirect apply(AccountResource rsrc)
- throws ResourceNotFoundException {
+ public Response.Redirect apply(AccountResource rsrc) throws ResourceNotFoundException {
AvatarProvider impl = avatarProvider.get();
if (impl == null) {
- throw (new ResourceNotFoundException())
- .caching(CacheControl.PUBLIC(1, TimeUnit.DAYS));
+ throw (new ResourceNotFoundException()).caching(CacheControl.PUBLIC(1, TimeUnit.DAYS));
}
String url = impl.getUrl(rsrc.getUser(), size);
if (Strings.isNullOrEmpty(url)) {
- throw (new ResourceNotFoundException())
- .caching(CacheControl.PUBLIC(1, TimeUnit.HOURS));
+ throw (new ResourceNotFoundException()).caching(CacheControl.PUBLIC(1, TimeUnit.HOURS));
}
return Response.redirect(url);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/GetAvatarChangeUrl.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/GetAvatarChangeUrl.java
index ec020fb..d340772 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/GetAvatarChangeUrl.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/GetAvatarChangeUrl.java
@@ -32,8 +32,7 @@
}
@Override
- public String apply(AccountResource rsrc)
- throws ResourceNotFoundException {
+ public String apply(AccountResource rsrc) throws ResourceNotFoundException {
AvatarProvider impl = avatarProvider.get();
if (impl == null) {
throw new ResourceNotFoundException();
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/GetCapabilities.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/GetCapabilities.java
index cbd0e32..cd3c0c8 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/GetCapabilities.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/GetCapabilities.java
@@ -49,14 +49,12 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
-import org.kohsuke.args4j.Option;
-
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
+import org.kohsuke.args4j.Option;
class GetCapabilities implements RestReadView<AccountResource> {
@Option(name = "-q", metaVar = "CAP", usage = "Capability to inspect")
@@ -66,22 +64,21 @@
}
Iterables.addAll(query, OptionUtil.splitOptionValue(name));
}
+
private Set<String> query;
private final Provider<CurrentUser> self;
private final DynamicMap<CapabilityDefinition> pluginCapabilities;
@Inject
- GetCapabilities(Provider<CurrentUser> self,
- DynamicMap<CapabilityDefinition> pluginCapabilities) {
+ GetCapabilities(Provider<CurrentUser> self, DynamicMap<CapabilityDefinition> pluginCapabilities) {
this.self = self;
this.pluginCapabilities = pluginCapabilities;
}
@Override
public Object apply(AccountResource resource) throws AuthException {
- if (self.get() != resource.getUser()
- && !self.get().getCapabilities().canAdministrateServer()) {
+ if (self.get() != resource.getUser() && !self.get().getCapabilities().canAdministrateServer()) {
throw new AuthException("restricted to administrator");
}
@@ -138,9 +135,9 @@
}
}
- return OutputFormat.JSON.newGson().toJsonTree(
- have,
- new TypeToken<Map<String, Object>>() {}.getType());
+ return OutputFormat.JSON
+ .newGson()
+ .toJsonTree(have, new TypeToken<Map<String, Object>>() {}.getType());
}
private boolean want(String name) {
@@ -149,8 +146,10 @@
private static class Range {
private transient PermissionRange range;
+
@SuppressWarnings("unused")
private int min;
+
@SuppressWarnings("unused")
private int max;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/GetDetail.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/GetDetail.java
index e47ceb3..9eafec0 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/GetDetail.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/GetDetail.java
@@ -23,7 +23,6 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
import java.sql.Timestamp;
import java.util.Collections;
import java.util.EnumSet;
@@ -44,8 +43,7 @@
AccountDetailInfo info = new AccountDetailInfo(a.getId().get());
info.registeredOn = a.getRegisteredOn();
try {
- directory.fillAccountInfo(Collections.singleton(info),
- EnumSet.allOf(FillOptions.class));
+ directory.fillAccountInfo(Collections.singleton(info), EnumSet.allOf(FillOptions.class));
} catch (DirectoryException e) {
Throwables.throwIfInstanceOf(e.getCause(), OrmException.class);
throw new OrmException(e);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/GetDiffPreferences.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/GetDiffPreferences.java
index 2c4a840..5a39bea 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/GetDiffPreferences.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/GetDiffPreferences.java
@@ -28,27 +28,25 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
+import java.io.IOException;
+import java.lang.reflect.Field;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
import org.eclipse.jgit.lib.Repository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.lang.reflect.Field;
-
@Singleton
public class GetDiffPreferences implements RestReadView<AccountResource> {
- private static final Logger log =
- LoggerFactory.getLogger(GetDiffPreferences.class);
+ private static final Logger log = LoggerFactory.getLogger(GetDiffPreferences.class);
private final Provider<CurrentUser> self;
private final Provider<AllUsersName> allUsersName;
private final GitRepositoryManager gitMgr;
@Inject
- GetDiffPreferences(Provider<CurrentUser> self,
+ GetDiffPreferences(
+ Provider<CurrentUser> self,
Provider<AllUsersName> allUsersName,
GitRepositoryManager gitMgr) {
this.self = self;
@@ -59,8 +57,7 @@
@Override
public DiffPreferencesInfo apply(AccountResource rsrc)
throws AuthException, ConfigInvalidException, IOException {
- if (self.get() != rsrc.getUser()
- && !self.get().getCapabilities().canAdministrateServer()) {
+ if (self.get() != rsrc.getUser() && !self.get().getCapabilities().canAdministrateServer()) {
throw new AuthException("restricted to administrator");
}
@@ -68,26 +65,28 @@
return readFromGit(id, gitMgr, allUsersName.get(), null);
}
- static DiffPreferencesInfo readFromGit(Account.Id id,
- GitRepositoryManager gitMgr, AllUsersName allUsersName,
- DiffPreferencesInfo in)
+ static DiffPreferencesInfo readFromGit(
+ Account.Id id, GitRepositoryManager gitMgr, AllUsersName allUsersName, DiffPreferencesInfo in)
throws IOException, ConfigInvalidException, RepositoryNotFoundException {
try (Repository git = gitMgr.openRepository(allUsersName)) {
// Load all users prefs.
- VersionedAccountPreferences dp =
- VersionedAccountPreferences.forDefault();
+ VersionedAccountPreferences dp = VersionedAccountPreferences.forDefault();
dp.load(git);
DiffPreferencesInfo allUserPrefs = new DiffPreferencesInfo();
- loadSection(dp.getConfig(), UserConfigSections.DIFF, null, allUserPrefs,
- DiffPreferencesInfo.defaults(), in);
+ loadSection(
+ dp.getConfig(),
+ UserConfigSections.DIFF,
+ null,
+ allUserPrefs,
+ DiffPreferencesInfo.defaults(),
+ in);
// Load user prefs
- VersionedAccountPreferences p =
- VersionedAccountPreferences.forUser(id);
+ VersionedAccountPreferences p = VersionedAccountPreferences.forUser(id);
p.load(git);
DiffPreferencesInfo prefs = new DiffPreferencesInfo();
- loadSection(p.getConfig(), UserConfigSections.DIFF, null, prefs,
- updateDefaults(allUserPrefs), in);
+ loadSection(
+ p.getConfig(), UserConfigSections.DIFF, null, prefs, updateDefaults(allUserPrefs), in);
return prefs;
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/GetEditPreferences.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/GetEditPreferences.java
index 02cfaa0..e385020 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/GetEditPreferences.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/GetEditPreferences.java
@@ -27,13 +27,11 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
+import java.io.IOException;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
import org.eclipse.jgit.lib.Repository;
-import java.io.IOException;
-
@Singleton
public class GetEditPreferences implements RestReadView<AccountResource> {
private final Provider<CurrentUser> self;
@@ -41,37 +39,37 @@
private final GitRepositoryManager gitMgr;
@Inject
- GetEditPreferences(Provider<CurrentUser> self,
- AllUsersName allUsersName,
- GitRepositoryManager gitMgr) {
+ GetEditPreferences(
+ Provider<CurrentUser> self, AllUsersName allUsersName, GitRepositoryManager gitMgr) {
this.self = self;
this.allUsersName = allUsersName;
this.gitMgr = gitMgr;
}
@Override
- public EditPreferencesInfo apply(AccountResource rsrc) throws AuthException,
- IOException, ConfigInvalidException {
- if (self.get() != rsrc.getUser()
- && !self.get().getCapabilities().canModifyAccount()) {
+ public EditPreferencesInfo apply(AccountResource rsrc)
+ throws AuthException, IOException, ConfigInvalidException {
+ if (self.get() != rsrc.getUser() && !self.get().getCapabilities().canModifyAccount()) {
throw new AuthException("requires Modify Account capability");
}
- return readFromGit(
- rsrc.getUser().getAccountId(), gitMgr, allUsersName, null);
+ return readFromGit(rsrc.getUser().getAccountId(), gitMgr, allUsersName, null);
}
- static EditPreferencesInfo readFromGit(Account.Id id,
- GitRepositoryManager gitMgr, AllUsersName allUsersName,
- EditPreferencesInfo in) throws IOException, ConfigInvalidException,
- RepositoryNotFoundException {
+ static EditPreferencesInfo readFromGit(
+ Account.Id id, GitRepositoryManager gitMgr, AllUsersName allUsersName, EditPreferencesInfo in)
+ throws IOException, ConfigInvalidException, RepositoryNotFoundException {
try (Repository git = gitMgr.openRepository(allUsersName)) {
- VersionedAccountPreferences p =
- VersionedAccountPreferences.forUser(id);
+ VersionedAccountPreferences p = VersionedAccountPreferences.forUser(id);
p.load(git);
- return loadSection(p.getConfig(), UserConfigSections.EDIT, null,
- new EditPreferencesInfo(), EditPreferencesInfo.defaults(), in);
+ return loadSection(
+ p.getConfig(),
+ UserConfigSections.EDIT,
+ null,
+ new EditPreferencesInfo(),
+ EditPreferencesInfo.defaults(),
+ in);
}
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/GetEmail.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/GetEmail.java
index 6763578b..edc2592 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/GetEmail.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/GetEmail.java
@@ -22,8 +22,7 @@
@Singleton
public class GetEmail implements RestReadView<AccountResource.Email> {
@Inject
- public GetEmail() {
- }
+ public GetEmail() {}
@Override
public EmailInfo apply(AccountResource.Email rsrc) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/GetEmails.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/GetEmails.java
index 14cc74e..5d4fd9d 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/GetEmails.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/GetEmails.java
@@ -16,7 +16,6 @@
import com.google.gerrit.extensions.restapi.RestReadView;
import com.google.inject.Singleton;
-
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
@@ -36,12 +35,14 @@
emails.add(e);
}
}
- Collections.sort(emails, new Comparator<EmailInfo>() {
- @Override
- public int compare(EmailInfo a, EmailInfo b) {
- return a.email.compareTo(b.email);
- }
- });
+ Collections.sort(
+ emails,
+ new Comparator<EmailInfo>() {
+ @Override
+ public int compare(EmailInfo a, EmailInfo b) {
+ return a.email.compareTo(b.email);
+ }
+ });
return emails;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/GetExternalIds.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/GetExternalIds.java
index 0b3674c..e215c9b 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/GetExternalIds.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/GetExternalIds.java
@@ -30,7 +30,6 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.util.Collection;
import java.util.Collections;
import java.util.List;
@@ -42,9 +41,7 @@
private final AuthConfig authConfig;
@Inject
- GetExternalIds(Provider<ReviewDb> db,
- Provider<CurrentUser> self,
- AuthConfig authConfig) {
+ GetExternalIds(Provider<ReviewDb> db, Provider<CurrentUser> self, AuthConfig authConfig) {
this.db = db;
this.self = self;
this.authConfig = authConfig;
@@ -57,27 +54,23 @@
throw new AuthException("not allowed to get external IDs");
}
- Collection<AccountExternalId> ids = db.get().accountExternalIds()
- .byAccount(resource.getUser().getAccountId()).toList();
+ Collection<AccountExternalId> ids =
+ db.get().accountExternalIds().byAccount(resource.getUser().getAccountId()).toList();
if (ids.isEmpty()) {
return ImmutableList.of();
}
- List<AccountExternalIdInfo> result =
- Lists.newArrayListWithCapacity(ids.size());
+ List<AccountExternalIdInfo> result = Lists.newArrayListWithCapacity(ids.size());
for (AccountExternalId id : ids) {
AccountExternalIdInfo info = new AccountExternalIdInfo();
info.identity = id.getExternalId();
info.emailAddress = id.getEmailAddress();
- info.trusted =
- toBoolean(authConfig.isIdentityTrustable(Collections.singleton(id)));
+ info.trusted = toBoolean(authConfig.isIdentityTrustable(Collections.singleton(id)));
// The identity can be deleted only if its not the one used to
// establish this web session, and if only if an identity was
// actually used to establish this web session.
if (!id.isScheme(SCHEME_USERNAME)) {
- AccountExternalId.Key last = resource.getUser()
- .getLastLoginExternalIdKey();
- info.canDelete =
- toBoolean(last == null || !last.get().equals(info.identity));
+ AccountExternalId.Key last = resource.getUser().getLastLoginExternalIdKey();
+ info.canDelete = toBoolean(last == null || !last.get().equals(info.identity));
}
result.add(info);
}
@@ -88,4 +81,3 @@
return v ? v : null;
}
}
-
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/GetGroups.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/GetGroups.java
index 5b71e0b..757cb44d 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/GetGroups.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/GetGroups.java
@@ -24,7 +24,6 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
import java.util.ArrayList;
import java.util.List;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/GetHttpPassword.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/GetHttpPassword.java
index c49ab98..135cdf6 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/GetHttpPassword.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/GetHttpPassword.java
@@ -33,10 +33,8 @@
}
@Override
- public String apply(AccountResource rsrc) throws AuthException,
- ResourceNotFoundException {
- if (self.get() != rsrc.getUser()
- && !self.get().getCapabilities().canAdministrateServer()) {
+ public String apply(AccountResource rsrc) throws AuthException, ResourceNotFoundException {
+ if (self.get() != rsrc.getUser() && !self.get().getCapabilities().canAdministrateServer()) {
throw new AuthException("not allowed to get http password");
}
AccountState s = rsrc.getUser().state();
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/GetOAuthToken.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/GetOAuthToken.java
index 5d343c4..8df8c6b 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/GetOAuthToken.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/GetOAuthToken.java
@@ -25,12 +25,11 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.net.URI;
import java.net.URISyntaxException;
@Singleton
-class GetOAuthToken implements RestReadView<AccountResource>{
+class GetOAuthToken implements RestReadView<AccountResource> {
private static final String BEARER_TYPE = "bearer";
@@ -39,7 +38,8 @@
private final String hostName;
@Inject
- GetOAuthToken(Provider<CurrentUser> self,
+ GetOAuthToken(
+ Provider<CurrentUser> self,
OAuthTokenCache tokenCache,
@CanonicalWebUrl Provider<String> urlProvider) {
this.self = self;
@@ -48,8 +48,8 @@
}
@Override
- public OAuthTokenInfo apply(AccountResource rsrc) throws AuthException,
- ResourceNotFoundException {
+ public OAuthTokenInfo apply(AccountResource rsrc)
+ throws AuthException, ResourceNotFoundException {
if (self.get() != rsrc.getUser()) {
throw new AuthException("not allowed to get access token");
}
@@ -84,5 +84,4 @@
public String expiresAt;
public String type;
}
-
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/GetPreferences.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/GetPreferences.java
index 3e83f4c..77cdbd4 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/GetPreferences.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/GetPreferences.java
@@ -29,17 +29,14 @@
private final AccountCache accountCache;
@Inject
- GetPreferences(Provider<CurrentUser> self,
- AccountCache accountCache) {
+ GetPreferences(Provider<CurrentUser> self, AccountCache accountCache) {
this.self = self;
this.accountCache = accountCache;
}
@Override
- public GeneralPreferencesInfo apply(AccountResource rsrc)
- throws AuthException {
- if (self.get() != rsrc.getUser()
- && !self.get().getCapabilities().canModifyAccount()) {
+ public GeneralPreferencesInfo apply(AccountResource rsrc) throws AuthException {
+ if (self.get() != rsrc.getUser() && !self.get().getCapabilities().canModifyAccount()) {
throw new AuthException("requires Modify Account capability");
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/GetSshKeys.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/GetSshKeys.java
index df125e0..980d880 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/GetSshKeys.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/GetSshKeys.java
@@ -26,12 +26,10 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.errors.ConfigInvalidException;
-import org.eclipse.jgit.errors.RepositoryNotFoundException;
-
import java.io.IOException;
import java.util.List;
+import org.eclipse.jgit.errors.ConfigInvalidException;
+import org.eclipse.jgit.errors.RepositoryNotFoundException;
@Singleton
public class GetSshKeys implements RestReadView<AccountResource> {
@@ -40,18 +38,16 @@
private final VersionedAuthorizedKeys.Accessor authorizedKeys;
@Inject
- GetSshKeys(Provider<CurrentUser> self,
- VersionedAuthorizedKeys.Accessor authorizedKeys) {
+ GetSshKeys(Provider<CurrentUser> self, VersionedAuthorizedKeys.Accessor authorizedKeys) {
this.self = self;
this.authorizedKeys = authorizedKeys;
}
@Override
public List<SshKeyInfo> apply(AccountResource rsrc)
- throws AuthException, OrmException, RepositoryNotFoundException,
- IOException, ConfigInvalidException {
- if (self.get() != rsrc.getUser()
- && !self.get().getCapabilities().canModifyAccount()) {
+ throws AuthException, OrmException, RepositoryNotFoundException, IOException,
+ ConfigInvalidException {
+ if (self.get() != rsrc.getUser() && !self.get().getCapabilities().canModifyAccount()) {
throw new AuthException("not allowed to get SSH keys");
}
return apply(rsrc.getUser());
@@ -59,9 +55,7 @@
public List<SshKeyInfo> apply(IdentifiedUser user)
throws RepositoryNotFoundException, IOException, ConfigInvalidException {
- return Lists.transform(
- authorizedKeys.getKeys(user.getAccountId()),
- GetSshKeys::newSshKeyInfo);
+ return Lists.transform(authorizedKeys.getKeys(user.getAccountId()), GetSshKeys::newSshKeyInfo);
}
public static SshKeyInfo newSshKeyInfo(AccountSshKey sshKey) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/GetUsername.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/GetUsername.java
index a5f271d..6541f55 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/GetUsername.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/GetUsername.java
@@ -23,12 +23,10 @@
@Singleton
public class GetUsername implements RestReadView<AccountResource> {
@Inject
- public GetUsername() {
- }
+ public GetUsername() {}
@Override
- public String apply(AccountResource rsrc) throws AuthException,
- ResourceNotFoundException {
+ public String apply(AccountResource rsrc) throws AuthException, ResourceNotFoundException {
String username = rsrc.getUser().getAccount().getUserName();
if (username == null) {
throw new ResourceNotFoundException();
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/GetWatchedProjects.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/GetWatchedProjects.java
index 61600f4e..f61704a 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/GetWatchedProjects.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/GetWatchedProjects.java
@@ -27,9 +27,6 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.errors.ConfigInvalidException;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
@@ -37,6 +34,7 @@
import java.util.List;
import java.util.Map;
import java.util.Set;
+import org.eclipse.jgit.errors.ConfigInvalidException;
@Singleton
public class GetWatchedProjects implements RestReadView<AccountResource> {
@@ -45,8 +43,7 @@
private final WatchConfig.Accessor watchConfig;
@Inject
- public GetWatchedProjects(Provider<IdentifiedUser> self,
- WatchConfig.Accessor watchConfig) {
+ public GetWatchedProjects(Provider<IdentifiedUser> self, WatchConfig.Accessor watchConfig) {
this.self = self;
this.watchConfig = watchConfig;
}
@@ -54,40 +51,34 @@
@Override
public List<ProjectWatchInfo> apply(AccountResource rsrc)
throws OrmException, AuthException, IOException, ConfigInvalidException {
- if (self.get() != rsrc.getUser()
- && !self.get().getCapabilities().canAdministrateServer()) {
- throw new AuthException("It is not allowed to list project watches "
- + "of other users");
+ if (self.get() != rsrc.getUser() && !self.get().getCapabilities().canAdministrateServer()) {
+ throw new AuthException("It is not allowed to list project watches " + "of other users");
}
Account.Id accountId = rsrc.getUser().getAccountId();
List<ProjectWatchInfo> projectWatchInfos = new ArrayList<>();
- for (Map.Entry<ProjectWatchKey, Set<NotifyType>> e : watchConfig
- .getProjectWatches(accountId).entrySet()) {
+ for (Map.Entry<ProjectWatchKey, Set<NotifyType>> e :
+ watchConfig.getProjectWatches(accountId).entrySet()) {
ProjectWatchInfo pwi = new ProjectWatchInfo();
pwi.filter = e.getKey().filter();
pwi.project = e.getKey().project().get();
- pwi.notifyAbandonedChanges =
- toBoolean(e.getValue().contains(NotifyType.ABANDONED_CHANGES));
- pwi.notifyNewChanges =
- toBoolean(e.getValue().contains(NotifyType.NEW_CHANGES));
- pwi.notifyNewPatchSets =
- toBoolean(e.getValue().contains(NotifyType.NEW_PATCHSETS));
- pwi.notifySubmittedChanges =
- toBoolean(e.getValue().contains(NotifyType.SUBMITTED_CHANGES));
- pwi.notifyAllComments =
- toBoolean(e.getValue().contains(NotifyType.ALL_COMMENTS));
+ pwi.notifyAbandonedChanges = toBoolean(e.getValue().contains(NotifyType.ABANDONED_CHANGES));
+ pwi.notifyNewChanges = toBoolean(e.getValue().contains(NotifyType.NEW_CHANGES));
+ pwi.notifyNewPatchSets = toBoolean(e.getValue().contains(NotifyType.NEW_PATCHSETS));
+ pwi.notifySubmittedChanges = toBoolean(e.getValue().contains(NotifyType.SUBMITTED_CHANGES));
+ pwi.notifyAllComments = toBoolean(e.getValue().contains(NotifyType.ALL_COMMENTS));
projectWatchInfos.add(pwi);
}
- Collections.sort(projectWatchInfos, new Comparator<ProjectWatchInfo>() {
- @Override
- public int compare(ProjectWatchInfo pwi1, ProjectWatchInfo pwi2) {
- return ComparisonChain.start()
- .compare(pwi1.project, pwi2.project)
- .compare(Strings.nullToEmpty(pwi1.filter),
- Strings.nullToEmpty(pwi2.filter))
- .result();
- }
- });
+ Collections.sort(
+ projectWatchInfos,
+ new Comparator<ProjectWatchInfo>() {
+ @Override
+ public int compare(ProjectWatchInfo pwi1, ProjectWatchInfo pwi2) {
+ return ComparisonChain.start()
+ .compare(pwi1.project, pwi2.project)
+ .compare(Strings.nullToEmpty(pwi1.filter), Strings.nullToEmpty(pwi2.filter))
+ .result();
+ }
+ });
return projectWatchInfos;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/GroupBackend.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/GroupBackend.java
index c65f6d6..bf71732 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/GroupBackend.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/GroupBackend.java
@@ -21,21 +21,16 @@
import com.google.gerrit.reviewdb.client.AccountGroup;
import com.google.gerrit.server.IdentifiedUser;
import com.google.gerrit.server.project.ProjectControl;
-
import java.util.Collection;
-/**
- * Implementations of GroupBackend provide lookup and membership accessors
- * to a group system.
- */
+/** Implementations of GroupBackend provide lookup and membership accessors to a group system. */
@ExtensionPoint
public interface GroupBackend {
/** @return {@code true} if the backend can operate on the UUID. */
boolean handles(AccountGroup.UUID uuid);
/**
- * Looks up a group in the backend. If the group does not exist, null is
- * returned.
+ * Looks up a group in the backend. If the group does not exist, null is returned.
*
* @param uuid the group identifier
* @return the group
@@ -44,16 +39,11 @@
GroupDescription.Basic get(AccountGroup.UUID uuid);
/** @return suggestions for the group name sorted by name. */
- Collection<GroupReference> suggest(
- String name,
- @Nullable ProjectControl project);
+ Collection<GroupReference> suggest(String name, @Nullable ProjectControl project);
/** @return the group membership checker for the backend. */
GroupMembership membershipsOf(IdentifiedUser user);
- /**
- * @return {@code true} if the group with the given UUID is visible to all
- * registered users.
- */
+ /** @return {@code true} if the group with the given UUID is visible to all registered users. */
boolean isVisibleToAll(AccountGroup.UUID uuid);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/GroupBackends.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/GroupBackends.java
index 69ca1e9..e029954 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/GroupBackends.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/GroupBackends.java
@@ -18,40 +18,36 @@
import com.google.gerrit.common.Nullable;
import com.google.gerrit.common.data.GroupReference;
import com.google.gerrit.server.project.ProjectControl;
-
import java.util.Collection;
import java.util.Comparator;
-/**
- * Utility class for dealing with a GroupBackend.
- */
+/** Utility class for dealing with a GroupBackend. */
public class GroupBackends {
public static final Comparator<GroupReference> GROUP_REF_NAME_COMPARATOR =
new Comparator<GroupReference>() {
- @Override
- public int compare(GroupReference a, GroupReference b) {
- return a.getName().compareTo(b.getName());
- }
- };
+ @Override
+ public int compare(GroupReference a, GroupReference b) {
+ return a.getName().compareTo(b.getName());
+ }
+ };
/**
- * Runs {@link GroupBackend#suggest(String, ProjectControl)} and filters the
- * result to return the best suggestion, or null if one does not exist.
+ * Runs {@link GroupBackend#suggest(String, ProjectControl)} and filters the result to return the
+ * best suggestion, or null if one does not exist.
*
* @param groupBackend the group backend
* @param name the name for which to suggest groups
* @return the best single GroupReference suggestion
*/
@Nullable
- public static GroupReference findBestSuggestion(GroupBackend groupBackend,
- String name) {
+ public static GroupReference findBestSuggestion(GroupBackend groupBackend, String name) {
return findBestSuggestion(groupBackend, name, null);
}
/**
- * Runs {@link GroupBackend#suggest(String, ProjectControl)} and filters the
- * result to return the best suggestion, or null if one does not exist.
+ * Runs {@link GroupBackend#suggest(String, ProjectControl)} and filters the result to return the
+ * best suggestion, or null if one does not exist.
*
* @param groupBackend the group backend
* @param name the name for which to suggest groups
@@ -59,8 +55,8 @@
* @return the best single GroupReference suggestion
*/
@Nullable
- public static GroupReference findBestSuggestion(GroupBackend groupBackend,
- String name, @Nullable ProjectControl project) {
+ public static GroupReference findBestSuggestion(
+ GroupBackend groupBackend, String name, @Nullable ProjectControl project) {
Collection<GroupReference> refs = groupBackend.suggest(name, project);
if (refs.size() == 1) {
return Iterables.getOnlyElement(refs);
@@ -75,22 +71,21 @@
}
/**
- * Runs {@link GroupBackend#suggest(String, ProjectControl)} and filters the
- * result to return the exact suggestion, or null if one does not exist.
+ * Runs {@link GroupBackend#suggest(String, ProjectControl)} and filters the result to return the
+ * exact suggestion, or null if one does not exist.
*
* @param groupBackend the group backend
* @param name the name for which to suggest groups
* @return the exact single GroupReference suggestion
*/
@Nullable
- public static GroupReference findExactSuggestion(
- GroupBackend groupBackend, String name) {
+ public static GroupReference findExactSuggestion(GroupBackend groupBackend, String name) {
return findExactSuggestion(groupBackend, name, null);
}
/**
- * Runs {@link GroupBackend#suggest(String, ProjectControl)} and filters the
- * result to return the exact suggestion, or null if one does not exist.
+ * Runs {@link GroupBackend#suggest(String, ProjectControl)} and filters the result to return the
+ * exact suggestion, or null if one does not exist.
*
* @param groupBackend the group backend
* @param name the name for which to suggest groups
@@ -114,6 +109,5 @@
return ref.getName().equalsIgnoreCase(name) || ref.getUUID().get().equals(name);
}
- private GroupBackends() {
- }
+ private GroupBackends() {}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/GroupCache.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/GroupCache.java
index 3214b35..8e30a24 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/GroupCache.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/GroupCache.java
@@ -17,7 +17,6 @@
import com.google.common.collect.ImmutableList;
import com.google.gerrit.common.Nullable;
import com.google.gerrit.reviewdb.client.AccountGroup;
-
import java.io.IOException;
/** Tracks group objects in memory for efficient access. */
@@ -27,9 +26,8 @@
AccountGroup get(AccountGroup.NameKey name);
/**
- * Lookup a group definition by its UUID. The returned definition may be null
- * if the group has been deleted and the UUID reference is stale, or was
- * copied from another server.
+ * Lookup a group definition by its UUID. The returned definition may be null if the group has
+ * been deleted and the UUID reference is stale, or was copied from another server.
*/
@Nullable
AccountGroup get(AccountGroup.UUID uuid);
@@ -42,6 +40,6 @@
void evict(AccountGroup group) throws IOException;
- void evictAfterRename(AccountGroup.NameKey oldName,
- AccountGroup.NameKey newName) throws IOException;
+ void evictAfterRename(AccountGroup.NameKey oldName, AccountGroup.NameKey newName)
+ throws IOException;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/GroupCacheImpl.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/GroupCacheImpl.java
index a920c22..5c8e3e9 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/GroupCacheImpl.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/GroupCacheImpl.java
@@ -31,20 +31,17 @@
import com.google.inject.Singleton;
import com.google.inject.TypeLiteral;
import com.google.inject.name.Named;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.io.IOException;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/** Tracks group objects in memory for efficient access. */
@Singleton
public class GroupCacheImpl implements GroupCache {
- private static final Logger log = LoggerFactory
- .getLogger(GroupCacheImpl.class);
+ private static final Logger log = LoggerFactory.getLogger(GroupCacheImpl.class);
private static final String BYID_NAME = "groups";
private static final String BYNAME_NAME = "groups_byname";
@@ -54,20 +51,14 @@
return new CacheModule() {
@Override
protected void configure() {
- cache(BYID_NAME,
- AccountGroup.Id.class,
- new TypeLiteral<Optional<AccountGroup>>() {})
- .loader(ByIdLoader.class);
+ cache(BYID_NAME, AccountGroup.Id.class, new TypeLiteral<Optional<AccountGroup>>() {})
+ .loader(ByIdLoader.class);
- cache(BYNAME_NAME,
- String.class,
- new TypeLiteral<Optional<AccountGroup>>() {})
- .loader(ByNameLoader.class);
+ cache(BYNAME_NAME, String.class, new TypeLiteral<Optional<AccountGroup>>() {})
+ .loader(ByNameLoader.class);
- cache(BYUUID_NAME,
- String.class,
- new TypeLiteral<Optional<AccountGroup>>() {})
- .loader(ByUUIDLoader.class);
+ cache(BYUUID_NAME, String.class, new TypeLiteral<Optional<AccountGroup>>() {})
+ .loader(ByUUIDLoader.class);
bind(GroupCacheImpl.class);
bind(GroupCache.class).to(GroupCacheImpl.class);
@@ -121,8 +112,8 @@
}
@Override
- public void evictAfterRename(final AccountGroup.NameKey oldName,
- final AccountGroup.NameKey newName) throws IOException {
+ public void evictAfterRename(
+ final AccountGroup.NameKey oldName, final AccountGroup.NameKey newName) throws IOException {
if (oldName != null) {
byName.invalidate(oldName.get());
}
@@ -169,8 +160,7 @@
}
@Override
- public void onCreateGroup(AccountGroup.NameKey newGroupName)
- throws IOException {
+ public void onCreateGroup(AccountGroup.NameKey newGroupName) throws IOException {
byName.invalidate(newGroupName.get());
indexer.get().index(get(newGroupName).getGroupUUID());
}
@@ -180,8 +170,7 @@
return new AccountGroup(name, key, null);
}
- static class ByIdLoader extends
- CacheLoader<AccountGroup.Id, Optional<AccountGroup>> {
+ static class ByIdLoader extends CacheLoader<AccountGroup.Id, Optional<AccountGroup>> {
private final SchemaFactory<ReviewDb> schema;
@Inject
@@ -190,8 +179,7 @@
}
@Override
- public Optional<AccountGroup> load(final AccountGroup.Id key)
- throws Exception {
+ public Optional<AccountGroup> load(final AccountGroup.Id key) throws Exception {
try (ReviewDb db = schema.open()) {
return Optional.ofNullable(db.accountGroups().get(key));
}
@@ -207,8 +195,7 @@
}
@Override
- public Optional<AccountGroup> load(String name)
- throws Exception {
+ public Optional<AccountGroup> load(String name) throws Exception {
try (ReviewDb db = schema.open()) {
AccountGroup.NameKey key = new AccountGroup.NameKey(name);
AccountGroupName r = db.accountGroupNames().get(key);
@@ -229,8 +216,7 @@
}
@Override
- public Optional<AccountGroup> load(String uuid)
- throws Exception {
+ public Optional<AccountGroup> load(String uuid) throws Exception {
try (ReviewDb db = schema.open()) {
List<AccountGroup> r;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/GroupComparator.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/GroupComparator.java
index 13800b5..4bab3a7 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/GroupComparator.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/GroupComparator.java
@@ -15,7 +15,6 @@
package com.google.gerrit.server.account;
import com.google.gerrit.reviewdb.client.AccountGroup;
-
import java.util.Comparator;
public class GroupComparator implements Comparator<AccountGroup> {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/GroupControl.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/GroupControl.java
index 2e03913..ee788ec 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/GroupControl.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/GroupControl.java
@@ -36,8 +36,7 @@
groupBackend = gb;
}
- public GroupControl controlFor(final CurrentUser who,
- final AccountGroup.UUID groupId)
+ public GroupControl controlFor(final CurrentUser who, final AccountGroup.UUID groupId)
throws NoSuchGroupException {
final GroupDescription.Basic group = groupBackend.get(groupId);
if (group == null) {
@@ -53,15 +52,13 @@
private final GroupBackend groupBackend;
@Inject
- Factory(final GroupCache gc, final Provider<CurrentUser> cu,
- final GroupBackend gb) {
+ Factory(final GroupCache gc, final Provider<CurrentUser> cu, final GroupBackend gb) {
groupCache = gc;
user = cu;
groupBackend = gb;
}
- public GroupControl controlFor(final AccountGroup.Id groupId)
- throws NoSuchGroupException {
+ public GroupControl controlFor(final AccountGroup.Id groupId) throws NoSuchGroupException {
final AccountGroup group = groupCache.get(groupId);
if (group == null) {
throw new NoSuchGroupException(groupId);
@@ -69,8 +66,7 @@
return controlFor(GroupDescriptions.forAccountGroup(group));
}
- public GroupControl controlFor(final AccountGroup.UUID groupId)
- throws NoSuchGroupException {
+ public GroupControl controlFor(final AccountGroup.UUID groupId) throws NoSuchGroupException {
final GroupDescription.Basic group = groupBackend.get(groupId);
if (group == null) {
throw new NoSuchGroupException(groupId);
@@ -86,8 +82,7 @@
return new GroupControl(user.get(), group, groupBackend);
}
- public GroupControl validateFor(final AccountGroup.Id groupId)
- throws NoSuchGroupException {
+ public GroupControl validateFor(final AccountGroup.Id groupId) throws NoSuchGroupException {
final GroupControl c = controlFor(groupId);
if (!c.isVisible()) {
throw new NoSuchGroupException(groupId);
@@ -95,8 +90,7 @@
return c;
}
- public GroupControl validateFor(final AccountGroup.UUID groupUUID)
- throws NoSuchGroupException {
+ public GroupControl validateFor(final AccountGroup.UUID groupUUID) throws NoSuchGroupException {
final GroupControl c = controlFor(groupUUID);
if (!c.isVisible()) {
throw new NoSuchGroupException(groupUUID);
@@ -112,7 +106,7 @@
GroupControl(CurrentUser who, GroupDescription.Basic gd, GroupBackend gb) {
user = who;
- group = gd;
+ group = gd;
groupBackend = gb;
}
@@ -131,10 +125,10 @@
* server administrators.
*/
return user.isInternalUser()
- || groupBackend.isVisibleToAll(group.getGroupUUID())
- || user.getEffectiveGroups().contains(group.getGroupUUID())
- || user.getCapabilities().canAdministrateServer()
- || isOwner();
+ || groupBackend.isVisibleToAll(group.getGroupUUID())
+ || user.getEffectiveGroups().contains(group.getGroupUUID())
+ || user.getCapabilities().canAdministrateServer()
+ || isOwner();
}
public boolean isOwner() {
@@ -143,8 +137,9 @@
isOwner = false;
} else if (isOwner == null) {
AccountGroup.UUID ownerUUID = accountGroup.getOwnerGroupUUID();
- isOwner = getUser().getEffectiveGroups().contains(ownerUUID)
- || getUser().getCapabilities().canAdministrateServer();
+ isOwner =
+ getUser().getEffectiveGroups().contains(ownerUUID)
+ || getUser().getCapabilities().canAdministrateServer();
}
return isOwner;
}
@@ -178,7 +173,6 @@
private boolean canSeeMembers() {
AccountGroup accountGroup = GroupDescriptions.toAccountGroup(group);
- return (accountGroup != null && accountGroup.isVisibleToAll())
- || isOwner();
+ return (accountGroup != null && accountGroup.isVisibleToAll()) || isOwner();
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/GroupDetailFactory.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/GroupDetailFactory.java
index 5f1840f..fb7d7e7 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/GroupDetailFactory.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/GroupDetailFactory.java
@@ -23,7 +23,6 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
-
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
@@ -41,7 +40,8 @@
private GroupControl control;
@Inject
- GroupDetailFactory(ReviewDb db,
+ GroupDetailFactory(
+ ReviewDb db,
GroupControl.Factory groupControl,
GroupCache groupCache,
@Assisted AccountGroup.Id groupId) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/GroupIncludeCache.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/GroupIncludeCache.java
index 0d1fd20..c702aef 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/GroupIncludeCache.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/GroupIncludeCache.java
@@ -15,7 +15,6 @@
package com.google.gerrit.server.account;
import com.google.gerrit.reviewdb.client.AccountGroup;
-
import java.util.Collection;
/** Tracks group inclusions in memory for efficient access. */
@@ -30,5 +29,6 @@
Collection<AccountGroup.UUID> allExternalMembers();
void evictSubgroupsOf(AccountGroup.UUID groupId);
+
void evictParentGroupsOf(AccountGroup.UUID groupId);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/GroupIncludeCacheImpl.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/GroupIncludeCacheImpl.java
index 02889bf..1c9baf8 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/GroupIncludeCacheImpl.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/GroupIncludeCacheImpl.java
@@ -28,22 +28,19 @@
import com.google.inject.Singleton;
import com.google.inject.TypeLiteral;
import com.google.inject.name.Named;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutionException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/** Tracks group inclusions in memory for efficient access. */
@Singleton
public class GroupIncludeCacheImpl implements GroupIncludeCache {
- private static final Logger log = LoggerFactory
- .getLogger(GroupIncludeCacheImpl.class);
+ private static final Logger log = LoggerFactory.getLogger(GroupIncludeCacheImpl.class);
private static final String PARENT_GROUPS_NAME = "groups_byinclude";
private static final String SUBGROUPS_NAME = "groups_members";
private static final String EXTERNAL_NAME = "groups_external";
@@ -52,20 +49,20 @@
return new CacheModule() {
@Override
protected void configure() {
- cache(PARENT_GROUPS_NAME,
- AccountGroup.UUID.class,
- new TypeLiteral<ImmutableList<AccountGroup.UUID>>() {})
- .loader(ParentGroupsLoader.class);
+ cache(
+ PARENT_GROUPS_NAME,
+ AccountGroup.UUID.class,
+ new TypeLiteral<ImmutableList<AccountGroup.UUID>>() {})
+ .loader(ParentGroupsLoader.class);
- cache(SUBGROUPS_NAME,
- AccountGroup.UUID.class,
- new TypeLiteral<ImmutableList<AccountGroup.UUID>>() {})
- .loader(SubgroupsLoader.class);
+ cache(
+ SUBGROUPS_NAME,
+ AccountGroup.UUID.class,
+ new TypeLiteral<ImmutableList<AccountGroup.UUID>>() {})
+ .loader(SubgroupsLoader.class);
- cache(EXTERNAL_NAME,
- String.class,
- new TypeLiteral<ImmutableList<AccountGroup.UUID>>() {})
- .loader(AllExternalLoader.class);
+ cache(EXTERNAL_NAME, String.class, new TypeLiteral<ImmutableList<AccountGroup.UUID>>() {})
+ .loader(AllExternalLoader.class);
bind(GroupIncludeCacheImpl.class);
bind(GroupIncludeCache.class).to(GroupIncludeCacheImpl.class);
@@ -73,24 +70,17 @@
};
}
- private final
- LoadingCache<AccountGroup.UUID, ImmutableList<AccountGroup.UUID>>
- subgroups;
- private final
- LoadingCache<AccountGroup.UUID, ImmutableList<AccountGroup.UUID>>
- parentGroups;
+ private final LoadingCache<AccountGroup.UUID, ImmutableList<AccountGroup.UUID>> subgroups;
+ private final LoadingCache<AccountGroup.UUID, ImmutableList<AccountGroup.UUID>> parentGroups;
private final LoadingCache<String, ImmutableList<AccountGroup.UUID>> external;
@Inject
GroupIncludeCacheImpl(
@Named(SUBGROUPS_NAME)
- LoadingCache<AccountGroup.UUID, ImmutableList<AccountGroup.UUID>>
- subgroups,
+ LoadingCache<AccountGroup.UUID, ImmutableList<AccountGroup.UUID>> subgroups,
@Named(PARENT_GROUPS_NAME)
- LoadingCache<AccountGroup.UUID, ImmutableList<AccountGroup.UUID>>
- parentGroups,
- @Named(EXTERNAL_NAME)
- LoadingCache<String, ImmutableList<AccountGroup.UUID>> external) {
+ LoadingCache<AccountGroup.UUID, ImmutableList<AccountGroup.UUID>> parentGroups,
+ @Named(EXTERNAL_NAME) LoadingCache<String, ImmutableList<AccountGroup.UUID>> external) {
this.subgroups = subgroups;
this.parentGroups = parentGroups;
this.external = external;
@@ -107,8 +97,7 @@
}
@Override
- public Collection<AccountGroup.UUID> parentGroupsOf(
- AccountGroup.UUID groupId) {
+ public Collection<AccountGroup.UUID> parentGroupsOf(AccountGroup.UUID groupId) {
try {
return parentGroups.get(groupId);
} catch (ExecutionException e) {
@@ -145,8 +134,8 @@
}
}
- static class SubgroupsLoader extends
- CacheLoader<AccountGroup.UUID, ImmutableList<AccountGroup.UUID>> {
+ static class SubgroupsLoader
+ extends CacheLoader<AccountGroup.UUID, ImmutableList<AccountGroup.UUID>> {
private final SchemaFactory<ReviewDb> schema;
@Inject
@@ -155,8 +144,7 @@
}
@Override
- public ImmutableList<AccountGroup.UUID> load(
- AccountGroup.UUID key) throws OrmException {
+ public ImmutableList<AccountGroup.UUID> load(AccountGroup.UUID key) throws OrmException {
try (ReviewDb db = schema.open()) {
List<AccountGroup> group = db.accountGroups().byUUID(key).toList();
if (group.size() != 1) {
@@ -164,8 +152,7 @@
}
Set<AccountGroup.UUID> ids = new HashSet<>();
- for (AccountGroupById agi : db.accountGroupById()
- .byGroup(group.get(0).getId())) {
+ for (AccountGroupById agi : db.accountGroupById().byGroup(group.get(0).getId())) {
ids.add(agi.getIncludeUUID());
}
return ImmutableList.copyOf(ids);
@@ -173,8 +160,8 @@
}
}
- static class ParentGroupsLoader extends
- CacheLoader<AccountGroup.UUID, ImmutableList<AccountGroup.UUID>> {
+ static class ParentGroupsLoader
+ extends CacheLoader<AccountGroup.UUID, ImmutableList<AccountGroup.UUID>> {
private final SchemaFactory<ReviewDb> schema;
@Inject
@@ -183,12 +170,10 @@
}
@Override
- public ImmutableList<AccountGroup.UUID> load(AccountGroup.UUID key)
- throws OrmException {
+ public ImmutableList<AccountGroup.UUID> load(AccountGroup.UUID key) throws OrmException {
try (ReviewDb db = schema.open()) {
Set<AccountGroup.Id> ids = new HashSet<>();
- for (AccountGroupById agi : db.accountGroupById()
- .byIncludeUUID(key)) {
+ for (AccountGroupById agi : db.accountGroupById().byIncludeUUID(key)) {
ids.add(agi.getGroupId());
}
@@ -201,8 +186,7 @@
}
}
- static class AllExternalLoader extends
- CacheLoader<String, ImmutableList<AccountGroup.UUID>> {
+ static class AllExternalLoader extends CacheLoader<String, ImmutableList<AccountGroup.UUID>> {
private final SchemaFactory<ReviewDb> schema;
@Inject
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/GroupMembers.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/GroupMembers.java
index 61f13d6..ea99b9b 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/GroupMembers.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/GroupMembers.java
@@ -28,7 +28,6 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
-
import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
@@ -46,7 +45,8 @@
private final CurrentUser currentUser;
@Inject
- GroupMembers(final GroupCache groupCache,
+ GroupMembers(
+ final GroupCache groupCache,
final GroupDetailFactory.Factory groupDetailFactory,
final AccountCache accountCache,
final ProjectControl.GenericFactory projectControl,
@@ -58,14 +58,15 @@
this.currentUser = currentUser;
}
- public Set<Account> listAccounts(final AccountGroup.UUID groupUUID,
- final Project.NameKey project) throws NoSuchGroupException,
- NoSuchProjectException, OrmException, IOException {
+ public Set<Account> listAccounts(final AccountGroup.UUID groupUUID, final Project.NameKey project)
+ throws NoSuchGroupException, NoSuchProjectException, OrmException, IOException {
return listAccounts(groupUUID, project, new HashSet<AccountGroup.UUID>());
}
- private Set<Account> listAccounts(final AccountGroup.UUID groupUUID,
- final Project.NameKey project, final Set<AccountGroup.UUID> seen)
+ private Set<Account> listAccounts(
+ final AccountGroup.UUID groupUUID,
+ final Project.NameKey project,
+ final Set<AccountGroup.UUID> seen)
throws NoSuchGroupException, OrmException, NoSuchProjectException, IOException {
if (SystemGroupBackend.PROJECT_OWNERS.equals(groupUUID)) {
return getProjectOwners(project, seen);
@@ -77,17 +78,16 @@
return Collections.emptySet();
}
- private Set<Account> getProjectOwners(final Project.NameKey project,
- final Set<AccountGroup.UUID> seen) throws NoSuchProjectException,
- NoSuchGroupException, OrmException, IOException {
+ private Set<Account> getProjectOwners(
+ final Project.NameKey project, final Set<AccountGroup.UUID> seen)
+ throws NoSuchProjectException, NoSuchGroupException, OrmException, IOException {
seen.add(SystemGroupBackend.PROJECT_OWNERS);
if (project == null) {
return Collections.emptySet();
}
final Iterable<AccountGroup.UUID> ownerGroups =
- projectControl.controlFor(project, currentUser).getProjectState()
- .getAllOwners();
+ projectControl.controlFor(project, currentUser).getProjectState().getAllOwners();
final HashSet<Account> projectOwners = new HashSet<>();
for (final AccountGroup.UUID ownerGroup : ownerGroups) {
@@ -98,12 +98,11 @@
return projectOwners;
}
- private Set<Account> getGroupMembers(final AccountGroup group,
- final Project.NameKey project, final Set<AccountGroup.UUID> seen)
+ private Set<Account> getGroupMembers(
+ final AccountGroup group, final Project.NameKey project, final Set<AccountGroup.UUID> seen)
throws NoSuchGroupException, OrmException, NoSuchProjectException, IOException {
seen.add(group.getGroupUUID());
- final GroupDetail groupDetail =
- groupDetailFactory.create(group.getId()).call();
+ final GroupDetail groupDetail = groupDetailFactory.create(group.getId()).call();
final Set<Account> members = new HashSet<>();
if (groupDetail.members != null) {
@@ -113,8 +112,7 @@
}
if (groupDetail.includes != null) {
for (final AccountGroupById groupInclude : groupDetail.includes) {
- final AccountGroup includedGroup =
- groupCache.get(groupInclude.getIncludeUUID());
+ final AccountGroup includedGroup = groupCache.get(groupInclude.getIncludeUUID());
if (includedGroup != null && !seen.contains(includedGroup.getGroupUUID())) {
members.addAll(listAccounts(includedGroup.getGroupUUID(), project, seen));
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/GroupMembership.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/GroupMembership.java
index c45b7b7..59b992a 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/GroupMembership.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/GroupMembership.java
@@ -15,35 +15,33 @@
package com.google.gerrit.server.account;
import com.google.gerrit.reviewdb.client.AccountGroup;
-
import java.util.Collections;
import java.util.Set;
/**
- * Implementations of GroupMembership provide methods to test
- * the presence of a user in a particular group.
+ * Implementations of GroupMembership provide methods to test the presence of a user in a particular
+ * group.
*/
public interface GroupMembership {
- GroupMembership EMPTY =
- new ListGroupMembership(Collections.<AccountGroup.UUID>emptySet());
+ GroupMembership EMPTY = new ListGroupMembership(Collections.<AccountGroup.UUID>emptySet());
/**
- * Returns {@code true} when the user this object was created for is a member
- * of the specified group.
+ * Returns {@code true} when the user this object was created for is a member of the specified
+ * group.
*/
boolean contains(AccountGroup.UUID groupId);
/**
- * Returns {@code true} when the user this object was created for is a member
- * of any of the specified group.
+ * Returns {@code true} when the user this object was created for is a member of any of the
+ * specified group.
*/
boolean containsAnyOf(Iterable<AccountGroup.UUID> groupIds);
/**
* Returns a set containing an input member of {@code contains(id)} is true.
- * <p>
- * This is batch form of contains that returns specific group information.
- * Implementors may implement the method as:
+ *
+ * <p>This is batch form of contains that returns specific group information. Implementors may
+ * implement the method as:
*
* <pre>
* Set<AccountGroup.UUID> r = new HashSet<>();
@@ -54,11 +52,10 @@
Set<AccountGroup.UUID> intersection(Iterable<AccountGroup.UUID> groupIds);
/**
- * Returns the set of groups that can be determined by the implementation.
- * This may not return all groups the {@link #contains(AccountGroup.UUID)}
- * would return {@code true} for, but will at least contain all top level
- * groups. This restriction stems from the API of some group systems, which
- * make it expensive to enumerate the members of a group.
+ * Returns the set of groups that can be determined by the implementation. This may not return all
+ * groups the {@link #contains(AccountGroup.UUID)} would return {@code true} for, but will at
+ * least contain all top level groups. This restriction stems from the API of some group systems,
+ * which make it expensive to enumerate the members of a group.
*/
Set<AccountGroup.UUID> getKnownGroups();
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/GroupUUID.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/GroupUUID.java
index b871c68..45c7052 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/GroupUUID.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/GroupUUID.java
@@ -15,13 +15,11 @@
package com.google.gerrit.server.account;
import com.google.gerrit.reviewdb.client.AccountGroup;
-
+import java.security.MessageDigest;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.PersonIdent;
-import java.security.MessageDigest;
-
public class GroupUUID {
public static AccountGroup.UUID make(String groupName, PersonIdent creator) {
MessageDigest md = Constants.newMessageDigest();
@@ -30,6 +28,5 @@
return new AccountGroup.UUID(ObjectId.fromRaw(md.digest()).name());
}
- private GroupUUID() {
- }
+ private GroupUUID() {}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/IncludingGroupMembership.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/IncludingGroupMembership.java
index f38d071..70801c3 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/IncludingGroupMembership.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/IncludingGroupMembership.java
@@ -21,7 +21,6 @@
import com.google.gerrit.server.IdentifiedUser;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
-
import java.util.HashSet;
import java.util.List;
import java.util.Map;
@@ -30,12 +29,11 @@
/**
* Group membership checker for the internal group system.
- * <p>
- * Groups the user is directly a member of are pulled from the in-memory
- * AccountCache by way of the IdentifiedUser. Transitive group memberhips are
- * resolved on demand starting from the requested group and looking for a path
- * to a group the user is a member of. Other group backends are supported by
- * recursively invoking the universal GroupMembership.
+ *
+ * <p>Groups the user is directly a member of are pulled from the in-memory AccountCache by way of
+ * the IdentifiedUser. Transitive group memberhips are resolved on demand starting from the
+ * requested group and looking for a path to a group the user is a member of. Other group backends
+ * are supported by recursively invoking the universal GroupMembership.
*/
public class IncludingGroupMembership implements GroupMembership {
public interface Factory {
@@ -48,8 +46,7 @@
private Set<AccountGroup.UUID> knownGroups;
@Inject
- IncludingGroupMembership(GroupIncludeCache includeCache,
- @Assisted IdentifiedUser user) {
+ IncludingGroupMembership(GroupIncludeCache includeCache, @Assisted IdentifiedUser user) {
this.includeCache = includeCache;
this.user = user;
@@ -123,8 +120,7 @@
r.remove(null);
List<AccountGroup.UUID> q = Lists.newArrayList(r);
- for (AccountGroup.UUID g : membership.intersection(
- includeCache.allExternalMembers())) {
+ for (AccountGroup.UUID g : membership.intersection(includeCache.allExternalMembers())) {
if (g != null && r.add(g)) {
q.add(g);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/Index.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/Index.java
index 53b0467..6943dca 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/Index.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/Index.java
@@ -22,29 +22,24 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.io.IOException;
@Singleton
public class Index implements RestModifyView<AccountResource, Input> {
- public static class Input {
- }
+ public static class Input {}
private final AccountCache accountCache;
private final Provider<CurrentUser> self;
@Inject
- Index(AccountCache accountCache,
- Provider<CurrentUser> self) {
+ Index(AccountCache accountCache, Provider<CurrentUser> self) {
this.accountCache = accountCache;
this.self = self;
}
@Override
- public Response<?> apply(AccountResource rsrc, Input input)
- throws IOException, AuthException {
- if (self.get() != rsrc.getUser()
- && !self.get().getCapabilities().canModifyAccount()) {
+ public Response<?> apply(AccountResource rsrc, Input input) throws IOException, AuthException {
+ if (self.get() != rsrc.getUser() && !self.get().getCapabilities().canModifyAccount()) {
throw new AuthException("not allowed to index account");
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/InternalAccountDirectory.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/InternalAccountDirectory.java
index d18babf..88eb8fa 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/InternalAccountDirectory.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/InternalAccountDirectory.java
@@ -26,7 +26,6 @@
import com.google.inject.AbstractModule;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
@@ -36,8 +35,7 @@
@Singleton
public class InternalAccountDirectory extends AccountDirectory {
- static final Set<FillOptions> ID_ONLY =
- Collections.unmodifiableSet(EnumSet.of(FillOptions.ID));
+ static final Set<FillOptions> ID_ONLY = Collections.unmodifiableSet(EnumSet.of(FillOptions.ID));
public static class Module extends AbstractModule {
@Override
@@ -51,7 +49,8 @@
private final IdentifiedUser.GenericFactory userFactory;
@Inject
- InternalAccountDirectory(AccountCache accountCache,
+ InternalAccountDirectory(
+ AccountCache accountCache,
DynamicItem<AvatarProvider> avatar,
IdentifiedUser.GenericFactory userFactory) {
this.accountCache = accountCache;
@@ -60,9 +59,7 @@
}
@Override
- public void fillAccountInfo(
- Iterable<? extends AccountInfo> in,
- Set<FillOptions> options)
+ public void fillAccountInfo(Iterable<? extends AccountInfo> in, Set<FillOptions> options)
throws DirectoryException {
if (options.equals(ID_ONLY)) {
return;
@@ -74,7 +71,8 @@
}
}
- private void fill(AccountInfo info,
+ private void fill(
+ AccountInfo info,
Account account,
@Nullable Collection<AccountExternalId> externalIds,
Set<FillOptions> options) {
@@ -94,14 +92,10 @@
info.email = account.getPreferredEmail();
}
if (options.contains(FillOptions.SECONDARY_EMAILS)) {
- info.secondaryEmails = externalIds != null
- ? getSecondaryEmails(account, externalIds)
- : null;
+ info.secondaryEmails = externalIds != null ? getSecondaryEmails(account, externalIds) : null;
}
if (options.contains(FillOptions.USERNAME)) {
- info.username = externalIds != null
- ? AccountState.getUserName(externalIds)
- : null;
+ info.username = externalIds != null ? AccountState.getUserName(externalIds) : null;
}
if (options.contains(FillOptions.STATUS)) {
@@ -130,8 +124,8 @@
}
}
- public List<String> getSecondaryEmails(Account account,
- Collection<AccountExternalId> externalIds) {
+ public List<String> getSecondaryEmails(
+ Account account, Collection<AccountExternalId> externalIds) {
List<String> emails = new ArrayList<>(AccountState.getEmails(externalIds));
if (account.getPreferredEmail() != null) {
emails.remove(account.getPreferredEmail());
@@ -141,10 +135,7 @@
}
private static void addAvatar(
- AvatarProvider provider,
- AccountInfo account,
- IdentifiedUser user,
- int size) {
+ AvatarProvider provider, AccountInfo account, IdentifiedUser user, int size) {
String url = provider.getUrl(user, size);
if (url != null) {
AvatarInfo avatar = new AvatarInfo();
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/InternalGroupBackend.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/InternalGroupBackend.java
index 2028654..b0ada0d 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/InternalGroupBackend.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/InternalGroupBackend.java
@@ -24,10 +24,8 @@
import com.google.gerrit.server.project.ProjectControl;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.lib.ObjectId;
-
import java.util.Collection;
+import org.eclipse.jgit.lib.ObjectId;
/** Implementation of GroupBackend for the internal group system. */
@Singleton
@@ -37,7 +35,8 @@
private final IncludingGroupMembership.Factory groupMembershipFactory;
@Inject
- InternalGroupBackend(GroupControl.Factory groupControlFactory,
+ InternalGroupBackend(
+ GroupControl.Factory groupControlFactory,
GroupCache groupCache,
IncludingGroupMembership.Factory groupMembershipFactory) {
this.groupControlFactory = groupControlFactory;
@@ -65,13 +64,15 @@
}
@Override
- public Collection<GroupReference> suggest(final String name,
- final ProjectControl project) {
- return groupCache.all().stream()
- .filter(group ->
- // startsWithIgnoreCase && isVisible
- group.getName().regionMatches(true, 0, name, 0, name.length())
- && groupControlFactory.controlFor(group).isVisible())
+ public Collection<GroupReference> suggest(final String name, final ProjectControl project) {
+ return groupCache
+ .all()
+ .stream()
+ .filter(
+ group ->
+ // startsWithIgnoreCase && isVisible
+ group.getName().regionMatches(true, 0, name, 0, name.length())
+ && groupControlFactory.controlFor(group).isVisible())
.map(GroupReference::forGroup)
.collect(toList());
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/ListGroupMembership.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/ListGroupMembership.java
index 118940f..60e7345 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/ListGroupMembership.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/ListGroupMembership.java
@@ -17,12 +17,9 @@
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.google.gerrit.reviewdb.client.AccountGroup;
-
import java.util.Set;
-/**
- * GroupMembership over an explicit list.
- */
+/** GroupMembership over an explicit list. */
public class ListGroupMembership implements GroupMembership {
private final Set<AccountGroup.UUID> groups;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/Module.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/Module.java
index c78008d..0080e34 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/Module.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/Module.java
@@ -63,8 +63,7 @@
post(ACCOUNT_KIND, "sshkeys").to(AddSshKey.class);
get(ACCOUNT_KIND, "watched.projects").to(GetWatchedProjects.class);
post(ACCOUNT_KIND, "watched.projects").to(PostWatchedProjects.class);
- post(ACCOUNT_KIND, "watched.projects:delete")
- .to(DeleteWatchedProjects.class);
+ post(ACCOUNT_KIND, "watched.projects:delete").to(DeleteWatchedProjects.class);
get(SSH_KEY_KIND).to(GetSshKey.class);
delete(SSH_KEY_KIND).to(DeleteSshKey.class);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/PostWatchedProjects.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/PostWatchedProjects.java
index 92fe837..55ba912 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/PostWatchedProjects.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/PostWatchedProjects.java
@@ -29,15 +29,13 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.errors.ConfigInvalidException;
-
import java.io.IOException;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
+import org.eclipse.jgit.errors.ConfigInvalidException;
@Singleton
public class PostWatchedProjects
@@ -49,7 +47,8 @@
private final WatchConfig.Accessor watchConfig;
@Inject
- public PostWatchedProjects(Provider<IdentifiedUser> self,
+ public PostWatchedProjects(
+ Provider<IdentifiedUser> self,
GetWatchedProjects getWatchedProjects,
ProjectsCollection projectsCollection,
AccountCache accountCache,
@@ -62,11 +61,9 @@
}
@Override
- public List<ProjectWatchInfo> apply(AccountResource rsrc,
- List<ProjectWatchInfo> input) throws OrmException, RestApiException,
- IOException, ConfigInvalidException {
- if (self.get() != rsrc.getUser()
- && !self.get().getCapabilities().canAdministrateServer()) {
+ public List<ProjectWatchInfo> apply(AccountResource rsrc, List<ProjectWatchInfo> input)
+ throws OrmException, RestApiException, IOException, ConfigInvalidException {
+ if (self.get() != rsrc.getUser() && !self.get().getCapabilities().canAdministrateServer()) {
throw new AuthException("not allowed to edit project watches");
}
Account.Id accountId = rsrc.getUser().getAccountId();
@@ -75,17 +72,16 @@
return getWatchedProjects.apply(rsrc);
}
- private Map<ProjectWatchKey, Set<NotifyType>> asMap(
- List<ProjectWatchInfo> input) throws BadRequestException,
- UnprocessableEntityException, IOException {
+ private Map<ProjectWatchKey, Set<NotifyType>> asMap(List<ProjectWatchInfo> input)
+ throws BadRequestException, UnprocessableEntityException, IOException {
Map<ProjectWatchKey, Set<NotifyType>> m = new HashMap<>();
for (ProjectWatchInfo info : input) {
if (info.project == null) {
throw new BadRequestException("project name must be specified");
}
- ProjectWatchKey key = ProjectWatchKey.create(
- projectsCollection.parse(info.project).getNameKey(), info.filter);
+ ProjectWatchKey key =
+ ProjectWatchKey.create(projectsCollection.parse(info.project).getNameKey(), info.filter);
if (m.containsKey(key)) {
throw new BadRequestException(
"duplicate entry for project " + format(info.project, info.filter));
@@ -119,8 +115,6 @@
private static String format(String project, String filter) {
return project
- + (filter != null && !WatchConfig.FILTER_ALL.equals(filter)
- ? " and filter " + filter
- : "");
+ + (filter != null && !WatchConfig.FILTER_ALL.equals(filter) ? " and filter " + filter : "");
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/PutAccount.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/PutAccount.java
index 239b954..da5a58f 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/PutAccount.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/PutAccount.java
@@ -22,8 +22,7 @@
import com.google.inject.Singleton;
@Singleton
-public class PutAccount
- implements RestModifyView<AccountResource, AccountInput> {
+public class PutAccount implements RestModifyView<AccountResource, AccountInput> {
@Override
public Response<AccountInfo> apply(AccountResource resource, AccountInput input)
throws ResourceConflictException {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/PutActive.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/PutActive.java
index 8cc134f..cbddefd 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/PutActive.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/PutActive.java
@@ -26,15 +26,13 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.io.IOException;
import java.util.Collections;
@RequiresCapability(GlobalCapability.MODIFY_ACCOUNT)
@Singleton
public class PutActive implements RestModifyView<AccountResource, Input> {
- public static class Input {
- }
+ public static class Input {}
private final Provider<ReviewDb> dbProvider;
private final AccountCache byIdCache;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/PutAgreement.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/PutAgreement.java
index b8b902f..423d5a1 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/PutAgreement.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/PutAgreement.java
@@ -37,14 +37,11 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
+import java.io.IOException;
import org.eclipse.jgit.lib.Config;
-import java.io.IOException;
-
@Singleton
-public class PutAgreement
- implements RestModifyView<AccountResource, AgreementInput> {
+public class PutAgreement implements RestModifyView<AccountResource, AgreementInput> {
private final ProjectCache projectCache;
private final GroupCache groupCache;
private final Provider<IdentifiedUser> self;
@@ -53,7 +50,8 @@
private final boolean agreementsEnabled;
@Inject
- PutAgreement(ProjectCache projectCache,
+ PutAgreement(
+ ProjectCache projectCache,
GroupCache groupCache,
Provider<IdentifiedUser> self,
AgreementSignup agreementSignup,
@@ -64,8 +62,7 @@
this.self = self;
this.agreementSignup = agreementSignup;
this.addMembers = addMembers;
- this.agreementsEnabled =
- config.getBoolean("auth", "contributorAgreements", false);
+ this.agreementsEnabled = config.getBoolean("auth", "contributorAgreements", false);
}
@Override
@@ -80,8 +77,8 @@
}
String agreementName = Strings.nullToEmpty(input.name);
- ContributorAgreement ca = projectCache.getAllProjects().getConfig()
- .getContributorAgreement(agreementName);
+ ContributorAgreement ca =
+ projectCache.getAllProjects().getConfig().getContributorAgreement(agreementName);
if (ca == null) {
throw new UnprocessableEntityException("contributor agreement not found");
}
@@ -106,5 +103,4 @@
return Response.ok(agreementName);
}
-
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/PutHttpPassword.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/PutHttpPassword.java
index 0cd93f1..311c12b 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/PutHttpPassword.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/PutHttpPassword.java
@@ -31,13 +31,11 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
-import org.apache.commons.codec.binary.Base64;
-
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Collections;
+import org.apache.commons.codec.binary.Base64;
@Singleton
public class PutHttpPassword implements RestModifyView<AccountResource, Input> {
@@ -62,8 +60,8 @@
private final AccountCache accountCache;
@Inject
- PutHttpPassword(Provider<CurrentUser> self, Provider<ReviewDb> dbProvider,
- AccountCache accountCache) {
+ PutHttpPassword(
+ Provider<CurrentUser> self, Provider<ReviewDb> dbProvider, AccountCache accountCache) {
this.self = self;
this.dbProvider = dbProvider;
this.accountCache = accountCache;
@@ -71,8 +69,8 @@
@Override
public Response<String> apply(AccountResource rsrc, Input input)
- throws AuthException, ResourceNotFoundException,
- ResourceConflictException, OrmException, IOException {
+ throws AuthException, ResourceNotFoundException, ResourceConflictException, OrmException,
+ IOException {
if (input == null) {
input = new Input();
}
@@ -80,22 +78,21 @@
String newPassword;
if (input.generate) {
- if (self.get() != rsrc.getUser()
- && !self.get().getCapabilities().canAdministrateServer()) {
+ if (self.get() != rsrc.getUser() && !self.get().getCapabilities().canAdministrateServer()) {
throw new AuthException("not allowed to generate HTTP password");
}
newPassword = generate();
} else if (input.httpPassword == null) {
- if (self.get() != rsrc.getUser()
- && !self.get().getCapabilities().canAdministrateServer()) {
+ if (self.get() != rsrc.getUser() && !self.get().getCapabilities().canAdministrateServer()) {
throw new AuthException("not allowed to clear HTTP password");
}
newPassword = null;
} else {
if (!self.get().getCapabilities().canAdministrateServer()) {
- throw new AuthException("not allowed to set HTTP password directly, "
- + "requires the Administrate Server permission");
+ throw new AuthException(
+ "not allowed to set HTTP password directly, "
+ + "requires the Administrate Server permission");
}
newPassword = input.httpPassword;
}
@@ -103,15 +100,16 @@
}
public Response<String> apply(IdentifiedUser user, String newPassword)
- throws ResourceNotFoundException, ResourceConflictException, OrmException,
- IOException {
+ throws ResourceNotFoundException, ResourceConflictException, OrmException, IOException {
if (user.getUserName() == null) {
throw new ResourceConflictException("username must be set");
}
- AccountExternalId id = dbProvider.get().accountExternalIds()
- .get(new AccountExternalId.Key(
- SCHEME_USERNAME, user.getUserName()));
+ AccountExternalId id =
+ dbProvider
+ .get()
+ .accountExternalIds()
+ .get(new AccountExternalId.Key(SCHEME_USERNAME, user.getUserName()));
if (id == null) {
throw new ResourceNotFoundException();
}
@@ -119,9 +117,7 @@
dbProvider.get().accountExternalIds().update(Collections.singleton(id));
accountCache.evict(user.getAccountId());
- return Strings.isNullOrEmpty(newPassword)
- ? Response.<String>none()
- : Response.ok(newPassword);
+ return Strings.isNullOrEmpty(newPassword) ? Response.<String>none() : Response.ok(newPassword);
}
public static String generate() {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/PutName.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/PutName.java
index 74c07e8..726508f 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/PutName.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/PutName.java
@@ -31,15 +31,13 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.io.IOException;
import java.util.Collections;
@Singleton
public class PutName implements RestModifyView<AccountResource, Input> {
public static class Input {
- @DefaultInput
- public String name;
+ @DefaultInput public String name;
}
private final Provider<CurrentUser> self;
@@ -48,8 +46,11 @@
private final AccountCache byIdCache;
@Inject
- PutName(Provider<CurrentUser> self, Realm realm,
- Provider<ReviewDb> dbProvider, AccountCache byIdCache) {
+ PutName(
+ Provider<CurrentUser> self,
+ Realm realm,
+ Provider<ReviewDb> dbProvider,
+ AccountCache byIdCache) {
this.self = self;
this.realm = realm;
this.dbProvider = dbProvider;
@@ -58,18 +59,16 @@
@Override
public Response<String> apply(AccountResource rsrc, Input input)
- throws AuthException, MethodNotAllowedException,
- ResourceNotFoundException, OrmException, IOException {
- if (self.get() != rsrc.getUser()
- && !self.get().getCapabilities().canModifyAccount()) {
+ throws AuthException, MethodNotAllowedException, ResourceNotFoundException, OrmException,
+ IOException {
+ if (self.get() != rsrc.getUser() && !self.get().getCapabilities().canModifyAccount()) {
throw new AuthException("not allowed to change name");
}
return apply(rsrc.getUser(), input);
}
public Response<String> apply(IdentifiedUser user, Input input)
- throws MethodNotAllowedException, ResourceNotFoundException, OrmException,
- IOException {
+ throws MethodNotAllowedException, ResourceNotFoundException, OrmException, IOException {
if (input == null) {
input = new Input();
}
@@ -86,7 +85,7 @@
dbProvider.get().accounts().update(Collections.singleton(a));
byIdCache.evict(a.getId());
return Strings.isNullOrEmpty(a.getFullName())
- ? Response.<String> none()
+ ? Response.<String>none()
: Response.ok(a.getFullName());
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/PutPreferred.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/PutPreferred.java
index 92357b5..3c80d2c 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/PutPreferred.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/PutPreferred.java
@@ -27,23 +27,19 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.io.IOException;
import java.util.Collections;
@Singleton
-public class PutPreferred implements
- RestModifyView<AccountResource.Email, Input> {
- static class Input {
- }
+public class PutPreferred implements RestModifyView<AccountResource.Email, Input> {
+ static class Input {}
private final Provider<CurrentUser> self;
private final Provider<ReviewDb> dbProvider;
private final AccountCache byIdCache;
@Inject
- PutPreferred(Provider<CurrentUser> self, Provider<ReviewDb> dbProvider,
- AccountCache byIdCache) {
+ PutPreferred(Provider<CurrentUser> self, Provider<ReviewDb> dbProvider, AccountCache byIdCache) {
this.self = self;
this.dbProvider = dbProvider;
this.byIdCache = byIdCache;
@@ -51,10 +47,8 @@
@Override
public Response<String> apply(AccountResource.Email rsrc, Input input)
- throws AuthException, ResourceNotFoundException, OrmException,
- IOException {
- if (self.get() != rsrc.getUser()
- && !self.get().getCapabilities().canModifyAccount()) {
+ throws AuthException, ResourceNotFoundException, OrmException, IOException {
+ if (self.get() != rsrc.getUser() && !self.get().getCapabilities().canModifyAccount()) {
throw new AuthException("not allowed to set preferred email address");
}
return apply(rsrc.getUser(), rsrc.getEmail());
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/PutStatus.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/PutStatus.java
index c61c356..d826899 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/PutStatus.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/PutStatus.java
@@ -29,22 +29,19 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.io.IOException;
import java.util.Collections;
@Singleton
public class PutStatus implements RestModifyView<AccountResource, Input> {
public static class Input {
- @DefaultInput
- String status;
+ @DefaultInput String status;
public Input(String status) {
this.status = status;
}
- public Input() {
- }
+ public Input() {}
}
private final Provider<CurrentUser> self;
@@ -52,8 +49,7 @@
private final AccountCache byIdCache;
@Inject
- PutStatus(Provider<CurrentUser> self, Provider<ReviewDb> dbProvider,
- AccountCache byIdCache) {
+ PutStatus(Provider<CurrentUser> self, Provider<ReviewDb> dbProvider, AccountCache byIdCache) {
this.self = self;
this.dbProvider = dbProvider;
this.byIdCache = byIdCache;
@@ -61,18 +57,15 @@
@Override
public Response<String> apply(AccountResource rsrc, Input input)
- throws AuthException,
- ResourceNotFoundException, OrmException, IOException {
- if (self.get() != rsrc.getUser()
- && !self.get().getCapabilities().canModifyAccount()) {
+ throws AuthException, ResourceNotFoundException, OrmException, IOException {
+ if (self.get() != rsrc.getUser() && !self.get().getCapabilities().canModifyAccount()) {
throw new AuthException("not allowed to set status");
}
return apply(rsrc.getUser(), input);
}
public Response<String> apply(IdentifiedUser user, Input input)
- throws ResourceNotFoundException, OrmException,
- IOException {
+ throws ResourceNotFoundException, OrmException, IOException {
if (input == null) {
input = new Input();
}
@@ -84,8 +77,6 @@
a.setStatus(Strings.nullToEmpty(input.status));
dbProvider.get().accounts().update(Collections.singleton(a));
byIdCache.evict(a.getId());
- return Strings.isNullOrEmpty(a.getStatus())
- ? Response.none()
- : Response.ok(a.getStatus());
+ return Strings.isNullOrEmpty(a.getStatus()) ? Response.none() : Response.ok(a.getStatus());
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/PutUsername.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/PutUsername.java
index 29168ed..9be57d9 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/PutUsername.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/PutUsername.java
@@ -29,14 +29,12 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.io.IOException;
@Singleton
public class PutUsername implements RestModifyView<AccountResource, Input> {
public static class Input {
- @DefaultInput
- public String username;
+ @DefaultInput public String username;
}
private final Provider<CurrentUser> self;
@@ -45,7 +43,8 @@
private final Provider<ReviewDb> db;
@Inject
- PutUsername(Provider<CurrentUser> self,
+ PutUsername(
+ Provider<CurrentUser> self,
ChangeUserName.Factory changeUserNameFactory,
Realm realm,
Provider<ReviewDb> db) {
@@ -56,11 +55,10 @@
}
@Override
- public String apply(AccountResource rsrc, Input input) throws AuthException,
- MethodNotAllowedException, UnprocessableEntityException,
- ResourceConflictException, OrmException, IOException {
- if (self.get() != rsrc.getUser()
- && !self.get().getCapabilities().canAdministrateServer()) {
+ public String apply(AccountResource rsrc, Input input)
+ throws AuthException, MethodNotAllowedException, UnprocessableEntityException,
+ ResourceConflictException, OrmException, IOException {
+ if (self.get() != rsrc.getUser() && !self.get().getCapabilities().canAdministrateServer()) {
throw new AuthException("not allowed to set username");
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/QueryAccounts.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/QueryAccounts.java
index cef829f..a8e6dc0 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/QueryAccounts.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/QueryAccounts.java
@@ -33,16 +33,14 @@
import com.google.gerrit.server.query.account.AccountQueryProcessor;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
-
-import org.eclipse.jgit.lib.Config;
-import org.kohsuke.args4j.Option;
-
import java.util.Collections;
import java.util.EnumSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
+import org.eclipse.jgit.lib.Config;
+import org.kohsuke.args4j.Option;
public class QueryAccounts implements RestReadView<TopLevelResource> {
private static final int MAX_SUGGEST_RESULTS = 100;
@@ -65,7 +63,12 @@
this.suggest = suggest;
}
- @Option(name = "--limit", aliases = {"-n"}, metaVar = "CNT", usage = "maximum number of users to return")
+ @Option(
+ name = "--limit",
+ aliases = {"-n"},
+ metaVar = "CNT",
+ usage = "maximum number of users to return"
+ )
public void setLimit(int n) {
queryProcessor.setLimit(n);
@@ -88,19 +91,29 @@
options.addAll(ListAccountsOption.fromBits(Integer.parseInt(hex, 16)));
}
- @Option(name = "--query", aliases = {"-q"}, metaVar = "QUERY", usage = "match users")
+ @Option(
+ name = "--query",
+ aliases = {"-q"},
+ metaVar = "QUERY",
+ usage = "match users"
+ )
public void setQuery(String query) {
this.query = query;
}
- @Option(name = "--start", aliases = {"-S"}, metaVar = "CNT",
- usage = "Number of accounts to skip")
+ @Option(
+ name = "--start",
+ aliases = {"-S"},
+ metaVar = "CNT",
+ usage = "Number of accounts to skip"
+ )
public void setStart(int start) {
this.start = start;
}
@Inject
- QueryAccounts(AccountLoader.Factory accountLoaderFactory,
+ QueryAccounts(
+ AccountLoader.Factory accountLoaderFactory,
AccountQueryBuilder queryBuilder,
AccountQueryProcessor queryProcessor,
@GerritServerConfig Config cfg) {
@@ -115,8 +128,7 @@
} else {
boolean suggest;
try {
- AccountVisibility av =
- cfg.getEnum("suggest", null, "accounts", AccountVisibility.ALL);
+ AccountVisibility av = cfg.getEnum("suggest", null, "accounts", AccountVisibility.ALL);
suggest = (av != AccountVisibility.NONE);
} catch (IllegalArgumentException err) {
suggest = cfg.getBoolean("suggest", null, "accounts", true);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/Realm.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/Realm.java
index 627f529..5d551bc 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/Realm.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/Realm.java
@@ -17,7 +17,6 @@
import com.google.gerrit.extensions.client.AccountFieldName;
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.server.IdentifiedUser;
-
import java.util.Set;
public interface Realm {
@@ -39,11 +38,10 @@
/**
* Locate an account whose local username is the given account name.
- * <p>
- * Generally this only works for local realms, such as one backed by an LDAP
- * directory, or where there is an {@link EmailExpander} configured that knows
- * how to convert the accountName into an email address, and then locate the
- * user by that email address.
+ *
+ * <p>Generally this only works for local realms, such as one backed by an LDAP directory, or
+ * where there is an {@link EmailExpander} configured that knows how to convert the accountName
+ * into an email address, and then locate the user by that email address.
*/
Account.Id lookup(String accountName);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/SetDiffPreferences.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/SetDiffPreferences.java
index c408155..986124a 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/SetDiffPreferences.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/SetDiffPreferences.java
@@ -31,22 +31,20 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
+import java.io.IOException;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
-import java.io.IOException;
-
@Singleton
-public class SetDiffPreferences implements
- RestModifyView<AccountResource, DiffPreferencesInfo> {
+public class SetDiffPreferences implements RestModifyView<AccountResource, DiffPreferencesInfo> {
private final Provider<CurrentUser> self;
private final Provider<MetaDataUpdate.User> metaDataUpdateFactory;
private final AllUsersName allUsersName;
private final GitRepositoryManager gitMgr;
@Inject
- SetDiffPreferences(Provider<CurrentUser> self,
+ SetDiffPreferences(
+ Provider<CurrentUser> self,
Provider<MetaDataUpdate.User> metaDataUpdateFactory,
AllUsersName allUsersName,
GitRepositoryManager gitMgr) {
@@ -59,9 +57,8 @@
@Override
public DiffPreferencesInfo apply(AccountResource rsrc, DiffPreferencesInfo in)
throws AuthException, BadRequestException, ConfigInvalidException,
- RepositoryNotFoundException, IOException {
- if (self.get() != rsrc.getUser()
- && !self.get().getCapabilities().canModifyAccount()) {
+ RepositoryNotFoundException, IOException {
+ if (self.get() != rsrc.getUser() && !self.get().getCapabilities().canModifyAccount()) {
throw new AuthException("requires Modify Account capability");
}
@@ -73,20 +70,22 @@
return writeToGit(readFromGit(id, gitMgr, allUsersName, in), id);
}
- private DiffPreferencesInfo writeToGit(DiffPreferencesInfo in,
- Account.Id userId) throws RepositoryNotFoundException, IOException,
- ConfigInvalidException {
+ private DiffPreferencesInfo writeToGit(DiffPreferencesInfo in, Account.Id userId)
+ throws RepositoryNotFoundException, IOException, ConfigInvalidException {
DiffPreferencesInfo out = new DiffPreferencesInfo();
try (MetaDataUpdate md = metaDataUpdateFactory.get().create(allUsersName)) {
- VersionedAccountPreferences prefs = VersionedAccountPreferences.forUser(
- userId);
+ VersionedAccountPreferences prefs = VersionedAccountPreferences.forUser(userId);
prefs.load(md);
DiffPreferencesInfo defaults = DiffPreferencesInfo.defaults();
- storeSection(prefs.getConfig(), UserConfigSections.DIFF, null, in,
- defaults);
+ storeSection(prefs.getConfig(), UserConfigSections.DIFF, null, in, defaults);
prefs.commit(md);
- loadSection(prefs.getConfig(), UserConfigSections.DIFF, null, out,
- DiffPreferencesInfo.defaults(), null);
+ loadSection(
+ prefs.getConfig(),
+ UserConfigSections.DIFF,
+ null,
+ out,
+ DiffPreferencesInfo.defaults(),
+ null);
}
return out;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/SetEditPreferences.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/SetEditPreferences.java
index 7bff42b..ca981b8 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/SetEditPreferences.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/SetEditPreferences.java
@@ -31,15 +31,12 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
+import java.io.IOException;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
-import java.io.IOException;
-
@Singleton
-public class SetEditPreferences implements
- RestModifyView<AccountResource, EditPreferencesInfo> {
+public class SetEditPreferences implements RestModifyView<AccountResource, EditPreferencesInfo> {
private final Provider<CurrentUser> self;
private final Provider<MetaDataUpdate.User> metaDataUpdateFactory;
@@ -47,7 +44,8 @@
private final AllUsersName allUsersName;
@Inject
- SetEditPreferences(Provider<CurrentUser> self,
+ SetEditPreferences(
+ Provider<CurrentUser> self,
Provider<MetaDataUpdate.User> metaDataUpdateFactory,
GitRepositoryManager gitMgr,
AllUsersName allUsersName) {
@@ -59,10 +57,9 @@
@Override
public EditPreferencesInfo apply(AccountResource rsrc, EditPreferencesInfo in)
- throws AuthException, BadRequestException, RepositoryNotFoundException,
- IOException, ConfigInvalidException {
- if (self.get() != rsrc.getUser()
- && !self.get().getCapabilities().canModifyAccount()) {
+ throws AuthException, BadRequestException, RepositoryNotFoundException, IOException,
+ ConfigInvalidException {
+ if (self.get() != rsrc.getUser() && !self.get().getCapabilities().canModifyAccount()) {
throw new AuthException("requires Modify Account capability");
}
@@ -77,12 +74,21 @@
try (MetaDataUpdate md = metaDataUpdateFactory.get().create(allUsersName)) {
prefs = VersionedAccountPreferences.forUser(accountId);
prefs.load(md);
- storeSection(prefs.getConfig(), UserConfigSections.EDIT, null,
+ storeSection(
+ prefs.getConfig(),
+ UserConfigSections.EDIT,
+ null,
readFromGit(accountId, gitMgr, allUsersName, in),
EditPreferencesInfo.defaults());
prefs.commit(md);
- out = loadSection(prefs.getConfig(), UserConfigSections.EDIT, null, out,
- EditPreferencesInfo.defaults(), null);
+ out =
+ loadSection(
+ prefs.getConfig(),
+ UserConfigSections.EDIT,
+ null,
+ out,
+ EditPreferencesInfo.defaults(),
+ null);
}
return out;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/SetPreferences.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/SetPreferences.java
index 3714cee..e1ed6aa 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/SetPreferences.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/SetPreferences.java
@@ -39,19 +39,16 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.errors.ConfigInvalidException;
-import org.eclipse.jgit.errors.RepositoryNotFoundException;
-import org.eclipse.jgit.lib.Config;
-
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
+import org.eclipse.jgit.errors.ConfigInvalidException;
+import org.eclipse.jgit.errors.RepositoryNotFoundException;
+import org.eclipse.jgit.lib.Config;
@Singleton
-public class SetPreferences implements
- RestModifyView<AccountResource, GeneralPreferencesInfo> {
+public class SetPreferences implements RestModifyView<AccountResource, GeneralPreferencesInfo> {
private final Provider<CurrentUser> self;
private final AccountCache cache;
private final GeneralPreferencesLoader loader;
@@ -60,7 +57,8 @@
private final DynamicMap<DownloadScheme> downloadSchemes;
@Inject
- SetPreferences(Provider<CurrentUser> self,
+ SetPreferences(
+ Provider<CurrentUser> self,
AccountCache cache,
GeneralPreferencesLoader loader,
Provider<MetaDataUpdate.User> metaDataUpdateFactory,
@@ -75,12 +73,9 @@
}
@Override
- public GeneralPreferencesInfo apply(AccountResource rsrc,
- GeneralPreferencesInfo i)
- throws AuthException, BadRequestException, IOException,
- ConfigInvalidException {
- if (self.get() != rsrc.getUser()
- && !self.get().getCapabilities().canModifyAccount()) {
+ public GeneralPreferencesInfo apply(AccountResource rsrc, GeneralPreferencesInfo i)
+ throws AuthException, BadRequestException, IOException, ConfigInvalidException {
+ if (self.get() != rsrc.getUser() && !self.get().getCapabilities().canModifyAccount()) {
throw new AuthException("requires Modify Account capability");
}
@@ -104,7 +99,11 @@
prefs = VersionedAccountPreferences.forUser(id);
prefs.load(md);
- storeSection(prefs.getConfig(), UserConfigSections.GENERAL, null, i,
+ storeSection(
+ prefs.getConfig(),
+ UserConfigSections.GENERAL,
+ null,
+ i,
GeneralPreferencesInfo.defaults());
storeMyChangeTableColumns(prefs, i.changeTable);
@@ -115,8 +114,7 @@
}
}
- public static void storeMyMenus(VersionedAccountPreferences prefs,
- List<MenuItem> my) {
+ public static void storeMyMenus(VersionedAccountPreferences prefs, List<MenuItem> my) {
Config cfg = prefs.getConfig();
if (my != null) {
unsetSection(cfg, UserConfigSections.MY);
@@ -128,13 +126,12 @@
}
}
- public static void storeMyChangeTableColumns(VersionedAccountPreferences
- prefs, List<String> changeTable) {
+ public static void storeMyChangeTableColumns(
+ VersionedAccountPreferences prefs, List<String> changeTable) {
Config cfg = prefs.getConfig();
if (changeTable != null) {
unsetSection(cfg, UserConfigSections.CHANGE_TABLE);
- cfg.setStringList(UserConfigSections.CHANGE_TABLE, null,
- CHANGE_TABLE_COLUMN, changeTable);
+ cfg.setStringList(UserConfigSections.CHANGE_TABLE, null, CHANGE_TABLE_COLUMN, changeTable);
}
}
@@ -148,13 +145,13 @@
private static void unsetSection(Config cfg, String section) {
cfg.unsetSection(section, null);
- for (String subsection: cfg.getSubsections(section)) {
+ for (String subsection : cfg.getSubsections(section)) {
cfg.unsetSection(section, subsection);
}
}
- public static void storeUrlAliases(VersionedAccountPreferences prefs,
- Map<String, String> urlAliases) {
+ public static void storeUrlAliases(
+ VersionedAccountPreferences prefs, Map<String, String> urlAliases) {
if (urlAliases != null) {
Config cfg = prefs.getConfig();
for (String subsection : cfg.getSubsections(URL_ALIAS)) {
@@ -170,19 +167,16 @@
}
}
- private void checkDownloadScheme(String downloadScheme)
- throws BadRequestException {
+ private void checkDownloadScheme(String downloadScheme) throws BadRequestException {
if (Strings.isNullOrEmpty(downloadScheme)) {
return;
}
for (DynamicMap.Entry<DownloadScheme> e : downloadSchemes) {
- if (e.getExportName().equals(downloadScheme)
- && e.getProvider().get().isEnabled()) {
+ if (e.getExportName().equals(downloadScheme) && e.getProvider().get().isEnabled()) {
return;
}
}
- throw new BadRequestException(
- "Unsupported download scheme: " + downloadScheme);
+ throw new BadRequestException("Unsupported download scheme: " + downloadScheme);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/SshKeys.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/SshKeys.java
index 44a3192..6336e08 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/SshKeys.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/SshKeys.java
@@ -26,22 +26,21 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
+import java.io.IOException;
import org.eclipse.jgit.errors.ConfigInvalidException;
-import java.io.IOException;
-
@Singleton
-public class SshKeys implements
- ChildCollection<AccountResource, AccountResource.SshKey> {
+public class SshKeys implements ChildCollection<AccountResource, AccountResource.SshKey> {
private final DynamicMap<RestView<AccountResource.SshKey>> views;
private final GetSshKeys list;
private final Provider<CurrentUser> self;
private final VersionedAuthorizedKeys.Accessor authorizedKeys;
@Inject
- SshKeys(DynamicMap<RestView<AccountResource.SshKey>> views,
- GetSshKeys list, Provider<CurrentUser> self,
+ SshKeys(
+ DynamicMap<RestView<AccountResource.SshKey>> views,
+ GetSshKeys list,
+ Provider<CurrentUser> self,
VersionedAuthorizedKeys.Accessor authorizedKeys) {
this.views = views;
this.list = list;
@@ -56,10 +55,8 @@
@Override
public AccountResource.SshKey parse(AccountResource rsrc, IdString id)
- throws ResourceNotFoundException, OrmException, IOException,
- ConfigInvalidException {
- if (self.get() != rsrc.getUser()
- && !self.get().getCapabilities().canModifyAccount()) {
+ throws ResourceNotFoundException, OrmException, IOException, ConfigInvalidException {
+ if (self.get() != rsrc.getUser() && !self.get().getCapabilities().canModifyAccount()) {
throw new ResourceNotFoundException();
}
return parse(rsrc.getUser(), id);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/StarredChanges.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/StarredChanges.java
index b71fc68..995aaa5 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/StarredChanges.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/StarredChanges.java
@@ -38,16 +38,14 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
+import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-
@Singleton
-public class StarredChanges implements
- ChildCollection<AccountResource, AccountResource.StarredChange>,
- AcceptsCreate<AccountResource> {
+public class StarredChanges
+ implements ChildCollection<AccountResource, AccountResource.StarredChange>,
+ AcceptsCreate<AccountResource> {
private static final Logger log = LoggerFactory.getLogger(StarredChanges.class);
private final ChangesCollection changes;
@@ -56,7 +54,8 @@
private final StarredChangesUtil starredChangesUtil;
@Inject
- StarredChanges(ChangesCollection changes,
+ StarredChanges(
+ ChangesCollection changes,
DynamicMap<RestView<AccountResource.StarredChange>> views,
Provider<Create> createProvider,
StarredChangesUtil starredChangesUtil) {
@@ -71,7 +70,8 @@
throws ResourceNotFoundException, OrmException {
IdentifiedUser user = parent.getUser();
ChangeResource change = changes.parse(TopLevelResource.INSTANCE, id);
- if (starredChangesUtil.getLabels(user.getAccountId(), change.getId())
+ if (starredChangesUtil
+ .getLabels(user.getAccountId(), change.getId())
.contains(StarredChangesUtil.DEFAULT_LABEL)) {
return new AccountResource.StarredChange(user, change);
}
@@ -87,8 +87,8 @@
public RestView<AccountResource> list() throws ResourceNotFoundException {
return new RestReadView<AccountResource>() {
@Override
- public Object apply(AccountResource self) throws BadRequestException,
- AuthException, OrmException {
+ public Object apply(AccountResource self)
+ throws BadRequestException, AuthException, OrmException {
QueryChanges query = changes.list();
query.addQuery("starredby:" + self.getUser().getAccountId().get());
return query.apply(TopLevelResource.INSTANCE);
@@ -98,11 +98,10 @@
@SuppressWarnings("unchecked")
@Override
- public RestModifyView<AccountResource, EmptyInput> create(
- AccountResource parent, IdString id) throws UnprocessableEntityException {
+ public RestModifyView<AccountResource, EmptyInput> create(AccountResource parent, IdString id)
+ throws UnprocessableEntityException {
try {
- return createProvider.get()
- .setChange(changes.parse(TopLevelResource.INSTANCE, id));
+ return createProvider.get().setChange(changes.parse(TopLevelResource.INSTANCE, id));
} catch (ResourceNotFoundException e) {
throw new UnprocessableEntityException(String.format("change %s not found", id.get()));
} catch (OrmException e) {
@@ -135,8 +134,12 @@
throw new AuthException("not allowed to add starred change");
}
try {
- starredChangesUtil.star(self.get().getAccountId(), change.getProject(),
- change.getId(), StarredChangesUtil.DEFAULT_LABELS, null);
+ starredChangesUtil.star(
+ self.get().getAccountId(),
+ change.getProject(),
+ change.getId(),
+ StarredChangesUtil.DEFAULT_LABELS,
+ null);
} catch (OrmDuplicateKeyException e) {
return Response.none();
}
@@ -145,8 +148,7 @@
}
@Singleton
- static class Put implements
- RestModifyView<AccountResource.StarredChange, EmptyInput> {
+ static class Put implements RestModifyView<AccountResource.StarredChange, EmptyInput> {
private final Provider<CurrentUser> self;
@Inject
@@ -165,8 +167,7 @@
}
@Singleton
- public static class Delete implements
- RestModifyView<AccountResource.StarredChange, EmptyInput> {
+ public static class Delete implements RestModifyView<AccountResource.StarredChange, EmptyInput> {
private final Provider<CurrentUser> self;
private final StarredChangesUtil starredChangesUtil;
@@ -177,18 +178,20 @@
}
@Override
- public Response<?> apply(AccountResource.StarredChange rsrc,
- EmptyInput in) throws AuthException, OrmException, IOException {
+ public Response<?> apply(AccountResource.StarredChange rsrc, EmptyInput in)
+ throws AuthException, OrmException, IOException {
if (self.get() != rsrc.getUser()) {
throw new AuthException("not allowed remove starred change");
}
- starredChangesUtil.star(self.get().getAccountId(),
- rsrc.getChange().getProject(), rsrc.getChange().getId(), null,
+ starredChangesUtil.star(
+ self.get().getAccountId(),
+ rsrc.getChange().getProject(),
+ rsrc.getChange().getId(),
+ null,
StarredChangesUtil.DEFAULT_LABELS);
return Response.none();
}
}
- public static class EmptyInput {
- }
+ public static class EmptyInput {}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/Stars.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/Stars.java
index fddbb6a..52c6cdf 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/Stars.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/Stars.java
@@ -38,15 +38,13 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;
@Singleton
-public class Stars implements
- ChildCollection<AccountResource, AccountResource.Star> {
+public class Stars implements ChildCollection<AccountResource, AccountResource.Star> {
private final ChangesCollection changes;
private final ListStarredChanges listStarredChanges;
@@ -54,7 +52,8 @@
private final DynamicMap<RestView<AccountResource.Star>> views;
@Inject
- Stars(ChangesCollection changes,
+ Stars(
+ ChangesCollection changes,
ListStarredChanges listStarredChanges,
StarredChangesUtil starredChangesUtil,
DynamicMap<RestView<AccountResource.Star>> views) {
@@ -69,8 +68,7 @@
throws ResourceNotFoundException, OrmException {
IdentifiedUser user = parent.getUser();
ChangeResource change = changes.parse(TopLevelResource.INSTANCE, id);
- Set<String> labels =
- starredChangesUtil.getLabels(user.getAccountId(), change.getId());
+ Set<String> labels = starredChangesUtil.getLabels(user.getAccountId(), change.getId());
return new AccountResource.Star(user, change, labels);
}
@@ -85,14 +83,12 @@
}
@Singleton
- public static class ListStarredChanges
- implements RestReadView<AccountResource> {
+ public static class ListStarredChanges implements RestReadView<AccountResource> {
private final Provider<CurrentUser> self;
private final ChangesCollection changes;
@Inject
- ListStarredChanges(Provider<CurrentUser> self,
- ChangesCollection changes) {
+ ListStarredChanges(Provider<CurrentUser> self, ChangesCollection changes) {
this.self = self;
this.changes = changes;
}
@@ -102,8 +98,7 @@
public List<ChangeInfo> apply(AccountResource rsrc)
throws BadRequestException, AuthException, OrmException {
if (self.get() != rsrc.getUser()) {
- throw new AuthException(
- "not allowed to list stars of another account");
+ throw new AuthException("not allowed to list stars of another account");
}
QueryChanges query = changes.list();
query.addQuery("has:stars");
@@ -112,38 +107,32 @@
}
@Singleton
- public static class Get implements
- RestReadView<AccountResource.Star> {
+ public static class Get implements RestReadView<AccountResource.Star> {
private final Provider<CurrentUser> self;
private final StarredChangesUtil starredChangesUtil;
@Inject
- Get(Provider<CurrentUser> self,
- StarredChangesUtil starredChangesUtil) {
+ Get(Provider<CurrentUser> self, StarredChangesUtil starredChangesUtil) {
this.self = self;
this.starredChangesUtil = starredChangesUtil;
}
@Override
- public SortedSet<String> apply(AccountResource.Star rsrc)
- throws AuthException, OrmException {
+ public SortedSet<String> apply(AccountResource.Star rsrc) throws AuthException, OrmException {
if (self.get() != rsrc.getUser()) {
throw new AuthException("not allowed to get stars of another account");
}
- return starredChangesUtil.getLabels(self.get().getAccountId(),
- rsrc.getChange().getId());
+ return starredChangesUtil.getLabels(self.get().getAccountId(), rsrc.getChange().getId());
}
}
@Singleton
- public static class Post implements
- RestModifyView<AccountResource.Star, StarsInput> {
+ public static class Post implements RestModifyView<AccountResource.Star, StarsInput> {
private final Provider<CurrentUser> self;
private final StarredChangesUtil starredChangesUtil;
@Inject
- Post(Provider<CurrentUser> self,
- StarredChangesUtil starredChangesUtil) {
+ Post(Provider<CurrentUser> self, StarredChangesUtil starredChangesUtil) {
this.self = self;
this.starredChangesUtil = starredChangesUtil;
}
@@ -152,12 +141,14 @@
public Collection<String> apply(AccountResource.Star rsrc, StarsInput in)
throws AuthException, BadRequestException, OrmException {
if (self.get() != rsrc.getUser()) {
- throw new AuthException(
- "not allowed to update stars of another account");
+ throw new AuthException("not allowed to update stars of another account");
}
try {
- return starredChangesUtil.star(self.get().getAccountId(),
- rsrc.getChange().getProject(), rsrc.getChange().getId(), in.add,
+ return starredChangesUtil.star(
+ self.get().getAccountId(),
+ rsrc.getChange().getProject(),
+ rsrc.getChange().getId(),
+ in.add,
in.remove);
} catch (IllegalLabelException e) {
throw new BadRequestException(e.getMessage());
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/UniversalGroupBackend.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/UniversalGroupBackend.java
index 31a3f22..a3223d9 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/UniversalGroupBackend.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/UniversalGroupBackend.java
@@ -34,24 +34,20 @@
import com.google.gerrit.server.project.ProjectControl;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.lib.Config;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
+import org.eclipse.jgit.lib.Config;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
- * Universal implementation of the GroupBackend that works with the injected
- * set of GroupBackends.
+ * Universal implementation of the GroupBackend that works with the injected set of GroupBackends.
*/
@Singleton
public class UniversalGroupBackend implements GroupBackend {
- private static final Logger log =
- LoggerFactory.getLogger(UniversalGroupBackend.class);
+ private static final Logger log = LoggerFactory.getLogger(UniversalGroupBackend.class);
private final DynamicSet<GroupBackend> backends;
@@ -105,41 +101,40 @@
}
private class UniversalGroupMembership implements GroupMembership {
- private final Map<GroupBackend, GroupMembership> memberships;
+ private final Map<GroupBackend, GroupMembership> memberships;
- private UniversalGroupMembership(IdentifiedUser user) {
- ImmutableMap.Builder<GroupBackend, GroupMembership> builder =
- ImmutableMap.builder();
- for (GroupBackend g : backends) {
- builder.put(g, g.membershipsOf(user));
- }
- this.memberships = builder.build();
- }
+ private UniversalGroupMembership(IdentifiedUser user) {
+ ImmutableMap.Builder<GroupBackend, GroupMembership> builder = ImmutableMap.builder();
+ for (GroupBackend g : backends) {
+ builder.put(g, g.membershipsOf(user));
+ }
+ this.memberships = builder.build();
+ }
- @Nullable
- private GroupMembership membership(AccountGroup.UUID uuid) {
- if (uuid != null) {
- for (Map.Entry<GroupBackend, GroupMembership> m : memberships.entrySet()) {
- if (m.getKey().handles(uuid)) {
- return m.getValue();
- }
- }
- }
- return null;
- }
+ @Nullable
+ private GroupMembership membership(AccountGroup.UUID uuid) {
+ if (uuid != null) {
+ for (Map.Entry<GroupBackend, GroupMembership> m : memberships.entrySet()) {
+ if (m.getKey().handles(uuid)) {
+ return m.getValue();
+ }
+ }
+ }
+ return null;
+ }
- @Override
- public boolean contains(AccountGroup.UUID uuid) {
- if (uuid == null) {
- return false;
- }
- GroupMembership m = membership(uuid);
- if (m == null) {
- log.debug("Unknown GroupMembership for UUID: " + uuid);
- return false;
- }
- return m.contains(uuid);
- }
+ @Override
+ public boolean contains(AccountGroup.UUID uuid) {
+ if (uuid == null) {
+ return false;
+ }
+ GroupMembership m = membership(uuid);
+ if (m == null) {
+ log.debug("Unknown GroupMembership for UUID: " + uuid);
+ return false;
+ }
+ return m.contains(uuid);
+ }
@Override
public boolean containsAnyOf(Iterable<AccountGroup.UUID> uuids) {
@@ -156,8 +151,8 @@
}
lookups.put(m, uuid);
}
- for (Map.Entry<GroupMembership, Collection<AccountGroup.UUID>> entry
- : lookups .asMap().entrySet()) {
+ for (Map.Entry<GroupMembership, Collection<AccountGroup.UUID>> entry :
+ lookups.asMap().entrySet()) {
GroupMembership m = entry.getKey();
Collection<AccountGroup.UUID> ids = entry.getValue();
if (ids.size() == 1) {
@@ -187,8 +182,8 @@
lookups.put(m, uuid);
}
Set<AccountGroup.UUID> groups = new HashSet<>();
- for (Map.Entry<GroupMembership, Collection<AccountGroup.UUID>> entry
- : lookups.asMap().entrySet()) {
+ for (Map.Entry<GroupMembership, Collection<AccountGroup.UUID>> entry :
+ lookups.asMap().entrySet()) {
groups.addAll(entry.getKey().intersection(entry.getValue()));
}
return groups;
@@ -219,31 +214,33 @@
private final UniversalGroupBackend universalGroupBackend;
@Inject
- ConfigCheck(@GerritServerConfig Config cfg,
- UniversalGroupBackend groupBackend) {
+ ConfigCheck(@GerritServerConfig Config cfg, UniversalGroupBackend groupBackend) {
this.cfg = cfg;
this.universalGroupBackend = groupBackend;
}
@Override
public void check() throws StartupException {
- String invalid = cfg.getSubsections("groups").stream()
- .filter(
- sub -> {
- AccountGroup.UUID uuid = new AccountGroup.UUID(sub);
- GroupBackend groupBackend = universalGroupBackend.backend(uuid);
- return groupBackend == null || groupBackend.get(uuid) == null;
- })
- .map(u -> "'" + u + "'")
- .collect(joining(","));
+ String invalid =
+ cfg.getSubsections("groups")
+ .stream()
+ .filter(
+ sub -> {
+ AccountGroup.UUID uuid = new AccountGroup.UUID(sub);
+ GroupBackend groupBackend = universalGroupBackend.backend(uuid);
+ return groupBackend == null || groupBackend.get(uuid) == null;
+ })
+ .map(u -> "'" + u + "'")
+ .collect(joining(","));
if (!invalid.isEmpty()) {
- throw new StartupException(String.format(
- "Subsections for 'groups' in gerrit.config must be valid group"
- + " UUIDs. The following group UUIDs could not be resolved: "
- + invalid
- + " Please remove/fix these 'groups' subsections in"
- + " gerrit.config."));
+ throw new StartupException(
+ String.format(
+ "Subsections for 'groups' in gerrit.config must be valid group"
+ + " UUIDs. The following group UUIDs could not be resolved: "
+ + invalid
+ + " Please remove/fix these 'groups' subsections in"
+ + " gerrit.config."));
}
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/VersionedAccountDestinations.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/VersionedAccountDestinations.java
index 426c6f6..f18e535 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/VersionedAccountDestinations.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/VersionedAccountDestinations.java
@@ -20,15 +20,13 @@
import com.google.gerrit.server.git.TabFile;
import com.google.gerrit.server.git.ValidationError;
import com.google.gerrit.server.git.VersionedMetaData;
-
+import java.io.IOException;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.lib.CommitBuilder;
import org.eclipse.jgit.lib.FileMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-
/** Preferences for user accounts. */
public class VersionedAccountDestinations extends VersionedMetaData {
private static final Logger log = LoggerFactory.getLogger(VersionedAccountDestinations.class);
@@ -73,8 +71,7 @@
}
@Override
- protected boolean onSave(CommitBuilder commit) throws IOException,
- ConfigInvalidException {
+ protected boolean onSave(CommitBuilder commit) throws IOException, ConfigInvalidException {
throw new UnsupportedOperationException("Cannot yet save destinations");
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/VersionedAccountPreferences.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/VersionedAccountPreferences.java
index 2273426..2eb0b54 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/VersionedAccountPreferences.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/VersionedAccountPreferences.java
@@ -18,13 +18,11 @@
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.reviewdb.client.RefNames;
import com.google.gerrit.server.git.VersionedMetaData;
-
+import java.io.IOException;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.lib.CommitBuilder;
import org.eclipse.jgit.lib.Config;
-import java.io.IOException;
-
/** Preferences for user accounts. */
public class VersionedAccountPreferences extends VersionedMetaData {
public static final String PREFERENCES = "preferences.config";
@@ -63,8 +61,7 @@
}
@Override
- protected boolean onSave(CommitBuilder commit) throws IOException,
- ConfigInvalidException {
+ protected boolean onSave(CommitBuilder commit) throws IOException, ConfigInvalidException {
if (Strings.isNullOrEmpty(commit.getMessage())) {
commit.setMessage("Updated preferences\n");
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/VersionedAccountQueries.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/VersionedAccountQueries.java
index 2ea6c53..e1fa8d6 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/VersionedAccountQueries.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/VersionedAccountQueries.java
@@ -18,14 +18,12 @@
import com.google.gerrit.reviewdb.client.RefNames;
import com.google.gerrit.server.git.QueryList;
import com.google.gerrit.server.git.VersionedMetaData;
-
+import java.io.IOException;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.lib.CommitBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-
/** Named Queries for user accounts. */
public class VersionedAccountQueries extends VersionedMetaData {
private static final Logger log = LoggerFactory.getLogger(VersionedAccountQueries.class);
@@ -52,13 +50,13 @@
@Override
protected void onLoad() throws IOException, ConfigInvalidException {
- queryList = QueryList.parse(readUTF8(QueryList.FILE_NAME),
- QueryList.createLoggerSink(QueryList.FILE_NAME, log));
+ queryList =
+ QueryList.parse(
+ readUTF8(QueryList.FILE_NAME), QueryList.createLoggerSink(QueryList.FILE_NAME, log));
}
@Override
- protected boolean onSave(CommitBuilder commit) throws IOException,
- ConfigInvalidException {
+ protected boolean onSave(CommitBuilder commit) throws IOException, ConfigInvalidException {
throw new UnsupportedOperationException("Cannot yet save named queries");
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/VersionedAuthorizedKeys.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/VersionedAuthorizedKeys.java
index 41ae498..8cffe92 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/VersionedAuthorizedKeys.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/VersionedAuthorizedKeys.java
@@ -35,38 +35,32 @@
import com.google.inject.Provider;
import com.google.inject.Singleton;
import com.google.inject.assistedinject.Assisted;
-
-import org.eclipse.jgit.errors.ConfigInvalidException;
-import org.eclipse.jgit.lib.CommitBuilder;
-import org.eclipse.jgit.lib.Repository;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
+import org.eclipse.jgit.errors.ConfigInvalidException;
+import org.eclipse.jgit.lib.CommitBuilder;
+import org.eclipse.jgit.lib.Repository;
/**
- * 'authorized_keys' file in the refs/users/CD/ABCD branches of the All-Users
- * repository.
+ * 'authorized_keys' file in the refs/users/CD/ABCD branches of the All-Users repository.
*
- * The `authorized_keys' files stores the public SSH keys of the user. The file
- * format matches the standard SSH file format, which means that each key is
- * stored on a separate line (see
+ * <p>The `authorized_keys' files stores the public SSH keys of the user. The file format matches
+ * the standard SSH file format, which means that each key is stored on a separate line (see
* https://en.wikibooks.org/wiki/OpenSSH/Client_Configuration_Files#.7E.2F.ssh.2Fauthorized_keys).
*
- * The order of the keys in the file determines the sequence numbers of the
- * keys. The first line corresponds to sequence number 1.
+ * <p>The order of the keys in the file determines the sequence numbers of the keys. The first line
+ * corresponds to sequence number 1.
*
- * Invalid keys are marked with the prefix <code># INVALID</code>.
+ * <p>Invalid keys are marked with the prefix <code># INVALID</code>.
*
- * To keep the sequence numbers intact when a key is deleted, a
- * <code># DELETED</code> line is inserted at the position where the key was
- * deleted.
+ * <p>To keep the sequence numbers intact when a key is deleted, a <code># DELETED</code> line is
+ * inserted at the position where the key was deleted.
*
- * Other comment lines are ignored on read, and are not written back when the
- * file is modified.
+ * <p>Other comment lines are ignored on read, and are not written back when the file is modified.
*/
public class VersionedAuthorizedKeys extends VersionedMetaData {
@Singleton
@@ -128,17 +122,17 @@
private VersionedAuthorizedKeys read(Account.Id accountId)
throws IOException, ConfigInvalidException {
try (Repository git = repoManager.openRepository(allUsersName)) {
- VersionedAuthorizedKeys authorizedKeys =
- authorizedKeysFactory.create(accountId);
+ VersionedAuthorizedKeys authorizedKeys = authorizedKeysFactory.create(accountId);
authorizedKeys.load(git);
return authorizedKeys;
}
}
- private void commit(VersionedAuthorizedKeys authorizedKeys)
- throws IOException {
- try (MetaDataUpdate md = metaDataUpdateFactory.get().create(allUsersName,
- userFactory.create(authorizedKeys.accountId))) {
+ private void commit(VersionedAuthorizedKeys authorizedKeys) throws IOException {
+ try (MetaDataUpdate md =
+ metaDataUpdateFactory
+ .get()
+ .create(allUsersName, userFactory.create(authorizedKeys.accountId))) {
authorizedKeys.commit(md);
}
}
@@ -161,9 +155,7 @@
private List<Optional<AccountSshKey>> keys;
@Inject
- public VersionedAuthorizedKeys(
- SshKeyCreator sshKeyCreator,
- @Assisted Account.Id accountId) {
+ public VersionedAuthorizedKeys(SshKeyCreator sshKeyCreator, @Assisted Account.Id accountId) {
this.sshKeyCreator = sshKeyCreator;
this.accountId = accountId;
this.ref = RefNames.refsUsers(accountId);
@@ -192,17 +184,15 @@
/** Returns all SSH keys. */
private List<AccountSshKey> getKeys() {
checkLoaded();
- return keys.stream().filter(Optional::isPresent).map(Optional::get)
- .collect(toList());
+ return keys.stream().filter(Optional::isPresent).map(Optional::get).collect(toList());
}
/**
* Returns the SSH key with the given sequence number.
*
* @param seq sequence number
- * @return the SSH key, <code>null</code> if there is no SSH key with this
- * sequence number, or if the SSH key with this sequence number has
- * been deleted
+ * @return the SSH key, <code>null</code> if there is no SSH key with this sequence number, or if
+ * the SSH key with this sequence number has been deleted
*/
private AccountSshKey getKey(int seq) {
checkLoaded();
@@ -212,7 +202,7 @@
/**
* Adds a new public SSH key.
*
- * If the specified public key exists already, the existing key is returned.
+ * <p>If the specified public key exists already, the existing key is returned.
*
* @param pub the public SSH key to be added
* @return the new SSH key
@@ -222,8 +212,7 @@
checkLoaded();
for (Optional<AccountSshKey> key : keys) {
- if (key.isPresent()
- && key.get().getSshPublicKey().trim().equals(pub.trim())) {
+ if (key.isPresent() && key.get().getSshPublicKey().trim().equals(pub.trim())) {
return key.get();
}
}
@@ -239,9 +228,8 @@
* Deletes the SSH key with the given sequence number.
*
* @param seq the sequence number
- * @return <code>true</code> if a key with this sequence number was found and
- * deleted, <code>false</code> if no key with the given sequence
- * number exists
+ * @return <code>true</code> if a key with this sequence number was found and deleted, <code>false
+ * </code> if no key with the given sequence number exists
*/
private boolean deleteKey(int seq) {
checkLoaded();
@@ -256,9 +244,9 @@
* Marks the SSH key with the given sequence number as invalid.
*
* @param seq the sequence number
- * @return <code>true</code> if a key with this sequence number was found and
- * marked as invalid, <code>false</code> if no key with the given
- * sequence number exists or if the key was already marked as invalid
+ * @return <code>true</code> if a key with this sequence number was found and marked as invalid,
+ * <code>false</code> if no key with the given sequence number exists or if the key was
+ * already marked as invalid
*/
private boolean markKeyInvalid(int seq) {
checkLoaded();
@@ -273,15 +261,13 @@
/**
* Sets new SSH keys.
*
- * The existing SSH keys are overwritten.
+ * <p>The existing SSH keys are overwritten.
*
* @param newKeys the new public SSH keys
*/
public void setKeys(Collection<AccountSshKey> newKeys) {
Ordering<AccountSshKey> o = Ordering.from(comparing(k -> k.getKey().get()));
- keys = new ArrayList<>(
- Collections.nCopies(o.max(newKeys).getKey().get(),
- Optional.empty()));
+ keys = new ArrayList<>(Collections.nCopies(o.max(newKeys).getKey().get(), Optional.empty()));
for (AccountSshKey key : newKeys) {
keys.set(key.getKey().get() - 1, Optional.of(key));
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/WatchConfig.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/WatchConfig.java
index 2976ab5..667ca37 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/WatchConfig.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/WatchConfig.java
@@ -41,12 +41,6 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.errors.ConfigInvalidException;
-import org.eclipse.jgit.lib.CommitBuilder;
-import org.eclipse.jgit.lib.Config;
-import org.eclipse.jgit.lib.Repository;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
@@ -55,18 +49,22 @@
import java.util.List;
import java.util.Map;
import java.util.Set;
+import org.eclipse.jgit.errors.ConfigInvalidException;
+import org.eclipse.jgit.lib.CommitBuilder;
+import org.eclipse.jgit.lib.Config;
+import org.eclipse.jgit.lib.Repository;
/**
- * ‘watch.config’ file in the user branch in the All-Users repository that
- * contains the watch configuration of the user.
- * <p>
- * The 'watch.config' file is a git config file that has one 'project' section
- * for all project watches of a project.
- * <p>
- * The project name is used as subsection name and the filters with the notify
- * types that decide for which events email notifications should be sent are
- * represented as 'notify' values in the subsection. A 'notify' value is
- * formatted as {@code <filter> [<comma-separated-list-of-notify-types>]}:
+ * ‘watch.config’ file in the user branch in the All-Users repository that contains the watch
+ * configuration of the user.
+ *
+ * <p>The 'watch.config' file is a git config file that has one 'project' section for all project
+ * watches of a project.
+ *
+ * <p>The project name is used as subsection name and the filters with the notify types that decide
+ * for which events email notifications should be sent are represented as 'notify' values in the
+ * subsection. A 'notify' value is formatted as {@code <filter>
+ * [<comma-separated-list-of-notify-types>]}:
*
* <pre>
* [project "foo"]
@@ -74,22 +72,20 @@
* notify = branch:master [ALL_COMMENTS, NEW_PATCHSETS]
* notify = branch:master owner:self [SUBMITTED_CHANGES]
* </pre>
- * <p>
- * If two notify values in the same subsection have the same filter they are
- * merged on the next save, taking the union of the notify types.
- * <p>
- * For watch configurations that notify on no event the list of notify types is
- * empty:
+ *
+ * <p>If two notify values in the same subsection have the same filter they are merged on the next
+ * save, taking the union of the notify types.
+ *
+ * <p>For watch configurations that notify on no event the list of notify types is empty:
*
* <pre>
* [project "foo"]
* notify = branch:master []
* </pre>
- * <p>
- * Unknown notify types are ignored and removed on save.
+ *
+ * <p>Unknown notify types are ignored and removed on save.
*/
-public class WatchConfig extends VersionedMetaData
- implements ValidationError.Sink {
+public class WatchConfig extends VersionedMetaData implements ValidationError.Sink {
@Singleton
public static class Accessor {
private final GitRepositoryManager repoManager;
@@ -109,8 +105,8 @@
this.userFactory = userFactory;
}
- public Map<ProjectWatchKey, Set<NotifyType>> getProjectWatches(
- Account.Id accountId) throws IOException, ConfigInvalidException {
+ public Map<ProjectWatchKey, Set<NotifyType>> getProjectWatches(Account.Id accountId)
+ throws IOException, ConfigInvalidException {
try (Repository git = repoManager.openRepository(allUsersName)) {
WatchConfig watchConfig = new WatchConfig(accountId);
watchConfig.load(git);
@@ -118,22 +114,20 @@
}
}
- public synchronized void upsertProjectWatches(Account.Id accountId,
- Map<ProjectWatchKey, Set<NotifyType>> newProjectWatches)
+ public synchronized void upsertProjectWatches(
+ Account.Id accountId, Map<ProjectWatchKey, Set<NotifyType>> newProjectWatches)
throws IOException, ConfigInvalidException {
WatchConfig watchConfig = read(accountId);
- Map<ProjectWatchKey, Set<NotifyType>> projectWatches =
- watchConfig.getProjectWatches();
+ Map<ProjectWatchKey, Set<NotifyType>> projectWatches = watchConfig.getProjectWatches();
projectWatches.putAll(newProjectWatches);
commit(watchConfig);
}
- public synchronized void deleteProjectWatches(Account.Id accountId,
- Collection<ProjectWatchKey> projectWatchKeys)
- throws IOException, ConfigInvalidException {
+ public synchronized void deleteProjectWatches(
+ Account.Id accountId, Collection<ProjectWatchKey> projectWatchKeys)
+ throws IOException, ConfigInvalidException {
WatchConfig watchConfig = read(accountId);
- Map<ProjectWatchKey, Set<NotifyType>> projectWatches =
- watchConfig.getProjectWatches();
+ Map<ProjectWatchKey, Set<NotifyType>> projectWatches = watchConfig.getProjectWatches();
boolean commit = false;
for (ProjectWatchKey key : projectWatchKeys) {
if (projectWatches.remove(key) != null) {
@@ -158,8 +152,7 @@
}
}
- private WatchConfig read(Account.Id accountId)
- throws IOException, ConfigInvalidException {
+ private WatchConfig read(Account.Id accountId) throws IOException, ConfigInvalidException {
try (Repository git = repoManager.openRepository(allUsersName)) {
WatchConfig watchConfig = new WatchConfig(accountId);
watchConfig.load(git);
@@ -167,10 +160,11 @@
}
}
- private void commit(WatchConfig watchConfig)
- throws IOException {
- try (MetaDataUpdate md = metaDataUpdateFactory.get().create(allUsersName,
- userFactory.create(watchConfig.accountId))) {
+ private void commit(WatchConfig watchConfig) throws IOException {
+ try (MetaDataUpdate md =
+ metaDataUpdateFactory
+ .get()
+ .create(allUsersName, userFactory.create(watchConfig.accountId))) {
watchConfig.commit(md);
}
}
@@ -178,13 +172,12 @@
@AutoValue
public abstract static class ProjectWatchKey {
- public static ProjectWatchKey create(Project.NameKey project,
- @Nullable String filter) {
- return new AutoValue_WatchConfig_ProjectWatchKey(project,
- Strings.emptyToNull(filter));
+ public static ProjectWatchKey create(Project.NameKey project, @Nullable String filter) {
+ return new AutoValue_WatchConfig_ProjectWatchKey(project, Strings.emptyToNull(filter));
}
public abstract Project.NameKey project();
+
public abstract @Nullable String filter();
}
@@ -229,12 +222,10 @@
@VisibleForTesting
public static Map<ProjectWatchKey, Set<NotifyType>> parse(
- Account.Id accountId, Config cfg,
- ValidationError.Sink validationErrorSink) {
+ Account.Id accountId, Config cfg, ValidationError.Sink validationErrorSink) {
Map<ProjectWatchKey, Set<NotifyType>> projectWatches = new HashMap<>();
for (String projectName : cfg.getSubsections(PROJECT)) {
- String[] notifyValues =
- cfg.getStringList(PROJECT, projectName, KEY_NOTIFY);
+ String[] notifyValues = cfg.getStringList(PROJECT, projectName, KEY_NOTIFY);
for (String nv : notifyValues) {
if (Strings.isNullOrEmpty(nv)) {
continue;
@@ -246,8 +237,8 @@
continue;
}
- ProjectWatchKey key = ProjectWatchKey
- .create(new Project.NameKey(projectName), notifyValue.filter());
+ ProjectWatchKey key =
+ ProjectWatchKey.create(new Project.NameKey(projectName), notifyValue.filter());
if (!projectWatches.containsKey(key)) {
projectWatches.put(key, EnumSet.noneOf(NotifyType.class));
}
@@ -262,14 +253,12 @@
return projectWatches;
}
- public void setProjectWatches(
- Map<ProjectWatchKey, Set<NotifyType>> projectWatches) {
+ public void setProjectWatches(Map<ProjectWatchKey, Set<NotifyType>> projectWatches) {
this.projectWatches = projectWatches;
}
@Override
- protected boolean onSave(CommitBuilder commit)
- throws IOException, ConfigInvalidException {
+ protected boolean onSave(CommitBuilder commit) throws IOException, ConfigInvalidException {
checkLoaded();
if (Strings.isNullOrEmpty(commit.getMessage())) {
@@ -284,18 +273,13 @@
ListMultimap<String, String> notifyValuesByProject =
MultimapBuilder.hashKeys().arrayListValues().build();
- for (Map.Entry<ProjectWatchKey, Set<NotifyType>> e : projectWatches
- .entrySet()) {
- NotifyValue notifyValue =
- NotifyValue.create(e.getKey().filter(), e.getValue());
- notifyValuesByProject.put(e.getKey().project().get(),
- notifyValue.toString());
+ for (Map.Entry<ProjectWatchKey, Set<NotifyType>> e : projectWatches.entrySet()) {
+ NotifyValue notifyValue = NotifyValue.create(e.getKey().filter(), e.getValue());
+ notifyValuesByProject.put(e.getKey().project().get(), notifyValue.toString());
}
- for (Map.Entry<String, Collection<String>> e : notifyValuesByProject.asMap()
- .entrySet()) {
- cfg.setStringList(PROJECT, e.getKey(), KEY_NOTIFY,
- new ArrayList<>(e.getValue()));
+ for (Map.Entry<String, Collection<String>> e : notifyValuesByProject.asMap().entrySet()) {
+ cfg.setStringList(PROJECT, e.getKey(), KEY_NOTIFY, new ArrayList<>(e.getValue()));
}
saveConfig(WATCH_CONFIG, cfg);
@@ -328,15 +312,20 @@
@AutoValue
public abstract static class NotifyValue {
- public static NotifyValue parse(Account.Id accountId, String project,
- String notifyValue, ValidationError.Sink validationErrorSink) {
+ public static NotifyValue parse(
+ Account.Id accountId,
+ String project,
+ String notifyValue,
+ ValidationError.Sink validationErrorSink) {
notifyValue = notifyValue.trim();
int i = notifyValue.lastIndexOf('[');
if (i < 0 || notifyValue.charAt(notifyValue.length() - 1) != ']') {
- validationErrorSink.error(new ValidationError(WATCH_CONFIG,
- String.format(
- "Invalid project watch of account %d for project %s: %s",
- accountId.get(), project, notifyValue)));
+ validationErrorSink.error(
+ new ValidationError(
+ WATCH_CONFIG,
+ String.format(
+ "Invalid project watch of account %d for project %s: %s",
+ accountId.get(), project, notifyValue)));
return null;
}
String filter = notifyValue.substring(0, i).trim();
@@ -346,16 +335,19 @@
Set<NotifyType> notifyTypes = EnumSet.noneOf(NotifyType.class);
if (i + 1 < notifyValue.length() - 2) {
- for (String nt : Splitter.on(',').trimResults().splitToList(
- notifyValue.substring(i + 1, notifyValue.length() - 1))) {
- NotifyType notifyType =
- Enums.getIfPresent(NotifyType.class, nt).orNull();
+ for (String nt :
+ Splitter.on(',')
+ .trimResults()
+ .splitToList(notifyValue.substring(i + 1, notifyValue.length() - 1))) {
+ NotifyType notifyType = Enums.getIfPresent(NotifyType.class, nt).orNull();
if (notifyType == null) {
- validationErrorSink.error(new ValidationError(WATCH_CONFIG,
- String.format(
- "Invalid notify type %s in project watch "
- + "of account %d for project %s: %s",
- nt, accountId.get(), project, notifyValue)));
+ validationErrorSink.error(
+ new ValidationError(
+ WATCH_CONFIG,
+ String.format(
+ "Invalid notify type %s in project watch "
+ + "of account %d for project %s: %s",
+ nt, accountId.get(), project, notifyValue)));
continue;
}
notifyTypes.add(notifyType);
@@ -364,21 +356,20 @@
return create(filter, notifyTypes);
}
- public static NotifyValue create(@Nullable String filter,
- Set<NotifyType> notifyTypes) {
- return new AutoValue_WatchConfig_NotifyValue(Strings.emptyToNull(filter),
- Sets.immutableEnumSet(notifyTypes));
+ public static NotifyValue create(@Nullable String filter, Set<NotifyType> notifyTypes) {
+ return new AutoValue_WatchConfig_NotifyValue(
+ Strings.emptyToNull(filter), Sets.immutableEnumSet(notifyTypes));
}
public abstract @Nullable String filter();
+
public abstract ImmutableSet<NotifyType> notifyTypes();
@Override
public String toString() {
List<NotifyType> notifyTypes = new ArrayList<>(notifyTypes());
StringBuilder notifyValue = new StringBuilder();
- notifyValue.append(firstNonNull(filter(), FILTER_ALL))
- .append(" [");
+ notifyValue.append(firstNonNull(filter(), FILTER_ALL)).append(" [");
Joiner.on(", ").appendTo(notifyValue, notifyTypes);
notifyValue.append("]");
return notifyValue.toString();
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/api/GerritApiImpl.java b/gerrit-server/src/main/java/com/google/gerrit/server/api/GerritApiImpl.java
index 577abe1..6241276 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/api/GerritApiImpl.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/api/GerritApiImpl.java
@@ -32,11 +32,8 @@
private final Projects projects;
@Inject
- GerritApiImpl(Accounts accounts,
- Changes changes,
- Config config,
- Groups groups,
- Projects projects) {
+ GerritApiImpl(
+ Accounts accounts, Changes changes, Config config, Groups groups, Projects projects) {
this.accounts = accounts;
this.changes = changes;
this.config = config;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/api/accounts/AccountApiImpl.java b/gerrit-server/src/main/java/com/google/gerrit/server/api/accounts/AccountApiImpl.java
index 3c20719..e1eb119 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/api/accounts/AccountApiImpl.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/api/accounts/AccountApiImpl.java
@@ -71,13 +71,11 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
-
-import org.eclipse.jgit.errors.ConfigInvalidException;
-
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
+import org.eclipse.jgit.errors.ConfigInvalidException;
public class AccountApiImpl implements AccountApi {
interface Factory {
@@ -119,7 +117,8 @@
private final PutStatus putStatus;
@Inject
- AccountApiImpl(AccountLoader.Factory ailf,
+ AccountApiImpl(
+ AccountLoader.Factory ailf,
ChangesCollection changes,
GetAvatar getAvatar,
GetPreferences getPreferences,
@@ -188,8 +187,7 @@
}
@Override
- public com.google.gerrit.extensions.common.AccountInfo get()
- throws RestApiException {
+ public com.google.gerrit.extensions.common.AccountInfo get() throws RestApiException {
AccountLoader accountLoader = accountLoaderFactory.create(true);
try {
AccountInfo ai = accountLoader.get(account.getUser().getAccountId());
@@ -231,8 +229,7 @@
}
@Override
- public GeneralPreferencesInfo setPreferences(GeneralPreferencesInfo in)
- throws RestApiException {
+ public GeneralPreferencesInfo setPreferences(GeneralPreferencesInfo in) throws RestApiException {
try {
return setPreferences.apply(account, in);
} catch (IOException | ConfigInvalidException e) {
@@ -250,8 +247,7 @@
}
@Override
- public DiffPreferencesInfo setDiffPreferences(DiffPreferencesInfo in)
- throws RestApiException {
+ public DiffPreferencesInfo setDiffPreferences(DiffPreferencesInfo in) throws RestApiException {
try {
return setDiffPreferences.apply(account, in);
} catch (IOException | ConfigInvalidException e) {
@@ -269,8 +265,7 @@
}
@Override
- public EditPreferencesInfo setEditPreferences(EditPreferencesInfo in)
- throws RestApiException {
+ public EditPreferencesInfo setEditPreferences(EditPreferencesInfo in) throws RestApiException {
try {
return setEditPreferences.apply(account, in);
} catch (IOException | ConfigInvalidException e) {
@@ -288,8 +283,8 @@
}
@Override
- public List<ProjectWatchInfo> setWatchedProjects(
- List<ProjectWatchInfo> in) throws RestApiException {
+ public List<ProjectWatchInfo> setWatchedProjects(List<ProjectWatchInfo> in)
+ throws RestApiException {
try {
return postWatchedProjects.apply(account, in);
} catch (OrmException | IOException | ConfigInvalidException e) {
@@ -298,8 +293,7 @@
}
@Override
- public void deleteWatchedProjects(List<ProjectWatchInfo> in)
- throws RestApiException {
+ public void deleteWatchedProjects(List<ProjectWatchInfo> in) throws RestApiException {
try {
deleteWatchedProjects.apply(account, in);
} catch (OrmException | IOException | ConfigInvalidException e) {
@@ -310,9 +304,7 @@
@Override
public void starChange(String changeId) throws RestApiException {
try {
- ChangeResource rsrc = changes.parse(
- TopLevelResource.INSTANCE,
- IdString.fromUrl(changeId));
+ ChangeResource rsrc = changes.parse(TopLevelResource.INSTANCE, IdString.fromUrl(changeId));
starredChangesCreate.setChange(rsrc);
starredChangesCreate.apply(account, new StarredChanges.EmptyInput());
} catch (OrmException | IOException e) {
@@ -323,23 +315,19 @@
@Override
public void unstarChange(String changeId) throws RestApiException {
try {
- ChangeResource rsrc =
- changes.parse(TopLevelResource.INSTANCE, IdString.fromUrl(changeId));
+ ChangeResource rsrc = changes.parse(TopLevelResource.INSTANCE, IdString.fromUrl(changeId));
AccountResource.StarredChange starredChange =
new AccountResource.StarredChange(account.getUser(), rsrc);
- starredChangesDelete.apply(starredChange,
- new StarredChanges.EmptyInput());
+ starredChangesDelete.apply(starredChange, new StarredChanges.EmptyInput());
} catch (OrmException | IOException e) {
throw new RestApiException("Cannot unstar change", e);
}
}
@Override
- public void setStars(String changeId, StarsInput input)
- throws RestApiException {
+ public void setStars(String changeId, StarsInput input) throws RestApiException {
try {
- AccountResource.Star rsrc =
- stars.parse(account, IdString.fromUrl(changeId));
+ AccountResource.Star rsrc = stars.parse(account, IdString.fromUrl(changeId));
starsPost.apply(rsrc, input);
} catch (OrmException e) {
throw new RestApiException("Cannot post stars", e);
@@ -349,8 +337,7 @@
@Override
public SortedSet<String> getStars(String changeId) throws RestApiException {
try {
- AccountResource.Star rsrc =
- stars.parse(account, IdString.fromUrl(changeId));
+ AccountResource.Star rsrc = stars.parse(account, IdString.fromUrl(changeId));
return starsGet.apply(rsrc);
} catch (OrmException e) {
throw new RestApiException("Cannot get stars", e);
@@ -368,8 +355,7 @@
@Override
public void addEmail(EmailInput input) throws RestApiException {
- AccountResource.Email rsrc =
- new AccountResource.Email(account.getUser(), input.email);
+ AccountResource.Email rsrc = new AccountResource.Email(account.getUser(), input.email);
try {
createEmailFactory.create(input.email).apply(rsrc, input);
} catch (EmailException | OrmException | IOException e) {
@@ -428,8 +414,8 @@
}
@Override
- public Map<String, GpgKeyInfo> putGpgKeys(List<String> add,
- List<String> delete) throws RestApiException {
+ public Map<String, GpgKeyInfo> putGpgKeys(List<String> add, List<String> delete)
+ throws RestApiException {
try {
return gpgApiAdapter.putGpgKeys(account, add, delete);
} catch (GpgException e) {
@@ -481,8 +467,7 @@
}
@Override
- public void deleteExternalIds(List<String> externalIds)
- throws RestApiException {
+ public void deleteExternalIds(List<String> externalIds) throws RestApiException {
try {
deleteExternalIds.apply(account, externalIds);
} catch (IOException | OrmException e) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/api/accounts/AccountExternalIdCreator.java b/gerrit-server/src/main/java/com/google/gerrit/server/api/accounts/AccountExternalIdCreator.java
index a0b9b4e..8be7c4d 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/api/accounts/AccountExternalIdCreator.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/api/accounts/AccountExternalIdCreator.java
@@ -16,22 +16,17 @@
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.reviewdb.client.AccountExternalId;
-
import java.util.List;
public interface AccountExternalIdCreator {
/**
- * Returns additional external identifiers to assign to a given
- * user when creating an account.
+ * Returns additional external identifiers to assign to a given user when creating an account.
*
* @param id the identifier of the account.
* @param username the name of the user.
- * @param email an optional email address to assign to the external
- * identifiers, or {@code null}.
- *
+ * @param email an optional email address to assign to the external identifiers, or {@code null}.
* @return a list of external identifiers, or an empty list.
*/
- List<AccountExternalId> create(Account.Id id, String username,
- String email);
+ List<AccountExternalId> create(Account.Id id, String username, String email);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/api/accounts/AccountInfoComparator.java b/gerrit-server/src/main/java/com/google/gerrit/server/api/accounts/AccountInfoComparator.java
index f89e5ca..7c468fc 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/api/accounts/AccountInfoComparator.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/api/accounts/AccountInfoComparator.java
@@ -17,20 +17,17 @@
import com.google.common.collect.ComparisonChain;
import com.google.common.collect.Ordering;
import com.google.gerrit.extensions.common.AccountInfo;
-
import java.util.Comparator;
public class AccountInfoComparator extends Ordering<AccountInfo>
implements Comparator<AccountInfo> {
- public static final AccountInfoComparator ORDER_NULLS_FIRST =
- new AccountInfoComparator();
+ public static final AccountInfoComparator ORDER_NULLS_FIRST = new AccountInfoComparator();
public static final AccountInfoComparator ORDER_NULLS_LAST =
new AccountInfoComparator().setNullsLast();
private boolean nullsLast;
- private AccountInfoComparator() {
- }
+ private AccountInfoComparator() {}
private AccountInfoComparator setNullsLast() {
this.nullsLast = true;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/api/accounts/AccountsImpl.java b/gerrit-server/src/main/java/com/google/gerrit/server/api/accounts/AccountsImpl.java
index 6a248f7..498b720 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/api/accounts/AccountsImpl.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/api/accounts/AccountsImpl.java
@@ -36,11 +36,9 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.errors.ConfigInvalidException;
-
import java.io.IOException;
import java.util.List;
+import org.eclipse.jgit.errors.ConfigInvalidException;
@Singleton
public class AccountsImpl implements Accounts {
@@ -51,7 +49,8 @@
private final Provider<QueryAccounts> queryAccountsProvider;
@Inject
- AccountsImpl(AccountsCollection accounts,
+ AccountsImpl(
+ AccountsCollection accounts,
AccountApiImpl.Factory api,
Provider<CurrentUser> self,
CreateAccount.Factory createAccount,
@@ -66,8 +65,7 @@
@Override
public AccountApi id(String id) throws RestApiException {
try {
- return api.create(accounts.parse(TopLevelResource.INSTANCE,
- IdString.fromDecoded(id)));
+ return api.create(accounts.parse(TopLevelResource.INSTANCE, IdString.fromDecoded(id)));
} catch (OrmException e) {
throw new RestApiException("Cannot parse change", e);
}
@@ -100,8 +98,8 @@
}
checkRequiresCapability(self, null, CreateAccount.class);
try {
- AccountInfo info = createAccount.create(in.username)
- .apply(TopLevelResource.INSTANCE, in).value();
+ AccountInfo info =
+ createAccount.create(in.username).apply(TopLevelResource.INSTANCE, in).value();
return id(info._accountId);
} catch (OrmException | IOException | ConfigInvalidException e) {
throw new RestApiException("Cannot create account " + in.username, e);
@@ -119,13 +117,11 @@
}
@Override
- public SuggestAccountsRequest suggestAccounts(String query)
- throws RestApiException {
+ public SuggestAccountsRequest suggestAccounts(String query) throws RestApiException {
return suggestAccounts().withQuery(query);
}
- private List<AccountInfo> suggestAccounts(SuggestAccountsRequest r)
- throws RestApiException {
+ private List<AccountInfo> suggestAccounts(SuggestAccountsRequest r) throws RestApiException {
try {
QueryAccounts myQueryAccounts = queryAccountsProvider.get();
myQueryAccounts.setSuggest(true);
@@ -152,8 +148,7 @@
return query().withQuery(query);
}
- private List<AccountInfo> query(QueryRequest r)
- throws RestApiException {
+ private List<AccountInfo> query(QueryRequest r) throws RestApiException {
try {
QueryAccounts myQueryAccounts = queryAccountsProvider.get();
myQueryAccounts.setQuery(r.getQuery());
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/api/accounts/GpgApiAdapter.java b/gerrit-server/src/main/java/com/google/gerrit/server/api/accounts/GpgApiAdapter.java
index a83110c..7def6fa 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/api/accounts/GpgApiAdapter.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/api/accounts/GpgApiAdapter.java
@@ -22,7 +22,6 @@
import com.google.gerrit.server.GpgException;
import com.google.gerrit.server.IdentifiedUser;
import com.google.gerrit.server.account.AccountResource;
-
import java.util.List;
import java.util.Map;
@@ -32,12 +31,11 @@
Map<String, GpgKeyInfo> listGpgKeys(AccountResource account)
throws RestApiException, GpgException;
- Map<String, GpgKeyInfo> putGpgKeys(AccountResource account, List<String> add,
- List<String> delete) throws RestApiException, GpgException;
-
- GpgKeyApi gpgKey(AccountResource account, IdString idStr)
+ Map<String, GpgKeyInfo> putGpgKeys(AccountResource account, List<String> add, List<String> delete)
throws RestApiException, GpgException;
- PushCertificateInfo checkPushCertificate(String certStr,
- IdentifiedUser expectedUser) throws GpgException;
+ GpgKeyApi gpgKey(AccountResource account, IdString idStr) throws RestApiException, GpgException;
+
+ PushCertificateInfo checkPushCertificate(String certStr, IdentifiedUser expectedUser)
+ throws GpgException;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/api/changes/ChangeApiImpl.java b/gerrit-server/src/main/java/com/google/gerrit/server/api/changes/ChangeApiImpl.java
index 2a4b5ca..52353ca 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/api/changes/ChangeApiImpl.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/api/changes/ChangeApiImpl.java
@@ -75,7 +75,6 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.assistedinject.Assisted;
-
import java.io.IOException;
import java.util.EnumSet;
import java.util.List;
@@ -99,8 +98,7 @@
private final Restore restore;
private final CreateMergePatchSet updateByMerge;
private final Provider<SubmittedTogether> submittedTogether;
- private final PublishDraftPatchSet.CurrentRevision
- publishDraftChange;
+ private final PublishDraftPatchSet.CurrentRevision publishDraftChange;
private final DeleteChange deleteChange;
private final GetTopic getTopic;
private final PutTopic putTopic;
@@ -122,7 +120,8 @@
private final Move move;
@Inject
- ChangeApiImpl(Changes changeApi,
+ ChangeApiImpl(
+ Changes changeApi,
Reviewers reviewers,
Revisions revisions,
ReviewerApiImpl.Factory reviewerApi,
@@ -206,8 +205,7 @@
@Override
public RevisionApi revision(String id) throws RestApiException {
try {
- return revisionApi.create(
- revisions.parse(change, IdString.fromDecoded(id)));
+ return revisionApi.create(revisions.parse(change, IdString.fromDecoded(id)));
} catch (OrmException | IOException e) {
throw new RestApiException("Cannot parse revision", e);
}
@@ -216,8 +214,7 @@
@Override
public ReviewerApi reviewer(String id) throws RestApiException {
try {
- return reviewerApi.create(
- reviewers.parse(change, IdString.fromDecoded(id)));
+ return reviewerApi.create(reviewers.parse(change, IdString.fromDecoded(id)));
} catch (OrmException e) {
throw new RestApiException("Cannot parse reviewer", e);
}
@@ -282,36 +279,35 @@
}
@Override
- public ChangeInfo createMergePatchSet(MergePatchSetInput in)
- throws RestApiException {
+ public ChangeInfo createMergePatchSet(MergePatchSetInput in) throws RestApiException {
try {
return updateByMerge.apply(change, in).value();
- } catch (IOException | UpdateException | InvalidChangeOperationException
- | OrmException e) {
+ } catch (IOException | UpdateException | InvalidChangeOperationException | OrmException e) {
throw new RestApiException("Cannot update change by merge", e);
}
}
@Override
public List<ChangeInfo> submittedTogether() throws RestApiException {
- SubmittedTogetherInfo info = submittedTogether(
- EnumSet.noneOf(ListChangesOption.class),
- EnumSet.noneOf(SubmittedTogetherOption.class));
+ SubmittedTogetherInfo info =
+ submittedTogether(
+ EnumSet.noneOf(ListChangesOption.class), EnumSet.noneOf(SubmittedTogetherOption.class));
return info.changes;
}
@Override
- public SubmittedTogetherInfo submittedTogether(
- EnumSet<SubmittedTogetherOption> options) throws RestApiException {
+ public SubmittedTogetherInfo submittedTogether(EnumSet<SubmittedTogetherOption> options)
+ throws RestApiException {
return submittedTogether(EnumSet.noneOf(ListChangesOption.class), options);
}
@Override
public SubmittedTogetherInfo submittedTogether(
- EnumSet<ListChangesOption> listOptions,
- EnumSet<SubmittedTogetherOption> submitOptions) throws RestApiException {
+ EnumSet<ListChangesOption> listOptions, EnumSet<SubmittedTogetherOption> submitOptions)
+ throws RestApiException {
try {
- return submittedTogether.get()
+ return submittedTogether
+ .get()
.addListChangesOption(listOptions)
.addSubmittedTogetherOption(submitOptions)
.applyInfo(change);
@@ -390,8 +386,7 @@
}
@Override
- public SuggestedReviewersRequest suggestReviewers(String query)
- throws RestApiException {
+ public SuggestedReviewersRequest suggestReviewers(String query) throws RestApiException {
return suggestReviewers().withQuery(query);
}
@@ -407,8 +402,7 @@
}
@Override
- public ChangeInfo get(EnumSet<ListChangesOption> s)
- throws RestApiException {
+ public ChangeInfo get(EnumSet<ListChangesOption> s) throws RestApiException {
try {
return changeJson.create(s).format(change);
} catch (OrmException e) {
@@ -455,8 +449,7 @@
}
@Override
- public AccountInfo setAssignee(AssigneeInput input)
- throws RestApiException {
+ public AccountInfo setAssignee(AssigneeInput input) throws RestApiException {
try {
return putAssignee.apply(change, input).value();
} catch (UpdateException | IOException | OrmException e) {
@@ -503,8 +496,7 @@
}
@Override
- public Map<String, List<RobotCommentInfo>> robotComments()
- throws RestApiException {
+ public Map<String, List<RobotCommentInfo>> robotComments() throws RestApiException {
try {
return listChangeRobotComments.apply(change);
} catch (OrmException e) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/api/changes/ChangeEditApiImpl.java b/gerrit-server/src/main/java/com/google/gerrit/server/api/changes/ChangeEditApiImpl.java
index b186767..de5c764 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/api/changes/ChangeEditApiImpl.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/api/changes/ChangeEditApiImpl.java
@@ -34,7 +34,6 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
-
import java.io.IOException;
import java.util.Optional;
@@ -57,7 +56,8 @@
private final ChangeResource changeResource;
@Inject
- public ChangeEditApiImpl(ChangeEdits.Detail editDetail,
+ public ChangeEditApiImpl(
+ ChangeEdits.Detail editDetail,
ChangeEdits.Post changeEditsPost,
DeleteChangeEdit deleteChangeEdit,
RebaseChangeEdit.Rebase rebaseChangeEdit,
@@ -126,8 +126,7 @@
}
@Override
- public void publish(PublishChangeEditInput publishChangeEditInput)
- throws RestApiException {
+ public void publish(PublishChangeEditInput publishChangeEditInput) throws RestApiException {
try {
publishChangeEdit.apply(changeResource, publishChangeEditInput);
} catch (IOException | OrmException | UpdateException e) {
@@ -136,23 +135,18 @@
}
@Override
- public Optional<BinaryResult> getFile(String filePath)
- throws RestApiException {
+ public Optional<BinaryResult> getFile(String filePath) throws RestApiException {
try {
ChangeEditResource changeEditResource = getChangeEditResource(filePath);
- Response<BinaryResult> fileResponse =
- changeEditsGet.apply(changeEditResource);
- return fileResponse.isNone()
- ? Optional.empty()
- : Optional.of(fileResponse.value());
+ Response<BinaryResult> fileResponse = changeEditsGet.apply(changeEditResource);
+ return fileResponse.isNone() ? Optional.empty() : Optional.of(fileResponse.value());
} catch (IOException | OrmException e) {
throw new RestApiException("Cannot retrieve file of change edit", e);
}
}
@Override
- public void renameFile(String oldFilePath, String newFilePath)
- throws RestApiException {
+ public void renameFile(String oldFilePath, String newFilePath) throws RestApiException {
try {
ChangeEdits.Post.Input renameInput = new ChangeEdits.Post.Input();
renameInput.oldPath = oldFilePath;
@@ -175,8 +169,7 @@
}
@Override
- public void modifyFile(String filePath, RawInput newContent)
- throws RestApiException {
+ public void modifyFile(String filePath, RawInput newContent) throws RestApiException {
try {
changeEditsPut.apply(changeResource.getControl(), filePath, newContent);
} catch (IOException | OrmException e) {
@@ -196,8 +189,7 @@
@Override
public String getCommitMessage() throws RestApiException {
try {
- try (BinaryResult binaryResult =
- getChangeEditCommitMessage.apply(changeResource)) {
+ try (BinaryResult binaryResult = getChangeEditCommitMessage.apply(changeResource)) {
return binaryResult.asString();
}
} catch (IOException | OrmException e) {
@@ -206,21 +198,18 @@
}
@Override
- public void modifyCommitMessage(String newCommitMessage)
- throws RestApiException {
+ public void modifyCommitMessage(String newCommitMessage) throws RestApiException {
ChangeEdits.EditMessage.Input input = new ChangeEdits.EditMessage.Input();
input.message = newCommitMessage;
try {
modifyChangeEditCommitMessage.apply(changeResource, input);
} catch (IOException | OrmException e) {
- throw new RestApiException("Cannot modify commit message of change edit",
- e);
+ throw new RestApiException("Cannot modify commit message of change edit", e);
}
}
private ChangeEditResource getChangeEditResource(String filePath)
- throws ResourceNotFoundException, AuthException, IOException,
- OrmException {
+ throws ResourceNotFoundException, AuthException, IOException, OrmException {
return changeEdits.parse(changeResource, IdString.fromDecoded(filePath));
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/api/changes/ChangesImpl.java b/gerrit-server/src/main/java/com/google/gerrit/server/api/changes/ChangesImpl.java
index bb2eea7..65218cd 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/api/changes/ChangesImpl.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/api/changes/ChangesImpl.java
@@ -39,7 +39,6 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.io.IOException;
import java.util.List;
@@ -51,7 +50,8 @@
private final Provider<QueryChanges> queryProvider;
@Inject
- ChangesImpl(ChangesCollection changes,
+ ChangesImpl(
+ ChangesCollection changes,
ChangeApiImpl.Factory api,
CreateChange createChange,
Provider<QueryChanges> queryProvider) {
@@ -67,20 +67,16 @@
}
@Override
- public ChangeApi id(String project, String branch, String id)
- throws RestApiException {
- return id(Joiner.on('~').join(ImmutableList.of(
- Url.encode(project),
- Url.encode(branch),
- Url.encode(id))));
+ public ChangeApi id(String project, String branch, String id) throws RestApiException {
+ return id(
+ Joiner.on('~')
+ .join(ImmutableList.of(Url.encode(project), Url.encode(branch), Url.encode(id))));
}
@Override
public ChangeApi id(String id) throws RestApiException {
try {
- return api.create(changes.parse(
- TopLevelResource.INSTANCE,
- IdString.fromUrl(id)));
+ return api.create(changes.parse(TopLevelResource.INSTANCE, IdString.fromUrl(id)));
} catch (OrmException e) {
throw new RestApiException("Cannot parse change", e);
}
@@ -89,11 +85,9 @@
@Override
public ChangeApi create(ChangeInput in) throws RestApiException {
try {
- ChangeInfo out = createChange.apply(
- TopLevelResource.INSTANCE, in).value();
+ ChangeInfo out = createChange.apply(TopLevelResource.INSTANCE, in).value();
return api.create(changes.parse(new Change.Id(out._number)));
- } catch (OrmException | IOException | InvalidChangeOperationException
- | UpdateException e) {
+ } catch (OrmException | IOException | InvalidChangeOperationException | UpdateException e) {
throw new RestApiException("Cannot create change", e);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/api/changes/CommentApiImpl.java b/gerrit-server/src/main/java/com/google/gerrit/server/api/changes/CommentApiImpl.java
index 0352aff..5c61e23 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/api/changes/CommentApiImpl.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/api/changes/CommentApiImpl.java
@@ -32,8 +32,7 @@
private final CommentResource comment;
@Inject
- CommentApiImpl(GetComment getComment,
- @Assisted CommentResource comment) {
+ CommentApiImpl(GetComment getComment, @Assisted CommentResource comment) {
this.getComment = getComment;
this.comment = comment;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/api/changes/DraftApiImpl.java b/gerrit-server/src/main/java/com/google/gerrit/server/api/changes/DraftApiImpl.java
index 2e2dfcc..e631501 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/api/changes/DraftApiImpl.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/api/changes/DraftApiImpl.java
@@ -38,7 +38,8 @@
private final DraftCommentResource draft;
@Inject
- DraftApiImpl(DeleteDraftComment deleteDraft,
+ DraftApiImpl(
+ DeleteDraftComment deleteDraft,
GetDraftComment getDraft,
PutDraftComment putDraft,
@Assisted DraftCommentResource draft) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/api/changes/FileApiImpl.java b/gerrit-server/src/main/java/com/google/gerrit/server/api/changes/FileApiImpl.java
index 2aa0f3d..aa66e7b 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/api/changes/FileApiImpl.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/api/changes/FileApiImpl.java
@@ -25,7 +25,6 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
-
import java.io.IOException;
class FileApiImpl implements FileApi {
@@ -38,9 +37,7 @@
private final FileResource file;
@Inject
- FileApiImpl(GetContent getContent,
- GetDiff getDiff,
- @Assisted FileResource file) {
+ FileApiImpl(GetContent getContent, GetDiff getDiff, @Assisted FileResource file) {
this.getContent = getContent;
this.getDiff = getDiff;
this.file = file;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/api/changes/ReviewerApiImpl.java b/gerrit-server/src/main/java/com/google/gerrit/server/api/changes/ReviewerApiImpl.java
index afda5fa..c57a371 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/api/changes/ReviewerApiImpl.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/api/changes/ReviewerApiImpl.java
@@ -27,7 +27,6 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
-
import java.util.Map;
public class ReviewerApiImpl implements ReviewerApi {
@@ -41,7 +40,8 @@
private final DeleteReviewer deleteReviewer;
@Inject
- ReviewerApiImpl(Votes.List listVotes,
+ ReviewerApiImpl(
+ Votes.List listVotes,
DeleteVote deleteVote,
DeleteReviewer deleteReviewer,
@Assisted ReviewerResource reviewer) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/api/changes/RevisionApiImpl.java b/gerrit-server/src/main/java/com/google/gerrit/server/api/changes/RevisionApiImpl.java
index a7aa2d0..fe821e6 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/api/changes/RevisionApiImpl.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/api/changes/RevisionApiImpl.java
@@ -75,14 +75,12 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.assistedinject.Assisted;
-
-import org.eclipse.jgit.lib.Repository;
-import org.eclipse.jgit.revwalk.RevWalk;
-
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;
+import org.eclipse.jgit.lib.Repository;
+import org.eclipse.jgit.revwalk.RevWalk;
class RevisionApiImpl implements RevisionApi {
interface Factory {
@@ -127,7 +125,8 @@
private final GetDescription getDescription;
@Inject
- RevisionApiImpl(GitRepositoryManager repoManager,
+ RevisionApiImpl(
+ GitRepositoryManager repoManager,
Changes changes,
RevisionReviewers revisionReviewers,
RevisionReviewerApiImpl.Factory revisionReviewerApi,
@@ -273,8 +272,7 @@
public boolean canRebase() throws RestApiException {
try (Repository repo = repoManager.openRepository(revision.getProject());
RevWalk rw = new RevWalk(repo)) {
- return rebaseUtil.canRebase(
- revision.getPatchSet(), revision.getChange().getDest(), repo, rw);
+ return rebaseUtil.canRebase(revision.getPatchSet(), revision.getChange().getDest(), repo, rw);
} catch (IOException e) {
throw new RestApiException("Cannot check if rebase is possible", e);
}
@@ -308,9 +306,7 @@
} else {
view = deleteReviewed;
}
- view.apply(
- files.parse(revision, IdString.fromDecoded(path)),
- new Reviewed.Input());
+ view.apply(files.parse(revision, IdString.fromDecoded(path)), new Reviewed.Input());
} catch (Exception e) {
throw new RestApiException("Cannot update reviewed flag", e);
}
@@ -320,9 +316,8 @@
@Override
public Set<String> reviewed() throws RestApiException {
try {
- return ImmutableSet.copyOf((Iterable<String>) listFiles
- .setReviewed(true)
- .apply(revision).value());
+ return ImmutableSet.copyOf(
+ (Iterable<String>) listFiles.setReviewed(true).apply(revision).value());
} catch (OrmException | IOException | PatchListNotAvailableException e) {
throw new RestApiException("Cannot list reviewed files", e);
}
@@ -351,7 +346,7 @@
@Override
public Map<String, FileInfo> files() throws RestApiException {
try {
- return (Map<String, FileInfo>)listFiles.apply(revision).value();
+ return (Map<String, FileInfo>) listFiles.apply(revision).value();
} catch (OrmException | IOException | PatchListNotAvailableException e) {
throw new RestApiException("Cannot retrieve files", e);
}
@@ -361,8 +356,7 @@
@Override
public Map<String, FileInfo> files(String base) throws RestApiException {
try {
- return (Map<String, FileInfo>) listFiles.setBase(base)
- .apply(revision).value();
+ return (Map<String, FileInfo>) listFiles.setBase(base).apply(revision).value();
} catch (OrmException | IOException | PatchListNotAvailableException e) {
throw new RestApiException("Cannot retrieve files", e);
}
@@ -372,8 +366,7 @@
@Override
public Map<String, FileInfo> files(int parentNum) throws RestApiException {
try {
- return (Map<String, FileInfo>) listFiles.setParent(parentNum)
- .apply(revision).value();
+ return (Map<String, FileInfo>) listFiles.setParent(parentNum).apply(revision).value();
} catch (OrmException | IOException | PatchListNotAvailableException e) {
throw new RestApiException("Cannot retrieve files", e);
}
@@ -381,8 +374,7 @@
@Override
public FileApi file(String path) {
- return fileApi.create(files.parse(revision,
- IdString.fromDecoded(path)));
+ return fileApi.create(files.parse(revision, IdString.fromDecoded(path)));
}
@Override
@@ -442,8 +434,7 @@
@Override
public DraftApi draft(String id) throws RestApiException {
try {
- return draftFactory.create(drafts.parse(revision,
- IdString.fromDecoded(id)));
+ return draftFactory.create(drafts.parse(revision, IdString.fromDecoded(id)));
} catch (OrmException e) {
throw new RestApiException("Cannot retrieve draft", e);
}
@@ -454,7 +445,8 @@
try {
String id = createDraft.apply(revision, in).value().id;
// Reread change to pick up new notes refs.
- return changes.id(revision.getChange().getId().get())
+ return changes
+ .id(revision.getChange().getId().get())
.revision(revision.getPatchSet().getId().get())
.draft(id);
} catch (UpdateException | OrmException e) {
@@ -465,8 +457,7 @@
@Override
public CommentApi comment(String id) throws RestApiException {
try {
- return commentFactory.create(comments.parse(revision,
- IdString.fromDecoded(id)));
+ return commentFactory.create(comments.parse(revision, IdString.fromDecoded(id)));
} catch (OrmException e) {
throw new RestApiException("Cannot retrieve comment", e);
}
@@ -475,8 +466,7 @@
@Override
public RobotCommentApi robotComment(String id) throws RestApiException {
try {
- return robotCommentFactory
- .create(robotComments.parse(revision, IdString.fromDecoded(id)));
+ return robotCommentFactory.create(robotComments.parse(revision, IdString.fromDecoded(id)));
} catch (OrmException e) {
throw new RestApiException("Cannot retrieve robot comment", e);
}
@@ -519,8 +509,7 @@
}
@Override
- public SubmitType testSubmitType(TestSubmitRuleInput in)
- throws RestApiException {
+ public SubmitType testSubmitType(TestSubmitRuleInput in) throws RestApiException {
try {
return testSubmitType.apply(revision, in);
} catch (OrmException e) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/api/changes/RevisionReviewerApiImpl.java b/gerrit-server/src/main/java/com/google/gerrit/server/api/changes/RevisionReviewerApiImpl.java
index 82740c4..b5828c1 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/api/changes/RevisionReviewerApiImpl.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/api/changes/RevisionReviewerApiImpl.java
@@ -25,7 +25,6 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
-
import java.util.Map;
public class RevisionReviewerApiImpl implements RevisionReviewerApi {
@@ -38,9 +37,8 @@
private final DeleteVote deleteVote;
@Inject
- RevisionReviewerApiImpl(Votes.List listVotes,
- DeleteVote deleteVote,
- @Assisted ReviewerResource reviewer) {
+ RevisionReviewerApiImpl(
+ Votes.List listVotes, DeleteVote deleteVote, @Assisted ReviewerResource reviewer) {
this.listVotes = listVotes;
this.deleteVote = deleteVote;
this.reviewer = reviewer;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/api/changes/RobotCommentApiImpl.java b/gerrit-server/src/main/java/com/google/gerrit/server/api/changes/RobotCommentApiImpl.java
index 9169a4f..ded98cb 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/api/changes/RobotCommentApiImpl.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/api/changes/RobotCommentApiImpl.java
@@ -32,8 +32,7 @@
private final RobotCommentResource comment;
@Inject
- RobotCommentApiImpl(GetRobotComment getComment,
- @Assisted RobotCommentResource comment) {
+ RobotCommentApiImpl(GetRobotComment getComment, @Assisted RobotCommentResource comment) {
this.getComment = getComment;
this.comment = comment;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/api/config/ServerImpl.java b/gerrit-server/src/main/java/com/google/gerrit/server/api/config/ServerImpl.java
index f433d2b..9b6ead0 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/api/config/ServerImpl.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/api/config/ServerImpl.java
@@ -28,10 +28,8 @@
import com.google.gerrit.server.config.SetPreferences;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.errors.ConfigInvalidException;
-
import java.io.IOException;
+import org.eclipse.jgit.errors.ConfigInvalidException;
@Singleton
public class ServerImpl implements Server {
@@ -42,7 +40,8 @@
private final GetServerInfo getServerInfo;
@Inject
- ServerImpl(GetPreferences getPreferences,
+ ServerImpl(
+ GetPreferences getPreferences,
SetPreferences setPreferences,
GetDiffPreferences getDiffPreferences,
SetDiffPreferences setDiffPreferences,
@@ -69,8 +68,7 @@
}
@Override
- public GeneralPreferencesInfo getDefaultPreferences()
- throws RestApiException {
+ public GeneralPreferencesInfo getDefaultPreferences() throws RestApiException {
try {
return getPreferences.apply(new ConfigResource());
} catch (IOException | ConfigInvalidException e) {
@@ -79,8 +77,8 @@
}
@Override
- public GeneralPreferencesInfo setDefaultPreferences(
- GeneralPreferencesInfo in) throws RestApiException {
+ public GeneralPreferencesInfo setDefaultPreferences(GeneralPreferencesInfo in)
+ throws RestApiException {
try {
return setPreferences.apply(new ConfigResource(), in);
} catch (IOException | ConfigInvalidException e) {
@@ -89,8 +87,7 @@
}
@Override
- public DiffPreferencesInfo getDefaultDiffPreferences()
- throws RestApiException {
+ public DiffPreferencesInfo getDefaultDiffPreferences() throws RestApiException {
try {
return getDiffPreferences.apply(new ConfigResource());
} catch (IOException | ConfigInvalidException e) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/api/groups/GroupApiImpl.java b/gerrit-server/src/main/java/com/google/gerrit/server/api/groups/GroupApiImpl.java
index b939a3b..15120d2 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/api/groups/GroupApiImpl.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/api/groups/GroupApiImpl.java
@@ -44,7 +44,6 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
-
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
@@ -220,8 +219,7 @@
@Override
public void addMembers(String... members) throws RestApiException {
try {
- addMembers.apply(
- rsrc, AddMembers.Input.fromMembers(Arrays.asList(members)));
+ addMembers.apply(rsrc, AddMembers.Input.fromMembers(Arrays.asList(members)));
} catch (OrmException | IOException e) {
throw new RestApiException("Cannot add group members", e);
}
@@ -230,8 +228,7 @@
@Override
public void removeMembers(String... members) throws RestApiException {
try {
- deleteMembers.apply(
- rsrc, AddMembers.Input.fromMembers(Arrays.asList(members)));
+ deleteMembers.apply(rsrc, AddMembers.Input.fromMembers(Arrays.asList(members)));
} catch (OrmException | IOException e) {
throw new RestApiException("Cannot remove group members", e);
}
@@ -249,8 +246,7 @@
@Override
public void addGroups(String... groups) throws RestApiException {
try {
- addGroups.apply(
- rsrc, AddIncludedGroups.Input.fromGroups(Arrays.asList(groups)));
+ addGroups.apply(rsrc, AddIncludedGroups.Input.fromGroups(Arrays.asList(groups)));
} catch (OrmException e) {
throw new RestApiException("Cannot add group members", e);
}
@@ -259,8 +255,7 @@
@Override
public void removeGroups(String... groups) throws RestApiException {
try {
- deleteGroups.apply(
- rsrc, AddIncludedGroups.Input.fromGroups(Arrays.asList(groups)));
+ deleteGroups.apply(rsrc, AddIncludedGroups.Input.fromGroups(Arrays.asList(groups)));
} catch (OrmException e) {
throw new RestApiException("Cannot remove group members", e);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/api/groups/GroupsImpl.java b/gerrit-server/src/main/java/com/google/gerrit/server/api/groups/GroupsImpl.java
index dcd8761..1d725a8 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/api/groups/GroupsImpl.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/api/groups/GroupsImpl.java
@@ -37,7 +37,6 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.io.IOException;
import java.util.List;
import java.util.SortedMap;
@@ -75,8 +74,7 @@
@Override
public GroupApi id(String id) throws RestApiException {
- return api.create(
- groups.parse(TopLevelResource.INSTANCE, IdString.fromDecoded(id)));
+ return api.create(groups.parse(TopLevelResource.INSTANCE, IdString.fromDecoded(id)));
}
@Override
@@ -93,8 +91,7 @@
}
checkRequiresCapability(user, null, CreateGroup.class);
try {
- GroupInfo info = createGroup.create(in.name)
- .apply(TopLevelResource.INSTANCE, in);
+ GroupInfo info = createGroup.create(in.name).apply(TopLevelResource.INSTANCE, in);
return id(info.id);
} catch (OrmException | IOException e) {
throw new RestApiException("Cannot create group " + in.name, e);
@@ -111,16 +108,14 @@
};
}
- private SortedMap<String, GroupInfo> list(ListRequest req)
- throws RestApiException {
+ private SortedMap<String, GroupInfo> list(ListRequest req) throws RestApiException {
TopLevelResource tlr = TopLevelResource.INSTANCE;
ListGroups list = listGroups.get();
list.setOptions(req.getOptions());
for (String project : req.getProjects()) {
try {
- list.addProject(
- projects.parse(tlr, IdString.fromDecoded(project)).getControl());
+ list.addProject(projects.parse(tlr, IdString.fromDecoded(project)).getControl());
} catch (IOException e) {
throw new RestApiException("Error looking up project " + project, e);
}
@@ -167,8 +162,7 @@
return query().withQuery(query);
}
- private List<GroupInfo> query(QueryRequest r)
- throws RestApiException {
+ private List<GroupInfo> query(QueryRequest r) throws RestApiException {
try {
QueryGroups myQueryGroups = queryGroups.get();
myQueryGroups.setQuery(r.getQuery());
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/api/projects/BranchApiImpl.java b/gerrit-server/src/main/java/com/google/gerrit/server/api/projects/BranchApiImpl.java
index 7fbb1f6..2fc7833 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/api/projects/BranchApiImpl.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/api/projects/BranchApiImpl.java
@@ -31,7 +31,6 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
-
import java.io.IOException;
public class BranchApiImpl implements BranchApi {
@@ -48,7 +47,8 @@
private final ProjectResource project;
@Inject
- BranchApiImpl(BranchesCollection branches,
+ BranchApiImpl(
+ BranchesCollection branches,
CreateBranch.Factory createBranchFactory,
DeleteBranch deleteBranch,
FilesCollection filesCollection,
@@ -95,8 +95,7 @@
@Override
public BinaryResult file(String path) throws RestApiException {
try {
- FileResource resource = filesCollection.parse(resource(),
- IdString.fromDecoded(path));
+ FileResource resource = filesCollection.parse(resource(), IdString.fromDecoded(path));
return getContent.apply(resource);
} catch (IOException e) {
throw new RestApiException("Cannot retrieve file", e);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/api/projects/ChildProjectApiImpl.java b/gerrit-server/src/main/java/com/google/gerrit/server/api/projects/ChildProjectApiImpl.java
index b972f5e..925b647 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/api/projects/ChildProjectApiImpl.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/api/projects/ChildProjectApiImpl.java
@@ -31,9 +31,7 @@
private final ChildProjectResource rsrc;
@AssistedInject
- ChildProjectApiImpl(
- GetChildProject getChildProject,
- @Assisted ChildProjectResource rsrc) {
+ ChildProjectApiImpl(GetChildProject getChildProject, @Assisted ChildProjectResource rsrc) {
this.getChildProject = getChildProject;
this.rsrc = rsrc;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/api/projects/ProjectApiImpl.java b/gerrit-server/src/main/java/com/google/gerrit/server/api/projects/ProjectApiImpl.java
index 8f7f1b2..e29d633 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/api/projects/ProjectApiImpl.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/api/projects/ProjectApiImpl.java
@@ -57,15 +57,14 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
-
-import org.eclipse.jgit.errors.ConfigInvalidException;
-
import java.io.IOException;
import java.util.List;
+import org.eclipse.jgit.errors.ConfigInvalidException;
public class ProjectApiImpl implements ProjectApi {
interface Factory {
ProjectApiImpl create(ProjectResource project);
+
ProjectApiImpl create(String name);
}
@@ -92,7 +91,8 @@
private final DeleteTags deleteTags;
@AssistedInject
- ProjectApiImpl(CurrentUser user,
+ ProjectApiImpl(
+ CurrentUser user,
CreateProject.Factory createProjectFactory,
ProjectApiImpl.Factory projectApi,
ProjectsCollection projects,
@@ -112,14 +112,33 @@
DeleteBranches deleteBranches,
DeleteTags deleteTags,
@Assisted ProjectResource project) {
- this(user, createProjectFactory, projectApi, projects, getDescription,
- putDescription, childApi, children, projectJson, branchApiFactory,
- tagApiFactory, getAccess, setAccess, getConfig, putConfig, listBranches,
- listTags, deleteBranches, deleteTags, project, null);
+ this(
+ user,
+ createProjectFactory,
+ projectApi,
+ projects,
+ getDescription,
+ putDescription,
+ childApi,
+ children,
+ projectJson,
+ branchApiFactory,
+ tagApiFactory,
+ getAccess,
+ setAccess,
+ getConfig,
+ putConfig,
+ listBranches,
+ listTags,
+ deleteBranches,
+ deleteTags,
+ project,
+ null);
}
@AssistedInject
- ProjectApiImpl(CurrentUser user,
+ ProjectApiImpl(
+ CurrentUser user,
CreateProject.Factory createProjectFactory,
ProjectApiImpl.Factory projectApi,
ProjectsCollection projects,
@@ -139,13 +158,32 @@
DeleteBranches deleteBranches,
DeleteTags deleteTags,
@Assisted String name) {
- this(user, createProjectFactory, projectApi, projects, getDescription,
- putDescription, childApi, children, projectJson, branchApiFactory,
- tagApiFactory, getAccess, setAccess, getConfig, putConfig, listBranches,
- listTags, deleteBranches, deleteTags, null, name);
+ this(
+ user,
+ createProjectFactory,
+ projectApi,
+ projects,
+ getDescription,
+ putDescription,
+ childApi,
+ children,
+ projectJson,
+ branchApiFactory,
+ tagApiFactory,
+ getAccess,
+ setAccess,
+ getConfig,
+ putConfig,
+ listBranches,
+ listTags,
+ deleteBranches,
+ deleteTags,
+ null,
+ name);
}
- private ProjectApiImpl(CurrentUser user,
+ private ProjectApiImpl(
+ CurrentUser user,
CreateProject.Factory createProjectFactory,
ProjectApiImpl.Factory projectApi,
ProjectsCollection projects,
@@ -204,8 +242,7 @@
throw new BadRequestException("name must match input.name");
}
checkRequiresCapability(user, null, CreateProject.class);
- createProjectFactory.create(name)
- .apply(TopLevelResource.INSTANCE, in);
+ createProjectFactory.create(name).apply(TopLevelResource.INSTANCE, in);
return projectApi.create(projects.parse(name));
} catch (IOException | ConfigInvalidException e) {
throw new RestApiException("Cannot create project: " + e.getMessage(), e);
@@ -235,8 +272,7 @@
}
@Override
- public ProjectAccessInfo access(ProjectAccessInput p)
- throws RestApiException {
+ public ProjectAccessInfo access(ProjectAccessInput p) throws RestApiException {
try {
return setAccess.apply(checkExists(), p);
} catch (IOException e) {
@@ -245,8 +281,7 @@
}
@Override
- public void description(DescriptionInput in)
- throws RestApiException {
+ public void description(DescriptionInput in) throws RestApiException {
try {
putDescription.apply(checkExists(), in);
} catch (IOException e) {
@@ -297,8 +332,7 @@
};
}
- private List<TagInfo> listTags(ListRefsRequest<TagInfo> request)
- throws RestApiException {
+ private List<TagInfo> listTags(ListRefsRequest<TagInfo> request) throws RestApiException {
listTags.setLimit(request.getLimit());
listTags.setStart(request.getStart());
listTags.setMatchSubstring(request.getSubstring());
@@ -316,8 +350,7 @@
}
@Override
- public List<ProjectInfo> children(boolean recursive)
- throws RestApiException {
+ public List<ProjectInfo> children(boolean recursive) throws RestApiException {
ListChildProjects list = children.list();
list.setRecursive(recursive);
return list.apply(checkExists());
@@ -326,8 +359,7 @@
@Override
public ChildProjectApi child(String name) throws RestApiException {
try {
- return childApi.create(
- children.parse(checkExists(), IdString.fromDecoded(name)));
+ return childApi.create(children.parse(checkExists(), IdString.fromDecoded(name)));
} catch (IOException e) {
throw new RestApiException("Cannot parse child project", e);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/api/projects/ProjectsImpl.java b/gerrit-server/src/main/java/com/google/gerrit/server/api/projects/ProjectsImpl.java
index 5d21c45..9483508 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/api/projects/ProjectsImpl.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/api/projects/ProjectsImpl.java
@@ -27,7 +27,6 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.io.IOException;
import java.util.SortedMap;
@@ -38,7 +37,8 @@
private final Provider<ListProjects> listProvider;
@Inject
- ProjectsImpl(ProjectsCollection projects,
+ ProjectsImpl(
+ ProjectsCollection projects,
ProjectApiImpl.Factory api,
Provider<ListProjects> listProvider) {
this.projects = projects;
@@ -82,8 +82,7 @@
};
}
- private SortedMap<String, ProjectInfo> list(ListRequest request)
- throws RestApiException {
+ private SortedMap<String, ProjectInfo> list(ListRequest request) throws RestApiException {
ListProjects lp = listProvider.get();
lp.setShowDescription(request.getDescription());
lp.setLimit(request.getLimit());
@@ -112,8 +111,7 @@
type = FilterType.PERMISSIONS;
break;
default:
- throw new BadRequestException(
- "Unknown filter type: " + request.getFilterType());
+ throw new BadRequestException("Unknown filter type: " + request.getFilterType());
}
lp.setFilterType(type);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/api/projects/TagApiImpl.java b/gerrit-server/src/main/java/com/google/gerrit/server/api/projects/TagApiImpl.java
index aa2c402..4e81407 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/api/projects/TagApiImpl.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/api/projects/TagApiImpl.java
@@ -28,7 +28,6 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
-
import java.io.IOException;
public class TagApiImpl implements TagApi {
@@ -44,7 +43,8 @@
private final ProjectResource project;
@Inject
- TagApiImpl(ListTags listTags,
+ TagApiImpl(
+ ListTags listTags,
CreateTag.Factory createTagFactory,
DeleteTag deleteTag,
TagsCollection tags,
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/args4j/AccountGroupIdHandler.java b/gerrit-server/src/main/java/com/google/gerrit/server/args4j/AccountGroupIdHandler.java
index bf74a4a..4d135b8 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/args4j/AccountGroupIdHandler.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/args4j/AccountGroupIdHandler.java
@@ -18,7 +18,6 @@
import com.google.gerrit.server.account.GroupCache;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
-
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.OptionDef;
@@ -30,16 +29,17 @@
private final GroupCache groupCache;
@Inject
- public AccountGroupIdHandler(final GroupCache groupCache,
- @Assisted final CmdLineParser parser, @Assisted final OptionDef option,
+ public AccountGroupIdHandler(
+ final GroupCache groupCache,
+ @Assisted final CmdLineParser parser,
+ @Assisted final OptionDef option,
@Assisted final Setter<AccountGroup.Id> setter) {
super(parser, option, setter);
this.groupCache = groupCache;
}
@Override
- public final int parseArguments(final Parameters params)
- throws CmdLineException {
+ public final int parseArguments(final Parameters params) throws CmdLineException {
final String n = params.getParameter(0);
final AccountGroup group = groupCache.get(new AccountGroup.NameKey(n));
if (group == null) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/args4j/AccountGroupUUIDHandler.java b/gerrit-server/src/main/java/com/google/gerrit/server/args4j/AccountGroupUUIDHandler.java
index 674fe08..79ab8c8 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/args4j/AccountGroupUUIDHandler.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/args4j/AccountGroupUUIDHandler.java
@@ -20,7 +20,6 @@
import com.google.gerrit.server.account.GroupBackends;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
-
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.OptionDef;
@@ -32,16 +31,17 @@
private final GroupBackend groupBackend;
@Inject
- public AccountGroupUUIDHandler(final GroupBackend groupBackend,
- @Assisted final CmdLineParser parser, @Assisted final OptionDef option,
+ public AccountGroupUUIDHandler(
+ final GroupBackend groupBackend,
+ @Assisted final CmdLineParser parser,
+ @Assisted final OptionDef option,
@Assisted final Setter<AccountGroup.UUID> setter) {
super(parser, option, setter);
this.groupBackend = groupBackend;
}
@Override
- public final int parseArguments(final Parameters params)
- throws CmdLineException {
+ public final int parseArguments(final Parameters params) throws CmdLineException {
final String n = params.getParameter(0);
GroupReference group = GroupBackends.findExactSuggestion(groupBackend, n);
if (group == null) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/args4j/AccountIdHandler.java b/gerrit-server/src/main/java/com/google/gerrit/server/args4j/AccountIdHandler.java
index 4cb96b3..7562801 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/args4j/AccountIdHandler.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/args4j/AccountIdHandler.java
@@ -26,7 +26,7 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.assistedinject.Assisted;
-
+import java.io.IOException;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.OptionDef;
@@ -34,8 +34,6 @@
import org.kohsuke.args4j.spi.Parameters;
import org.kohsuke.args4j.spi.Setter;
-import java.io.IOException;
-
public class AccountIdHandler extends OptionHandler<Account.Id> {
private final Provider<ReviewDb> db;
private final AccountResolver accountResolver;
@@ -59,8 +57,7 @@
}
@Override
- public int parseArguments(Parameters params)
- throws CmdLineException {
+ public int parseArguments(Parameters params) throws CmdLineException {
String token = params.getParameter(0);
Account.Id accountId;
try {
@@ -92,8 +89,7 @@
return 1;
}
- private Account.Id createAccountByLdap(String user)
- throws CmdLineException, IOException {
+ private Account.Id createAccountByLdap(String user) throws CmdLineException, IOException {
if (!user.matches(Account.USER_NAME_PATTERN)) {
throw new CmdLineException(owner, "user \"" + user + "\" not found");
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/args4j/ChangeIdHandler.java b/gerrit-server/src/main/java/com/google/gerrit/server/args4j/ChangeIdHandler.java
index 00eaf94..fe2a94b 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/args4j/ChangeIdHandler.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/args4j/ChangeIdHandler.java
@@ -23,7 +23,6 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.assistedinject.Assisted;
-
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.OptionDef;
@@ -38,20 +37,20 @@
public ChangeIdHandler(
// TODO(dborowitz): Not sure whether this is injectable here.
Provider<InternalChangeQuery> queryProvider,
- @Assisted final CmdLineParser parser, @Assisted final OptionDef option,
+ @Assisted final CmdLineParser parser,
+ @Assisted final OptionDef option,
@Assisted final Setter<Change.Id> setter) {
super(parser, option, setter);
this.queryProvider = queryProvider;
}
@Override
- public final int parseArguments(final Parameters params)
- throws CmdLineException {
+ public final int parseArguments(final Parameters params) throws CmdLineException {
final String token = params.getParameter(0);
final String[] tokens = token.split(",");
if (tokens.length != 3) {
- throw new CmdLineException(owner, "change should be specified as "
- + "<project>,<branch>,<change-id>");
+ throw new CmdLineException(
+ owner, "change should be specified as " + "<project>,<branch>,<change-id>");
}
try {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/args4j/ObjectIdHandler.java b/gerrit-server/src/main/java/com/google/gerrit/server/args4j/ObjectIdHandler.java
index b7f2fb9..aa8a958 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/args4j/ObjectIdHandler.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/args4j/ObjectIdHandler.java
@@ -16,7 +16,6 @@
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
-
import org.eclipse.jgit.lib.ObjectId;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
@@ -28,8 +27,10 @@
public class ObjectIdHandler extends OptionHandler<ObjectId> {
@Inject
- public ObjectIdHandler(@Assisted final CmdLineParser parser,
- @Assisted final OptionDef option, @Assisted final Setter<ObjectId> setter) {
+ public ObjectIdHandler(
+ @Assisted final CmdLineParser parser,
+ @Assisted final OptionDef option,
+ @Assisted final Setter<ObjectId> setter) {
super(parser, option, setter);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/args4j/PatchSetIdHandler.java b/gerrit-server/src/main/java/com/google/gerrit/server/args4j/PatchSetIdHandler.java
index a48568f..e8283be 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/args4j/PatchSetIdHandler.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/args4j/PatchSetIdHandler.java
@@ -17,7 +17,6 @@
import com.google.gerrit.reviewdb.client.PatchSet;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
-
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.OptionDef;
@@ -28,21 +27,21 @@
public class PatchSetIdHandler extends OptionHandler<PatchSet.Id> {
@Inject
- public PatchSetIdHandler(@Assisted final CmdLineParser parser,
- @Assisted final OptionDef option, @Assisted final Setter<PatchSet.Id> setter) {
+ public PatchSetIdHandler(
+ @Assisted final CmdLineParser parser,
+ @Assisted final OptionDef option,
+ @Assisted final Setter<PatchSet.Id> setter) {
super(parser, option, setter);
}
@Override
- public final int parseArguments(final Parameters params)
- throws CmdLineException {
+ public final int parseArguments(final Parameters params) throws CmdLineException {
final String token = params.getParameter(0);
final PatchSet.Id id;
try {
id = PatchSet.Id.parse(token);
} catch (IllegalArgumentException e) {
- throw new CmdLineException(owner, "\"" + token
- + "\" is not a valid patch set");
+ throw new CmdLineException(owner, "\"" + token + "\" is not a valid patch set");
}
setter.addValue(id);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/args4j/ProjectControlHandler.java b/gerrit-server/src/main/java/com/google/gerrit/server/args4j/ProjectControlHandler.java
index 8771c23d..02e907f 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/args4j/ProjectControlHandler.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/args4j/ProjectControlHandler.java
@@ -22,7 +22,7 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.assistedinject.Assisted;
-
+import java.io.IOException;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.OptionDef;
@@ -32,11 +32,8 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-
public class ProjectControlHandler extends OptionHandler<ProjectControl> {
- private static final Logger log = LoggerFactory
- .getLogger(ProjectControlHandler.class);
+ private static final Logger log = LoggerFactory.getLogger(ProjectControlHandler.class);
private final ProjectControl.GenericFactory projectControlFactory;
private final Provider<CurrentUser> user;
@@ -44,7 +41,8 @@
public ProjectControlHandler(
final ProjectControl.GenericFactory projectControlFactory,
Provider<CurrentUser> user,
- @Assisted final CmdLineParser parser, @Assisted final OptionDef option,
+ @Assisted final CmdLineParser parser,
+ @Assisted final OptionDef option,
@Assisted final Setter<ProjectControl> setter) {
super(parser, option, setter);
this.projectControlFactory = projectControlFactory;
@@ -52,8 +50,7 @@
}
@Override
- public final int parseArguments(final Parameters params)
- throws CmdLineException {
+ public final int parseArguments(final Parameters params) throws CmdLineException {
String projectName = params.getParameter(0);
while (projectName.endsWith("/")) {
@@ -74,17 +71,14 @@
final ProjectControl control;
try {
- control = projectControlFactory.validateFor(
- nameKey,
- ProjectControl.OWNER | ProjectControl.VISIBLE,
- user.get());
+ control =
+ projectControlFactory.validateFor(
+ nameKey, ProjectControl.OWNER | ProjectControl.VISIBLE, user.get());
} catch (NoSuchProjectException e) {
throw new CmdLineException(owner, e.getMessage());
} catch (IOException e) {
log.warn("Cannot load project " + nameWithoutSuffix, e);
- throw new CmdLineException(
- owner,
- new NoSuchProjectException(nameKey).getMessage());
+ throw new CmdLineException(owner, new NoSuchProjectException(nameKey).getMessage());
}
setter.addValue(control);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/args4j/SocketAddressHandler.java b/gerrit-server/src/main/java/com/google/gerrit/server/args4j/SocketAddressHandler.java
index 0c20b2d..e0193c5 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/args4j/SocketAddressHandler.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/args4j/SocketAddressHandler.java
@@ -17,7 +17,7 @@
import com.google.gerrit.server.util.SocketUtil;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
-
+import java.net.SocketAddress;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.OptionDef;
@@ -25,19 +25,18 @@
import org.kohsuke.args4j.spi.Parameters;
import org.kohsuke.args4j.spi.Setter;
-import java.net.SocketAddress;
-
public class SocketAddressHandler extends OptionHandler<SocketAddress> {
@Inject
- public SocketAddressHandler(@Assisted final CmdLineParser parser,
- @Assisted final OptionDef option, @Assisted final Setter<SocketAddress> setter) {
+ public SocketAddressHandler(
+ @Assisted final CmdLineParser parser,
+ @Assisted final OptionDef option,
+ @Assisted final Setter<SocketAddress> setter) {
super(parser, option, setter);
}
@Override
- public final int parseArguments(final Parameters params)
- throws CmdLineException {
+ public final int parseArguments(final Parameters params) throws CmdLineException {
final String token = params.getParameter(0);
try {
setter.addValue(SocketUtil.parse(token, 0));
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/args4j/SubcommandHandler.java b/gerrit-server/src/main/java/com/google/gerrit/server/args4j/SubcommandHandler.java
index 619ec1f..b7af2e7 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/args4j/SubcommandHandler.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/args4j/SubcommandHandler.java
@@ -16,7 +16,6 @@
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
-
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.OptionDef;
@@ -27,14 +26,15 @@
public class SubcommandHandler extends OptionHandler<String> {
@Inject
- public SubcommandHandler(@Assisted final CmdLineParser parser,
- @Assisted final OptionDef option, @Assisted final Setter<String> setter) {
+ public SubcommandHandler(
+ @Assisted final CmdLineParser parser,
+ @Assisted final OptionDef option,
+ @Assisted final Setter<String> setter) {
super(parser, option, setter);
}
@Override
- public final int parseArguments(final Parameters params)
- throws CmdLineException {
+ public final int parseArguments(final Parameters params) throws CmdLineException {
setter.addValue(params.getParameter(0));
owner.stopOptionParsing();
return 1;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/args4j/TimestampHandler.java b/gerrit-server/src/main/java/com/google/gerrit/server/args4j/TimestampHandler.java
index 21ef31a..eddfbcd 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/args4j/TimestampHandler.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/args4j/TimestampHandler.java
@@ -16,7 +16,11 @@
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
-
+import java.sql.Timestamp;
+import java.text.DateFormat;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.TimeZone;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.OptionDef;
@@ -24,18 +28,14 @@
import org.kohsuke.args4j.spi.Parameters;
import org.kohsuke.args4j.spi.Setter;
-import java.sql.Timestamp;
-import java.text.DateFormat;
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
-import java.util.TimeZone;
-
public class TimestampHandler extends OptionHandler<Timestamp> {
public static final String TIMESTAMP_FORMAT = "yyyyMMdd_HHmm";
@Inject
- public TimestampHandler(@Assisted CmdLineParser parser,
- @Assisted OptionDef option, @Assisted Setter<Timestamp> setter) {
+ public TimestampHandler(
+ @Assisted CmdLineParser parser,
+ @Assisted OptionDef option,
+ @Assisted Setter<Timestamp> setter) {
super(parser, option, setter);
}
@@ -48,9 +48,10 @@
setter.addValue(new Timestamp(fmt.parse(timestamp).getTime()));
return 1;
} catch (ParseException e) {
- throw new CmdLineException(owner,
- String.format("Invalid timestamp: %s; expected format: %s",
- timestamp, TIMESTAMP_FORMAT), e);
+ throw new CmdLineException(
+ owner,
+ String.format("Invalid timestamp: %s; expected format: %s", timestamp, TIMESTAMP_FORMAT),
+ e);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/auth/AuthBackend.java b/gerrit-server/src/main/java/com/google/gerrit/server/auth/AuthBackend.java
index 1050926..9ec3366 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/auth/AuthBackend.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/auth/AuthBackend.java
@@ -16,9 +16,7 @@
import com.google.gerrit.extensions.annotations.ExtensionPoint;
-/**
- * Implementations of AuthBackend authenticate users for incoming request.
- */
+/** Implementations of AuthBackend authenticate users for incoming request. */
@ExtensionPoint
public interface AuthBackend {
@@ -26,24 +24,20 @@
String getDomain();
/**
- * Authenticate inspects the AuthRequest and returns authenticated user. If
- * the request is unable to be authenticated, an exception will be thrown. The
- * {@link MissingCredentialsException} must be thrown when there are no
- * credentials for the request. It is expected that at most one AuthBackend
- * will either return an AuthUser or throw a non-MissingCredentialsException.
+ * Authenticate inspects the AuthRequest and returns authenticated user. If the request is unable
+ * to be authenticated, an exception will be thrown. The {@link MissingCredentialsException} must
+ * be thrown when there are no credentials for the request. It is expected that at most one
+ * AuthBackend will either return an AuthUser or throw a non-MissingCredentialsException.
*
* @param req the object describing the request.
* @return the successfully authenticated user.
* @throws MissingCredentialsException when there are no credentials.
- * @throws InvalidCredentialsException when the credentials are present and
- * invalid.
- * @throws UnknownUserException when the credentials are valid but there is
- * no matching user.
- * @throws UserNotAllowedException when the credentials are valid but the user
- * is not allowed.
+ * @throws InvalidCredentialsException when the credentials are present and invalid.
+ * @throws UnknownUserException when the credentials are valid but there is no matching user.
+ * @throws UserNotAllowedException when the credentials are valid but the user is not allowed.
* @throws AuthException when any other error occurs.
*/
- AuthUser authenticate(AuthRequest req) throws MissingCredentialsException,
- InvalidCredentialsException, UnknownUserException,
- UserNotAllowedException, AuthException;
+ AuthUser authenticate(AuthRequest req)
+ throws MissingCredentialsException, InvalidCredentialsException, UnknownUserException,
+ UserNotAllowedException, AuthException;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/auth/AuthException.java b/gerrit-server/src/main/java/com/google/gerrit/server/auth/AuthException.java
index 8cf4a0a..0c41f5b 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/auth/AuthException.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/auth/AuthException.java
@@ -14,14 +14,11 @@
package com.google.gerrit.server.auth;
-/**
- * Base type for authentication exceptions.
- */
+/** Base type for authentication exceptions. */
public class AuthException extends Exception {
private static final long serialVersionUID = -8946302676525580372L;
- public AuthException() {
- }
+ public AuthException() {}
public AuthException(String msg) {
super(msg);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/auth/AuthRequest.java b/gerrit-server/src/main/java/com/google/gerrit/server/auth/AuthRequest.java
index e194eb7..c933190 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/auth/AuthRequest.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/auth/AuthRequest.java
@@ -15,12 +15,9 @@
package com.google.gerrit.server.auth;
import com.google.gerrit.common.Nullable;
-
import java.util.Objects;
-/**
- * Defines an abstract request for user authentication to Gerrit.
- */
+/** Defines an abstract request for user authentication to Gerrit. */
public abstract class AuthRequest {
private final String username;
private final String password;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/auth/AuthUser.java b/gerrit-server/src/main/java/com/google/gerrit/server/auth/AuthUser.java
index f2c8222..71f29a4 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/auth/AuthUser.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/auth/AuthUser.java
@@ -19,14 +19,10 @@
import com.google.auto.value.AutoValue;
import com.google.gerrit.common.Nullable;
-/**
- * An authenticated user as specified by the AuthBackend.
- */
+/** An authenticated user as specified by the AuthBackend. */
public class AuthUser {
- /**
- * Globally unique identifier for the user.
- */
+ /** Globally unique identifier for the user. */
@AutoValue
public abstract static class UUID {
/**
@@ -87,7 +83,6 @@
@Override
public String toString() {
- return String.format("AuthUser[uuid=%s, username=%s]", getUUID(),
- getUsername());
+ return String.format("AuthUser[uuid=%s, username=%s]", getUUID(), getUsername());
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/auth/InternalAuthBackend.java b/gerrit-server/src/main/java/com/google/gerrit/server/auth/InternalAuthBackend.java
index 6ecea5e..3f2938f 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/auth/InternalAuthBackend.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/auth/InternalAuthBackend.java
@@ -20,7 +20,6 @@
import com.google.gerrit.server.config.AuthConfig;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
import java.util.Locale;
@Singleton
@@ -41,10 +40,9 @@
@Override
public AuthUser authenticate(AuthRequest req)
- throws MissingCredentialsException, InvalidCredentialsException,
- UnknownUserException, UserNotAllowedException, AuthException {
- if (Strings.isNullOrEmpty(req.getUsername())
- || Strings.isNullOrEmpty(req.getPassword())) {
+ throws MissingCredentialsException, InvalidCredentialsException, UnknownUserException,
+ UserNotAllowedException, AuthException {
+ if (Strings.isNullOrEmpty(req.getUsername()) || Strings.isNullOrEmpty(req.getPassword())) {
throw new MissingCredentialsException();
}
@@ -59,8 +57,10 @@
if (who == null) {
throw new UnknownUserException();
} else if (!who.getAccount().isActive()) {
- throw new UserNotAllowedException("Authentication failed for " + username
- + ": account inactive or not provisioned in Gerrit");
+ throw new UserNotAllowedException(
+ "Authentication failed for "
+ + username
+ + ": account inactive or not provisioned in Gerrit");
}
req.checkPassword(who.getPassword(username));
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/auth/InvalidCredentialsException.java b/gerrit-server/src/main/java/com/google/gerrit/server/auth/InvalidCredentialsException.java
index bca8586..c96a429 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/auth/InvalidCredentialsException.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/auth/InvalidCredentialsException.java
@@ -15,14 +15,13 @@
package com.google.gerrit.server.auth;
/**
- * An authentication exception that is thrown when the credentials are present
- * and are unable to be verified.
+ * An authentication exception that is thrown when the credentials are present and are unable to be
+ * verified.
*/
public class InvalidCredentialsException extends AuthException {
private static final long serialVersionUID = 3709201042080444276L;
- public InvalidCredentialsException() {
- }
+ public InvalidCredentialsException() {}
public InvalidCredentialsException(String msg) {
super(msg);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/auth/MissingCredentialsException.java b/gerrit-server/src/main/java/com/google/gerrit/server/auth/MissingCredentialsException.java
index 062728a..f853370 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/auth/MissingCredentialsException.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/auth/MissingCredentialsException.java
@@ -15,17 +15,15 @@
package com.google.gerrit.server.auth;
/**
- * An authentication exception that is thrown when the credentials are not
- * present. This indicates that the AuthBackend has none of the needed
- * information in the request to perform authentication. If parts of the
- * authentication information is available to the backend, then a different
+ * An authentication exception that is thrown when the credentials are not present. This indicates
+ * that the AuthBackend has none of the needed information in the request to perform authentication.
+ * If parts of the authentication information is available to the backend, then a different
* AuthException should be used.
*/
public class MissingCredentialsException extends AuthException {
private static final long serialVersionUID = -6499866977513508051L;
- public MissingCredentialsException() {
- }
+ public MissingCredentialsException() {}
public MissingCredentialsException(String msg) {
super(msg);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/auth/UniversalAuthBackend.java b/gerrit-server/src/main/java/com/google/gerrit/server/auth/UniversalAuthBackend.java
index 76a9fd6..b0360e4 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/auth/UniversalAuthBackend.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/auth/UniversalAuthBackend.java
@@ -19,14 +19,10 @@
import com.google.gerrit.extensions.registration.DynamicSet;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
import java.util.ArrayList;
import java.util.List;
-/**
- * Universal implementation of the AuthBackend that works with the injected
- * set of AuthBackends.
- */
+/** Universal implementation of the AuthBackend that works with the injected set of AuthBackends. */
@Singleton
public final class UniversalAuthBackend implements AuthBackend {
private final DynamicSet<AuthBackend> authBackends;
@@ -59,14 +55,15 @@
throw new MissingCredentialsException();
}
- String msg = String.format("Multiple AuthBackends attempted to handle request:"
- + " authUsers=%s authExs=%s", authUsers, authExs);
+ String msg =
+ String.format(
+ "Multiple AuthBackends attempted to handle request:" + " authUsers=%s authExs=%s",
+ authUsers, authExs);
throw new AuthException(msg);
}
@Override
public String getDomain() {
- throw new UnsupportedOperationException(
- "UniversalAuthBackend doesn't support domain.");
+ throw new UnsupportedOperationException("UniversalAuthBackend doesn't support domain.");
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/auth/UnknownUserException.java b/gerrit-server/src/main/java/com/google/gerrit/server/auth/UnknownUserException.java
index 124912a..289d7d8 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/auth/UnknownUserException.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/auth/UnknownUserException.java
@@ -15,14 +15,12 @@
package com.google.gerrit.server.auth;
/**
- * An authentication exception that is thrown when credentials are presented for
- * an unknown user.
+ * An authentication exception that is thrown when credentials are presented for an unknown user.
*/
public class UnknownUserException extends AuthException {
private static final long serialVersionUID = 1626186166924670754L;
- public UnknownUserException() {
- }
+ public UnknownUserException() {}
public UnknownUserException(String msg) {
super(msg);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/auth/UserNotAllowedException.java b/gerrit-server/src/main/java/com/google/gerrit/server/auth/UserNotAllowedException.java
index 2420330..1b23cb1 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/auth/UserNotAllowedException.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/auth/UserNotAllowedException.java
@@ -15,15 +15,13 @@
package com.google.gerrit.server.auth;
/**
- * An authentication exception that is thrown when the user credentials are
- * valid, but not allowed to authenticate for other reasons i.e. account
- * disabled.
+ * An authentication exception that is thrown when the user credentials are valid, but not allowed
+ * to authenticate for other reasons i.e. account disabled.
*/
public class UserNotAllowedException extends AuthException {
private static final long serialVersionUID = -1531411999932922558L;
- public UserNotAllowedException() {
- }
+ public UserNotAllowedException() {}
public UserNotAllowedException(String msg) {
super(msg);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/auth/ldap/Helper.java b/gerrit-server/src/main/java/com/google/gerrit/server/auth/ldap/Helper.java
index 1e45387..1acd647 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/auth/ldap/Helper.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/auth/ldap/Helper.java
@@ -28,9 +28,6 @@
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.google.inject.name.Named;
-
-import org.eclipse.jgit.lib.Config;
-
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
@@ -41,7 +38,6 @@
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.TimeUnit;
-
import javax.naming.CompositeName;
import javax.naming.Context;
import javax.naming.Name;
@@ -55,8 +51,10 @@
import javax.security.auth.Subject;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
+import org.eclipse.jgit.lib.Config;
-@Singleton class Helper {
+@Singleton
+class Helper {
static final String LDAP_UUID = "ldap:";
private final Cache<String, ImmutableSet<String>> parentGroups;
@@ -74,9 +72,9 @@
private final boolean groupsVisibleToAll;
@Inject
- Helper(@GerritServerConfig final Config config,
- @Named(LdapModule.PARENT_GROUPS_CACHE)
- Cache<String, ImmutableSet<String>> parentGroups) {
+ Helper(
+ @GerritServerConfig final Config config,
+ @Named(LdapModule.PARENT_GROUPS_CACHE) Cache<String, ImmutableSet<String>> parentGroups) {
this.config = config;
this.server = LdapRealm.optional(config, "server");
this.username = LdapRealm.optional(config, "username");
@@ -84,27 +82,23 @@
this.referral = LdapRealm.optional(config, "referral", "ignore");
this.sslVerify = config.getBoolean("ldap", "sslverify", true);
this.groupsVisibleToAll = config.getBoolean("ldap", "groupsVisibleToAll", false);
- this.authentication =
- LdapRealm.optional(config, "authentication", "simple");
+ this.authentication = LdapRealm.optional(config, "authentication", "simple");
String readTimeout = LdapRealm.optional(config, "readTimeout");
if (readTimeout != null) {
readTimeoutMillis =
- Long.toString(ConfigUtil.getTimeUnit(readTimeout, 0,
- TimeUnit.MILLISECONDS));
+ Long.toString(ConfigUtil.getTimeUnit(readTimeout, 0, TimeUnit.MILLISECONDS));
} else {
readTimeoutMillis = null;
}
String connectTimeout = LdapRealm.optional(config, "connectTimeout");
if (connectTimeout != null) {
connectTimeoutMillis =
- Long.toString(ConfigUtil.getTimeUnit(connectTimeout, 0,
- TimeUnit.MILLISECONDS));
+ Long.toString(ConfigUtil.getTimeUnit(connectTimeout, 0, TimeUnit.MILLISECONDS));
} else {
connectTimeoutMillis = null;
}
this.parentGroups = parentGroups;
- this.useConnectionPooling =
- LdapRealm.optional(config, "useConnectionPooling", false);
+ this.useConnectionPooling = LdapRealm.optional(config, "useConnectionPooling", false);
}
private Properties createContextProperties() {
@@ -141,18 +135,19 @@
return new InitialDirContext(env);
}
- private DirContext kerberosOpen(final Properties env) throws LoginException,
- NamingException {
+ private DirContext kerberosOpen(final Properties env) throws LoginException, NamingException {
LoginContext ctx = new LoginContext("KerberosLogin");
ctx.login();
Subject subject = ctx.getSubject();
try {
- return Subject.doAs(subject, new PrivilegedExceptionAction<DirContext>() {
- @Override
- public DirContext run() throws NamingException {
- return new InitialDirContext(env);
- }
- });
+ return Subject.doAs(
+ subject,
+ new PrivilegedExceptionAction<DirContext>() {
+ @Override
+ public DirContext run() throws NamingException {
+ return new InitialDirContext(env);
+ }
+ });
} catch (PrivilegedActionException e) {
Throwables.throwIfInstanceOf(e.getException(), NamingException.class);
Throwables.throwIfInstanceOf(e.getException(), RuntimeException.class);
@@ -187,8 +182,8 @@
return ldapSchema;
}
- LdapQuery.Result findAccount(Helper.LdapSchema schema,
- DirContext ctx, String username, boolean fetchMemberOf)
+ LdapQuery.Result findAccount(
+ Helper.LdapSchema schema, DirContext ctx, String username, boolean fetchMemberOf)
throws NamingException, AccountException {
final HashMap<String, String> params = new HashMap<>();
params.put(LdapRealm.USERNAME, username);
@@ -211,8 +206,8 @@
throw new NoSuchUserException(username);
}
- Set<AccountGroup.UUID> queryForGroups(final DirContext ctx,
- final String username, LdapQuery.Result account)
+ Set<AccountGroup.UUID> queryForGroups(
+ final DirContext ctx, final String username, LdapQuery.Result account)
throws NamingException {
final LdapSchema schema = getSchema(ctx);
final Set<String> groupDNs = new HashSet<>();
@@ -274,9 +269,13 @@
return ImmutableSet.copyOf(actual);
}
- private void recursivelyExpandGroups(final Set<String> groupDNs,
- final LdapSchema schema, final DirContext ctx, final String groupDN) {
- if (groupDNs.add(groupDN) && schema.accountMemberField != null
+ private void recursivelyExpandGroups(
+ final Set<String> groupDNs,
+ final LdapSchema schema,
+ final DirContext ctx,
+ final String groupDN) {
+ if (groupDNs.add(groupDN)
+ && schema.accountMemberField != null
&& schema.accountMemberExpandGroups) {
ImmutableSet<String> cachedParentsDNs = parentGroups.getIfPresent(groupDN);
if (cachedParentsDNs == null) {
@@ -286,7 +285,7 @@
final Name compositeGroupName = new CompositeName().add(groupDN);
final Attribute in =
ctx.getAttributes(compositeGroupName, schema.accountMemberFieldArray)
- .get(schema.accountMemberField);
+ .get(schema.accountMemberField);
if (in != null) {
final NamingEnumeration<?> groups = in.getAll();
try {
@@ -352,11 +351,13 @@
for (String groupBase : groupBases) {
if (groupMemberPattern != null) {
final LdapQuery groupMemberQuery =
- new LdapQuery(groupBase, groupScope, new ParameterizedString(
- groupMemberPattern), Collections.<String> emptySet());
+ new LdapQuery(
+ groupBase,
+ groupScope,
+ new ParameterizedString(groupMemberPattern),
+ Collections.<String>emptySet());
if (groupMemberQuery.getParameters().isEmpty()) {
- throw new IllegalArgumentException(
- "No variables in ldap.groupMemberPattern");
+ throw new IllegalArgumentException("No variables in ldap.groupMemberPattern");
}
for (final String name : groupMemberQuery.getParameters()) {
@@ -369,14 +370,12 @@
// Account query
//
- accountFullName =
- LdapRealm.paramString(config, "accountFullName", type.accountFullName());
+ accountFullName = LdapRealm.paramString(config, "accountFullName", type.accountFullName());
if (accountFullName != null) {
accountAtts.addAll(accountFullName.getParameterNames());
}
accountEmailAddress =
- LdapRealm.paramString(config, "accountEmailAddress", type
- .accountEmailAddress());
+ LdapRealm.paramString(config, "accountEmailAddress", type.accountEmailAddress());
if (accountEmailAddress != null) {
accountAtts.addAll(accountEmailAddress.getParameterNames());
}
@@ -393,8 +392,7 @@
accountMemberFieldArray = null;
}
accountMemberExpandGroups =
- LdapRealm.optional(config, "accountMemberExpandGroups",
- type.accountMemberExpandGroups());
+ LdapRealm.optional(config, "accountMemberExpandGroups", type.accountMemberExpandGroups());
final SearchScope accountScope = LdapRealm.scope(config, "accountScope");
final String accountPattern =
@@ -409,18 +407,20 @@
}
for (String accountBase : LdapRealm.requiredList(config, "accountBase")) {
LdapQuery accountQuery =
- new LdapQuery(accountBase, accountScope, new ParameterizedString(
- accountPattern), accountAtts);
+ new LdapQuery(
+ accountBase, accountScope, new ParameterizedString(accountPattern), accountAtts);
if (accountQuery.getParameters().isEmpty()) {
- throw new IllegalArgumentException(
- "No variables in ldap.accountPattern");
+ throw new IllegalArgumentException("No variables in ldap.accountPattern");
}
accountQueryList.add(accountQuery);
if (accountWithMemberOfAtts != null) {
LdapQuery accountWithMemberOfQuery =
- new LdapQuery(accountBase, accountScope, new ParameterizedString(
- accountPattern), accountWithMemberOfAtts);
+ new LdapQuery(
+ accountBase,
+ accountScope,
+ new ParameterizedString(accountPattern),
+ accountWithMemberOfAtts);
accountWithMemberOfQueryList.add(accountWithMemberOfQuery);
}
}
@@ -430,8 +430,11 @@
try {
return LdapType.guessType(ctx);
} catch (NamingException e) {
- LdapRealm.log.warn("Cannot discover type of LDAP server at " + server
- + ", assuming the server is RFC 2307 compliant.", e);
+ LdapRealm.log.warn(
+ "Cannot discover type of LDAP server at "
+ + server
+ + ", assuming the server is RFC 2307 compliant.",
+ e);
return LdapType.RFC_2307;
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/auth/ldap/LdapAuthBackend.java b/gerrit-server/src/main/java/com/google/gerrit/server/auth/ldap/LdapAuthBackend.java
index 3dddf4d..2854294 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/auth/ldap/LdapAuthBackend.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/auth/ldap/LdapAuthBackend.java
@@ -27,20 +27,15 @@
import com.google.gerrit.server.config.AuthConfig;
import com.google.gerrit.server.config.GerritServerConfig;
import com.google.inject.Inject;
-
+import java.util.Locale;
+import javax.naming.NamingException;
+import javax.naming.directory.DirContext;
+import javax.security.auth.login.LoginException;
import org.eclipse.jgit.lib.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.util.Locale;
-
-import javax.naming.NamingException;
-import javax.naming.directory.DirContext;
-import javax.security.auth.login.LoginException;
-
-/**
- * Implementation of AuthBackend for the LDAP authentication system.
- */
+/** Implementation of AuthBackend for the LDAP authentication system. */
public class LdapAuthBackend implements AuthBackend {
private static final Logger log = LoggerFactory.getLogger(LdapAuthBackend.class);
@@ -49,13 +44,10 @@
private final boolean lowerCaseUsername;
@Inject
- public LdapAuthBackend(Helper helper,
- AuthConfig authConfig,
- @GerritServerConfig Config config) {
+ public LdapAuthBackend(Helper helper, AuthConfig authConfig, @GerritServerConfig Config config) {
this.helper = helper;
this.authConfig = authConfig;
- this.lowerCaseUsername =
- config.getBoolean("ldap", "localUsernameToLowerCase", false);
+ this.lowerCaseUsername = config.getBoolean("ldap", "localUsernameToLowerCase", false);
}
@Override
@@ -65,15 +57,14 @@
@Override
public AuthUser authenticate(AuthRequest req)
- throws MissingCredentialsException, InvalidCredentialsException,
- UnknownUserException, UserNotAllowedException, AuthException {
+ throws MissingCredentialsException, InvalidCredentialsException, UnknownUserException,
+ UserNotAllowedException, AuthException {
if (req.getUsername() == null) {
throw new MissingCredentialsException();
}
- final String username = lowerCaseUsername
- ? req.getUsername().toLowerCase(Locale.US)
- : req.getUsername();
+ final String username =
+ lowerCaseUsername ? req.getUsername().toLowerCase(Locale.US) : req.getUsername();
try {
final DirContext ctx;
if (authConfig.getAuthType() == AuthType.LDAP_BIND) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/auth/ldap/LdapGroupBackend.java b/gerrit-server/src/main/java/com/google/gerrit/server/auth/ldap/LdapGroupBackend.java
index bd4a3b0..8511318 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/auth/ldap/LdapGroupBackend.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/auth/ldap/LdapGroupBackend.java
@@ -37,27 +37,22 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.name.Named;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
-
import javax.naming.InvalidNameException;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.ldap.LdapName;
import javax.naming.ldap.Rdn;
import javax.security.auth.login.LoginException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
-/**
- * Implementation of GroupBackend for the LDAP group system.
- */
+/** Implementation of GroupBackend for the LDAP group system. */
public class LdapGroupBackend implements GroupBackend {
static final Logger log = LoggerFactory.getLogger(LdapGroupBackend.class);
@@ -88,11 +83,10 @@
return uuid.get().startsWith(LDAP_UUID);
}
- private static GroupReference groupReference(ParameterizedString p,
- LdapQuery.Result res) throws NamingException {
+ private static GroupReference groupReference(ParameterizedString p, LdapQuery.Result res)
+ throws NamingException {
return new GroupReference(
- new AccountGroup.UUID(LDAP_UUID + res.getDN()),
- LDAP_NAME + LdapRealm.apply(p, res));
+ new AccountGroup.UUID(LDAP_UUID + res.getDN()), LDAP_NAME + LdapRealm.apply(p, res));
}
private static String cnFor(String dn) {
@@ -125,8 +119,7 @@
String groupDn = uuid.get().substring(LDAP_UUID.length());
CurrentUser user = userProvider.get();
- if (!(user.isIdentifiedUser())
- || !membershipsOf(user.asIdentifiedUser()).contains(uuid)) {
+ if (!(user.isIdentifiedUser()) || !membershipsOf(user.asIdentifiedUser()).contains(uuid)) {
try {
if (!existsCache.get(groupDn)) {
return null;
@@ -196,7 +189,6 @@
return null;
}
-
private Set<GroupReference> suggestLdap(String name) {
if (name.isEmpty()) {
return Collections.emptySet();
@@ -209,14 +201,12 @@
// Do exact lookups until there are at least 3 characters.
name = Rdn.escapeValue(name) + ((name.length() >= 3) ? "*" : "");
LdapSchema schema = helper.getSchema(ctx);
- ParameterizedString filter = ParameterizedString.asis(
- schema.groupPattern.replace(GROUPNAME, name).toString());
- Set<String> returnAttrs =
- new HashSet<>(schema.groupName.getParameterNames());
+ ParameterizedString filter =
+ ParameterizedString.asis(schema.groupPattern.replace(GROUPNAME, name).toString());
+ Set<String> returnAttrs = new HashSet<>(schema.groupName.getParameterNames());
Map<String, String> params = Collections.emptyMap();
for (String groupBase : schema.groupBases) {
- LdapQuery query = new LdapQuery(
- groupBase, schema.groupScope, filter, returnAttrs);
+ LdapQuery query = new LdapQuery(groupBase, schema.groupScope, filter, returnAttrs);
for (LdapQuery.Result res : query.query(ctx, params)) {
out.add(groupReference(schema.groupName, res));
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/auth/ldap/LdapGroupMembership.java b/gerrit-server/src/main/java/com/google/gerrit/server/auth/ldap/LdapGroupMembership.java
index 7853320..7bef2e7 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/auth/ldap/LdapGroupMembership.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/auth/ldap/LdapGroupMembership.java
@@ -19,7 +19,6 @@
import com.google.gerrit.server.account.GroupMembership;
import com.google.gerrit.server.account.ListGroupMembership;
import com.google.gerrit.server.project.ProjectCache;
-
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ExecutionException;
@@ -66,8 +65,7 @@
try {
membership = new ListGroupMembership(membershipCache.get(id));
} catch (ExecutionException e) {
- LdapGroupBackend.log.warn(String.format(
- "Cannot lookup membershipsOf %s in LDAP", id), e);
+ LdapGroupBackend.log.warn(String.format("Cannot lookup membershipsOf %s in LDAP", id), e);
membership = GroupMembership.EMPTY;
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/auth/ldap/LdapModule.java b/gerrit-server/src/main/java/com/google/gerrit/server/auth/ldap/LdapModule.java
index 217df2f..05228b4 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/auth/ldap/LdapModule.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/auth/ldap/LdapModule.java
@@ -25,7 +25,6 @@
import com.google.gerrit.server.cache.CacheModule;
import com.google.inject.Scopes;
import com.google.inject.TypeLiteral;
-
import java.util.Optional;
import java.util.Set;
@@ -35,30 +34,21 @@
static final String GROUP_EXIST_CACHE = "ldap_group_existence";
static final String PARENT_GROUPS_CACHE = "ldap_groups_byinclude";
-
@Override
protected void configure() {
- cache(GROUP_CACHE,
- String.class,
- new TypeLiteral<Set<AccountGroup.UUID>>() {})
- .expireAfterWrite(1, HOURS)
- .loader(LdapRealm.MemberLoader.class);
+ cache(GROUP_CACHE, String.class, new TypeLiteral<Set<AccountGroup.UUID>>() {})
+ .expireAfterWrite(1, HOURS)
+ .loader(LdapRealm.MemberLoader.class);
- cache(USERNAME_CACHE,
- String.class,
- new TypeLiteral<Optional<Account.Id>>() {})
- .loader(LdapRealm.UserLoader.class);
+ cache(USERNAME_CACHE, String.class, new TypeLiteral<Optional<Account.Id>>() {})
+ .loader(LdapRealm.UserLoader.class);
- cache(GROUP_EXIST_CACHE,
- String.class,
- new TypeLiteral<Boolean>() {})
- .expireAfterWrite(1, HOURS)
- .loader(LdapRealm.ExistenceLoader.class);
+ cache(GROUP_EXIST_CACHE, String.class, new TypeLiteral<Boolean>() {})
+ .expireAfterWrite(1, HOURS)
+ .loader(LdapRealm.ExistenceLoader.class);
- cache(PARENT_GROUPS_CACHE,
- String.class,
- new TypeLiteral<ImmutableSet<String>>() {})
- .expireAfterWrite(1, HOURS);
+ cache(PARENT_GROUPS_CACHE, String.class, new TypeLiteral<ImmutableSet<String>>() {})
+ .expireAfterWrite(1, HOURS);
bind(Helper.class);
bind(Realm.class).to(LdapRealm.class).in(Scopes.SINGLETON);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/auth/ldap/LdapQuery.java b/gerrit-server/src/main/java/com/google/gerrit/server/auth/ldap/LdapQuery.java
index e9ae8f5..28eb05d 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/auth/ldap/LdapQuery.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/auth/ldap/LdapQuery.java
@@ -15,14 +15,12 @@
package com.google.gerrit.server.auth.ldap;
import com.google.gerrit.common.data.ParameterizedString;
-
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
-
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.PartialResultException;
@@ -41,8 +39,11 @@
private final ParameterizedString pattern;
private final String[] returnAttributes;
- LdapQuery(final String base, final SearchScope searchScope,
- final ParameterizedString pattern, final Set<String> returnAttributes) {
+ LdapQuery(
+ final String base,
+ final SearchScope searchScope,
+ final ParameterizedString pattern,
+ final Set<String> returnAttributes) {
this.base = base;
this.searchScope = searchScope;
@@ -126,9 +127,9 @@
@Override
public String toString() {
try {
- return getDN();
+ return getDN();
} catch (NamingException e) {
- return "";
+ return "";
}
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/auth/ldap/LdapRealm.java b/gerrit-server/src/main/java/com/google/gerrit/server/auth/ldap/LdapRealm.java
index 4af066f..0e05330 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/auth/ldap/LdapRealm.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/auth/ldap/LdapRealm.java
@@ -39,11 +39,6 @@
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.google.inject.name.Named;
-
-import org.eclipse.jgit.lib.Config;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
@@ -53,12 +48,14 @@
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ExecutionException;
-
import javax.naming.CompositeName;
import javax.naming.Name;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.security.auth.login.LoginException;
+import org.eclipse.jgit.lib.Config;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
@Singleton
class LdapRealm extends AbstractRealm {
@@ -85,8 +82,10 @@
AuthConfig authConfig,
EmailExpander emailExpander,
LdapGroupBackend groupBackend,
- @Named(LdapModule.GROUP_CACHE) final LoadingCache<String, Set<AccountGroup.UUID>> membershipCache,
- @Named(LdapModule.USERNAME_CACHE) final LoadingCache<String, Optional<Account.Id>> usernameCache,
+ @Named(LdapModule.GROUP_CACHE)
+ final LoadingCache<String, Set<AccountGroup.UUID>> membershipCache,
+ @Named(LdapModule.USERNAME_CACHE)
+ final LoadingCache<String, Optional<Account.Id>> usernameCache,
@GerritServerConfig final Config config) {
this.helper = helper;
this.authConfig = authConfig;
@@ -144,14 +143,12 @@
return v;
}
- static List<String> optionalList(final Config config,
- final String name) {
+ static List<String> optionalList(final Config config, final String name) {
String[] s = config.getStringList("ldap", null, name);
return Arrays.asList(s);
}
- static List<String> requiredList(final Config config,
- final String name) {
+ static List<String> requiredList(final Config config, final String name) {
List<String> vlist = optionalList(config, name);
if (vlist.isEmpty()) {
@@ -194,11 +191,10 @@
}
}
- private static void checkBackendCompliance(String configOption,
- String suppliedValue, boolean disabledByBackend) {
+ private static void checkBackendCompliance(
+ String configOption, String suppliedValue, boolean disabledByBackend) {
if (disabledByBackend && !Strings.isNullOrEmpty(suppliedValue)) {
- String msg = String.format("LDAP backend doesn't support: ldap.%s",
- configOption);
+ String msg = String.format("LDAP backend doesn't support: ldap.%s", configOption);
log.error(msg);
throw new IllegalArgumentException(msg);
}
@@ -209,8 +205,7 @@
return !readOnlyAccountFields.contains(field);
}
- static String apply(ParameterizedString p, LdapQuery.Result m)
- throws NamingException {
+ static String apply(ParameterizedString p, LdapQuery.Result m) throws NamingException {
if (p == null) {
return null;
}
@@ -225,8 +220,7 @@
}
@Override
- public AuthRequest authenticate(final AuthRequest who)
- throws AccountException {
+ public AuthRequest authenticate(final AuthRequest who) throws AccountException {
if (config.getBoolean("ldap", "localUsernameToLowerCase", false)) {
who.setLocalUser(who.getLocalUser().toLowerCase(Locale.US));
}
@@ -241,8 +235,7 @@
}
try {
final Helper.LdapSchema schema = helper.getSchema(ctx);
- final LdapQuery.Result m = helper.findAccount(schema, ctx, username,
- fetchMemberOfEagerly);
+ final LdapQuery.Result m = helper.findAccount(schema, ctx, username, fetchMemberOfEagerly);
if (authConfig.getAuthType() == AuthType.LDAP && !who.isSkipAuthentication()) {
// We found the user account, but we need to verify
@@ -277,12 +270,11 @@
GroupReference mandatoryGroupRef =
GroupBackends.findExactSuggestion(groupBackend, mandatoryGroup);
if (mandatoryGroupRef == null) {
- throw new AccountException("Could not identify mandatory group: " +
- mandatoryGroup);
+ throw new AccountException("Could not identify mandatory group: " + mandatoryGroup);
}
if (!groups.contains(mandatoryGroupRef.getUUID())) {
- throw new AccountException("Not member of mandatory LDAP group: " +
- mandatoryGroupRef.getName());
+ throw new AccountException(
+ "Not member of mandatory LDAP group: " + mandatoryGroupRef.getName());
}
}
// Regardless if we enabled fetchMemberOfEagerly, we already have the
@@ -337,8 +329,7 @@
public Optional<Account.Id> load(String username) throws Exception {
try (ReviewDb db = schema.open()) {
return Optional.ofNullable(
- db.accountExternalIds().get(
- new AccountExternalId.Key(SCHEME_GERRIT, username)))
+ db.accountExternalIds().get(new AccountExternalId.Key(SCHEME_GERRIT, username)))
.map(AccountExternalId::getAccountId);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/auth/ldap/LdapType.java b/gerrit-server/src/main/java/com/google/gerrit/server/auth/ldap/LdapType.java
index 4e68653..5df13f9 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/auth/ldap/LdapType.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/auth/ldap/LdapType.java
@@ -25,8 +25,9 @@
static LdapType guessType(final DirContext ctx) throws NamingException {
final Attributes rootAtts = ctx.getAttributes("");
Attribute supported = rootAtts.get("supportedCapabilities");
- if (supported != null && (supported.contains("1.2.840.113556.1.4.800")
- || supported.contains("1.2.840.113556.1.4.1851"))) {
+ if (supported != null
+ && (supported.contains("1.2.840.113556.1.4.800")
+ || supported.contains("1.2.840.113556.1.4.1851"))) {
return new ActiveDirectory();
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/auth/oauth/OAuthRealm.java b/gerrit-server/src/main/java/com/google/gerrit/server/auth/oauth/OAuthRealm.java
index 6b92289..a1d9350 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/auth/oauth/OAuthRealm.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/auth/oauth/OAuthRealm.java
@@ -27,12 +27,10 @@
import com.google.gerrit.server.config.GerritServerConfig;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.lib.Config;
-
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
+import org.eclipse.jgit.lib.Config;
@Singleton
public class OAuthRealm extends AbstractRealm {
@@ -40,8 +38,7 @@
private final Set<AccountFieldName> editableAccountFields;
@Inject
- OAuthRealm(DynamicMap<OAuthLoginProvider> loginProviders,
- @GerritServerConfig Config config) {
+ OAuthRealm(DynamicMap<OAuthLoginProvider> loginProviders, @GerritServerConfig Config config) {
this.loginProviders = loginProviders;
this.editableAccountFields = new HashSet<>();
// User name should be always editable, because not all OAuth providers
@@ -61,23 +58,17 @@
}
/**
- * Authenticates with the {@link OAuthLoginProvider} specified
- * in the authentication request.
+ * Authenticates with the {@link OAuthLoginProvider} specified in the authentication request.
*
- * {@link AccountManager} calls this method without password
- * if authenticity of the user has already been established.
- * In that case we can skip the authentication request to the
- * {@code OAuthLoginService}.
+ * <p>{@link AccountManager} calls this method without password if authenticity of the user has
+ * already been established. In that case we can skip the authentication request to the {@code
+ * OAuthLoginService}.
*
* @param who the authentication request.
- *
- * @return the authentication request with resolved email address
- * and display name in case the authenticity of the user could
- * be established; otherwise {@code who} is returned unchanged.
- *
- * @throws AccountException if the authentication request with
- * the OAuth2 server failed or no {@code OAuthLoginProvider} was
- * available to handle the request.
+ * @return the authentication request with resolved email address and display name in case the
+ * authenticity of the user could be established; otherwise {@code who} is returned unchanged.
+ * @throws AccountException if the authentication request with the OAuth2 server failed or no
+ * {@code OAuthLoginProvider} was available to handle the request.
*/
@Override
public AuthRequest authenticate(AuthRequest who) throws AccountException {
@@ -118,8 +109,7 @@
}
@Override
- public void onCreateAccount(AuthRequest who, Account account) {
- }
+ public void onCreateAccount(AuthRequest who, Account account) {}
@Override
public Account.Id lookup(String accountName) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/auth/oauth/OAuthTokenCache.java b/gerrit-server/src/main/java/com/google/gerrit/server/auth/oauth/OAuthTokenCache.java
index 94bdb06..1ac3bca 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/auth/oauth/OAuthTokenCache.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/auth/oauth/OAuthTokenCache.java
@@ -45,7 +45,8 @@
private final Cache<Account.Id, OAuthToken> cache;
@Inject
- OAuthTokenCache(@Named(OAUTH_TOKENS) Cache<Account.Id, OAuthToken> cache,
+ OAuthTokenCache(
+ @Named(OAUTH_TOKENS) Cache<Account.Id, OAuthToken> cache,
DynamicItem<OAuthTokenEncrypter> encrypter) {
this.cache = cache;
this.encrypter = encrypter;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/auth/openid/OpenIdProviderPattern.java b/gerrit-server/src/main/java/com/google/gerrit/server/auth/openid/OpenIdProviderPattern.java
index 7e15f52..4350037 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/auth/openid/OpenIdProviderPattern.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/auth/openid/OpenIdProviderPattern.java
@@ -27,8 +27,7 @@
protected boolean regex;
protected String pattern;
- protected OpenIdProviderPattern() {
- }
+ protected OpenIdProviderPattern() {}
public boolean matches(String id) {
return regex ? id.matches(pattern) : id.startsWith(pattern);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/avatar/AvatarProvider.java b/gerrit-server/src/main/java/com/google/gerrit/server/avatar/AvatarProvider.java
index 571a7e5..72134c1 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/avatar/AvatarProvider.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/avatar/AvatarProvider.java
@@ -20,7 +20,7 @@
/**
* Provide avatar URLs for specified user.
*
- * Invoked by Gerrit when Avatar image requests are made.
+ * <p>Invoked by Gerrit when Avatar image requests are made.
*/
@ExtensionPoint
public interface AvatarProvider {
@@ -28,14 +28,13 @@
* Get avatar URL.
*
* @param forUser The user for which to load an avatar image
- * @param imageSize A requested image size, in pixels. An imageSize of 0
- * indicates to use whatever default size the provider determines.
- * AvatarProviders may ignore the requested image size. The web
- * interface will resize any image to match imageSize, so ideally the
- * provider should return an image sized correctly.
- * @return a URL of an avatar image for the specified user. A return value of
- * {@code null} is acceptable, and results in the server responding
- * with a 404. This will hide the avatar image in the web UI.
+ * @param imageSize A requested image size, in pixels. An imageSize of 0 indicates to use whatever
+ * default size the provider determines. AvatarProviders may ignore the requested image size.
+ * The web interface will resize any image to match imageSize, so ideally the provider should
+ * return an image sized correctly.
+ * @return a URL of an avatar image for the specified user. A return value of {@code null} is
+ * acceptable, and results in the server responding with a 404. This will hide the avatar
+ * image in the web UI.
*/
String getUrl(IdentifiedUser forUser, int imageSize);
@@ -43,8 +42,8 @@
* Gets a URL for a user to modify their avatar image.
*
* @param forUser The user wishing to change their avatar image
- * @return a URL the user should visit to modify their avatar, or null if
- * modification is not possible.
+ * @return a URL the user should visit to modify their avatar, or null if modification is not
+ * possible.
*/
String getChangeAvatarUrl(IdentifiedUser forUser);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/cache/CacheBinding.java b/gerrit-server/src/main/java/com/google/gerrit/server/cache/CacheBinding.java
index 343827c..abb0f32 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/cache/CacheBinding.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/cache/CacheBinding.java
@@ -18,7 +18,6 @@
import com.google.common.cache.Weigher;
import com.google.gerrit.common.Nullable;
import com.google.inject.TypeLiteral;
-
import java.util.concurrent.TimeUnit;
/** Configure a cache declared within a {@link CacheModule} instance. */
@@ -39,11 +38,21 @@
CacheBinding<K, V> weigher(Class<? extends Weigher<K, V>> clazz);
String name();
+
TypeLiteral<K> keyType();
+
TypeLiteral<V> valueType();
+
long maximumWeight();
+
long diskLimit();
- @Nullable Long expireAfterWrite(TimeUnit unit);
- @Nullable Weigher<K, V> weigher();
- @Nullable CacheLoader<K, V> loader();
+
+ @Nullable
+ Long expireAfterWrite(TimeUnit unit);
+
+ @Nullable
+ Weigher<K, V> weigher();
+
+ @Nullable
+ CacheLoader<K, V> loader();
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/cache/CacheMetrics.java b/gerrit-server/src/main/java/com/google/gerrit/server/cache/CacheMetrics.java
index ebf8259..862f4e8 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/cache/CacheMetrics.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/cache/CacheMetrics.java
@@ -25,65 +25,71 @@
import com.google.gerrit.metrics.MetricMaker;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
import java.util.Set;
@Singleton
public class CacheMetrics {
@Inject
- public CacheMetrics(MetricMaker metrics,
- final DynamicMap<Cache<?, ?>> cacheMap) {
+ public CacheMetrics(MetricMaker metrics, final DynamicMap<Cache<?, ?>> cacheMap) {
Field<String> F_NAME = Field.ofString("cache_name");
final CallbackMetric1<String, Long> memEnt =
- metrics.newCallbackMetric("caches/memory_cached", Long.class,
+ metrics.newCallbackMetric(
+ "caches/memory_cached",
+ Long.class,
new Description("Memory entries").setGauge().setUnit("entries"),
F_NAME);
final CallbackMetric1<String, Double> memHit =
- metrics.newCallbackMetric("caches/memory_hit_ratio", Double.class,
+ metrics.newCallbackMetric(
+ "caches/memory_hit_ratio",
+ Double.class,
new Description("Memory hit ratio").setGauge().setUnit("percent"),
F_NAME);
final CallbackMetric1<String, Long> memEvict =
- metrics.newCallbackMetric("caches/memory_eviction_count", Long.class,
- new Description("Memory eviction count").setGauge()
- .setUnit("evicted entries"),
+ metrics.newCallbackMetric(
+ "caches/memory_eviction_count",
+ Long.class,
+ new Description("Memory eviction count").setGauge().setUnit("evicted entries"),
F_NAME);
final CallbackMetric1<String, Long> perDiskEnt =
- metrics.newCallbackMetric("caches/disk_cached", Long.class,
- new Description("Disk entries used by persistent cache").setGauge()
- .setUnit("entries"),
+ metrics.newCallbackMetric(
+ "caches/disk_cached",
+ Long.class,
+ new Description("Disk entries used by persistent cache").setGauge().setUnit("entries"),
F_NAME);
final CallbackMetric1<String, Double> perDiskHit =
- metrics.newCallbackMetric("caches/disk_hit_ratio", Double.class,
- new Description("Disk hit ratio for persistent cache").setGauge()
- .setUnit("percent"),
+ metrics.newCallbackMetric(
+ "caches/disk_hit_ratio",
+ Double.class,
+ new Description("Disk hit ratio for persistent cache").setGauge().setUnit("percent"),
F_NAME);
final Set<CallbackMetric<?>> cacheMetrics =
- ImmutableSet.<CallbackMetric<?>> of(memEnt, memHit, memEvict,
- perDiskEnt, perDiskHit);
+ ImmutableSet.<CallbackMetric<?>>of(memEnt, memHit, memEvict, perDiskEnt, perDiskHit);
- metrics.newTrigger(cacheMetrics, new Runnable() {
- @Override
- public void run() {
- for (DynamicMap.Entry<Cache<?, ?>> e : cacheMap) {
- Cache<?, ?> c = e.getProvider().get();
- String name = metricNameOf(e);
- CacheStats cstats = c.stats();
- memEnt.set(name, c.size());
- memHit.set(name, cstats.hitRate() * 100);
- memEvict.set(name, cstats.evictionCount());
- if (c instanceof PersistentCache) {
- PersistentCache.DiskStats d = ((PersistentCache) c).diskStats();
- perDiskEnt.set(name, d.size());
- perDiskHit.set(name, hitRatio(d));
+ metrics.newTrigger(
+ cacheMetrics,
+ new Runnable() {
+ @Override
+ public void run() {
+ for (DynamicMap.Entry<Cache<?, ?>> e : cacheMap) {
+ Cache<?, ?> c = e.getProvider().get();
+ String name = metricNameOf(e);
+ CacheStats cstats = c.stats();
+ memEnt.set(name, c.size());
+ memHit.set(name, cstats.hitRate() * 100);
+ memEvict.set(name, cstats.evictionCount());
+ if (c instanceof PersistentCache) {
+ PersistentCache.DiskStats d = ((PersistentCache) c).diskStats();
+ perDiskEnt.set(name, d.size());
+ perDiskHit.set(name, hitRatio(d));
+ }
+ }
+ for (CallbackMetric<?> cbm : cacheMetrics) {
+ cbm.prune();
+ }
}
- }
- for (CallbackMetric<?> cbm : cacheMetrics) {
- cbm.prune();
- }
- }
- });
+ });
}
private static double hitRatio(PersistentCache.DiskStats d) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/cache/CacheModule.java b/gerrit-server/src/main/java/com/google/gerrit/server/cache/CacheModule.java
index 9f51de7..e68eb43 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/cache/CacheModule.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/cache/CacheModule.java
@@ -26,16 +26,12 @@
import com.google.inject.TypeLiteral;
import com.google.inject.name.Names;
import com.google.inject.util.Types;
-
import java.io.Serializable;
import java.lang.reflect.Type;
-/**
- * Miniature DSL to support binding {@link Cache} instances in Guice.
- */
+/** Miniature DSL to support binding {@link Cache} instances in Guice. */
public abstract class CacheModule extends FactoryModule {
- private static final TypeLiteral<Cache<?, ?>> ANY_CACHE =
- new TypeLiteral<Cache<?, ?>>() {};
+ private static final TypeLiteral<Cache<?, ?>> ANY_CACHE = new TypeLiteral<Cache<?, ?>>() {};
/**
* Declare a named in-memory cache.
@@ -44,10 +40,7 @@
* @param <V> type of value stored by the cache.
* @return binding to describe the cache.
*/
- protected <K, V> CacheBinding<K, V> cache(
- String name,
- Class<K> keyType,
- Class<V> valType) {
+ protected <K, V> CacheBinding<K, V> cache(String name, Class<K> keyType, Class<V> valType) {
return cache(name, TypeLiteral.get(keyType), TypeLiteral.get(valType));
}
@@ -58,10 +51,7 @@
* @param <V> type of value stored by the cache.
* @return binding to describe the cache.
*/
- protected <K, V> CacheBinding<K, V> cache(
- String name,
- Class<K> keyType,
- TypeLiteral<V> valType) {
+ protected <K, V> CacheBinding<K, V> cache(String name, Class<K> keyType, TypeLiteral<V> valType) {
return cache(name, TypeLiteral.get(keyType), valType);
}
@@ -73,12 +63,8 @@
* @return binding to describe the cache.
*/
protected <K, V> CacheBinding<K, V> cache(
- String name,
- TypeLiteral<K> keyType,
- TypeLiteral<V> valType) {
- Type type = Types.newParameterizedType(
- Cache.class,
- keyType.getType(), valType.getType());
+ String name, TypeLiteral<K> keyType, TypeLiteral<V> valType) {
+ Type type = Types.newParameterizedType(Cache.class, keyType.getType(), valType.getType());
@SuppressWarnings("unchecked")
Key<Cache<K, V>> key = (Key<Cache<K, V>>) Key.get(type, Names.named(name));
@@ -89,24 +75,21 @@
return m.maximumWeight(1024);
}
- <K,V> Provider<CacheLoader<K,V>> bindCacheLoader(
- CacheProvider<K, V> m,
- Class<? extends CacheLoader<K,V>> impl) {
- Type type = Types.newParameterizedType(
- Cache.class,
- m.keyType().getType(), m.valueType().getType());
+ <K, V> Provider<CacheLoader<K, V>> bindCacheLoader(
+ CacheProvider<K, V> m, Class<? extends CacheLoader<K, V>> impl) {
+ Type type =
+ Types.newParameterizedType(Cache.class, m.keyType().getType(), m.valueType().getType());
- Type loadingType = Types.newParameterizedType(
- LoadingCache.class,
- m.keyType().getType(), m.valueType().getType());
+ Type loadingType =
+ Types.newParameterizedType(
+ LoadingCache.class, m.keyType().getType(), m.valueType().getType());
- Type loaderType = Types.newParameterizedType(
- CacheLoader.class,
- m.keyType().getType(), m.valueType().getType());
+ Type loaderType =
+ Types.newParameterizedType(
+ CacheLoader.class, m.keyType().getType(), m.valueType().getType());
@SuppressWarnings("unchecked")
- Key<LoadingCache<K, V>> key =
- (Key<LoadingCache<K, V>>) Key.get(type, Names.named(m.name));
+ Key<LoadingCache<K, V>> key = (Key<LoadingCache<K, V>>) Key.get(type, Names.named(m.name));
@SuppressWarnings("unchecked")
Key<LoadingCache<K, V>> loadingKey =
@@ -121,16 +104,13 @@
return getProvider(loaderKey);
}
- <K,V> Provider<Weigher<K,V>> bindWeigher(
- CacheProvider<K, V> m,
- Class<? extends Weigher<K,V>> impl) {
- Type weigherType = Types.newParameterizedType(
- Weigher.class,
- m.keyType().getType(), m.valueType().getType());
+ <K, V> Provider<Weigher<K, V>> bindWeigher(
+ CacheProvider<K, V> m, Class<? extends Weigher<K, V>> impl) {
+ Type weigherType =
+ Types.newParameterizedType(Weigher.class, m.keyType().getType(), m.valueType().getType());
@SuppressWarnings("unchecked")
- Key<Weigher<K, V>> key =
- (Key<Weigher<K, V>>) Key.get(weigherType, Names.named(m.name));
+ Key<Weigher<K, V>> key = (Key<Weigher<K, V>>) Key.get(weigherType, Names.named(m.name));
bind(key).to(impl).in(Scopes.SINGLETON);
return getProvider(key);
@@ -144,9 +124,7 @@
* @return binding to describe the cache.
*/
protected <K extends Serializable, V extends Serializable> CacheBinding<K, V> persist(
- String name,
- Class<K> keyType,
- Class<V> valType) {
+ String name, Class<K> keyType, Class<V> valType) {
return persist(name, TypeLiteral.get(keyType), TypeLiteral.get(valType));
}
@@ -158,9 +136,7 @@
* @return binding to describe the cache.
*/
protected <K extends Serializable, V extends Serializable> CacheBinding<K, V> persist(
- String name,
- Class<K> keyType,
- TypeLiteral<V> valType) {
+ String name, Class<K> keyType, TypeLiteral<V> valType) {
return persist(name, TypeLiteral.get(keyType), valType);
}
@@ -172,10 +148,7 @@
* @return binding to describe the cache.
*/
protected <K extends Serializable, V extends Serializable> CacheBinding<K, V> persist(
- String name,
- TypeLiteral<K> keyType,
- TypeLiteral<V> valType) {
- return ((CacheProvider<K, V>) cache(name, keyType, valType))
- .persist(true);
+ String name, TypeLiteral<K> keyType, TypeLiteral<V> valType) {
+ return ((CacheProvider<K, V>) cache(name, keyType, valType)).persist(true);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/cache/CacheProvider.java b/gerrit-server/src/main/java/com/google/gerrit/server/cache/CacheProvider.java
index c73760c..86df104 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/cache/CacheProvider.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/cache/CacheProvider.java
@@ -26,12 +26,9 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.TypeLiteral;
-
import java.util.concurrent.TimeUnit;
-class CacheProvider<K, V>
- implements Provider<Cache<K, V>>,
- CacheBinding<K, V> {
+class CacheProvider<K, V> implements Provider<Cache<K, V>>, CacheBinding<K, V> {
private final CacheModule module;
final String name;
private final TypeLiteral<K> keyType;
@@ -48,10 +45,7 @@
private PersistentCacheFactory persistentCacheFactory;
private boolean frozen;
- CacheProvider(CacheModule module,
- String name,
- TypeLiteral<K> keyType,
- TypeLiteral<V> valType) {
+ CacheProvider(CacheModule module, String name, TypeLiteral<K> keyType, TypeLiteral<V> valType) {
this.module = module;
this.name = name;
this.keyType = keyType;
@@ -89,8 +83,7 @@
@Override
public CacheBinding<K, V> diskLimit(long limit) {
Preconditions.checkState(!frozen, "binding frozen, cannot be modified");
- Preconditions.checkState(persist,
- "diskLimit supported for persistent caches only");
+ Preconditions.checkState(persist, "diskLimit supported for persistent caches only");
diskLimit = limit;
return this;
}
@@ -150,9 +143,7 @@
@Override
@Nullable
public Long expireAfterWrite(TimeUnit unit) {
- return expireAfterWrite != null
- ? unit.convert(expireAfterWrite, SECONDS)
- : null;
+ return expireAfterWrite != null ? unit.convert(expireAfterWrite, SECONDS) : null;
}
@Override
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/cache/CacheRemovalListener.java b/gerrit-server/src/main/java/com/google/gerrit/server/cache/CacheRemovalListener.java
index bdc1220..2f9ed59 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/cache/CacheRemovalListener.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/cache/CacheRemovalListener.java
@@ -16,8 +16,6 @@
import com.google.common.cache.RemovalNotification;
-public interface CacheRemovalListener<K,V> {
- void onRemoval(String pluginName,
- String cacheName,
- RemovalNotification<K, V> notification);
+public interface CacheRemovalListener<K, V> {
+ void onRemoval(String pluginName, String cacheName, RemovalNotification<K, V> notification);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/cache/ForwardingRemovalListener.java b/gerrit-server/src/main/java/com/google/gerrit/server/cache/ForwardingRemovalListener.java
index 96b437d..be06601 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/cache/ForwardingRemovalListener.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/cache/ForwardingRemovalListener.java
@@ -22,8 +22,8 @@
import com.google.inject.assistedinject.Assisted;
/**
- * This listener dispatches removal events to all other RemovalListeners
- * attached via the DynamicSet API.
+ * This listener dispatches removal events to all other RemovalListeners attached via the DynamicSet
+ * API.
*
* @param <K>
* @param <V>
@@ -39,8 +39,8 @@
private String pluginName = "gerrit";
@Inject
- ForwardingRemovalListener(DynamicSet<CacheRemovalListener> listeners,
- @Assisted String cacheName) {
+ ForwardingRemovalListener(
+ DynamicSet<CacheRemovalListener> listeners, @Assisted String cacheName) {
this.listeners = listeners;
this.cacheName = cacheName;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/cache/MemoryCacheFactory.java b/gerrit-server/src/main/java/com/google/gerrit/server/cache/MemoryCacheFactory.java
index 6b8b489..49fcd5b 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/cache/MemoryCacheFactory.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/cache/MemoryCacheFactory.java
@@ -21,7 +21,5 @@
public interface MemoryCacheFactory {
<K, V> Cache<K, V> build(CacheBinding<K, V> def);
- <K, V> LoadingCache<K, V> build(
- CacheBinding<K, V> def,
- CacheLoader<K, V> loader);
+ <K, V> LoadingCache<K, V> build(CacheBinding<K, V> def, CacheLoader<K, V> loader);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/cache/PersistentCacheFactory.java b/gerrit-server/src/main/java/com/google/gerrit/server/cache/PersistentCacheFactory.java
index 0769b2a..c52c232 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/cache/PersistentCacheFactory.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/cache/PersistentCacheFactory.java
@@ -22,9 +22,7 @@
public interface PersistentCacheFactory {
<K, V> Cache<K, V> build(CacheBinding<K, V> def);
- <K, V> LoadingCache<K, V> build(
- CacheBinding<K, V> def,
- CacheLoader<K, V> loader);
+ <K, V> LoadingCache<K, V> build(CacheBinding<K, V> def, CacheLoader<K, V> loader);
void onStop(Plugin plugin);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/Abandon.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/Abandon.java
index 54c217d..2f523e0 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/Abandon.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/Abandon.java
@@ -39,15 +39,13 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
+import java.util.Collection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.util.Collection;
-
@Singleton
-public class Abandon implements RestModifyView<ChangeResource, AbandonInput>,
- UiAction<ChangeResource> {
+public class Abandon
+ implements RestModifyView<ChangeResource, AbandonInput>, UiAction<ChangeResource> {
private static final Logger log = LoggerFactory.getLogger(Abandon.class);
private final Provider<ReviewDb> dbProvider;
@@ -77,32 +75,30 @@
if (!control.canAbandon(dbProvider.get())) {
throw new AuthException("abandon not permitted");
}
- Change change = abandon(control, input.message, input.notify,
- notifyUtil.resolveAccounts(input.notifyDetails));
+ Change change =
+ abandon(
+ control, input.message, input.notify, notifyUtil.resolveAccounts(input.notifyDetails));
return json.create(ChangeJson.NO_OPTIONS).format(change);
}
- public Change abandon(ChangeControl control)
- throws RestApiException, UpdateException {
+ public Change abandon(ChangeControl control) throws RestApiException, UpdateException {
return abandon(control, "", NotifyHandling.ALL, ImmutableListMultimap.of());
}
public Change abandon(ChangeControl control, String msgTxt)
throws RestApiException, UpdateException {
- return abandon(control, msgTxt, NotifyHandling.ALL,
- ImmutableListMultimap.of());
+ return abandon(control, msgTxt, NotifyHandling.ALL, ImmutableListMultimap.of());
}
- public Change abandon(ChangeControl control, String msgTxt,
+ public Change abandon(
+ ChangeControl control,
+ String msgTxt,
NotifyHandling notifyHandling,
ListMultimap<RecipientType, Account.Id> accountsToNotify)
- throws RestApiException, UpdateException {
+ throws RestApiException, UpdateException {
CurrentUser user = control.getUser();
- Account account = user.isIdentifiedUser()
- ? user.asIdentifiedUser().getAccount()
- : null;
- AbandonOp op = abandonOpFactory.create(account, msgTxt, notifyHandling,
- accountsToNotify);
+ Account account = user.isIdentifiedUser() ? user.asIdentifiedUser().getAccount() : null;
+ AbandonOp op = abandonOpFactory.create(account, msgTxt, notifyHandling, accountsToNotify);
try (BatchUpdate u =
batchUpdateFactory.create(
dbProvider.get(),
@@ -115,55 +111,51 @@
}
/**
- * If an extension has more than one changes to abandon that belong to the
- * same project, they should use the batch instead of abandoning one by one.
- * <p>
- * It's the caller's responsibility to ensure that all jobs inside the same
- * batch have the matching project from its ChangeControl. Violations will
- * result in a ResourceConflictException.
+ * If an extension has more than one changes to abandon that belong to the same project, they
+ * should use the batch instead of abandoning one by one.
+ *
+ * <p>It's the caller's responsibility to ensure that all jobs inside the same batch have the
+ * matching project from its ChangeControl. Violations will result in a ResourceConflictException.
*/
- public void batchAbandon(Project.NameKey project, CurrentUser user,
- Collection<ChangeControl> controls, String msgTxt,
+ public void batchAbandon(
+ Project.NameKey project,
+ CurrentUser user,
+ Collection<ChangeControl> controls,
+ String msgTxt,
NotifyHandling notifyHandling,
ListMultimap<RecipientType, Account.Id> accountsToNotify)
- throws RestApiException, UpdateException {
+ throws RestApiException, UpdateException {
if (controls.isEmpty()) {
return;
}
- Account account = user.isIdentifiedUser()
- ? user.asIdentifiedUser().getAccount()
- : null;
- try (BatchUpdate u = batchUpdateFactory.create(
- dbProvider.get(), project, user, TimeUtil.nowTs())) {
+ Account account = user.isIdentifiedUser() ? user.asIdentifiedUser().getAccount() : null;
+ try (BatchUpdate u =
+ batchUpdateFactory.create(dbProvider.get(), project, user, TimeUtil.nowTs())) {
for (ChangeControl control : controls) {
if (!project.equals(control.getProject().getNameKey())) {
throw new ResourceConflictException(
String.format(
"Project name \"%s\" doesn't match \"%s\"",
- control.getProject().getNameKey().get(),
- project.get()));
+ control.getProject().getNameKey().get(), project.get()));
}
u.addOp(
control.getId(),
- abandonOpFactory.create(account, msgTxt, notifyHandling,
- accountsToNotify));
+ abandonOpFactory.create(account, msgTxt, notifyHandling, accountsToNotify));
}
u.execute();
}
}
- public void batchAbandon(Project.NameKey project, CurrentUser user,
- Collection<ChangeControl> controls, String msgTxt)
+ public void batchAbandon(
+ Project.NameKey project, CurrentUser user, Collection<ChangeControl> controls, String msgTxt)
throws RestApiException, UpdateException {
- batchAbandon(project, user, controls, msgTxt, NotifyHandling.ALL,
- ImmutableListMultimap.of());
+ batchAbandon(project, user, controls, msgTxt, NotifyHandling.ALL, ImmutableListMultimap.of());
}
- public void batchAbandon(Project.NameKey project, CurrentUser user,
- Collection<ChangeControl> controls)
+ public void batchAbandon(
+ Project.NameKey project, CurrentUser user, Collection<ChangeControl> controls)
throws RestApiException, UpdateException {
- batchAbandon(project, user, controls, "", NotifyHandling.ALL,
- ImmutableListMultimap.of());
+ batchAbandon(project, user, controls, "", NotifyHandling.ALL, ImmutableListMultimap.of());
}
@Override
@@ -175,10 +167,11 @@
log.error("Cannot check canAbandon status. Assuming false.", e);
}
return new UiAction.Description()
- .setLabel("Abandon")
- .setTitle("Abandon the change")
- .setVisible(resource.getChange().getStatus().isOpen()
- && resource.getChange().getStatus() != Change.Status.DRAFT
- && canAbandon);
+ .setLabel("Abandon")
+ .setTitle("Abandon the change")
+ .setVisible(
+ resource.getChange().getStatus().isOpen()
+ && resource.getChange().getStatus() != Change.Status.DRAFT
+ && canAbandon);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/AbandonUtil.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/AbandonUtil.java
index 566e9fa..7c408c8 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/AbandonUtil.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/AbandonUtil.java
@@ -27,14 +27,12 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
@Singleton
public class AbandonUtil {
@@ -66,18 +64,14 @@
}
try {
- String query = "status:new age:"
- + TimeUnit.MILLISECONDS.toMinutes(cfg.getAbandonAfter())
- + "m";
+ String query =
+ "status:new age:" + TimeUnit.MILLISECONDS.toMinutes(cfg.getAbandonAfter()) + "m";
if (!cfg.getAbandonIfMergeable()) {
query += " -is:mergeable";
}
List<ChangeData> changesToAbandon =
- queryProcessor
- .enforceVisibility(false)
- .query(queryBuilder.parse(query))
- .entities();
+ queryProcessor.enforceVisibility(false).query(queryBuilder.parse(query)).entities();
ImmutableListMultimap.Builder<Project.NameKey, ChangeControl> builder =
ImmutableListMultimap.builder();
for (ChangeData cd : changesToAbandon) {
@@ -89,14 +83,12 @@
ListMultimap<Project.NameKey, ChangeControl> abandons = builder.build();
String message = cfg.getAbandonMessage();
for (Project.NameKey project : abandons.keySet()) {
- Collection<ChangeControl> changes =
- getValidChanges(abandons.get(project), query);
+ Collection<ChangeControl> changes = getValidChanges(abandons.get(project), query);
try {
abandon.batchAbandon(project, internalUser, changes, message);
count += changes.size();
} catch (Throwable e) {
- StringBuilder msg =
- new StringBuilder("Failed to auto-abandon inactive change(s):");
+ StringBuilder msg = new StringBuilder("Failed to auto-abandon inactive change(s):");
for (ChangeControl change : changes) {
msg.append(" ").append(change.getId().get());
}
@@ -104,11 +96,9 @@
log.error(msg.toString(), e);
}
}
- log.info(String.format("Auto-Abandoned %d of %d changes.",
- count, changesToAbandon.size()));
+ log.info(String.format("Auto-Abandoned %d of %d changes.", count, changesToAbandon.size()));
} catch (QueryParseException | OrmException e) {
- log.error(
- "Failed to query inactive open changes for auto-abandoning.", e);
+ log.error("Failed to query inactive open changes for auto-abandoning.", e);
}
}
@@ -119,15 +109,15 @@
for (ChangeControl cc : changeControls) {
String newQuery = query + " change:" + cc.getId();
List<ChangeData> changesToAbandon =
- queryProcessor.enforceVisibility(false)
- .query(queryBuilder.parse(newQuery)).entities();
+ queryProcessor.enforceVisibility(false).query(queryBuilder.parse(newQuery)).entities();
if (!changesToAbandon.isEmpty()) {
validChanges.add(cc);
} else {
log.debug(
"Change data with id \"{}\" does not satisfy the query \"{}\""
+ " any more, hence skipping it in clean up",
- cc.getId(), query);
+ cc.getId(),
+ query);
}
}
return validChanges;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/AccountPatchReviewStore.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/AccountPatchReviewStore.java
index 1ea8404..944b2cb 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/AccountPatchReviewStore.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/AccountPatchReviewStore.java
@@ -17,19 +17,17 @@
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.reviewdb.client.PatchSet;
import com.google.gwtorm.server.OrmException;
-
import java.util.Collection;
/**
* Store for reviewed flags on changes.
*
- * A reviewed flag is a tuple of (patch set ID, file, account ID) and records
- * whether the user has reviewed a file in a patch set. Each user can easily
- * have thousands of reviewed flags and the number of reviewed flags is growing
- * without bound. The store must be able handle this data volume efficiently.
+ * <p>A reviewed flag is a tuple of (patch set ID, file, account ID) and records whether the user
+ * has reviewed a file in a patch set. Each user can easily have thousands of reviewed flags and the
+ * number of reviewed flags is growing without bound. The store must be able handle this data volume
+ * efficiently.
*
- * For a multi-master setup the store must replicate the data between the
- * masters.
+ * <p>For a multi-master setup the store must replicate the data between the masters.
*/
public interface AccountPatchReviewStore {
/**
@@ -38,12 +36,11 @@
* @param psId patch set ID
* @param accountId account ID of the user
* @param path file path
- * @return {@code true} if the reviewed flag was updated, {@code false} if the
- * reviewed flag was already set
+ * @return {@code true} if the reviewed flag was updated, {@code false} if the reviewed flag was
+ * already set
* @throws OrmException thrown if updating the reviewed flag failed
*/
- boolean markReviewed(PatchSet.Id psId, Account.Id accountId, String path)
- throws OrmException;
+ boolean markReviewed(PatchSet.Id psId, Account.Id accountId, String path) throws OrmException;
/**
* Marks the given files in the given patch set as reviewed by the given user.
@@ -53,41 +50,34 @@
* @param paths file paths
* @throws OrmException thrown if updating the reviewed flag failed
*/
- void markReviewed(PatchSet.Id psId, Account.Id accountId,
- Collection<String> paths) throws OrmException;
+ void markReviewed(PatchSet.Id psId, Account.Id accountId, Collection<String> paths)
+ throws OrmException;
/**
- * Clears the reviewed flag for the given file in the given patch set for the
- * given user.
+ * Clears the reviewed flag for the given file in the given patch set for the given user.
*
* @param psId patch set ID
* @param accountId account ID of the user
* @param path file path
* @throws OrmException thrown if clearing the reviewed flag failed
*/
- void clearReviewed(PatchSet.Id psId, Account.Id accountId, String path)
- throws OrmException;
+ void clearReviewed(PatchSet.Id psId, Account.Id accountId, String path) throws OrmException;
/**
- * Clears the reviewed flags for all files in the given patch set for all
- * users.
+ * Clears the reviewed flags for all files in the given patch set for all users.
*
* @param psId patch set ID
* @throws OrmException thrown if clearing the reviewed flags failed
*/
void clearReviewed(PatchSet.Id psId) throws OrmException;
-
/**
- * Returns the paths of all files in the given patch set the have been
- * reviewed by the given user.
+ * Returns the paths of all files in the given patch set the have been reviewed by the given user.
*
* @param psId patch set ID
* @param accountId account ID of the user
- * @return the paths of all files in the given patch set the have been
- * reviewed by the given user
+ * @return the paths of all files in the given patch set the have been reviewed by the given user
* @throws OrmException thrown if accessing the reviewed flags failed
*/
- Collection<String> findReviewed(PatchSet.Id psId, Account.Id accountId)
- throws OrmException;
+ Collection<String> findReviewed(PatchSet.Id psId, Account.Id accountId) throws OrmException;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/ActionJson.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/ActionJson.java
index 4c405d9..779f4db 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/ActionJson.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/ActionJson.java
@@ -39,7 +39,6 @@
import com.google.inject.Provider;
import com.google.inject.Singleton;
import com.google.inject.util.Providers;
-
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.LinkedHashMap;
@@ -68,15 +67,13 @@
this.visitorSet = visitorSet;
}
- public Map<String, ActionInfo> format(RevisionResource rsrc)
- throws OrmException {
+ public Map<String, ActionInfo> format(RevisionResource rsrc) throws OrmException {
ChangeInfo changeInfo = null;
RevisionInfo revisionInfo = null;
List<ActionVisitor> visitors = visitors();
if (!visitors.isEmpty()) {
changeInfo = changeJson().format(rsrc);
- revisionInfo =
- checkNotNull(Iterables.getOnlyElement(changeInfo.revisions.values()));
+ revisionInfo = checkNotNull(Iterables.getOnlyElement(changeInfo.revisions.values()));
changeInfo.revisions = null;
}
return toActionMap(rsrc, visitors, changeInfo, revisionInfo);
@@ -96,8 +93,8 @@
return to;
}
- public RevisionInfo addRevisionActions(@Nullable ChangeInfo changeInfo,
- RevisionInfo to, RevisionResource rsrc) throws OrmException {
+ public RevisionInfo addRevisionActions(
+ @Nullable ChangeInfo changeInfo, RevisionInfo to, RevisionResource rsrc) throws OrmException {
List<ActionVisitor> visitors = visitors();
if (!visitors.isEmpty()) {
if (changeInfo != null) {
@@ -140,8 +137,7 @@
return copy;
}
- private RevisionInfo copy(List<ActionVisitor> visitors,
- RevisionInfo revisionInfo) {
+ private RevisionInfo copy(List<ActionVisitor> visitors, RevisionInfo revisionInfo) {
if (visitors.isEmpty()) {
return null;
}
@@ -168,10 +164,8 @@
}
Provider<CurrentUser> userProvider = Providers.of(ctl.getUser());
- FluentIterable<UiAction.Description> descs = UiActions.from(
- changeViews,
- changeResourceFactory.create(ctl),
- userProvider);
+ FluentIterable<UiAction.Description> descs =
+ UiActions.from(changeViews, changeResourceFactory.create(ctl), userProvider);
// The followup action is a client-side only operation that does not
// have a server side handler. It must be manually registered into the
// resulting action map.
@@ -184,7 +178,8 @@
descs = descs.append(descr);
}
- ACTION: for (UiAction.Description d : descs) {
+ ACTION:
+ for (UiAction.Description d : descs) {
ActionInfo actionInfo = new ActionInfo(d);
for (ActionVisitor visitor : visitors) {
if (!visitor.visit(d.getId(), actionInfo, changeInfo)) {
@@ -196,17 +191,18 @@
return out;
}
- private Map<String, ActionInfo> toActionMap(RevisionResource rsrc,
- List<ActionVisitor> visitors, ChangeInfo changeInfo,
+ private Map<String, ActionInfo> toActionMap(
+ RevisionResource rsrc,
+ List<ActionVisitor> visitors,
+ ChangeInfo changeInfo,
RevisionInfo revisionInfo) {
if (!rsrc.getControl().getUser().isIdentifiedUser()) {
return ImmutableMap.of();
}
Map<String, ActionInfo> out = new LinkedHashMap<>();
- Provider<CurrentUser> userProvider = Providers.of(
- rsrc.getControl().getUser());
- ACTION: for (UiAction.Description d : UiActions.from(
- revisions, rsrc, userProvider)) {
+ Provider<CurrentUser> userProvider = Providers.of(rsrc.getControl().getUser());
+ ACTION:
+ for (UiAction.Description d : UiActions.from(revisions, rsrc, userProvider)) {
ActionInfo actionInfo = new ActionInfo(d);
for (ActionVisitor visitor : visitors) {
if (!visitor.visit(d.getId(), actionInfo, changeInfo, revisionInfo)) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/AllowedFormats.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/AllowedFormats.java
index 756ce88..20e586f 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/AllowedFormats.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/AllowedFormats.java
@@ -21,7 +21,6 @@
import com.google.gerrit.server.config.DownloadConfig;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
@@ -44,8 +43,9 @@
// Zip is not supported because it may be interpreted by a Java plugin as a
// valid JAR file, whose code would have access to cookies on the domain.
- allowed = Sets.immutableEnumSet(
- Iterables.filter(cfg.getArchiveFormats(), f -> f != ArchiveFormat.ZIP));
+ allowed =
+ Sets.immutableEnumSet(
+ Iterables.filter(cfg.getArchiveFormats(), f -> f != ArchiveFormat.ZIP));
}
public Set<ArchiveFormat> getAllowed() {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/ArchiveFormat.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/ArchiveFormat.java
index 9c517f0..73ef23e 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/ArchiveFormat.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/ArchiveFormat.java
@@ -14,6 +14,9 @@
package com.google.gerrit.server.change;
+import java.io.Closeable;
+import java.io.IOException;
+import java.io.OutputStream;
import org.apache.commons.compress.archivers.ArchiveOutputStream;
import org.eclipse.jgit.api.ArchiveCommand;
import org.eclipse.jgit.api.ArchiveCommand.Format;
@@ -25,10 +28,6 @@
import org.eclipse.jgit.lib.FileMode;
import org.eclipse.jgit.lib.ObjectLoader;
-import java.io.Closeable;
-import java.io.IOException;
-import java.io.OutputStream;
-
public enum ArchiveFormat {
TGZ("application/x-gzip", new TgzFormat()),
TAR("application/x-tar", new TarFormat()),
@@ -61,16 +60,14 @@
return format.suffixes();
}
- public ArchiveOutputStream createArchiveOutputStream(OutputStream o)
- throws IOException {
- return (ArchiveOutputStream)this.format.createArchiveOutputStream(o);
+ public ArchiveOutputStream createArchiveOutputStream(OutputStream o) throws IOException {
+ return (ArchiveOutputStream) this.format.createArchiveOutputStream(o);
}
- public <T extends Closeable> void putEntry(T out, String path, byte[] data)
- throws IOException {
+ public <T extends Closeable> void putEntry(T out, String path, byte[] data) throws IOException {
@SuppressWarnings("unchecked")
ArchiveCommand.Format<T> fmt = (Format<T>) format;
- fmt.putEntry(out, path, FileMode.REGULAR_FILE,
- new ObjectLoader.SmallObject(FileMode.TYPE_FILE, data));
+ fmt.putEntry(
+ out, path, FileMode.REGULAR_FILE, new ObjectLoader.SmallObject(FileMode.TYPE_FILE, data));
}
-}
\ No newline at end of file
+}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/ChangeCleanupRunner.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/ChangeCleanupRunner.java
index 310c8cb..04899ed 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/ChangeCleanupRunner.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/ChangeCleanupRunner.java
@@ -25,16 +25,13 @@
import com.google.gerrit.server.util.OneOffRequestContext;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
-
+import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.util.concurrent.TimeUnit;
-
/** Runnable to enable scheduling change cleanups to run periodically */
public class ChangeCleanupRunner implements Runnable {
- private static final Logger log = LoggerFactory
- .getLogger(ChangeCleanupRunner.class);
+ private static final Logger log = LoggerFactory.getLogger(ChangeCleanupRunner.class);
public static class Module extends LifecycleModule {
@Override
@@ -49,9 +46,7 @@
private final ChangeCleanupConfig cfg;
@Inject
- Lifecycle(WorkQueue queue,
- ChangeCleanupRunner runner,
- ChangeCleanupConfig cfg) {
+ Lifecycle(WorkQueue queue, ChangeCleanupRunner runner, ChangeCleanupConfig cfg) {
this.queue = queue;
this.runner = runner;
this.cfg = cfg;
@@ -65,12 +60,11 @@
if (delay == MISSING_CONFIG && interval == MISSING_CONFIG) {
log.info("Ignoring missing changeCleanup schedule configuration");
} else if (delay < 0 || interval <= 0) {
- log.warn(String.format(
- "Ignoring invalid changeCleanup schedule configuration: %s",
- scheduleConfig));
+ log.warn(
+ String.format(
+ "Ignoring invalid changeCleanup schedule configuration: %s", scheduleConfig));
} else {
- queue.getDefaultQueue().scheduleAtFixedRate(runner, delay,
- interval, TimeUnit.MILLISECONDS);
+ queue.getDefaultQueue().scheduleAtFixedRate(runner, delay, interval, TimeUnit.MILLISECONDS);
}
}
@@ -84,9 +78,7 @@
private final AbandonUtil abandonUtil;
@Inject
- ChangeCleanupRunner(
- OneOffRequestContext oneOffRequestContext,
- AbandonUtil abandonUtil) {
+ ChangeCleanupRunner(OneOffRequestContext oneOffRequestContext, AbandonUtil abandonUtil) {
this.oneOffRequestContext = oneOffRequestContext;
this.abandonUtil = abandonUtil;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/ChangeEditResource.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/ChangeEditResource.java
index 9deb864..108e180 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/ChangeEditResource.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/ChangeEditResource.java
@@ -24,10 +24,12 @@
/**
* Represents change edit resource, that is actualy two kinds of resources:
+ *
* <ul>
- * <li>the change edit itself</li>
- * <li>a path within the edit</li>
+ * <li>the change edit itself
+ * <li>a path within the edit
* </ul>
+ *
* distinguished by whether path is null or not.
*/
public class ChangeEditResource implements RestResource {
@@ -38,8 +40,7 @@
private final ChangeEdit edit;
private final String path;
- public ChangeEditResource(ChangeResource change, ChangeEdit edit,
- String path) {
+ public ChangeEditResource(ChangeResource change, ChangeEdit edit, String path) {
this.change = change;
this.edit = edit;
this.path = path;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/ChangeEdits.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/ChangeEdits.java
index 86527b2..2225460 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/ChangeEdits.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/ChangeEdits.java
@@ -53,23 +53,21 @@
import com.google.inject.Provider;
import com.google.inject.Singleton;
import com.google.inject.assistedinject.Assisted;
-
+import java.io.IOException;
+import java.util.List;
+import java.util.Optional;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;
import org.kohsuke.args4j.Option;
-import java.io.IOException;
-import java.util.List;
-import java.util.Optional;
-
@Singleton
-public class ChangeEdits implements
- ChildCollection<ChangeResource, ChangeEditResource>,
- AcceptsCreate<ChangeResource>,
- AcceptsPost<ChangeResource>,
- AcceptsDelete<ChangeResource> {
+public class ChangeEdits
+ implements ChildCollection<ChangeResource, ChangeEditResource>,
+ AcceptsCreate<ChangeResource>,
+ AcceptsPost<ChangeResource>,
+ AcceptsDelete<ChangeResource> {
private final DynamicMap<RestView<ChangeEditResource>> views;
private final Create.Factory createFactory;
private final DeleteFile.Factory deleteFileFactory;
@@ -78,7 +76,8 @@
private final Post post;
@Inject
- ChangeEdits(DynamicMap<RestView<ChangeEditResource>> views,
+ ChangeEdits(
+ DynamicMap<RestView<ChangeEditResource>> views,
Create.Factory createFactory,
Provider<Detail> detail,
ChangeEditUtil editUtil,
@@ -104,8 +103,7 @@
@Override
public ChangeEditResource parse(ChangeResource rsrc, IdString id)
- throws ResourceNotFoundException, AuthException, IOException,
- OrmException {
+ throws ResourceNotFoundException, AuthException, IOException, OrmException {
Optional<ChangeEdit> edit = editUtil.byChange(rsrc.getChange());
if (!edit.isPresent()) {
throw new ResourceNotFoundException(id);
@@ -115,12 +113,10 @@
@SuppressWarnings("unchecked")
@Override
- public Create create(ChangeResource parent, IdString id)
- throws RestApiException {
+ public Create create(ChangeResource parent, IdString id) throws RestApiException {
return createFactory.create(id.get());
}
-
@SuppressWarnings("unchecked")
@Override
public Post post(ChangeResource parent) throws RestApiException {
@@ -128,23 +124,20 @@
}
/**
- * Create handler that is activated when collection element is accessed
- * but doesn't exist, e. g. PUT request with a path was called but
- * change edit wasn't created yet. Change edit is created and PUT
- * handler is called.
- */
+ * Create handler that is activated when collection element is accessed but doesn't exist, e. g.
+ * PUT request with a path was called but change edit wasn't created yet. Change edit is created
+ * and PUT handler is called.
+ */
@SuppressWarnings("unchecked")
@Override
- public DeleteFile delete(ChangeResource parent, IdString id)
- throws RestApiException {
+ public DeleteFile delete(ChangeResource parent, IdString id) throws RestApiException {
// It's safe to assume that id can never be null, because
// otherwise we would end up in dedicated endpoint for
// deleting of change edits and not a file in change edit
return deleteFileFactory.create(id.get());
}
- public static class Create implements
- RestModifyView<ChangeResource, Put.Input> {
+ public static class Create implements RestModifyView<ChangeResource, Put.Input> {
interface Factory {
Create create(String path);
@@ -154,25 +147,21 @@
private final String path;
@Inject
- Create(Put putEdit,
- @Assisted String path) {
+ Create(Put putEdit, @Assisted String path) {
this.putEdit = putEdit;
this.path = path;
}
@Override
public Response<?> apply(ChangeResource resource, Put.Input input)
- throws AuthException, ResourceConflictException, IOException,
- OrmException {
+ throws AuthException, ResourceConflictException, IOException, OrmException {
putEdit.apply(resource.getControl(), path, input.content);
return Response.none();
}
}
- public static class DeleteFile implements
- RestModifyView<ChangeResource, DeleteFile.Input> {
- public static class Input {
- }
+ public static class DeleteFile implements RestModifyView<ChangeResource, DeleteFile.Input> {
+ public static class Input {}
interface Factory {
DeleteFile create(String path);
@@ -182,16 +171,14 @@
private final String path;
@Inject
- DeleteFile(DeleteContent deleteContent,
- @Assisted String path) {
+ DeleteFile(DeleteContent deleteContent, @Assisted String path) {
this.deleteContent = deleteContent;
this.path = path;
}
@Override
public Response<?> apply(ChangeResource rsrc, DeleteFile.Input in)
- throws IOException, AuthException, ResourceConflictException,
- OrmException {
+ throws IOException, AuthException, ResourceConflictException, OrmException {
return deleteContent.apply(rsrc.getControl(), path);
}
}
@@ -214,7 +201,8 @@
boolean downloadCommands;
@Inject
- Detail(ChangeEditUtil editUtil,
+ Detail(
+ ChangeEditUtil editUtil,
ChangeEditJson editJson,
FileInfoJson fileInfoJson,
Revisions revisions) {
@@ -225,8 +213,8 @@
}
@Override
- public Response<EditInfo> apply(ChangeResource rsrc) throws AuthException,
- IOException, ResourceNotFoundException, OrmException {
+ public Response<EditInfo> apply(ChangeResource rsrc)
+ throws AuthException, IOException, ResourceNotFoundException, OrmException {
Optional<ChangeEdit> edit = editUtil.byChange(rsrc.getChange());
if (!edit.isPresent()) {
return Response.none();
@@ -236,16 +224,12 @@
if (list) {
PatchSet basePatchSet = null;
if (base != null) {
- RevisionResource baseResource = revisions.parse(
- rsrc, IdString.fromDecoded(base));
+ RevisionResource baseResource = revisions.parse(rsrc, IdString.fromDecoded(base));
basePatchSet = baseResource.getPatchSet();
}
try {
editInfo.files =
- fileInfoJson.toFileInfoMap(
- rsrc.getChange(),
- edit.get().getRevision(),
- basePatchSet);
+ fileInfoJson.toFileInfoMap(rsrc.getChange(), edit.get().getRevision(), basePatchSet);
} catch (PatchListNotAvailableException e) {
throw new ResourceNotFoundException(e.getMessage());
}
@@ -255,17 +239,17 @@
}
/**
- * Post to edit collection resource. Two different operations are
- * supported:
+ * Post to edit collection resource. Two different operations are supported:
+ *
* <ul>
- * <li>Create non existing change edit</li>
- * <li>Restore path in existing change edit</li>
+ * <li>Create non existing change edit
+ * <li>Restore path in existing change edit
* </ul>
+ *
* The combination of two operations in one request is supported.
*/
@Singleton
- public static class Post implements
- RestModifyView<ChangeResource, Post.Input> {
+ public static class Post implements RestModifyView<ChangeResource, Post.Input> {
public static class Input {
public String restorePath;
public String oldPath;
@@ -276,25 +260,21 @@
private final GitRepositoryManager repositoryManager;
@Inject
- Post(ChangeEditModifier editModifier,
- GitRepositoryManager repositoryManager) {
+ Post(ChangeEditModifier editModifier, GitRepositoryManager repositoryManager) {
this.editModifier = editModifier;
this.repositoryManager = repositoryManager;
}
@Override
public Response<?> apply(ChangeResource resource, Post.Input input)
- throws AuthException, IOException, ResourceConflictException,
- OrmException {
+ throws AuthException, IOException, ResourceConflictException, OrmException {
Project.NameKey project = resource.getProject();
try (Repository repository = repositoryManager.openRepository(project)) {
ChangeControl changeControl = resource.getControl();
if (isRestoreFile(input)) {
- editModifier.restoreFile(repository, changeControl,
- input.restorePath);
+ editModifier.restoreFile(repository, changeControl, input.restorePath);
} else if (isRenameFile(input)) {
- editModifier.renameFile(repository, changeControl, input.oldPath,
- input.newPath);
+ editModifier.renameFile(repository, changeControl, input.oldPath, input.newPath);
} else {
editModifier.createEdit(repository, changeControl);
}
@@ -315,38 +295,30 @@
}
}
- /**
- * Put handler that is activated when PUT request is called on
- * collection element.
- */
+ /** Put handler that is activated when PUT request is called on collection element. */
@Singleton
- public static class Put implements
- RestModifyView<ChangeEditResource, Put.Input> {
+ public static class Put implements RestModifyView<ChangeEditResource, Put.Input> {
public static class Input {
- @DefaultInput
- public RawInput content;
+ @DefaultInput public RawInput content;
}
private final ChangeEditModifier editModifier;
private final GitRepositoryManager repositoryManager;
@Inject
- Put(ChangeEditModifier editModifier,
- GitRepositoryManager repositoryManager) {
+ Put(ChangeEditModifier editModifier, GitRepositoryManager repositoryManager) {
this.editModifier = editModifier;
this.repositoryManager = repositoryManager;
}
@Override
public Response<?> apply(ChangeEditResource rsrc, Input input)
- throws AuthException, ResourceConflictException, IOException,
- OrmException {
+ throws AuthException, ResourceConflictException, IOException, OrmException {
return apply(rsrc.getControl(), rsrc.getPath(), input.content);
}
- public Response<?> apply(ChangeControl changeControl, String path,
- RawInput newContent) throws ResourceConflictException, AuthException,
- IOException, OrmException {
+ public Response<?> apply(ChangeControl changeControl, String path, RawInput newContent)
+ throws ResourceConflictException, AuthException, IOException, OrmException {
if (Strings.isNullOrEmpty(path) || path.charAt(0) == '/') {
throw new ResourceConflictException("Invalid path: " + path);
}
@@ -363,36 +335,32 @@
/**
* Handler to delete a file.
- * <p>
- * This deletes the file from the repository completely. This is not the same
- * as reverting or restoring a file to its previous contents.
+ *
+ * <p>This deletes the file from the repository completely. This is not the same as reverting or
+ * restoring a file to its previous contents.
*/
@Singleton
- public static class DeleteContent implements
- RestModifyView<ChangeEditResource, DeleteContent.Input> {
- public static class Input {
- }
+ public static class DeleteContent
+ implements RestModifyView<ChangeEditResource, DeleteContent.Input> {
+ public static class Input {}
private final ChangeEditModifier editModifier;
private final GitRepositoryManager repositoryManager;
@Inject
- DeleteContent(ChangeEditModifier editModifier,
- GitRepositoryManager repositoryManager) {
+ DeleteContent(ChangeEditModifier editModifier, GitRepositoryManager repositoryManager) {
this.editModifier = editModifier;
this.repositoryManager = repositoryManager;
}
@Override
public Response<?> apply(ChangeEditResource rsrc, DeleteContent.Input input)
- throws AuthException, ResourceConflictException, OrmException,
- IOException {
+ throws AuthException, ResourceConflictException, OrmException, IOException {
return apply(rsrc.getControl(), rsrc.getPath());
}
public Response<?> apply(ChangeControl changeControl, String filePath)
- throws AuthException, IOException, OrmException,
- ResourceConflictException {
+ throws AuthException, IOException, OrmException, ResourceConflictException {
Project.NameKey project = changeControl.getChange().getProject();
try (Repository repository = repositoryManager.openRepository(project)) {
editModifier.deleteFile(repository, changeControl, filePath);
@@ -406,9 +374,11 @@
public static class Get implements RestReadView<ChangeEditResource> {
private final FileContentUtil fileContentUtil;
- @Option(name = "--base", aliases = {"-b"},
- usage = "whether to load the content on the base revision instead of the"
- + " change edit")
+ @Option(
+ name = "--base",
+ aliases = {"-b"},
+ usage = "whether to load the content on the base revision instead of the" + " change edit"
+ )
private boolean base;
@Inject
@@ -417,17 +387,16 @@
}
@Override
- public Response<BinaryResult> apply(ChangeEditResource rsrc)
- throws IOException {
+ public Response<BinaryResult> apply(ChangeEditResource rsrc) throws IOException {
try {
ChangeEdit edit = rsrc.getChangeEdit();
- return Response.ok(fileContentUtil.getContent(
- rsrc.getControl().getProjectControl().getProjectState(),
- base
- ? ObjectId.fromString(
- edit.getBasePatchSet().getRevision().get())
- : ObjectId.fromString(edit.getRevision().get()),
- rsrc.getPath()));
+ return Response.ok(
+ fileContentUtil.getContent(
+ rsrc.getControl().getProjectControl().getProjectState(),
+ base
+ ? ObjectId.fromString(edit.getBasePatchSet().getRevision().get())
+ : ObjectId.fromString(edit.getRevision().get()),
+ rsrc.getPath()));
} catch (ResourceNotFoundException rnfe) {
return Response.none();
}
@@ -449,7 +418,8 @@
ChangeEdit edit = rsrc.getChangeEdit();
Change change = edit.getChange();
List<DiffWebLinkInfo> links =
- webLinks.getDiffLinks(change.getProject().get(),
+ webLinks.getDiffLinks(
+ change.getProject().get(),
change.getChangeId(),
edit.getBasePatchSet().getPatchSetId(),
edit.getBasePatchSet().getRefName(),
@@ -467,27 +437,24 @@
}
@Singleton
- public static class EditMessage implements
- RestModifyView<ChangeResource, EditMessage.Input> {
+ public static class EditMessage implements RestModifyView<ChangeResource, EditMessage.Input> {
public static class Input {
- @DefaultInput
- public String message;
+ @DefaultInput public String message;
}
private final ChangeEditModifier editModifier;
private final GitRepositoryManager repositoryManager;
@Inject
- EditMessage(ChangeEditModifier editModifier,
- GitRepositoryManager repositoryManager) {
+ EditMessage(ChangeEditModifier editModifier, GitRepositoryManager repositoryManager) {
this.editModifier = editModifier;
this.repositoryManager = repositoryManager;
}
@Override
- public Object apply(ChangeResource rsrc, Input input) throws AuthException,
- IOException, BadRequestException, ResourceConflictException,
- OrmException {
+ public Object apply(ChangeResource rsrc, Input input)
+ throws AuthException, IOException, BadRequestException, ResourceConflictException,
+ OrmException {
if (input == null || Strings.isNullOrEmpty(input.message)) {
throw new BadRequestException("commit message must be provided");
}
@@ -508,29 +475,31 @@
private final GitRepositoryManager repoManager;
private final ChangeEditUtil editUtil;
- @Option(name = "--base", aliases = {"-b"},
- usage = "whether to load the message on the base revision instead"
- + " of the change edit")
+ @Option(
+ name = "--base",
+ aliases = {"-b"},
+ usage = "whether to load the message on the base revision instead" + " of the change edit"
+ )
private boolean base;
@Inject
- GetMessage(GitRepositoryManager repoManager,
- ChangeEditUtil editUtil) {
+ GetMessage(GitRepositoryManager repoManager, ChangeEditUtil editUtil) {
this.repoManager = repoManager;
this.editUtil = editUtil;
}
@Override
- public BinaryResult apply(ChangeResource rsrc) throws AuthException,
- IOException, ResourceNotFoundException, OrmException {
+ public BinaryResult apply(ChangeResource rsrc)
+ throws AuthException, IOException, ResourceNotFoundException, OrmException {
Optional<ChangeEdit> edit = editUtil.byChange(rsrc.getChange());
String msg;
if (edit.isPresent()) {
if (base) {
try (Repository repo = repoManager.openRepository(rsrc.getProject());
RevWalk rw = new RevWalk(repo)) {
- RevCommit commit = rw.parseCommit(ObjectId.fromString(
- edit.get().getBasePatchSet().getRevision().get()));
+ RevCommit commit =
+ rw.parseCommit(
+ ObjectId.fromString(edit.get().getBasePatchSet().getRevision().get()));
msg = commit.getFullMessage();
}
} else {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/ChangeIncludedIn.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/ChangeIncludedIn.java
index 77e6942..f852a97 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/ChangeIncludedIn.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/ChangeIncludedIn.java
@@ -26,7 +26,6 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.io.IOException;
@Singleton
@@ -36,9 +35,7 @@
private IncludedIn includedIn;
@Inject
- ChangeIncludedIn(Provider<ReviewDb> db,
- PatchSetUtil psUtil,
- IncludedIn includedIn) {
+ ChangeIncludedIn(Provider<ReviewDb> db, PatchSetUtil psUtil, IncludedIn includedIn) {
this.db = db;
this.psUtil = psUtil;
this.includedIn = includedIn;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/ChangeInserter.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/ChangeInserter.java
index 1956643..2562557 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/ChangeInserter.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/ChangeInserter.java
@@ -63,14 +63,6 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
-
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.revwalk.RevCommit;
-import org.eclipse.jgit.transport.ReceiveCommand;
-import org.eclipse.jgit.util.ChangeIdUtil;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
@@ -78,14 +70,19 @@
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.revwalk.RevCommit;
+import org.eclipse.jgit.transport.ReceiveCommand;
+import org.eclipse.jgit.util.ChangeIdUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class ChangeInserter extends BatchUpdate.InsertChangeOp {
public interface Factory {
ChangeInserter create(Change.Id cid, RevCommit rc, String refName);
}
- private static final Logger log =
- LoggerFactory.getLogger(ChangeInserter.class);
+ private static final Logger log = LoggerFactory.getLogger(ChangeInserter.class);
private final ProjectControl.GenericFactory projectControlFactory;
private final IdentifiedUser.GenericFactory userFactory;
@@ -111,11 +108,9 @@
private String message;
private String patchSetDescription;
private List<String> groups = Collections.emptyList();
- private CommitValidators.Policy validatePolicy =
- CommitValidators.Policy.GERRIT;
+ private CommitValidators.Policy validatePolicy = CommitValidators.Policy.GERRIT;
private NotifyHandling notify = NotifyHandling.ALL;
- private ListMultimap<RecipientType, Account.Id> accountsToNotify =
- ImmutableListMultimap.of();
+ private ListMultimap<RecipientType, Account.Id> accountsToNotify = ImmutableListMultimap.of();
private Set<Account.Id> reviewers;
private Set<Account.Id> extraCC;
private Map<String, Short> approvals;
@@ -133,7 +128,8 @@
private String pushCert;
@Inject
- ChangeInserter(ProjectControl.GenericFactory projectControlFactory,
+ ChangeInserter(
+ ProjectControl.GenericFactory projectControlFactory,
IdentifiedUser.GenericFactory userFactory,
ChangeControl.GenericFactory changeControlFactory,
PatchSetInfoFactory patchSetInfoFactory,
@@ -176,12 +172,13 @@
@Override
public Change createChange(Context ctx) {
- change = new Change(
- getChangeKey(commit),
- changeId,
- ctx.getAccountId(),
- new Branch.NameKey(ctx.getProject(), refName),
- ctx.getWhen());
+ change =
+ new Change(
+ getChangeKey(commit),
+ changeId,
+ ctx.getAccountId(),
+ new Branch.NameKey(ctx.getProject(), refName),
+ ctx.getWhen());
change.setStatus(MoreObjects.firstNonNull(status, Change.Status.NEW));
change.setTopic(topic);
return change;
@@ -192,9 +189,13 @@
if (!idList.isEmpty()) {
return new Change.Key(idList.get(idList.size() - 1).trim());
}
- ObjectId id = ChangeIdUtil.computeChangeId(commit.getTree(), commit,
- commit.getAuthorIdent(), commit.getCommitterIdent(),
- commit.getShortMessage());
+ ObjectId id =
+ ChangeIdUtil.computeChangeId(
+ commit.getTree(),
+ commit,
+ commit.getAuthorIdent(),
+ commit.getCommitterIdent(),
+ commit.getShortMessage());
StringBuilder changeId = new StringBuilder();
changeId.append("I").append(ObjectId.toString(id));
return new Change.Key(changeId.toString());
@@ -256,22 +257,19 @@
}
public ChangeInserter setDraft(boolean draft) {
- checkState(change == null,
- "setDraft(boolean) only valid before creating change");
+ checkState(change == null, "setDraft(boolean) only valid before creating change");
return setStatus(draft ? Change.Status.DRAFT : Change.Status.NEW);
}
public ChangeInserter setStatus(Change.Status status) {
- checkState(change == null,
- "setStatus(Change.Status) only valid before creating change");
+ checkState(change == null, "setStatus(Change.Status) only valid before creating change");
this.status = status;
return this;
}
public ChangeInserter setGroups(List<String> groups) {
checkNotNull(groups, "groups may not be empty");
- checkState(patchSet == null,
- "setGroups(Iterable<String>) only valid before creating change");
+ checkState(patchSet == null, "setGroups(Iterable<String>) only valid before creating change");
this.groups = groups;
return this;
}
@@ -300,8 +298,7 @@
}
public PatchSet getPatchSet() {
- checkState(patchSet != null,
- "getPatchSet() only valid after creating change");
+ checkState(patchSet != null, "getPatchSet() only valid after creating change");
return patchSet;
}
@@ -319,21 +316,18 @@
if (message == null) {
return null;
}
- checkState(changeMessage != null,
- "getChangeMessage() only valid after inserting change");
+ checkState(changeMessage != null, "getChangeMessage() only valid after inserting change");
return changeMessage;
}
@Override
- public void updateRepo(RepoContext ctx)
- throws ResourceConflictException, IOException {
+ public void updateRepo(RepoContext ctx) throws ResourceConflictException, IOException {
validate(ctx);
if (!updateRef) {
return;
}
if (updateRefCommand == null) {
- ctx.addRefUpdate(
- new ReceiveCommand(ObjectId.zeroId(), commit, psId.toRefName()));
+ ctx.addRefUpdate(new ReceiveCommand(ObjectId.zeroId(), commit, psId.toRefName()));
} else {
ctx.addRefUpdate(updateRefCommand);
}
@@ -359,8 +353,17 @@
if (newGroups.isEmpty()) {
newGroups = GroupCollector.getDefaultGroups(commit);
}
- patchSet = psUtil.insert(ctx.getDb(), ctx.getRevWalk(), update, psId,
- commit, draft, newGroups, pushCert, patchSetDescription);
+ patchSet =
+ psUtil.insert(
+ ctx.getDb(),
+ ctx.getRevWalk(),
+ update,
+ psId,
+ commit,
+ draft,
+ newGroups,
+ pushCert,
+ patchSetDescription);
/* TODO: fixStatus is used here because the tests
* (byStatusClosed() in AbstractQueryChangesTest)
@@ -373,30 +376,39 @@
update.fixStatus(change.getStatus());
LabelTypes labelTypes = ctl.getProjectControl().getLabelTypes();
- approvalsUtil.addReviewers(db, update, labelTypes, change, patchSet,
+ approvalsUtil.addReviewers(
+ db,
+ update,
+ labelTypes,
+ change,
+ patchSet,
patchSetInfo,
filterOnChangeVisibility(db, ctx.getNotes(), reviewers),
- Collections.<Account.Id> emptySet());
+ Collections.<Account.Id>emptySet());
approvalsUtil.addApprovalsForNewPatchSet(
db, update, labelTypes, patchSet, ctx.getControl(), approvals);
if (message != null) {
- changeMessage = ChangeMessagesUtil.newMessage(
- patchSet.getId(), ctx.getUser(), patchSet.getCreatedOn(),
- message, ChangeMessagesUtil.TAG_UPLOADED_PATCH_SET);
+ changeMessage =
+ ChangeMessagesUtil.newMessage(
+ patchSet.getId(),
+ ctx.getUser(),
+ patchSet.getCreatedOn(),
+ message,
+ ChangeMessagesUtil.TAG_UPLOADED_PATCH_SET);
cmUtil.addChangeMessage(db, update, changeMessage);
}
return true;
}
- private Set<Account.Id> filterOnChangeVisibility(final ReviewDb db,
- final ChangeNotes notes, Set<Account.Id> accounts) {
- return accounts.stream()
+ private Set<Account.Id> filterOnChangeVisibility(
+ final ReviewDb db, final ChangeNotes notes, Set<Account.Id> accounts) {
+ return accounts
+ .stream()
.filter(
accountId -> {
try {
IdentifiedUser user = userFactory.create(accountId);
- return changeControlFactory.controlFor(notes, user)
- .isVisible(db);
+ return changeControlFactory.controlFor(notes, user).isVisible(db);
} catch (OrmException e) {
log.warn(
String.format(
@@ -411,31 +423,31 @@
@Override
public void postUpdate(Context ctx) throws OrmException {
- if (sendMail
- && (notify != NotifyHandling.NONE || !accountsToNotify.isEmpty())) {
- Runnable sender = new Runnable() {
- @Override
- public void run() {
- try {
- CreateChangeSender cm = createChangeSenderFactory
- .create(change.getProject(), change.getId());
- cm.setFrom(change.getOwner());
- cm.setPatchSet(patchSet, patchSetInfo);
- cm.setNotify(notify);
- cm.setAccountsToNotify(accountsToNotify);
- cm.addReviewers(reviewers);
- cm.addExtraCC(extraCC);
- cm.send();
- } catch (Exception e) {
- log.error("Cannot send email for new change " + change.getId(), e);
- }
- }
+ if (sendMail && (notify != NotifyHandling.NONE || !accountsToNotify.isEmpty())) {
+ Runnable sender =
+ new Runnable() {
+ @Override
+ public void run() {
+ try {
+ CreateChangeSender cm =
+ createChangeSenderFactory.create(change.getProject(), change.getId());
+ cm.setFrom(change.getOwner());
+ cm.setPatchSet(patchSet, patchSetInfo);
+ cm.setNotify(notify);
+ cm.setAccountsToNotify(accountsToNotify);
+ cm.addReviewers(reviewers);
+ cm.addExtraCC(extraCC);
+ cm.send();
+ } catch (Exception e) {
+ log.error("Cannot send email for new change " + change.getId(), e);
+ }
+ }
- @Override
- public String toString() {
- return "send-email newchange";
- }
- };
+ @Override
+ public String toString() {
+ return "send-email newchange";
+ }
+ };
if (requestScopePropagator != null) {
sendEmailExecutor.submit(requestScopePropagator.wrap(sender));
} else {
@@ -449,11 +461,10 @@
* show a transition from an oldValue of 0 to the new value.
*/
if (fireRevisionCreated) {
- revisionCreated.fire(change, patchSet, ctx.getAccount(),
- ctx.getWhen(), notify);
+ revisionCreated.fire(change, patchSet, ctx.getAccount(), ctx.getWhen(), notify);
if (approvals != null && !approvals.isEmpty()) {
- ChangeControl changeControl = changeControlFactory.controlFor(
- ctx.getDb(), change, ctx.getUser());
+ ChangeControl changeControl =
+ changeControlFactory.controlFor(ctx.getDb(), change, ctx.getUser());
List<LabelType> labels = changeControl.getLabelTypes().getLabelTypes();
Map<String, Short> allApprovals = new HashMap<>();
Map<String, Short> oldApprovals = new HashMap<>();
@@ -467,35 +478,30 @@
oldApprovals.put(entry.getKey(), (short) 0);
}
}
- commentAdded.fire(change, patchSet,
- ctx.getAccount(), null,
- allApprovals, oldApprovals, ctx.getWhen());
+ commentAdded.fire(
+ change, patchSet, ctx.getAccount(), null, allApprovals, oldApprovals, ctx.getWhen());
}
}
}
- private void validate(RepoContext ctx)
- throws IOException, ResourceConflictException {
+ private void validate(RepoContext ctx) throws IOException, ResourceConflictException {
if (validatePolicy == CommitValidators.Policy.NONE) {
return;
}
try {
- RefControl refControl = projectControlFactory
- .controlFor(ctx.getProject(), ctx.getUser()).controlForRef(refName);
+ RefControl refControl =
+ projectControlFactory.controlFor(ctx.getProject(), ctx.getUser()).controlForRef(refName);
String refName = psId.toRefName();
- CommitReceivedEvent event = new CommitReceivedEvent(
- new ReceiveCommand(
- ObjectId.zeroId(),
- commit.getId(),
- refName),
- refControl.getProjectControl().getProject(),
- change.getDest().get(),
- commit,
- ctx.getIdentifiedUser());
+ CommitReceivedEvent event =
+ new CommitReceivedEvent(
+ new ReceiveCommand(ObjectId.zeroId(), commit.getId(), refName),
+ refControl.getProjectControl().getProject(),
+ change.getDest().get(),
+ commit,
+ ctx.getIdentifiedUser());
commitValidatorsFactory
- .create(
- validatePolicy, refControl, new NoSshInfo(), ctx.getRepository())
+ .create(validatePolicy, refControl, new NoSshInfo(), ctx.getRepository())
.validate(event);
} catch (CommitValidationException e) {
throw new ResourceConflictException(e.getFullMessage());
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/ChangeJson.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/ChangeJson.java
index f4d7f8a..8e1ab10 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/ChangeJson.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/ChangeJson.java
@@ -121,15 +121,6 @@
import com.google.inject.Provider;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
-
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.lib.Ref;
-import org.eclipse.jgit.lib.Repository;
-import org.eclipse.jgit.revwalk.RevCommit;
-import org.eclipse.jgit.revwalk.RevWalk;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
@@ -144,6 +135,13 @@
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.lib.Ref;
+import org.eclipse.jgit.lib.Repository;
+import org.eclipse.jgit.revwalk.RevCommit;
+import org.eclipse.jgit.revwalk.RevWalk;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class ChangeJson {
private static final Logger log = LoggerFactory.getLogger(ChangeJson.class);
@@ -152,19 +150,12 @@
// efficiency reasons. Callers that care about submittability after taking
// vote squashing into account should be looking at the submit action.
public static final SubmitRuleOptions SUBMIT_RULE_OPTIONS_LENIENT =
- ChangeField.SUBMIT_RULE_OPTIONS_LENIENT
- .toBuilder()
- .fastEvalLabels(true)
- .build();
+ ChangeField.SUBMIT_RULE_OPTIONS_LENIENT.toBuilder().fastEvalLabels(true).build();
public static final SubmitRuleOptions SUBMIT_RULE_OPTIONS_STRICT =
- ChangeField.SUBMIT_RULE_OPTIONS_STRICT
- .toBuilder()
- .fastEvalLabels(true)
- .build();
+ ChangeField.SUBMIT_RULE_OPTIONS_STRICT.toBuilder().fastEvalLabels(true).build();
- public static final Set<ListChangesOption> NO_OPTIONS =
- Collections.emptySet();
+ public static final Set<ListChangesOption> NO_OPTIONS = Collections.emptySet();
public static final ImmutableSet<ListChangesOption> REQUIRE_LAZY_LOAD =
ImmutableSet.of(ALL_REVISIONS, MESSAGES);
@@ -251,9 +242,8 @@
this.changeKindCache = changeKindCache;
this.indexes = indexes;
this.approvalsUtil = approvalsUtil;
- this.options = options.isEmpty()
- ? EnumSet.noneOf(ListChangesOption.class)
- : EnumSet.copyOf(options);
+ this.options =
+ options.isEmpty() ? EnumSet.noneOf(ListChangesOption.class) : EnumSet.copyOf(options);
}
public ChangeJson lazyLoad(boolean load) {
@@ -274,8 +264,7 @@
return format(changeDataFactory.create(db.get(), change));
}
- public ChangeInfo format(Project.NameKey project, Change.Id id)
- throws OrmException {
+ public ChangeInfo format(Project.NameKey project, Change.Id id) throws OrmException {
ChangeNotes notes;
try {
notes = notesFactory.createChecked(db.get(), project, id);
@@ -292,8 +281,8 @@
return format(cd, Optional.empty(), true);
}
- private ChangeInfo format(ChangeData cd, Optional<PatchSet.Id> limitToPsId,
- boolean fillAccountLoader)
+ private ChangeInfo format(
+ ChangeData cd, Optional<PatchSet.Id> limitToPsId, boolean fillAccountLoader)
throws OrmException {
try {
if (fillAccountLoader) {
@@ -303,8 +292,11 @@
return res;
}
return toChangeInfo(cd, limitToPsId);
- } catch (PatchListNotAvailableException | GpgException | OrmException
- | IOException | RuntimeException e) {
+ } catch (PatchListNotAvailableException
+ | GpgException
+ | OrmException
+ | IOException
+ | RuntimeException e) {
if (!has(CHECK)) {
Throwables.throwIfInstanceOf(e, OrmException.class);
throw new OrmException(e);
@@ -318,11 +310,10 @@
return format(cd, Optional.of(rsrc.getPatchSet().getId()), true);
}
- public List<List<ChangeInfo>> formatQueryResults(
- List<QueryResult<ChangeData>> in) throws OrmException {
+ public List<List<ChangeInfo>> formatQueryResults(List<QueryResult<ChangeData>> in)
+ throws OrmException {
accountLoader = accountLoaderFactory.create(has(DETAILED_ACCOUNTS));
- ensureLoaded(
- FluentIterable.from(in).transformAndConcat(QueryResult::entities));
+ ensureLoaded(FluentIterable.from(in).transformAndConcat(QueryResult::entities));
List<List<ChangeInfo>> res = Lists.newArrayListWithCapacity(in.size());
Map<Change.Id, ChangeInfo> out = new HashMap<>();
@@ -337,8 +328,7 @@
return res;
}
- public List<ChangeInfo> formatChangeDatas(Collection<ChangeData> in)
- throws OrmException {
+ public List<ChangeInfo> formatChangeDatas(Collection<ChangeData> in) throws OrmException {
accountLoader = accountLoaderFactory.create(has(DETAILED_ACCOUNTS));
ensureLoaded(in);
List<ChangeInfo> out = new ArrayList<>(in.size());
@@ -372,21 +362,22 @@
return options.contains(option);
}
- private List<ChangeInfo> toChangeInfo(Map<Change.Id, ChangeInfo> out,
- List<ChangeData> changes) {
+ private List<ChangeInfo> toChangeInfo(Map<Change.Id, ChangeInfo> out, List<ChangeData> changes) {
List<ChangeInfo> info = Lists.newArrayListWithCapacity(changes.size());
for (ChangeData cd : changes) {
ChangeInfo i = out.get(cd.getId());
if (i == null) {
try {
i = toChangeInfo(cd, Optional.empty());
- } catch (PatchListNotAvailableException | GpgException | OrmException
- | IOException | RuntimeException e) {
+ } catch (PatchListNotAvailableException
+ | GpgException
+ | OrmException
+ | IOException
+ | RuntimeException e) {
if (has(CHECK)) {
i = checkOnly(cd);
} else {
- log.warn(
- "Omitting corrupt change " + cd.getId() + " from results", e);
+ log.warn("Omitting corrupt change " + cd.getId() + " from results", e);
continue;
}
}
@@ -437,9 +428,8 @@
return info;
}
- private ChangeInfo toChangeInfo(ChangeData cd,
- Optional<PatchSet.Id> limitToPsId) throws PatchListNotAvailableException,
- GpgException, OrmException, IOException {
+ private ChangeInfo toChangeInfo(ChangeData cd, Optional<PatchSet.Id> limitToPsId)
+ throws PatchListNotAvailableException, GpgException, OrmException, IOException {
ChangeInfo out = new ChangeInfo();
CurrentUser user = userProvider.get();
ChangeControl ctl = cd.changeControl().forUser(user);
@@ -490,9 +480,7 @@
if (user.isIdentifiedUser()) {
Collection<String> stars = cd.stars().get(user.getAccountId());
- out.starred = stars.contains(StarredChangesUtil.DEFAULT_LABEL)
- ? true
- : null;
+ out.starred = stars.contains(StarredChangesUtil.DEFAULT_LABEL) ? true : null;
if (!stars.isEmpty()) {
out.stars = stars;
}
@@ -509,8 +497,7 @@
if (out.labels != null && has(DETAILED_LABELS)) {
// If limited to specific patch sets but not the current patch set, don't
// list permitted labels, since users can't vote on those patch sets.
- if (!limitToPsId.isPresent()
- || limitToPsId.get().equals(in.currentPatchSetId())) {
+ if (!limitToPsId.isPresent() || limitToPsId.get().equals(in.currentPatchSetId())) {
out.permittedLabels =
cd.change().getStatus() != Change.Status.ABANDONED
? permittedLabels(ctl, cd)
@@ -518,10 +505,9 @@
}
out.reviewers = new HashMap<>();
- for (Map.Entry<ReviewerStateInternal, Map<Account.Id, Timestamp>> e
- : cd.reviewers().asTable().rowMap().entrySet()) {
- out.reviewers.put(e.getKey().asReviewerState(),
- toAccountInfo(e.getValue().keySet()));
+ for (Map.Entry<ReviewerStateInternal, Map<Account.Id, Timestamp>> e :
+ cd.reviewers().asTable().rowMap().entrySet()) {
+ out.reviewers.put(e.getKey().asReviewerState(), toAccountInfo(e.getValue().keySet()));
}
out.removableReviewers = removableReviewers(ctl, out);
@@ -532,9 +518,7 @@
}
boolean needMessages = has(MESSAGES);
- boolean needRevisions = has(ALL_REVISIONS)
- || has(CURRENT_REVISION)
- || limitToPsId.isPresent();
+ boolean needRevisions = has(ALL_REVISIONS) || has(CURRENT_REVISION) || limitToPsId.isPresent();
Map<PatchSet.Id, PatchSet> src;
if (needMessages || needRevisions) {
src = loadPatchSets(cd, limitToPsId);
@@ -567,8 +551,7 @@
return out;
}
- private Collection<ReviewerUpdateInfo> reviewerUpdates(ChangeData cd)
- throws OrmException {
+ private Collection<ReviewerUpdateInfo> reviewerUpdates(ChangeData cd) throws OrmException {
List<ReviewerStatusUpdate> reviewerUpdates = cd.reviewerUpdates();
List<ReviewerUpdateInfo> result = new ArrayList<>(reviewerUpdates.size());
for (ReviewerStatusUpdate c : reviewerUpdates) {
@@ -583,17 +566,15 @@
}
private boolean submittable(ChangeData cd) throws OrmException {
- return SubmitRecord.findOkRecord(
- cd.submitRecords(SUBMIT_RULE_OPTIONS_STRICT))
- .isPresent();
+ return SubmitRecord.findOkRecord(cd.submitRecords(SUBMIT_RULE_OPTIONS_STRICT)).isPresent();
}
private List<SubmitRecord> submitRecords(ChangeData cd) throws OrmException {
return cd.submitRecords(SUBMIT_RULE_OPTIONS_LENIENT);
}
- private Map<String, LabelInfo> labelsFor(ChangeControl ctl,
- ChangeData cd, boolean standard, boolean detailed) throws OrmException {
+ private Map<String, LabelInfo> labelsFor(
+ ChangeControl ctl, ChangeData cd, boolean standard, boolean detailed) throws OrmException {
if (!standard && !detailed) {
return null;
}
@@ -603,15 +584,15 @@
}
LabelTypes labelTypes = ctl.getLabelTypes();
- Map<String, LabelWithStatus> withStatus = cd.change().getStatus().isOpen()
- ? labelsForOpenChange(ctl, cd, labelTypes, standard, detailed)
- : labelsForClosedChange(ctl, cd, labelTypes, standard, detailed);
- return ImmutableMap.copyOf(
- Maps.transformValues(withStatus, LabelWithStatus::label));
+ Map<String, LabelWithStatus> withStatus =
+ cd.change().getStatus().isOpen()
+ ? labelsForOpenChange(ctl, cd, labelTypes, standard, detailed)
+ : labelsForClosedChange(ctl, cd, labelTypes, standard, detailed);
+ return ImmutableMap.copyOf(Maps.transformValues(withStatus, LabelWithStatus::label));
}
- private Map<String, LabelWithStatus> labelsForOpenChange(ChangeControl ctl,
- ChangeData cd, LabelTypes labelTypes, boolean standard, boolean detailed)
+ private Map<String, LabelWithStatus> labelsForOpenChange(
+ ChangeControl ctl, ChangeData cd, LabelTypes labelTypes, boolean standard, boolean detailed)
throws OrmException {
Map<String, LabelWithStatus> labels = initLabels(cd, labelTypes, standard);
if (detailed) {
@@ -638,8 +619,8 @@
return labels;
}
- private Map<String, LabelWithStatus> initLabels(ChangeData cd,
- LabelTypes labelTypes, boolean standard) throws OrmException {
+ private Map<String, LabelWithStatus> initLabels(
+ ChangeData cd, LabelTypes labelTypes, boolean standard) throws OrmException {
// Don't use Maps.newTreeMap(Comparator) due to OpenJDK bug 100167.
Map<String, LabelWithStatus> labels = new TreeMap<>(labelTypes.nameComparator());
for (SubmitRecord rec : submitRecords(cd)) {
@@ -675,8 +656,8 @@
return labels;
}
- private void setLabelScores(LabelType type,
- LabelWithStatus l, short score, Account.Id accountId) {
+ private void setLabelScores(
+ LabelType type, LabelWithStatus l, short score, Account.Id accountId) {
if (l.label().approved != null || l.label().rejected != null) {
return;
}
@@ -701,11 +682,11 @@
}
}
- private void setAllApprovals(ChangeControl baseCtrl, ChangeData cd,
- Map<String, LabelWithStatus> labels) throws OrmException {
+ private void setAllApprovals(
+ ChangeControl baseCtrl, ChangeData cd, Map<String, LabelWithStatus> labels)
+ throws OrmException {
Change.Status status = cd.change().getStatus();
- checkState(status.isOpen(),
- "should not call setAllApprovals on %s change", status);
+ checkState(status.isOpen(), "should not call setAllApprovals on %s change", status);
// Include a user in the output for this label if either:
// - They are an explicit reviewer.
@@ -716,8 +697,8 @@
allUsers.add(psa.getAccountId());
}
- Table<Account.Id, String, PatchSetApproval> current = HashBasedTable.create(
- allUsers.size(), baseCtrl.getLabelTypes().getLabelTypes().size());
+ Table<Account.Id, String, PatchSetApproval> current =
+ HashBasedTable.create(allUsers.size(), baseCtrl.getLabelTypes().getLabelTypes().size());
for (PatchSetApproval psa : cd.currentApprovals()) {
current.put(psa.getAccountId(), psa.getLabel(), psa);
}
@@ -725,8 +706,7 @@
for (Account.Id accountId : allUsers) {
IdentifiedUser user = userFactory.create(accountId);
ChangeControl ctl = baseCtrl.forUser(user);
- Map<String, VotingRangeInfo> pvr =
- getPermittedVotingRanges(permittedLabels(ctl, cd));
+ Map<String, VotingRangeInfo> pvr = getPermittedVotingRanges(permittedLabels(ctl, cd));
for (Map.Entry<String, LabelWithStatus> e : labels.entrySet()) {
LabelType lt = ctl.getLabelTypes().byLabel(e.getKey());
if (lt == null) {
@@ -735,8 +715,7 @@
continue;
}
Integer value;
- VotingRangeInfo permittedVotingRange =
- pvr.getOrDefault(lt.getName(), null);
+ VotingRangeInfo permittedVotingRange = pvr.getOrDefault(lt.getName(), null);
String tag = null;
Timestamp date = null;
PatchSetApproval psa = current.get(accountId, lt.getName());
@@ -759,8 +738,8 @@
// user can vote on this label.
value = labelNormalizer.canVote(ctl, lt, accountId) ? 0 : null;
}
- addApproval(e.getValue().label(),
- approvalInfo(accountId, value, permittedVotingRange, tag, date));
+ addApproval(
+ e.getValue().label(), approvalInfo(accountId, value, permittedVotingRange, tag, date));
}
}
}
@@ -768,22 +747,23 @@
private Map<String, VotingRangeInfo> getPermittedVotingRanges(
Map<String, Collection<String>> permittedLabels) {
Map<String, VotingRangeInfo> permittedVotingRanges =
- Maps.newHashMapWithExpectedSize(permittedLabels.size());
+ Maps.newHashMapWithExpectedSize(permittedLabels.size());
for (String label : permittedLabels.keySet()) {
- List<Integer> permittedVotingRange = permittedLabels.get(label)
- .stream()
- .map(this::parseRangeValue)
- .filter(java.util.Objects::nonNull)
- .sorted()
- .collect(toList());
+ List<Integer> permittedVotingRange =
+ permittedLabels
+ .get(label)
+ .stream()
+ .map(this::parseRangeValue)
+ .filter(java.util.Objects::nonNull)
+ .sorted()
+ .collect(toList());
if (permittedVotingRange.isEmpty()) {
permittedVotingRanges.put(label, null);
} else {
int minPermittedValue = permittedVotingRange.get(0);
int maxPermittedValue = Iterables.getLast(permittedVotingRange);
- permittedVotingRanges.put(label,
- new VotingRangeInfo(minPermittedValue, maxPermittedValue));
+ permittedVotingRanges.put(label, new VotingRangeInfo(minPermittedValue, maxPermittedValue));
}
}
return permittedVotingRanges;
@@ -798,15 +778,17 @@
return Ints.tryParse(value);
}
- private Timestamp getSubmittedOn(ChangeData cd)
- throws OrmException {
+ private Timestamp getSubmittedOn(ChangeData cd) throws OrmException {
Optional<PatchSetApproval> s = cd.getSubmitApproval();
return s.isPresent() ? s.get().getGranted() : null;
}
private Map<String, LabelWithStatus> labelsForClosedChange(
- ChangeControl baseCtrl, ChangeData cd, LabelTypes labelTypes,
- boolean standard, boolean detailed)
+ ChangeControl baseCtrl,
+ ChangeData cd,
+ LabelTypes labelTypes,
+ boolean standard,
+ boolean detailed)
throws OrmException {
Set<Account.Id> allUsers = new HashSet<>();
if (detailed) {
@@ -864,15 +846,15 @@
}
if (detailed) {
- labels.entrySet().stream()
+ labels
+ .entrySet()
+ .stream()
.filter(e -> labelTypes.byLabel(e.getKey()) != null)
- .forEach(e -> setLabelValues(labelTypes.byLabel(e.getKey()),
- e.getValue()));
+ .forEach(e -> setLabelValues(labelTypes.byLabel(e.getKey()), e.getValue()));
}
for (Account.Id accountId : allUsers) {
- Map<String, ApprovalInfo> byLabel =
- Maps.newHashMapWithExpectedSize(labels.size());
+ Map<String, ApprovalInfo> byLabel = Maps.newHashMapWithExpectedSize(labels.size());
Map<String, VotingRangeInfo> pvr = Collections.emptyMap();
if (detailed) {
ChangeControl ctl = baseCtrl.forUser(userFactory.create(accountId));
@@ -910,15 +892,23 @@
return labels;
}
- private ApprovalInfo approvalInfo(Account.Id id, Integer value,
- VotingRangeInfo permittedVotingRange, String tag, Timestamp date) {
+ private ApprovalInfo approvalInfo(
+ Account.Id id,
+ Integer value,
+ VotingRangeInfo permittedVotingRange,
+ String tag,
+ Timestamp date) {
ApprovalInfo ai = getApprovalInfo(id, value, permittedVotingRange, tag, date);
accountLoader.put(ai);
return ai;
}
- public static ApprovalInfo getApprovalInfo(Account.Id id, Integer value,
- VotingRangeInfo permittedVotingRange, String tag, Timestamp date) {
+ public static ApprovalInfo getApprovalInfo(
+ Account.Id id,
+ Integer value,
+ VotingRangeInfo permittedVotingRange,
+ String tag,
+ Timestamp date) {
ApprovalInfo ai = new ApprovalInfo(id.get());
ai.value = value;
ai.permittedVotingRange = permittedVotingRange;
@@ -977,10 +967,8 @@
}
}
}
- List<String> toClear =
- Lists.newArrayListWithCapacity(permitted.keySet().size());
- for (Map.Entry<String, Collection<String>> e
- : permitted.asMap().entrySet()) {
+ List<String> toClear = Lists.newArrayListWithCapacity(permitted.keySet().size());
+ for (Map.Entry<String, Collection<String>> e : permitted.asMap().entrySet()) {
if (isOnlyZero(e.getValue())) {
toClear.add(e.getKey());
}
@@ -991,27 +979,24 @@
return permitted.asMap();
}
- private Map<String, Short> currentLabels(ChangeControl ctl)
- throws OrmException {
+ private Map<String, Short> currentLabels(ChangeControl ctl) throws OrmException {
Map<String, Short> result = new HashMap<>();
- for (PatchSetApproval psa : approvalsUtil.byPatchSetUser(
- db.get(), ctl, ctl.getChange().currentPatchSetId(),
- ctl.getUser().getAccountId())) {
+ for (PatchSetApproval psa :
+ approvalsUtil.byPatchSetUser(
+ db.get(), ctl, ctl.getChange().currentPatchSetId(), ctl.getUser().getAccountId())) {
result.put(psa.getLabel(), psa.getValue());
}
return result;
}
- private Collection<ChangeMessageInfo> messages(ChangeControl ctl, ChangeData cd,
- Map<PatchSet.Id, PatchSet> map)
- throws OrmException {
+ private Collection<ChangeMessageInfo> messages(
+ ChangeControl ctl, ChangeData cd, Map<PatchSet.Id, PatchSet> map) throws OrmException {
List<ChangeMessage> messages = cmUtil.byChange(db.get(), cd.notes());
if (messages.isEmpty()) {
return Collections.emptyList();
}
- List<ChangeMessageInfo> result =
- Lists.newArrayListWithCapacity(messages.size());
+ List<ChangeMessageInfo> result = Lists.newArrayListWithCapacity(messages.size());
for (ChangeMessage message : messages) {
PatchSet.Id patchNum = message.getPatchSetId();
PatchSet ps = patchNum != null ? map.get(patchNum) : null;
@@ -1029,8 +1014,7 @@
return result;
}
- private Collection<AccountInfo> removableReviewers(ChangeControl ctl,
- ChangeInfo out) {
+ private Collection<AccountInfo> removableReviewers(ChangeControl ctl, ChangeInfo out) {
// Although this is called removableReviewers, this method also determines
// which CCs are removable.
//
@@ -1084,9 +1068,9 @@
return result;
}
- private Collection<AccountInfo> toAccountInfo(
- Collection<Account.Id> accounts) {
- return accounts.stream()
+ private Collection<AccountInfo> toAccountInfo(Collection<Account.Id> accounts) {
+ return accounts
+ .stream()
.map(accountLoader::get)
.sorted(AccountInfoComparator.ORDER_NULLS_FIRST)
.collect(toList());
@@ -1100,26 +1084,23 @@
return null;
}
- private Map<String, RevisionInfo> revisions(ChangeControl ctl, ChangeData cd,
- Map<PatchSet.Id, PatchSet> map, ChangeInfo changeInfo)
- throws PatchListNotAvailableException, GpgException, OrmException,
- IOException {
+ private Map<String, RevisionInfo> revisions(
+ ChangeControl ctl, ChangeData cd, Map<PatchSet.Id, PatchSet> map, ChangeInfo changeInfo)
+ throws PatchListNotAvailableException, GpgException, OrmException, IOException {
Map<String, RevisionInfo> res = new LinkedHashMap<>();
try (Repository repo = openRepoIfNecessary(ctl)) {
for (PatchSet in : map.values()) {
- if ((has(ALL_REVISIONS)
- || in.getId().equals(ctl.getChange().currentPatchSetId()))
+ if ((has(ALL_REVISIONS) || in.getId().equals(ctl.getChange().currentPatchSetId()))
&& ctl.isPatchVisible(in, db.get())) {
- res.put(in.getRevision().get(),
- toRevisionInfo(ctl, cd, in, repo, false, changeInfo));
+ res.put(in.getRevision().get(), toRevisionInfo(ctl, cd, in, repo, false, changeInfo));
}
}
return res;
}
}
- private Map<PatchSet.Id, PatchSet> loadPatchSets(ChangeData cd,
- Optional<PatchSet.Id> limitToPsId) throws OrmException {
+ private Map<PatchSet.Id, PatchSet> loadPatchSets(ChangeData cd, Optional<PatchSet.Id> limitToPsId)
+ throws OrmException {
Collection<PatchSet> src;
if (has(ALL_REVISIONS) || has(MESSAGES)) {
src = cd.patchSets();
@@ -1133,8 +1114,7 @@
} else {
ps = cd.currentPatchSet();
if (ps == null) {
- throw new OrmException(
- "missing current patch set for change " + cd.getId());
+ throw new OrmException("missing current patch set for change " + cd.getId());
}
}
src = Collections.singletonList(ps);
@@ -1147,21 +1127,24 @@
}
public RevisionInfo getRevisionInfo(ChangeControl ctl, PatchSet in)
- throws PatchListNotAvailableException, GpgException, OrmException,
- IOException {
+ throws PatchListNotAvailableException, GpgException, OrmException, IOException {
accountLoader = accountLoaderFactory.create(has(DETAILED_ACCOUNTS));
try (Repository repo = openRepoIfNecessary(ctl)) {
- RevisionInfo rev = toRevisionInfo(
- ctl, changeDataFactory.create(db.get(), ctl), in, repo, true, null);
+ RevisionInfo rev =
+ toRevisionInfo(ctl, changeDataFactory.create(db.get(), ctl), in, repo, true, null);
accountLoader.fill();
return rev;
}
}
- private RevisionInfo toRevisionInfo(ChangeControl ctl, ChangeData cd,
- PatchSet in, @Nullable Repository repo, boolean fillCommit,
- @Nullable ChangeInfo changeInfo) throws PatchListNotAvailableException,
- GpgException, OrmException, IOException {
+ private RevisionInfo toRevisionInfo(
+ ChangeControl ctl,
+ ChangeData cd,
+ PatchSet in,
+ @Nullable Repository repo,
+ boolean fillCommit,
+ @Nullable ChangeInfo changeInfo)
+ throws PatchListNotAvailableException, GpgException, OrmException, IOException {
Change c = ctl.getChange();
RevisionInfo out = new RevisionInfo();
out.isCurrent = in.getId().equals(c.currentPatchSetId());
@@ -1174,8 +1157,7 @@
out.kind = changeKindCache.getChangeKind(repo, cd, in);
out.description = in.getDescription();
- boolean setCommit = has(ALL_COMMITS)
- || (out.isCurrent && has(CURRENT_COMMIT));
+ boolean setCommit = has(ALL_COMMITS) || (out.isCurrent && has(CURRENT_COMMIT));
boolean addFooters = out.isCurrent && has(COMMIT_FOOTERS);
if (setCommit || addFooters) {
Project.NameKey project = c.getProject();
@@ -1189,13 +1171,14 @@
if (addFooters) {
Ref ref = repo.exactRef(ctl.getChange().getDest().get());
RevCommit mergeTip = null;
- if (ref != null){
+ if (ref != null) {
mergeTip = rw.parseCommit(ref.getObjectId());
rw.parseBody(mergeTip);
}
- out.commitWithFooters = mergeUtilFactory
- .create(projectCache.get(project))
- .createCommitMessageOnSubmit(commit, mergeTip, ctl, in.getId());
+ out.commitWithFooters =
+ mergeUtilFactory
+ .create(projectCache.get(project))
+ .createCommitMessageOnSubmit(commit, mergeTip, ctl, in.getId());
}
}
}
@@ -1210,15 +1193,15 @@
&& has(CURRENT_ACTIONS)
&& userProvider.get().isIdentifiedUser()) {
- actionJson.addRevisionActions(changeInfo, out,
- new RevisionResource(changeResourceFactory.create(ctl), in));
+ actionJson.addRevisionActions(
+ changeInfo, out, new RevisionResource(changeResourceFactory.create(ctl), in));
}
if (gpgApi.isEnabled() && has(PUSH_CERTIFICATES)) {
if (in.getPushCertificate() != null) {
- out.pushCertificate = gpgApi.checkPushCertificate(
- in.getPushCertificate(),
- userFactory.create(in.getUploader()));
+ out.pushCertificate =
+ gpgApi.checkPushCertificate(
+ in.getPushCertificate(), userFactory.create(in.getUploader()));
} else {
out.pushCertificate = new PushCertificateInfo();
}
@@ -1227,8 +1210,9 @@
return out;
}
- CommitInfo toCommit(ChangeControl ctl, RevWalk rw, RevCommit commit,
- boolean addLinks, boolean fillCommit) throws IOException {
+ CommitInfo toCommit(
+ ChangeControl ctl, RevWalk rw, RevCommit commit, boolean addLinks, boolean fillCommit)
+ throws IOException {
Project.NameKey project = ctl.getProject().getNameKey();
CommitInfo info = new CommitInfo();
if (fillCommit) {
@@ -1241,8 +1225,7 @@
info.message = commit.getFullMessage();
if (addLinks) {
- List<WebLinkInfo> links =
- webLinks.getPatchSetLinks(project, commit.name());
+ List<WebLinkInfo> links = webLinks.getPatchSetLinks(project, commit.name());
info.webLinks = links.isEmpty() ? null : links;
}
@@ -1252,8 +1235,7 @@
i.commit = parent.name();
i.subject = parent.getShortMessage();
if (addLinks) {
- List<WebLinkInfo> parentLinks =
- webLinks.getParentLinks(project, parent.name());
+ List<WebLinkInfo> parentLinks = webLinks.getParentLinks(project, parent.name());
i.webLinks = parentLinks.isEmpty() ? null : parentLinks;
}
info.parents.add(i);
@@ -1261,8 +1243,7 @@
return info;
}
- private Map<String, FetchInfo> makeFetchMap(ChangeControl ctl, PatchSet in)
- throws OrmException {
+ private Map<String, FetchInfo> makeFetchMap(ChangeControl ctl, PatchSet in) throws OrmException {
Map<String, FetchInfo> r = new LinkedHashMap<>();
for (DynamicMap.Entry<DownloadScheme> e : downloadSchemes) {
@@ -1273,8 +1254,7 @@
continue;
}
- if (!scheme.isAuthSupported()
- && !ctl.forUser(anonymous).isPatchVisible(in, db.get())) {
+ if (!scheme.isAuthSupported() && !ctl.forUser(anonymous).isPatchVisible(in, db.get())) {
continue;
}
@@ -1285,17 +1265,19 @@
r.put(schemeName, fetchInfo);
if (has(DOWNLOAD_COMMANDS)) {
- populateFetchMap(scheme, downloadCommands, projectName, refName,
- fetchInfo);
+ populateFetchMap(scheme, downloadCommands, projectName, refName, fetchInfo);
}
}
return r;
}
- public static void populateFetchMap(DownloadScheme scheme,
- DynamicMap<DownloadCommand> commands, String projectName,
- String refName, FetchInfo fetchInfo) {
+ public static void populateFetchMap(
+ DownloadScheme scheme,
+ DynamicMap<DownloadCommand> commands,
+ String projectName,
+ String refName,
+ FetchInfo fetchInfo) {
for (DynamicMap.Entry<DownloadCommand> e2 : commands) {
String commandName = e2.getExportName();
DownloadCommand command = e2.getProvider().get();
@@ -1306,8 +1288,7 @@
}
}
- private static void addCommand(FetchInfo fetchInfo, String commandName,
- String c) {
+ private static void addCommand(FetchInfo fetchInfo, String commandName, String c) {
if (fetchInfo.commands == null) {
fetchInfo.commands = new TreeMap<>();
}
@@ -1315,10 +1296,9 @@
}
static void finish(ChangeInfo info) {
- info.id = Joiner.on('~').join(
- Url.encode(info.project),
- Url.encode(info.branch),
- Url.encode(info.changeId));
+ info.id =
+ Joiner.on('~')
+ .join(Url.encode(info.project), Url.encode(info.branch), Url.encode(info.changeId));
}
private static void addApproval(LabelInfo label, ApprovalInfo approval) {
@@ -1330,12 +1310,13 @@
@AutoValue
abstract static class LabelWithStatus {
- private static LabelWithStatus create(LabelInfo label,
- SubmitRecord.Label.Status status) {
+ private static LabelWithStatus create(LabelInfo label, SubmitRecord.Label.Status status) {
return new AutoValue_ChangeJson_LabelWithStatus(label, status);
}
abstract LabelInfo label();
- @Nullable abstract SubmitRecord.Label.Status status();
+
+ @Nullable
+ abstract SubmitRecord.Label.Status status();
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/ChangeKindCache.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/ChangeKindCache.java
index e971eff..aa47827 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/ChangeKindCache.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/ChangeKindCache.java
@@ -21,22 +21,20 @@
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gerrit.server.query.change.ChangeData;
-
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Repository;
/**
* Cache of {@link ChangeKind} per commit.
- * <p>
- * This is immutable conditioned on the merge strategy (unless the JGit strategy
- * implementation changes, which might invalidate old entries).
+ *
+ * <p>This is immutable conditioned on the merge strategy (unless the JGit strategy implementation
+ * changes, which might invalidate old entries).
*/
public interface ChangeKindCache {
- ChangeKind getChangeKind(Project.NameKey project, @Nullable Repository repo,
- ObjectId prior, ObjectId next);
+ ChangeKind getChangeKind(
+ Project.NameKey project, @Nullable Repository repo, ObjectId prior, ObjectId next);
ChangeKind getChangeKind(ReviewDb db, Change change, PatchSet patch);
- ChangeKind getChangeKind(@Nullable Repository repo, ChangeData cd,
- PatchSet patch);
+ ChangeKind getChangeKind(@Nullable Repository repo, ChangeData cd, PatchSet patch);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/ChangeKindCacheImpl.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/ChangeKindCacheImpl.java
index b3207e9..030ddd2 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/ChangeKindCacheImpl.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/ChangeKindCacheImpl.java
@@ -38,7 +38,16 @@
import com.google.inject.Inject;
import com.google.inject.Module;
import com.google.inject.name.Named;
-
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.Serializable;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
import org.eclipse.jgit.errors.LargeObjectException;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.lib.ObjectId;
@@ -50,20 +59,8 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.io.Serializable;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Objects;
-import java.util.Set;
-import java.util.concurrent.Callable;
-import java.util.concurrent.ExecutionException;
-
public class ChangeKindCacheImpl implements ChangeKindCache {
- private static final Logger log =
- LoggerFactory.getLogger(ChangeKindCacheImpl.class);
+ private static final Logger log = LoggerFactory.getLogger(ChangeKindCacheImpl.class);
private static final String ID_CACHE = "change_kind";
@@ -85,7 +82,6 @@
private final ChangeData.Factory changeDataFactory;
private final GitRepositoryManager repoManager;
-
@Inject
NoCache(
@GerritServerConfig Config serverConfig,
@@ -97,28 +93,25 @@
}
@Override
- public ChangeKind getChangeKind(Project.NameKey project,
- @Nullable Repository repo, ObjectId prior, ObjectId next) {
+ public ChangeKind getChangeKind(
+ Project.NameKey project, @Nullable Repository repo, ObjectId prior, ObjectId next) {
try {
Key key = new Key(prior, next, useRecursiveMerge);
return new Loader(key, repoManager, project, repo).call();
} catch (IOException e) {
- log.warn("Cannot check trivial rebase of new patch set " + next.name()
- + " in " + project, e);
+ log.warn(
+ "Cannot check trivial rebase of new patch set " + next.name() + " in " + project, e);
return ChangeKind.REWORK;
}
}
@Override
- public ChangeKind getChangeKind(ReviewDb db, Change change,
- PatchSet patch) {
- return getChangeKindInternal(this, db, change, patch, changeDataFactory,
- repoManager);
+ public ChangeKind getChangeKind(ReviewDb db, Change change, PatchSet patch) {
+ return getChangeKindInternal(this, db, change, patch, changeDataFactory, repoManager);
}
@Override
- public ChangeKind getChangeKind(@Nullable Repository repo, ChangeData cd,
- PatchSet patch) {
+ public ChangeKind getChangeKind(@Nullable Repository repo, ChangeData cd, PatchSet patch) {
return getChangeKindInternal(this, repo, cd, patch);
}
}
@@ -132,8 +125,7 @@
private Key(ObjectId prior, ObjectId next, boolean useRecursiveMerge) {
checkNotNull(next, "next");
- String strategyName = MergeUtil.mergeStrategyName(
- true, useRecursiveMerge);
+ String strategyName = MergeUtil.mergeStrategyName(true, useRecursiveMerge);
this.prior = prior.copy();
this.next = next.copy();
this.strategyName = strategyName;
@@ -192,8 +184,11 @@
private final Project.NameKey projectName;
private final Repository alreadyOpenRepo;
- private Loader(Key key, GitRepositoryManager repoManager,
- Project.NameKey projectName, @Nullable Repository alreadyOpenRepo) {
+ private Loader(
+ Key key,
+ GitRepositoryManager repoManager,
+ Project.NameKey projectName,
+ @Nullable Repository alreadyOpenRepo) {
this.key = key;
this.repoManager = repoManager;
this.projectName = projectName;
@@ -230,8 +225,7 @@
}
if ((prior.getParentCount() != 1 || next.getParentCount() != 1)
- && (!onlyFirstParentChanged(prior, next)
- || prior.getParentCount() == 0)) {
+ && (!onlyFirstParentChanged(prior, next) || prior.getParentCount() == 0)) {
// Trivial rebases done by machine only work well on 1 parent.
return ChangeKind.REWORK;
}
@@ -240,8 +234,7 @@
// having the same tree as would exist when the prior commit is
// cherry-picked onto the next commit's new first parent.
try (ObjectInserter ins = new InMemoryInserter(repo)) {
- ThreeWayMerger merger =
- MergeUtil.newThreeWayMerger(repo, ins, key.strategyName);
+ ThreeWayMerger merger = MergeUtil.newThreeWayMerger(repo, ins, key.strategyName);
merger.setBase(prior.getParent(0));
if (merger.merge(next.getParent(0), prior)
&& merger.getResultTreeId().equals(next.getTree())) {
@@ -308,7 +301,9 @@
public static class ChangeKindWeigher implements Weigher<Key, ChangeKind> {
@Override
public int weigh(Key key, ChangeKind changeKind) {
- return 16 + 2 * 36 + 2 * key.strategyName.length() // Size of Key, 64 bit JVM
+ return 16
+ + 2 * 36
+ + 2 * key.strategyName.length() // Size of Key, 64 bit JVM
+ 2 * changeKind.name().length(); // Size of ChangeKind, 64 bit JVM
}
}
@@ -331,35 +326,29 @@
}
@Override
- public ChangeKind getChangeKind(Project.NameKey project,
- @Nullable Repository repo, ObjectId prior, ObjectId next) {
+ public ChangeKind getChangeKind(
+ Project.NameKey project, @Nullable Repository repo, ObjectId prior, ObjectId next) {
try {
Key key = new Key(prior, next, useRecursiveMerge);
return cache.get(key, new Loader(key, repoManager, project, repo));
} catch (ExecutionException e) {
- log.warn("Cannot check trivial rebase of new patch set " + next.name()
- + " in " + project, e);
+ log.warn("Cannot check trivial rebase of new patch set " + next.name() + " in " + project, e);
return ChangeKind.REWORK;
}
}
@Override
public ChangeKind getChangeKind(ReviewDb db, Change change, PatchSet patch) {
- return getChangeKindInternal(this, db, change, patch, changeDataFactory,
- repoManager);
+ return getChangeKindInternal(this, db, change, patch, changeDataFactory, repoManager);
}
@Override
- public ChangeKind getChangeKind(@Nullable Repository repo, ChangeData cd,
- PatchSet patch) {
+ public ChangeKind getChangeKind(@Nullable Repository repo, ChangeData cd, PatchSet patch) {
return getChangeKindInternal(this, repo, cd, patch);
}
private static ChangeKind getChangeKindInternal(
- ChangeKindCache cache,
- @Nullable Repository repo,
- ChangeData change,
- PatchSet patch) {
+ ChangeKindCache cache, @Nullable Repository repo, ChangeData change, PatchSet patch) {
ChangeKind kind = ChangeKind.REWORK;
// Trivial case: if we're on the first patch, we don't need to use
// the repository.
@@ -368,9 +357,8 @@
Collection<PatchSet> patchSetCollection = change.patchSets();
PatchSet priorPs = patch;
for (PatchSet ps : patchSetCollection) {
- if (ps.getId().get() < patch.getId().get() &&
- (ps.getId().get() > priorPs.getId().get() ||
- priorPs == patch)) {
+ if (ps.getId().get() < patch.getId().get()
+ && (ps.getId().get() > priorPs.getId().get() || priorPs == patch)) {
// We only want the previous patch set, so walk until the last one
priorPs = ps;
}
@@ -382,14 +370,20 @@
// and deletes the draft.
if (priorPs != patch) {
kind =
- cache.getChangeKind(change.project(), repo,
+ cache.getChangeKind(
+ change.project(),
+ repo,
ObjectId.fromString(priorPs.getRevision().get()),
ObjectId.fromString(patch.getRevision().get()));
}
} catch (OrmException e) {
// Do nothing; assume we have a complex change
- log.warn("Unable to get change kind for patchSet " + patch.getPatchSetId() +
- "of change " + change.getId(), e);
+ log.warn(
+ "Unable to get change kind for patchSet "
+ + patch.getPatchSetId()
+ + "of change "
+ + change.getId(),
+ e);
}
}
return kind;
@@ -408,12 +402,15 @@
// the repository.
if (patch.getId().get() > 1) {
try (Repository repo = repoManager.openRepository(change.getProject())) {
- kind = getChangeKindInternal(cache, repo,
- changeDataFactory.create(db, change), patch);
+ kind = getChangeKindInternal(cache, repo, changeDataFactory.create(db, change), patch);
} catch (IOException e) {
// Do nothing; assume we have a complex change
- log.warn("Unable to get change kind for patchSet " + patch.getPatchSetId() +
- "of change " + change.getChangeId(), e);
+ log.warn(
+ "Unable to get change kind for patchSet "
+ + patch.getPatchSetId()
+ + "of change "
+ + change.getChangeId(),
+ e);
}
}
return kind;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/ChangeResource.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/ChangeResource.java
index 05d12b3..236ecad 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/ChangeResource.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/ChangeResource.java
@@ -35,15 +35,14 @@
import com.google.inject.TypeLiteral;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
-
import org.eclipse.jgit.lib.ObjectId;
public class ChangeResource implements RestResource, HasETag {
/**
* JSON format version number for ETag computations.
- * <p>
- * Should be bumped on any JSON format change (new fields, etc.) so that
- * otherwise unmodified changes get new ETags.
+ *
+ * <p>Should be bumped on any JSON format change (new fields, etc.) so that otherwise unmodified
+ * changes get new ETags.
*/
public static final int JSON_FORMAT_VERSION = 1;
@@ -58,8 +57,7 @@
private final ChangeControl control;
@AssistedInject
- ChangeResource(StarredChangesUtil starredChangesUtil,
- @Assisted ChangeControl control) {
+ ChangeResource(StarredChangesUtil starredChangesUtil, @Assisted ChangeControl control) {
this.starredChangesUtil = starredChangesUtil;
this.control = control;
}
@@ -92,9 +90,9 @@
// unrelated to the UI.
public void prepareETag(Hasher h, CurrentUser user) {
h.putInt(JSON_FORMAT_VERSION)
- .putLong(getChange().getLastUpdatedOn().getTime())
- .putInt(getChange().getRowVersion())
- .putInt(user.isIdentifiedUser() ? user.getAccountId().get() : 0);
+ .putLong(getChange().getLastUpdatedOn().getTime())
+ .putInt(getChange().getRowVersion())
+ .putInt(user.isIdentifiedUser() ? user.getAccountId().get() : 0);
if (user.isIdentifiedUser()) {
for (AccountGroup.UUID uuid : user.getEffectiveGroups().getKnownGroups()) {
@@ -123,9 +121,7 @@
CurrentUser user = control.getUser();
Hasher h = Hashing.md5().newHasher();
if (user.isIdentifiedUser()) {
- h.putString(
- starredChangesUtil.getObjectId(user.getAccountId(), getId()).name(),
- UTF_8);
+ h.putString(starredChangesUtil.getObjectId(user.getAccountId(), getId()).name(), UTF_8);
}
prepareETag(h, user);
return h.hash().toString();
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/ChangeTriplet.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/ChangeTriplet.java
index fc3e70a..71a3db7 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/ChangeTriplet.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/ChangeTriplet.java
@@ -19,7 +19,6 @@
import com.google.gerrit.reviewdb.client.Branch;
import com.google.gerrit.reviewdb.client.Change;
import com.google.gerrit.reviewdb.client.Project;
-
import java.util.Optional;
@AutoValue
@@ -29,17 +28,14 @@
}
private static String format(Branch.NameKey branch, Change.Key change) {
- return branch.getParentKey().get()
- + "~" + branch.getShortName()
- + "~" + change.get();
+ return branch.getParentKey().get() + "~" + branch.getShortName() + "~" + change.get();
}
/**
* Parse a triplet out of a string.
*
* @param triplet string of the form "project~branch~id".
- * @return the triplet if the input string has the proper format, or absent if
- * not.
+ * @return the triplet if the input string has the proper format, or absent if not.
*/
public static Optional<ChangeTriplet> parse(String triplet) {
int t2 = triplet.lastIndexOf('~');
@@ -52,9 +48,9 @@
String branch = Url.decode(triplet.substring(t1 + 1, t2));
String changeId = Url.decode(triplet.substring(t2 + 1));
- ChangeTriplet result = new AutoValue_ChangeTriplet(
- new Branch.NameKey(new Project.NameKey(project), branch),
- new Change.Key(changeId));
+ ChangeTriplet result =
+ new AutoValue_ChangeTriplet(
+ new Branch.NameKey(new Project.NameKey(project), branch), new Change.Key(changeId));
return Optional.of(result);
}
@@ -63,6 +59,7 @@
}
public abstract Branch.NameKey branch();
+
public abstract Change.Key id();
@Override
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/ChangesCollection.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/ChangesCollection.java
index b89691a..eeb1ab3 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/ChangesCollection.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/ChangesCollection.java
@@ -32,13 +32,11 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.util.List;
@Singleton
-public class ChangesCollection implements
- RestCollection<TopLevelResource, ChangeResource>,
- AcceptsPost<TopLevelResource> {
+public class ChangesCollection
+ implements RestCollection<TopLevelResource, ChangeResource>, AcceptsPost<TopLevelResource> {
private final Provider<ReviewDb> db;
private final Provider<CurrentUser> user;
private final Provider<QueryChanges> queryFactory;
@@ -92,8 +90,7 @@
return changeResourceFactory.create(ctl);
}
- public ChangeResource parse(Change.Id id)
- throws ResourceNotFoundException, OrmException {
+ public ChangeResource parse(Change.Id id) throws ResourceNotFoundException, OrmException {
List<ChangeControl> ctls = changeFinder.find(id, user.get());
if (ctls.isEmpty()) {
throw new ResourceNotFoundException(toIdString(id));
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/Check.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/Check.java
index f4869be..1f24afb 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/Check.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/Check.java
@@ -25,11 +25,10 @@
import com.google.gerrit.server.project.ChangeControl;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
-
import java.util.EnumSet;
-public class Check implements RestReadView<ChangeResource>,
- RestModifyView<ChangeResource, FixInput> {
+public class Check
+ implements RestReadView<ChangeResource>, RestModifyView<ChangeResource, FixInput> {
private final ChangeJson.Factory jsonFactory;
@Inject
@@ -38,8 +37,7 @@
}
@Override
- public Response<ChangeInfo> apply(ChangeResource rsrc)
- throws RestApiException, OrmException {
+ public Response<ChangeInfo> apply(ChangeResource rsrc) throws RestApiException, OrmException {
return Response.withMustRevalidate(newChangeJson().format(rsrc));
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/CherryPick.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/CherryPick.java
index b5eb193..5178774 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/CherryPick.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/CherryPick.java
@@ -37,20 +37,18 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.io.IOException;
@Singleton
-public class CherryPick implements RestModifyView<RevisionResource, CherryPickInput>,
- UiAction<RevisionResource> {
+public class CherryPick
+ implements RestModifyView<RevisionResource, CherryPickInput>, UiAction<RevisionResource> {
private final Provider<ReviewDb> dbProvider;
private final CherryPickChange cherryPickChange;
private final ChangeJson.Factory json;
@Inject
- CherryPick(Provider<ReviewDb> dbProvider,
- CherryPickChange cherryPickChange,
- ChangeJson.Factory json) {
+ CherryPick(
+ Provider<ReviewDb> dbProvider, CherryPickChange cherryPickChange, ChangeJson.Factory json) {
this.dbProvider = dbProvider;
this.cherryPickChange = cherryPickChange;
this.json = json;
@@ -64,8 +62,7 @@
if (input.message == null || input.message.trim().isEmpty()) {
throw new BadRequestException("message must be non-empty");
- } else if (input.destination == null
- || input.destination.trim().isEmpty()) {
+ } else if (input.destination == null || input.destination.trim().isEmpty()) {
throw new BadRequestException("destination must be non-empty");
}
@@ -84,18 +81,23 @@
String refName = RefNames.fullName(input.destination);
RefControl refControl = projectControl.controlForRef(refName);
if (!refControl.canUpload()) {
- throw new AuthException("Not allowed to cherry pick "
- + revision.getChange().getId().toString() + " to "
- + input.destination);
+ throw new AuthException(
+ "Not allowed to cherry pick "
+ + revision.getChange().getId().toString()
+ + " to "
+ + input.destination);
}
try {
Change.Id cherryPickedChangeId =
- cherryPickChange.cherryPick(revision.getChange(),
- revision.getPatchSet(), input.message, refName,
- refControl, parent);
- return json.create(ChangeJson.NO_OPTIONS).format(revision.getProject(),
- cherryPickedChangeId);
+ cherryPickChange.cherryPick(
+ revision.getChange(),
+ revision.getPatchSet(),
+ input.message,
+ refName,
+ refControl,
+ parent);
+ return json.create(ChangeJson.NO_OPTIONS).format(revision.getProject(), cherryPickedChangeId);
} catch (InvalidChangeOperationException e) {
throw new BadRequestException(e.getMessage());
} catch (IntegrationException | NoSuchChangeException e) {
@@ -106,9 +108,8 @@
@Override
public UiAction.Description getDescription(RevisionResource resource) {
return new UiAction.Description()
- .setLabel("Cherry Pick")
- .setTitle("Cherry pick change to a different branch")
- .setVisible(resource.getControl().getProjectControl().canUpload()
- && resource.isCurrent());
+ .setLabel("Cherry Pick")
+ .setTitle("Cherry pick change to a different branch")
+ .setVisible(resource.getControl().getProjectControl().canUpload() && resource.isCurrent());
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/CherryPickChange.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/CherryPickChange.java
index f09e268..a7ac1ed 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/CherryPickChange.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/CherryPickChange.java
@@ -54,7 +54,10 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
+import java.io.IOException;
+import java.sql.Timestamp;
+import java.util.List;
+import java.util.TimeZone;
import org.eclipse.jgit.errors.IncorrectObjectTypeException;
import org.eclipse.jgit.errors.MissingObjectException;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
@@ -65,11 +68,6 @@
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.util.ChangeIdUtil;
-import java.io.IOException;
-import java.sql.Timestamp;
-import java.util.List;
-import java.util.TimeZone;
-
@Singleton
public class CherryPickChange {
@@ -87,7 +85,8 @@
private final BatchUpdate.Factory batchUpdateFactory;
@Inject
- CherryPickChange(Provider<ReviewDb> db,
+ CherryPickChange(
+ Provider<ReviewDb> db,
Sequences seq,
Provider<InternalChangeQuery> queryProvider,
@GerritPersonIdent PersonIdent myIdent,
@@ -113,13 +112,16 @@
this.batchUpdateFactory = batchUpdateFactory;
}
- public Change.Id cherryPick(Change change, PatchSet patch,
- final String message, final String ref, final RefControl refControl,
- int parent) throws NoSuchChangeException,
- OrmException, MissingObjectException,
- IncorrectObjectTypeException, IOException,
- InvalidChangeOperationException, IntegrationException, UpdateException,
- RestApiException {
+ public Change.Id cherryPick(
+ Change change,
+ PatchSet patch,
+ final String message,
+ final String ref,
+ final RefControl refControl,
+ int parent)
+ throws NoSuchChangeException, OrmException, MissingObjectException,
+ IncorrectObjectTypeException, IOException, InvalidChangeOperationException,
+ IntegrationException, UpdateException, RestApiException {
if (Strings.isNullOrEmpty(ref)) {
throw new InvalidChangeOperationException(
@@ -134,12 +136,11 @@
// created later on, to ensure the cherry-picked commit is flushed
// before patch sets are updated.
ObjectInserter oi = git.newObjectInserter();
- CodeReviewRevWalk revWalk =
- CodeReviewCommit.newRevWalk(oi.newReader())) {
+ CodeReviewRevWalk revWalk = CodeReviewCommit.newRevWalk(oi.newReader())) {
Ref destRef = git.getRefDatabase().exactRef(ref);
if (destRef == null) {
- throw new InvalidChangeOperationException(String.format(
- "Branch %s does not exist.", destinationBranch));
+ throw new InvalidChangeOperationException(
+ String.format("Branch %s does not exist.", destinationBranch));
}
CodeReviewCommit mergeTip = revWalk.parseCommit(destRef.getObjectId());
@@ -148,35 +149,44 @@
revWalk.parseCommit(ObjectId.fromString(patch.getRevision().get()));
if (parent <= 0 || parent > commitToCherryPick.getParentCount()) {
- throw new InvalidChangeOperationException(String.format(
- "Cherry Pick: Parent %s does not exist. Please specify a parent in"
- + " range [1, %s].",
- parent, commitToCherryPick.getParentCount()));
+ throw new InvalidChangeOperationException(
+ String.format(
+ "Cherry Pick: Parent %s does not exist. Please specify a parent in"
+ + " range [1, %s].",
+ parent, commitToCherryPick.getParentCount()));
}
Timestamp now = TimeUtil.nowTs();
- PersonIdent committerIdent =
- identifiedUser.newCommitterIdent(now, serverTimeZone);
+ PersonIdent committerIdent = identifiedUser.newCommitterIdent(now, serverTimeZone);
final ObjectId computedChangeId =
- ChangeIdUtil
- .computeChangeId(commitToCherryPick.getTree(), mergeTip,
- commitToCherryPick.getAuthorIdent(), committerIdent, message);
- String commitMessage =
- ChangeIdUtil.insertId(message, computedChangeId).trim() + '\n';
+ ChangeIdUtil.computeChangeId(
+ commitToCherryPick.getTree(),
+ mergeTip,
+ commitToCherryPick.getAuthorIdent(),
+ committerIdent,
+ message);
+ String commitMessage = ChangeIdUtil.insertId(message, computedChangeId).trim() + '\n';
CodeReviewCommit cherryPickCommit;
try {
- ProjectState projectState = refControl.getProjectControl()
- .getProjectState();
- cherryPickCommit = mergeUtilFactory.create(projectState)
- .createCherryPickFromCommit(git, oi, mergeTip,
- commitToCherryPick, committerIdent, commitMessage, revWalk,
- parent - 1, false);
+ ProjectState projectState = refControl.getProjectControl().getProjectState();
+ cherryPickCommit =
+ mergeUtilFactory
+ .create(projectState)
+ .createCherryPickFromCommit(
+ git,
+ oi,
+ mergeTip,
+ commitToCherryPick,
+ committerIdent,
+ commitMessage,
+ revWalk,
+ parent - 1,
+ false);
Change.Key changeKey;
- final List<String> idList = cherryPickCommit.getFooterLines(
- FooterConstants.CHANGE_ID);
+ final List<String> idList = cherryPickCommit.getFooterLines(FooterConstants.CHANGE_ID);
if (!idList.isEmpty()) {
final String idStr = idList.get(idList.size() - 1).trim();
changeKey = new Change.Key(idStr);
@@ -184,27 +194,27 @@
changeKey = new Change.Key("I" + computedChangeId.name());
}
- Branch.NameKey newDest =
- new Branch.NameKey(change.getProject(), destRef.getName());
- List<ChangeData> destChanges = queryProvider.get()
- .setLimit(2)
- .byBranchKey(newDest, changeKey);
+ Branch.NameKey newDest = new Branch.NameKey(change.getProject(), destRef.getName());
+ List<ChangeData> destChanges =
+ queryProvider.get().setLimit(2).byBranchKey(newDest, changeKey);
if (destChanges.size() > 1) {
- throw new InvalidChangeOperationException("Several changes with key "
- + changeKey + " reside on the same branch. "
- + "Cannot create a new patch set.");
+ throw new InvalidChangeOperationException(
+ "Several changes with key "
+ + changeKey
+ + " reside on the same branch. "
+ + "Cannot create a new patch set.");
}
- try (BatchUpdate bu = batchUpdateFactory.create(
- db.get(), change.getDest().getParentKey(), identifiedUser, now)) {
+ try (BatchUpdate bu =
+ batchUpdateFactory.create(
+ db.get(), change.getDest().getParentKey(), identifiedUser, now)) {
bu.setRepository(git, revWalk, oi);
Change.Id result;
if (destChanges.size() == 1) {
// The change key exists on the destination branch. The cherry pick
// will be added as a new patch set.
- ChangeControl destCtl = refControl.getProjectControl()
- .controlFor(destChanges.get(0).notes());
- result = insertPatchSet(
- bu, git, destCtl, cherryPickCommit);
+ ChangeControl destCtl =
+ refControl.getProjectControl().controlFor(destChanges.get(0).notes());
+ result = insertPatchSet(bu, git, destCtl, cherryPickCommit);
} else {
// Change key not found on destination branch. We can create a new
// change.
@@ -213,13 +223,13 @@
newTopic = change.getTopic() + "-" + newDest.getShortName();
}
result =
- createNewChange(bu, cherryPickCommit,
- refControl.getRefName(), newTopic, change.getDest());
+ createNewChange(
+ bu, cherryPickCommit, refControl.getRefName(), newTopic, change.getDest());
- bu.addOp(change.getId(),
+ bu.addOp(
+ change.getId(),
new AddMessageToSourceChangeOp(
- changeMessagesUtil, patch.getId(), destinationBranch,
- cherryPickCommit));
+ changeMessagesUtil, patch.getId(), destinationBranch, cherryPickCommit));
}
bu.execute();
return result;
@@ -232,35 +242,39 @@
}
}
- private Change.Id insertPatchSet(BatchUpdate bu, Repository git,
- ChangeControl destCtl, CodeReviewCommit cherryPickCommit)
+ private Change.Id insertPatchSet(
+ BatchUpdate bu, Repository git, ChangeControl destCtl, CodeReviewCommit cherryPickCommit)
throws IOException, OrmException {
Change destChange = destCtl.getChange();
- PatchSet.Id psId =
- ChangeUtil.nextPatchSetId(git, destChange.currentPatchSetId());
- PatchSetInserter inserter = patchSetInserterFactory
- .create(destCtl, psId, cherryPickCommit);
+ PatchSet.Id psId = ChangeUtil.nextPatchSetId(git, destChange.currentPatchSetId());
+ PatchSetInserter inserter = patchSetInserterFactory.create(destCtl, psId, cherryPickCommit);
PatchSet.Id newPatchSetId = inserter.getPatchSetId();
PatchSet current = psUtil.current(db.get(), destCtl.getNotes());
- bu.addOp(destChange.getId(), inserter
- .setMessage("Uploaded patch set " + newPatchSetId.get() + ".")
- .setDraft(current.isDraft())
- .setNotify(NotifyHandling.NONE));
+ bu.addOp(
+ destChange.getId(),
+ inserter
+ .setMessage("Uploaded patch set " + newPatchSetId.get() + ".")
+ .setDraft(current.isDraft())
+ .setNotify(NotifyHandling.NONE));
return destChange.getId();
}
- private Change.Id createNewChange(BatchUpdate bu,
- CodeReviewCommit cherryPickCommit, String refName, String topic,
- Branch.NameKey sourceBranch) throws OrmException {
+ private Change.Id createNewChange(
+ BatchUpdate bu,
+ CodeReviewCommit cherryPickCommit,
+ String refName,
+ String topic,
+ Branch.NameKey sourceBranch)
+ throws OrmException {
Change.Id changeId = new Change.Id(seq.nextChangeId());
- ChangeInserter ins = changeInserterFactory.create(
- changeId, cherryPickCommit, refName)
- .setValidatePolicy(CommitValidators.Policy.GERRIT)
- .setTopic(topic);
+ ChangeInserter ins =
+ changeInserterFactory
+ .create(changeId, cherryPickCommit, refName)
+ .setValidatePolicy(CommitValidators.Policy.GERRIT)
+ .setTopic(topic);
- ins.setMessage(
- messageForDestinationChange(ins.getPatchSetId(), sourceBranch));
+ ins.setMessage(messageForDestinationChange(ins.getPatchSetId(), sourceBranch));
bu.insertChange(ins);
return changeId;
}
@@ -271,8 +285,8 @@
private final String destBranch;
private final ObjectId cherryPickCommit;
- private AddMessageToSourceChangeOp(ChangeMessagesUtil cmUtil,
- PatchSet.Id psId, String destBranch, ObjectId cherryPickCommit) {
+ private AddMessageToSourceChangeOp(
+ ChangeMessagesUtil cmUtil, PatchSet.Id psId, String destBranch, ObjectId cherryPickCommit) {
this.cmUtil = cmUtil;
this.psId = psId;
this.destBranch = destBranch;
@@ -281,29 +295,33 @@
@Override
public boolean updateChange(ChangeContext ctx) throws OrmException {
- StringBuilder sb = new StringBuilder("Patch Set ")
- .append(psId.get())
- .append(": Cherry Picked")
- .append("\n\n")
- .append("This patchset was cherry picked to branch ")
- .append(destBranch)
- .append(" as commit ")
- .append(cherryPickCommit.name());
- ChangeMessage changeMessage = ChangeMessagesUtil.newMessage(
- psId, ctx.getUser(), ctx.getWhen(), sb.toString(),
- ChangeMessagesUtil.TAG_CHERRY_PICK_CHANGE);
+ StringBuilder sb =
+ new StringBuilder("Patch Set ")
+ .append(psId.get())
+ .append(": Cherry Picked")
+ .append("\n\n")
+ .append("This patchset was cherry picked to branch ")
+ .append(destBranch)
+ .append(" as commit ")
+ .append(cherryPickCommit.name());
+ ChangeMessage changeMessage =
+ ChangeMessagesUtil.newMessage(
+ psId,
+ ctx.getUser(),
+ ctx.getWhen(),
+ sb.toString(),
+ ChangeMessagesUtil.TAG_CHERRY_PICK_CHANGE);
cmUtil.addChangeMessage(ctx.getDb(), ctx.getUpdate(psId), changeMessage);
return true;
}
}
- private String messageForDestinationChange(PatchSet.Id patchSetId,
- Branch.NameKey sourceBranch) {
+ private String messageForDestinationChange(PatchSet.Id patchSetId, Branch.NameKey sourceBranch) {
return new StringBuilder("Patch Set ")
- .append(patchSetId.get())
- .append(": Cherry Picked from branch ")
- .append(sourceBranch.getShortName())
- .append(".")
- .toString();
+ .append(patchSetId.get())
+ .append(": Cherry Picked from branch ")
+ .append(sourceBranch.getShortName())
+ .append(".")
+ .toString();
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/CommentJson.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/CommentJson.java
index eb6d151..4651c6b 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/CommentJson.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/CommentJson.java
@@ -33,7 +33,6 @@
import com.google.gerrit.server.account.AccountLoader;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
-
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@@ -71,11 +70,9 @@
return new RobotCommentFormatter();
}
- private abstract class BaseCommentFormatter<F extends Comment,
- T extends CommentInfo> {
+ private abstract class BaseCommentFormatter<F extends Comment, T extends CommentInfo> {
public T format(F comment) throws OrmException {
- AccountLoader loader =
- fillAccounts ? accountLoaderFactory.create(true) : null;
+ AccountLoader loader = fillAccounts ? accountLoaderFactory.create(true) : null;
T info = toInfo(comment, loader);
if (loader != null) {
loader.fill();
@@ -83,10 +80,8 @@
return info;
}
- public Map<String, List<T>> format(Iterable<F> comments)
- throws OrmException {
- AccountLoader loader =
- fillAccounts ? accountLoaderFactory.create(true) : null;
+ public Map<String, List<T>> format(Iterable<F> comments) throws OrmException {
+ AccountLoader loader = fillAccounts ? accountLoaderFactory.create(true) : null;
Map<String, List<T>> out = new TreeMap<>();
@@ -112,12 +107,12 @@
}
public List<T> formatAsList(Iterable<F> comments) throws OrmException {
- AccountLoader loader =
- fillAccounts ? accountLoaderFactory.create(true) : null;
+ AccountLoader loader = fillAccounts ? accountLoaderFactory.create(true) : null;
- List<T> out = FluentIterable.from(comments)
- .transform(c -> toInfo(c, loader))
- .toSortedList(COMMENT_INFO_ORDER);
+ List<T> out =
+ FluentIterable.from(comments)
+ .transform(c -> toInfo(c, loader))
+ .toSortedList(COMMENT_INFO_ORDER);
if (loader != null) {
loader.fill();
@@ -127,8 +122,7 @@
protected abstract T toInfo(F comment, AccountLoader loader);
- protected void fillCommentInfo(Comment c, CommentInfo r,
- AccountLoader loader) {
+ protected void fillCommentInfo(Comment c, CommentInfo r, AccountLoader loader) {
if (fillPatchSet) {
r.patchSet = c.key.patchSetId;
}
@@ -175,12 +169,10 @@
return ci;
}
- private CommentFormatter() {
- }
+ private CommentFormatter() {}
}
- class RobotCommentFormatter
- extends BaseCommentFormatter<RobotComment, RobotCommentInfo> {
+ class RobotCommentFormatter extends BaseCommentFormatter<RobotComment, RobotCommentInfo> {
@Override
protected RobotCommentInfo toInfo(RobotComment c, AccountLoader loader) {
RobotCommentInfo rci = new RobotCommentInfo();
@@ -199,23 +191,23 @@
return null;
}
- return fixSuggestions.stream()
- .map(this::toFixSuggestionInfo)
- .collect(Collectors.toList());
+ return fixSuggestions.stream().map(this::toFixSuggestionInfo).collect(Collectors.toList());
}
private FixSuggestionInfo toFixSuggestionInfo(FixSuggestion fixSuggestion) {
FixSuggestionInfo fixSuggestionInfo = new FixSuggestionInfo();
fixSuggestionInfo.fixId = fixSuggestion.fixId;
fixSuggestionInfo.description = fixSuggestion.description;
- fixSuggestionInfo.replacements = fixSuggestion.replacements.stream()
- .map(this::toFixReplacementInfo)
- .collect(Collectors.toList());
+ fixSuggestionInfo.replacements =
+ fixSuggestion
+ .replacements
+ .stream()
+ .map(this::toFixReplacementInfo)
+ .collect(Collectors.toList());
return fixSuggestionInfo;
}
- private FixReplacementInfo toFixReplacementInfo(
- FixReplacement fixReplacement) {
+ private FixReplacementInfo toFixReplacementInfo(FixReplacement fixReplacement) {
FixReplacementInfo fixReplacementInfo = new FixReplacementInfo();
fixReplacementInfo.path = fixReplacement.path;
fixReplacementInfo.range = toRange(fixReplacement.range);
@@ -223,7 +215,6 @@
return fixReplacementInfo;
}
- private RobotCommentFormatter() {
- }
+ private RobotCommentFormatter() {}
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/Comments.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/Comments.java
index 6ce7dda..935aa4e 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/Comments.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/Comments.java
@@ -36,8 +36,10 @@
private final CommentsUtil commentsUtil;
@Inject
- Comments(DynamicMap<RestView<CommentResource>> views,
- ListRevisionComments list, Provider<ReviewDb> dbProvider,
+ Comments(
+ DynamicMap<RestView<CommentResource>> views,
+ ListRevisionComments list,
+ Provider<ReviewDb> dbProvider,
CommentsUtil commentsUtil) {
this.views = views;
this.list = list;
@@ -61,8 +63,8 @@
String uuid = id.get();
ChangeNotes notes = rev.getNotes();
- for (Comment c : commentsUtil.publishedByPatchSet(dbProvider.get(),
- notes, rev.getPatchSet().getId())) {
+ for (Comment c :
+ commentsUtil.publishedByPatchSet(dbProvider.get(), notes, rev.getPatchSet().getId())) {
if (uuid.equals(c.key.uuid)) {
return new CommentResource(rev, c);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/ConsistencyChecker.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/ConsistencyChecker.java
index 4b8d695..1edf9b4 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/ConsistencyChecker.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/ConsistencyChecker.java
@@ -57,7 +57,14 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
-
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
import org.eclipse.jgit.errors.IncorrectObjectTypeException;
import org.eclipse.jgit.errors.MissingObjectException;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
@@ -73,31 +80,18 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
/**
* Checks changes for various kinds of inconsistency and corruption.
- * <p>
- * A single instance may be reused for checking multiple changes, but not
- * concurrently.
+ *
+ * <p>A single instance may be reused for checking multiple changes, but not concurrently.
*/
public class ConsistencyChecker {
- private static final Logger log =
- LoggerFactory.getLogger(ConsistencyChecker.class);
+ private static final Logger log = LoggerFactory.getLogger(ConsistencyChecker.class);
@AutoValue
public abstract static class Result {
- private static Result create(ChangeControl ctl,
- List<ProblemInfo> problems) {
- return new AutoValue_ConsistencyChecker_Result(
- ctl.getId(), ctl.getChange(), problems);
+ private static Result create(ChangeControl ctl, List<ProblemInfo> problems) {
+ return new AutoValue_ConsistencyChecker_Result(ctl.getId(), ctl.getChange(), problems);
}
public abstract Change.Id id();
@@ -216,8 +210,8 @@
try {
currPs = psUtil.current(db.get(), ctl.getNotes());
if (currPs == null) {
- problem(String.format("Current patch set %d not found",
- change().currentPatchSetId().get()));
+ problem(
+ String.format("Current patch set %d not found", change().currentPatchSetId().get()));
}
} catch (OrmException e) {
error("Failed to look up current patch set", e);
@@ -245,16 +239,13 @@
} catch (OrmException e) {
return error("Failed to look up patch sets", e);
}
- patchSetsBySha = MultimapBuilder.hashKeys(all.size())
- .treeSetValues(PS_ID_ORDER)
- .build();
+ patchSetsBySha = MultimapBuilder.hashKeys(all.size()).treeSetValues(PS_ID_ORDER).build();
Map<String, Ref> refs;
try {
- refs = repo.getRefDatabase().exactRef(
- all.stream()
- .map(ps -> ps.getId().toRefName())
- .toArray(String[]::new));
+ refs =
+ repo.getRefDatabase()
+ .exactRef(all.stream().map(ps -> ps.getId().toRefName()).toArray(String[]::new));
} catch (IOException e) {
error("error reading refs", e);
refs = Collections.emptyMap();
@@ -265,8 +256,7 @@
// Check revision format.
int psNum = ps.getId().get();
String refName = ps.getId().toRefName();
- ObjectId objId =
- parseObjectId(ps.getRevision().get(), "patch set " + psNum);
+ ObjectId objId = parseObjectId(ps.getRevision().get(), "patch set " + psNum);
if (objId == null) {
continue;
}
@@ -278,21 +268,18 @@
if (ref == null) {
refProblem = problem("Ref missing: " + refName);
} else if (!objId.equals(ref.getObjectId())) {
- String actual = ref.getObjectId() != null
- ? ref.getObjectId().name()
- : "null";
- refProblem = problem(String.format(
- "Expected %s to point to %s, found %s",
- ref.getName(), objId.name(), actual));
+ String actual = ref.getObjectId() != null ? ref.getObjectId().name() : "null";
+ refProblem =
+ problem(
+ String.format(
+ "Expected %s to point to %s, found %s", ref.getName(), objId.name(), actual));
}
// Check object existence.
- RevCommit psCommit = parseCommit(
- objId, String.format("patch set %d", psNum));
+ RevCommit psCommit = parseCommit(objId, String.format("patch set %d", psNum));
if (psCommit == null) {
if (fix != null && fix.deletePatchSetIfCommitMissing) {
- deletePatchSetOps.add(
- new DeletePatchSetFromDbOp(lastProblem(), ps.getId()));
+ deletePatchSetOps.add(new DeletePatchSetFromDbOp(lastProblem(), ps.getId()));
}
continue;
} else if (refProblem != null && fix != null) {
@@ -307,12 +294,12 @@
deletePatchSets(deletePatchSetOps);
// Check for duplicates.
- for (Map.Entry<ObjectId, Collection<PatchSet>> e
- : patchSetsBySha.asMap().entrySet()) {
+ for (Map.Entry<ObjectId, Collection<PatchSet>> e : patchSetsBySha.asMap().entrySet()) {
if (e.getValue().size() > 1) {
- problem(String.format("Multiple patch sets pointing to %s: %s",
- e.getKey().name(),
- Collections2.transform(e.getValue(), PatchSet::getPatchSetId)));
+ problem(
+ String.format(
+ "Multiple patch sets pointing to %s: %s",
+ e.getKey().name(), Collections2.transform(e.getValue(), PatchSet::getPatchSetId)));
}
}
@@ -332,8 +319,7 @@
problem("Destination ref not found (may be new branch): " + refName);
return;
}
- tip = parseCommit(dest.getObjectId(),
- "destination ref " + refName);
+ tip = parseCommit(dest.getObjectId(), "destination ref " + refName);
if (tip == null) {
return;
}
@@ -345,8 +331,7 @@
try {
merged = rw.isMergedInto(currPsCommit, tip);
} catch (IOException e) {
- problem("Error checking whether patch set " + currPs.getId().get()
- + " is merged");
+ problem("Error checking whether patch set " + currPs.getId().get() + " is merged");
return;
}
checkMergedBitMatchesStatus(currPs.getId(), currPsCommit, merged);
@@ -355,14 +340,14 @@
private ProblemInfo wrongChangeStatus(PatchSet.Id psId, RevCommit commit) {
String refName = change().getDest().get();
- return problem(String.format(
- "Patch set %d (%s) is merged into destination ref %s (%s), but change"
- + " status is %s", psId.get(), commit.name(),
- refName, tip.name(), change().getStatus()));
+ return problem(
+ String.format(
+ "Patch set %d (%s) is merged into destination ref %s (%s), but change"
+ + " status is %s",
+ psId.get(), commit.name(), refName, tip.name(), change().getStatus()));
}
- private void checkMergedBitMatchesStatus(PatchSet.Id psId, RevCommit commit,
- boolean merged) {
+ private void checkMergedBitMatchesStatus(PatchSet.Id psId, RevCommit commit, boolean merged) {
String refName = change().getDest().get();
if (merged && change().getStatus() != Change.Status.MERGED) {
ProblemInfo p = wrongChangeStatus(psId, commit);
@@ -370,16 +355,16 @@
fixMerged(p);
}
} else if (!merged && change().getStatus() == Change.Status.MERGED) {
- problem(String.format("Patch set %d (%s) is not merged into"
- + " destination ref %s (%s), but change status is %s",
- currPs.getId().get(), commit.name(), refName, tip.name(),
- change().getStatus()));
+ problem(
+ String.format(
+ "Patch set %d (%s) is not merged into"
+ + " destination ref %s (%s), but change status is %s",
+ currPs.getId().get(), commit.name(), refName, tip.name(), change().getStatus()));
}
}
private void checkExpectMergedAs() {
- ObjectId objId =
- parseObjectId(fix.expectMergedAs, "expected merged commit");
+ ObjectId objId = parseObjectId(fix.expectMergedAs, "expected merged commit");
RevCommit commit = parseCommit(objId, "expected merged commit");
if (commit == null) {
return;
@@ -387,9 +372,10 @@
try {
if (!rw.isMergedInto(commit, tip)) {
- problem(String.format("Expected merged commit %s is not merged into"
- + " destination ref %s (%s)",
- commit.name(), change().getDest().get(), tip.name()));
+ problem(
+ String.format(
+ "Expected merged commit %s is not merged into" + " destination ref %s (%s)",
+ commit.name(), change().getDest().get(), tip.name()));
return;
}
@@ -403,8 +389,10 @@
continue;
}
try {
- Change c = notesFactory.createChecked(
- db.get(), change().getProject(), psId.getParentKey()).getChange();
+ Change c =
+ notesFactory
+ .createChecked(db.get(), change().getProject(), psId.getParentKey())
+ .getChange();
if (!c.getDest().equals(change().getDest())) {
continue;
}
@@ -418,13 +406,14 @@
case 0:
// No patch set for this commit; insert one.
rw.parseBody(commit);
- String changeId = Iterables.getFirst(
- commit.getFooterLines(FooterConstants.CHANGE_ID), null);
+ String changeId =
+ Iterables.getFirst(commit.getFooterLines(FooterConstants.CHANGE_ID), null);
// Missing Change-Id footer is ok, but mismatched is not.
if (changeId != null && !changeId.equals(change().getKey().get())) {
- problem(String.format("Expected merged commit %s has Change-Id: %s,"
- + " but expected %s",
- commit.name(), changeId, change().getKey().get()));
+ problem(
+ String.format(
+ "Expected merged commit %s has Change-Id: %s," + " but expected %s",
+ commit.name(), changeId, change().getKey().get()));
return;
}
insertMergedPatchSet(commit, null, false);
@@ -448,41 +437,40 @@
break;
default:
- problem(String.format(
- "Multiple patch sets for expected merged commit %s: %s",
- commit.name(), intKeyOrdering().sortedCopy(thisCommitPsIds)));
+ problem(
+ String.format(
+ "Multiple patch sets for expected merged commit %s: %s",
+ commit.name(), intKeyOrdering().sortedCopy(thisCommitPsIds)));
break;
}
} catch (IOException e) {
- error("Error looking up expected merged commit " + fix.expectMergedAs,
- e);
+ error("Error looking up expected merged commit " + fix.expectMergedAs, e);
}
}
- private void insertMergedPatchSet(final RevCommit commit,
- final @Nullable PatchSet.Id psIdToDelete, boolean reuseOldPsId) {
- ProblemInfo notFound =
- problem("No patch set found for merged commit " + commit.name());
+ private void insertMergedPatchSet(
+ final RevCommit commit, final @Nullable PatchSet.Id psIdToDelete, boolean reuseOldPsId) {
+ ProblemInfo notFound = problem("No patch set found for merged commit " + commit.name());
if (!user.get().isIdentifiedUser()) {
notFound.status = Status.FIX_FAILED;
- notFound.outcome =
- "Must be called by an identified user to insert new patch set";
+ notFound.outcome = "Must be called by an identified user to insert new patch set";
return;
}
ProblemInfo insertPatchSetProblem;
ProblemInfo deleteOldPatchSetProblem;
if (psIdToDelete == null) {
- insertPatchSetProblem = problem(String.format(
- "Expected merged commit %s has no associated patch set",
- commit.name()));
+ insertPatchSetProblem =
+ problem(
+ String.format(
+ "Expected merged commit %s has no associated patch set", commit.name()));
deleteOldPatchSetProblem = null;
} else {
- String msg = String.format(
- "Expected merge commit %s corresponds to patch set %s,"
- + " not the current patch set %s",
- commit.name(), psIdToDelete.get(),
- change().currentPatchSetId().get());
+ String msg =
+ String.format(
+ "Expected merge commit %s corresponds to patch set %s,"
+ + " not the current patch set %s",
+ commit.name(), psIdToDelete.get(), change().currentPatchSetId().get());
// Maybe an identical problem, but different fix.
deleteOldPatchSetProblem = reuseOldPsId ? null : problem(msg);
insertPatchSetProblem = problem(msg);
@@ -496,11 +484,11 @@
currProblems.add(insertPatchSetProblem);
try {
- PatchSet.Id psId = (psIdToDelete != null && reuseOldPsId)
- ? psIdToDelete
- : ChangeUtil.nextPatchSetId(repo, change().currentPatchSetId());
- PatchSetInserter inserter =
- patchSetInserterFactory.create(ctl, psId, commit);
+ PatchSet.Id psId =
+ (psIdToDelete != null && reuseOldPsId)
+ ? psIdToDelete
+ : ChangeUtil.nextPatchSetId(repo, change().currentPatchSetId());
+ PatchSetInserter inserter = patchSetInserterFactory.create(ctl, psId, commit);
try (BatchUpdate bu = newBatchUpdate();
ObjectInserter oi = repo.newObjectInserter()) {
bu.setRepository(repo, rw, oi);
@@ -508,35 +496,37 @@
if (psIdToDelete != null) {
// Delete the given patch set ref. If reuseOldPsId is true,
// PatchSetInserter will reinsert the same ref, making it a no-op.
- bu.addOp(ctl.getId(), new BatchUpdate.Op() {
- @Override
- public void updateRepo(RepoContext ctx) throws IOException {
- ctx.addRefUpdate(new ReceiveCommand(
- commit, ObjectId.zeroId(), psIdToDelete.toRefName()));
- }
- });
+ bu.addOp(
+ ctl.getId(),
+ new BatchUpdate.Op() {
+ @Override
+ public void updateRepo(RepoContext ctx) throws IOException {
+ ctx.addRefUpdate(
+ new ReceiveCommand(commit, ObjectId.zeroId(), psIdToDelete.toRefName()));
+ }
+ });
if (!reuseOldPsId) {
- bu.addOp(ctl.getId(), new DeletePatchSetFromDbOp(
- checkNotNull(deleteOldPatchSetProblem), psIdToDelete));
+ bu.addOp(
+ ctl.getId(),
+ new DeletePatchSetFromDbOp(checkNotNull(deleteOldPatchSetProblem), psIdToDelete));
}
}
- bu.addOp(ctl.getId(), inserter
- .setValidatePolicy(CommitValidators.Policy.NONE)
- .setFireRevisionCreated(false)
- .setNotify(NotifyHandling.NONE)
- .setAllowClosed(true)
- .setMessage(
- "Patch set for merged commit inserted by consistency checker"));
+ bu.addOp(
+ ctl.getId(),
+ inserter
+ .setValidatePolicy(CommitValidators.Policy.NONE)
+ .setFireRevisionCreated(false)
+ .setNotify(NotifyHandling.NONE)
+ .setAllowClosed(true)
+ .setMessage("Patch set for merged commit inserted by consistency checker"));
bu.addOp(ctl.getId(), new FixMergedOp(notFound));
bu.execute();
}
- ctl = changeControlFactory.controlFor(
- db.get(), inserter.getChange(), ctl.getUser());
+ ctl = changeControlFactory.controlFor(db.get(), inserter.getChange(), ctl.getUser());
insertPatchSetProblem.status = Status.FIXED;
insertPatchSetProblem.outcome = "Inserted as patch set " + psId.get();
- } catch (OrmException | IOException | UpdateException
- | RestApiException e) {
+ } catch (OrmException | IOException | UpdateException | RestApiException e) {
warn(e);
for (ProblemInfo pi : currProblems) {
pi.status = Status.FIX_FAILED;
@@ -556,8 +546,7 @@
@Override
public boolean updateChange(ChangeContext ctx) throws OrmException {
ctx.getChange().setStatus(Change.Status.MERGED);
- ctx.getUpdate(ctx.getChange().currentPatchSetId())
- .fixStatus(Change.Status.MERGED);
+ ctx.getUpdate(ctx.getChange().currentPatchSetId()).fixStatus(Change.Status.MERGED);
p.status = Status.FIXED;
p.outcome = "Marked change as merged";
return true;
@@ -578,8 +567,7 @@
}
private BatchUpdate newBatchUpdate() {
- return updateFactory.create(
- db.get(), change().getProject(), ctl.getUser(), TimeUtil.nowTs());
+ return updateFactory.create(db.get(), change().getProject(), ctl.getUser(), TimeUtil.nowTs());
}
private void fixPatchSetRef(ProblemInfo p, PatchSet ps) {
@@ -659,12 +647,9 @@
// Delete dangling key references.
ReviewDb db = DeleteChangeOp.unwrap(ctx.getDb());
accountPatchReviewStore.get().clearReviewed(psId);
- db.changeMessages().delete(
- db.changeMessages().byChange(psId.getParentKey()));
- db.patchSetApprovals().delete(
- db.patchSetApprovals().byPatchSet(psId));
- db.patchComments().delete(
- db.patchComments().byPatchSet(psId));
+ db.changeMessages().delete(db.changeMessages().byChange(psId.getParentKey()));
+ db.patchSetApprovals().delete(db.patchSetApprovals().byPatchSet(psId));
+ db.patchComments().delete(db.patchComments().byPatchSet(psId));
db.patchSets().deleteKeys(Collections.singleton(psId));
// NoteDb requires no additional fiddling; setting the state to deleted is
@@ -677,8 +662,7 @@
}
}
- private static class NoPatchSetsWouldRemainException
- extends RestApiException {
+ private static class NoPatchSetsWouldRemainException extends RestApiException {
private static final long serialVersionUID = 1L;
private NoPatchSetsWouldRemainException() {
@@ -698,8 +682,7 @@
@Override
public boolean updateChange(ChangeContext ctx)
- throws OrmException, PatchSetInfoNotAvailableException,
- NoPatchSetsWouldRemainException {
+ throws OrmException, PatchSetInfoNotAvailableException, NoPatchSetsWouldRemainException {
if (!toDelete.contains(ctx.getChange().currentPatchSetId())) {
return false;
}
@@ -716,8 +699,8 @@
throw new NoPatchSetsWouldRemainException();
}
PatchSet.Id latest = ReviewDbUtil.intKeyOrdering().max(all);
- ctx.getChange().setCurrentPatchSet(
- patchSetInfoFactory.get(ctx.getDb(), ctx.getNotes(), latest));
+ ctx.getChange()
+ .setCurrentPatchSet(patchSetInfoFactory.get(ctx.getDb(), ctx.getNotes(), latest));
return true;
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/CreateChange.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/CreateChange.java
index 62d9b53..f6f6879 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/CreateChange.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/CreateChange.java
@@ -66,7 +66,12 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.sql.Timestamp;
+import java.util.Collections;
+import java.util.List;
+import java.util.TimeZone;
import org.eclipse.jgit.lib.CommitBuilder;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.lib.ObjectId;
@@ -79,16 +84,8 @@
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.util.ChangeIdUtil;
-import java.io.IOException;
-import java.io.UnsupportedEncodingException;
-import java.sql.Timestamp;
-import java.util.Collections;
-import java.util.List;
-import java.util.TimeZone;
-
@Singleton
-public class CreateChange implements
- RestModifyView<TopLevelResource, ChangeInput> {
+public class CreateChange implements RestModifyView<TopLevelResource, ChangeInput> {
private final String anonymousCowardName;
private final Provider<ReviewDb> db;
@@ -109,7 +106,8 @@
private final NotifyUtil notifyUtil;
@Inject
- CreateChange(@AnonymousCowardName String anonymousCowardName,
+ CreateChange(
+ @AnonymousCowardName String anonymousCowardName,
Provider<ReviewDb> db,
GitRepositoryManager gitManager,
AccountCache accountCache,
@@ -139,16 +137,15 @@
this.updateFactory = updateFactory;
this.psUtil = psUtil;
this.allowDrafts = config.getBoolean("change", "allowDrafts", true);
- this.submitType = config
- .getEnum("project", null, "submitType", SubmitType.MERGE_IF_NECESSARY);
+ this.submitType = config.getEnum("project", null, "submitType", SubmitType.MERGE_IF_NECESSARY);
this.mergeUtilFactory = mergeUtilFactory;
this.notifyUtil = notifyUtil;
}
@Override
public Response<ChangeInfo> apply(TopLevelResource parent, ChangeInput input)
- throws OrmException, IOException, InvalidChangeOperationException,
- RestApiException, UpdateException {
+ throws OrmException, IOException, InvalidChangeOperationException, RestApiException,
+ UpdateException {
if (Strings.isNullOrEmpty(input.project)) {
throw new BadRequestException("project must be non-empty");
}
@@ -162,8 +159,7 @@
}
if (input.status != null) {
- if (input.status != ChangeStatus.NEW
- && input.status != ChangeStatus.DRAFT) {
+ if (input.status != ChangeStatus.NEW && input.status != ChangeStatus.DRAFT) {
throw new BadRequestException("unsupported change status");
}
@@ -187,21 +183,18 @@
Project.NameKey project = rsrc.getNameKey();
try (Repository git = gitManager.openRepository(project);
- ObjectInserter oi = git.newObjectInserter();
- RevWalk rw = new RevWalk(oi.newReader())) {
+ ObjectInserter oi = git.newObjectInserter();
+ RevWalk rw = new RevWalk(oi.newReader())) {
ObjectId parentCommit;
List<String> groups;
if (input.baseChange != null) {
- List<ChangeControl> ctls = changeFinder.find(
- input.baseChange, rsrc.getControl().getUser());
+ List<ChangeControl> ctls = changeFinder.find(input.baseChange, rsrc.getControl().getUser());
if (ctls.size() != 1) {
- throw new InvalidChangeOperationException(
- "Base change not found: " + input.baseChange);
+ throw new InvalidChangeOperationException("Base change not found: " + input.baseChange);
}
ChangeControl ctl = Iterables.getOnlyElement(ctls);
if (!ctl.isVisible(db.get())) {
- throw new InvalidChangeOperationException(
- "Base change not found: " + input.baseChange);
+ throw new InvalidChangeOperationException("Base change not found: " + input.baseChange);
}
PatchSet ps = psUtil.current(db.get(), ctl.getNotes());
parentCommit = ObjectId.fromString(ps.getRevision().get());
@@ -210,61 +203,58 @@
Ref destRef = git.getRefDatabase().exactRef(refName);
if (destRef != null) {
if (Boolean.TRUE.equals(input.newBranch)) {
- throw new ResourceConflictException(String.format(
- "Branch %s already exists.", refName));
+ throw new ResourceConflictException(
+ String.format("Branch %s already exists.", refName));
}
parentCommit = destRef.getObjectId();
} else {
if (Boolean.TRUE.equals(input.newBranch)) {
parentCommit = null;
} else {
- throw new UnprocessableEntityException(String.format(
- "Branch %s does not exist.", refName));
+ throw new UnprocessableEntityException(
+ String.format("Branch %s does not exist.", refName));
}
}
groups = Collections.emptyList();
}
- RevCommit mergeTip =
- parentCommit == null ? null : rw.parseCommit(parentCommit);
+ RevCommit mergeTip = parentCommit == null ? null : rw.parseCommit(parentCommit);
Timestamp now = TimeUtil.nowTs();
IdentifiedUser me = user.get().asIdentifiedUser();
PersonIdent author = me.newCommitterIdent(now, serverTimeZone);
AccountState account = accountCache.get(me.getAccountId());
- GeneralPreferencesInfo info =
- account.getAccount().getGeneralPreferencesInfo();
+ GeneralPreferencesInfo info = account.getAccount().getGeneralPreferencesInfo();
- ObjectId treeId =
- mergeTip == null ? emptyTreeId(oi) : mergeTip.getTree();
- ObjectId id = ChangeIdUtil.computeChangeId(treeId,
- mergeTip, author, author, input.subject);
+ ObjectId treeId = mergeTip == null ? emptyTreeId(oi) : mergeTip.getTree();
+ ObjectId id = ChangeIdUtil.computeChangeId(treeId, mergeTip, author, author, input.subject);
String commitMessage = ChangeIdUtil.insertId(input.subject, id);
if (Boolean.TRUE.equals(info.signedOffBy)) {
- commitMessage += String.format("%s%s",
- SIGNED_OFF_BY_TAG,
- account.getAccount().getNameEmail(anonymousCowardName));
+ commitMessage +=
+ String.format(
+ "%s%s", SIGNED_OFF_BY_TAG, account.getAccount().getNameEmail(anonymousCowardName));
}
RevCommit c;
if (input.merge != null) {
// create a merge commit
- if (!(submitType.equals(SubmitType.MERGE_ALWAYS) ||
- submitType.equals(SubmitType.MERGE_IF_NECESSARY))) {
- throw new BadRequestException(
- "Submit type: " + submitType + " is not supported");
+ if (!(submitType.equals(SubmitType.MERGE_ALWAYS)
+ || submitType.equals(SubmitType.MERGE_IF_NECESSARY))) {
+ throw new BadRequestException("Submit type: " + submitType + " is not supported");
}
- c = newMergeCommit(git, oi, rw, rsrc.getControl(), mergeTip, input.merge,
- author, commitMessage);
+ c =
+ newMergeCommit(
+ git, oi, rw, rsrc.getControl(), mergeTip, input.merge, author, commitMessage);
} else {
// create an empty commit
c = newCommit(oi, rw, author, mergeTip, commitMessage);
}
Change.Id changeId = new Change.Id(seq.nextChangeId());
- ChangeInserter ins = changeInserterFactory.create(changeId, c, refName)
- .setValidatePolicy(CommitValidators.Policy.GERRIT);
- ins.setMessage(String.format("Uploaded patch set %s.",
- ins.getPatchSetId().get()));
+ ChangeInserter ins =
+ changeInserterFactory
+ .create(changeId, c, refName)
+ .setValidatePolicy(CommitValidators.Policy.GERRIT);
+ ins.setMessage(String.format("Uploaded patch set %s.", ins.getPatchSetId().get()));
String topic = input.topic;
if (topic != null) {
topic = Strings.emptyToNull(topic.trim());
@@ -274,8 +264,7 @@
ins.setGroups(groups);
ins.setNotify(input.notify);
ins.setAccountsToNotify(notifyUtil.resolveAccounts(input.notifyDetails));
- try (BatchUpdate bu = updateFactory.create(
- db.get(), project, me, now)) {
+ try (BatchUpdate bu = updateFactory.create(db.get(), project, me, now)) {
bu.setRepository(git, rw, oi);
bu.insertChange(ins);
bu.execute();
@@ -287,8 +276,12 @@
}
}
- private static RevCommit newCommit(ObjectInserter oi, RevWalk rw,
- PersonIdent authorIdent, RevCommit mergeTip, String commitMessage)
+ private static RevCommit newCommit(
+ ObjectInserter oi,
+ RevWalk rw,
+ PersonIdent authorIdent,
+ RevCommit mergeTip,
+ String commitMessage)
throws IOException {
CommitBuilder commit = new CommitBuilder();
if (mergeTip == null) {
@@ -303,9 +296,15 @@
return rw.parseCommit(insert(oi, commit));
}
- private RevCommit newMergeCommit(Repository repo, ObjectInserter oi,
- RevWalk rw, ProjectControl projectControl, RevCommit mergeTip,
- MergeInput merge, PersonIdent authorIdent, String commitMessage)
+ private RevCommit newMergeCommit(
+ Repository repo,
+ ObjectInserter oi,
+ RevWalk rw,
+ ProjectControl projectControl,
+ RevCommit mergeTip,
+ MergeInput merge,
+ PersonIdent authorIdent,
+ String commitMessage)
throws RestApiException, IOException {
if (Strings.isNullOrEmpty(merge.source)) {
throw new BadRequestException("merge.source must be non-empty");
@@ -313,31 +312,27 @@
RevCommit sourceCommit = MergeUtil.resolveCommit(repo, rw, merge.source);
if (!projectControl.canReadCommit(db.get(), repo, sourceCommit)) {
- throw new BadRequestException(
- "do not have read permission for: " + merge.source);
+ throw new BadRequestException("do not have read permission for: " + merge.source);
}
- MergeUtil mergeUtil =
- mergeUtilFactory.create(projectControl.getProjectState());
+ MergeUtil mergeUtil = mergeUtilFactory.create(projectControl.getProjectState());
// default merge strategy from project settings
- String mergeStrategy = MoreObjects.firstNonNull(
- Strings.emptyToNull(merge.strategy),
- mergeUtil.mergeStrategyName());
+ String mergeStrategy =
+ MoreObjects.firstNonNull(
+ Strings.emptyToNull(merge.strategy), mergeUtil.mergeStrategyName());
- return MergeUtil.createMergeCommit(repo, oi, mergeTip, sourceCommit,
- mergeStrategy, authorIdent, commitMessage, rw);
+ return MergeUtil.createMergeCommit(
+ repo, oi, mergeTip, sourceCommit, mergeStrategy, authorIdent, commitMessage, rw);
}
- private static ObjectId insert(ObjectInserter inserter,
- CommitBuilder commit) throws IOException,
- UnsupportedEncodingException {
+ private static ObjectId insert(ObjectInserter inserter, CommitBuilder commit)
+ throws IOException, UnsupportedEncodingException {
ObjectId id = inserter.insert(commit);
inserter.flush();
return id;
}
- private static ObjectId emptyTreeId(ObjectInserter inserter)
- throws IOException {
+ private static ObjectId emptyTreeId(ObjectInserter inserter) throws IOException {
return inserter.insert(new TreeFormatter());
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/CreateDraftComment.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/CreateDraftComment.java
index 5a7b756..6a7647c 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/CreateDraftComment.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/CreateDraftComment.java
@@ -41,7 +41,6 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.util.Collections;
@Singleton
@@ -54,7 +53,8 @@
private final PatchListCache patchListCache;
@Inject
- CreateDraftComment(Provider<ReviewDb> db,
+ CreateDraftComment(
+ Provider<ReviewDb> db,
BatchUpdate.Factory updateFactory,
Provider<CommentJson> commentJson,
CommentsUtil commentsUtil,
@@ -81,13 +81,13 @@
throw new BadRequestException("range endLine must be on the same line as the comment");
}
- try (BatchUpdate bu = updateFactory.create(
- db.get(), rsrc.getProject(), rsrc.getUser(), TimeUtil.nowTs())) {
+ try (BatchUpdate bu =
+ updateFactory.create(db.get(), rsrc.getProject(), rsrc.getUser(), TimeUtil.nowTs())) {
Op op = new Op(rsrc.getPatchSet().getId(), in);
bu.addOp(rsrc.getChange().getId(), op);
bu.execute();
- return Response.created(commentJson.get().setFillAccounts(false)
- .newCommentFormatter().format(op.comment));
+ return Response.created(
+ commentJson.get().setFillAccounts(false).newCommentFormatter().format(op.comment));
}
}
@@ -104,25 +104,23 @@
@Override
public boolean updateChange(ChangeContext ctx)
- throws ResourceNotFoundException, OrmException,
- UnprocessableEntityException {
+ throws ResourceNotFoundException, OrmException, UnprocessableEntityException {
PatchSet ps = psUtil.get(ctx.getDb(), ctx.getNotes(), psId);
if (ps == null) {
throw new ResourceNotFoundException("patch set not found: " + psId);
}
String parentUuid = Url.decode(in.inReplyTo);
- comment = commentsUtil.newComment(
- ctx, in.path, ps.getId(), in.side(), in.message.trim(),
- in.unresolved, parentUuid);
+ comment =
+ commentsUtil.newComment(
+ ctx, in.path, ps.getId(), in.side(), in.message.trim(), in.unresolved, parentUuid);
comment.setLineNbrAndRange(in.line, in.range);
comment.tag = in.tag;
- setCommentRevId(
- comment, patchListCache, ctx.getChange(), ps);
+ setCommentRevId(comment, patchListCache, ctx.getChange(), ps);
- commentsUtil.putComments(ctx.getDb(), ctx.getUpdate(psId), Status.DRAFT,
- Collections.singleton(comment));
+ commentsUtil.putComments(
+ ctx.getDb(), ctx.getUpdate(psId), Status.DRAFT, Collections.singleton(comment));
ctx.bumpLastUpdatedOn(false);
return true;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/CreateMergePatchSet.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/CreateMergePatchSet.java
index ceebce9..b6fea79 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/CreateMergePatchSet.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/CreateMergePatchSet.java
@@ -51,7 +51,10 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
+import java.io.IOException;
+import java.sql.Timestamp;
+import java.util.EnumSet;
+import java.util.TimeZone;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.ObjectInserter;
import org.eclipse.jgit.lib.PersonIdent;
@@ -61,14 +64,8 @@
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.util.ChangeIdUtil;
-import java.io.IOException;
-import java.sql.Timestamp;
-import java.util.EnumSet;
-import java.util.TimeZone;
-
@Singleton
-public class CreateMergePatchSet implements
- RestModifyView<ChangeResource, MergePatchSetInput> {
+public class CreateMergePatchSet implements RestModifyView<ChangeResource, MergePatchSetInput> {
private final Provider<ReviewDb> db;
private final GitRepositoryManager gitManager;
@@ -81,7 +78,8 @@
private final PatchSetInserter.Factory patchSetInserterFactory;
@Inject
- CreateMergePatchSet(Provider<ReviewDb> db,
+ CreateMergePatchSet(
+ Provider<ReviewDb> db,
GitRepositoryManager gitManager,
@GerritPersonIdent PersonIdent myIdent,
Provider<CurrentUser> user,
@@ -103,8 +101,8 @@
@Override
public Response<ChangeInfo> apply(ChangeResource req, MergePatchSetInput in)
- throws OrmException, IOException, InvalidChangeOperationException,
- RestApiException, UpdateException {
+ throws OrmException, IOException, InvalidChangeOperationException, RestApiException,
+ UpdateException {
if (in.merge == null) {
throw new BadRequestException("merge field is required");
}
@@ -116,8 +114,7 @@
ChangeControl ctl = req.getControl();
if (!ctl.isVisible(db.get())) {
- throw new InvalidChangeOperationException(
- "Base change not found: " + req.getId());
+ throw new InvalidChangeOperationException("Base change not found: " + req.getId());
}
PatchSet ps = psUtil.current(db.get(), ctl.getNotes());
if (!ctl.canAddPatchSet(db.get())) {
@@ -132,50 +129,62 @@
ObjectInserter oi = git.newObjectInserter();
RevWalk rw = new RevWalk(oi.newReader())) {
- RevCommit sourceCommit =
- MergeUtil.resolveCommit(git, rw, merge.source);
+ RevCommit sourceCommit = MergeUtil.resolveCommit(git, rw, merge.source);
if (!projectControl.canReadCommit(db.get(), git, sourceCommit)) {
throw new ResourceNotFoundException(
"cannot find source commit: " + merge.source + " to merge.");
}
- RevCommit currentPsCommit =
- rw.parseCommit(ObjectId.fromString(ps.getRevision().get()));
+ RevCommit currentPsCommit = rw.parseCommit(ObjectId.fromString(ps.getRevision().get()));
Timestamp now = TimeUtil.nowTs();
IdentifiedUser me = user.get().asIdentifiedUser();
PersonIdent author = me.newCommitterIdent(now, serverTimeZone);
RevCommit newCommit =
- createMergeCommit(in, projectControl, dest, git, oi, rw,
- currentPsCommit, sourceCommit, author,
+ createMergeCommit(
+ in,
+ projectControl,
+ dest,
+ git,
+ oi,
+ rw,
+ currentPsCommit,
+ sourceCommit,
+ author,
ObjectId.fromString(change.getKey().get().substring(1)));
PatchSet.Id nextPsId = ChangeUtil.nextPatchSetId(ps.getId());
- PatchSetInserter psInserter =
- patchSetInserterFactory.create(ctl, nextPsId, newCommit);
- try (BatchUpdate bu = batchUpdateFactory
- .create(db.get(), project, me, now)) {
+ PatchSetInserter psInserter = patchSetInserterFactory.create(ctl, nextPsId, newCommit);
+ try (BatchUpdate bu = batchUpdateFactory.create(db.get(), project, me, now)) {
bu.setRepository(git, rw, oi);
- bu.addOp(ctl.getId(), psInserter
- .setMessage("Uploaded patch set " + nextPsId.get() + ".")
- .setDraft(ps.isDraft())
- .setNotify(NotifyHandling.NONE));
+ bu.addOp(
+ ctl.getId(),
+ psInserter
+ .setMessage("Uploaded patch set " + nextPsId.get() + ".")
+ .setDraft(ps.isDraft())
+ .setNotify(NotifyHandling.NONE));
bu.execute();
}
- ChangeJson json =
- jsonFactory.create(EnumSet.of(ListChangesOption.CURRENT_REVISION));
+ ChangeJson json = jsonFactory.create(EnumSet.of(ListChangesOption.CURRENT_REVISION));
return Response.ok(json.format(psInserter.getChange()));
}
}
- private RevCommit createMergeCommit(MergePatchSetInput in,
- ProjectControl projectControl, Branch.NameKey dest, Repository git,
- ObjectInserter oi, RevWalk rw, RevCommit currentPsCommit,
- RevCommit sourceCommit, PersonIdent author, ObjectId changeId)
- throws ResourceNotFoundException, MergeIdenticalTreeException,
- MergeConflictException, IOException {
+ private RevCommit createMergeCommit(
+ MergePatchSetInput in,
+ ProjectControl projectControl,
+ Branch.NameKey dest,
+ Repository git,
+ ObjectInserter oi,
+ RevWalk rw,
+ RevCommit currentPsCommit,
+ RevCommit sourceCommit,
+ PersonIdent author,
+ ObjectId changeId)
+ throws ResourceNotFoundException, MergeIdenticalTreeException, MergeConflictException,
+ IOException {
ObjectId parentCommit;
if (in.inheritParent) {
@@ -200,12 +209,12 @@
commitMsg = currentPsCommit.getFullMessage();
}
- String mergeStrategy = MoreObjects.firstNonNull(
- Strings.emptyToNull(in.merge.strategy),
- mergeUtilFactory.create(projectControl.getProjectState())
- .mergeStrategyName());
+ String mergeStrategy =
+ MoreObjects.firstNonNull(
+ Strings.emptyToNull(in.merge.strategy),
+ mergeUtilFactory.create(projectControl.getProjectState()).mergeStrategyName());
- return MergeUtil.createMergeCommit(git, oi, mergeTip, sourceCommit,
- mergeStrategy, author, commitMsg, rw);
+ return MergeUtil.createMergeCommit(
+ git, oi, mergeTip, sourceCommit, mergeStrategy, author, commitMsg, rw);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/DeleteAssignee.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/DeleteAssignee.java
index 4d5b739..f1769f6 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/DeleteAssignee.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/DeleteAssignee.java
@@ -41,9 +41,8 @@
@Singleton
public class DeleteAssignee implements RestModifyView<ChangeResource, Input> {
- public static class Input {
+ public static class Input {}
- }
private final BatchUpdate.Factory batchUpdateFactory;
private final ChangeMessagesUtil cmUtil;
private final Provider<ReviewDb> db;
@@ -52,7 +51,8 @@
private final AccountLoader.Factory accountLoaderFactory;
@Inject
- DeleteAssignee(BatchUpdate.Factory batchUpdateFactory,
+ DeleteAssignee(
+ BatchUpdate.Factory batchUpdateFactory,
ChangeMessagesUtil cmUtil,
Provider<ReviewDb> db,
AssigneeChanged assigneeChanged,
@@ -69,17 +69,15 @@
@Override
public Response<AccountInfo> apply(ChangeResource rsrc, Input input)
throws RestApiException, UpdateException, OrmException {
- try (BatchUpdate bu = batchUpdateFactory.create(db.get(),
- rsrc.getProject(),
- rsrc.getUser(), TimeUtil.nowTs())) {
+ try (BatchUpdate bu =
+ batchUpdateFactory.create(db.get(), rsrc.getProject(), rsrc.getUser(), TimeUtil.nowTs())) {
Op op = new Op();
bu.addOp(rsrc.getChange().getId(), op);
bu.execute();
Account.Id deletedAssignee = op.getDeletedAssignee();
return deletedAssignee == null
? Response.none()
- : Response.ok(accountLoaderFactory.create(true)
- .fillOne(deletedAssignee));
+ : Response.ok(accountLoaderFactory.create(true).fillOne(deletedAssignee));
}
}
@@ -88,8 +86,7 @@
private Account deletedAssignee;
@Override
- public boolean updateChange(ChangeContext ctx)
- throws RestApiException, OrmException{
+ public boolean updateChange(ChangeContext ctx) throws RestApiException, OrmException {
if (!ctx.getControl().canEditAssignee()) {
throw new AuthException("Delete Assignee not permitted");
}
@@ -99,8 +96,7 @@
if (currentAssigneeId == null) {
return false;
}
- IdentifiedUser deletedAssigneeUser =
- userFactory.create(currentAssigneeId);
+ IdentifiedUser deletedAssigneeUser = userFactory.create(currentAssigneeId);
deletedAssignee = deletedAssigneeUser.getAccount();
// noteDb
update.removeAssignee();
@@ -114,18 +110,20 @@
return deletedAssignee != null ? deletedAssignee.getId() : null;
}
- private void addMessage(BatchUpdate.ChangeContext ctx, ChangeUpdate update,
- IdentifiedUser deletedAssignee) throws OrmException {
- ChangeMessage cmsg = ChangeMessagesUtil.newMessage(
- ctx, "Assignee deleted: " + deletedAssignee.getNameEmail(),
- ChangeMessagesUtil.TAG_DELETE_ASSIGNEE);
+ private void addMessage(
+ BatchUpdate.ChangeContext ctx, ChangeUpdate update, IdentifiedUser deletedAssignee)
+ throws OrmException {
+ ChangeMessage cmsg =
+ ChangeMessagesUtil.newMessage(
+ ctx,
+ "Assignee deleted: " + deletedAssignee.getNameEmail(),
+ ChangeMessagesUtil.TAG_DELETE_ASSIGNEE);
cmUtil.addChangeMessage(ctx.getDb(), update, cmsg);
}
@Override
public void postUpdate(Context ctx) throws OrmException {
- assigneeChanged.fire(change, ctx.getAccount(), deletedAssignee,
- ctx.getWhen());
+ assigneeChanged.fire(change, ctx.getAccount(), deletedAssignee, ctx.getWhen());
}
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/DeleteChange.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/DeleteChange.java
index 18d7074..d0c9a25 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/DeleteChange.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/DeleteChange.java
@@ -31,14 +31,12 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import org.eclipse.jgit.lib.Config;
@Singleton
-public class DeleteChange implements
- RestModifyView<ChangeResource, Input>, UiAction<ChangeResource> {
- public static class Input {
- }
+public class DeleteChange
+ implements RestModifyView<ChangeResource, Input>, UiAction<ChangeResource> {
+ public static class Input {}
private final Provider<ReviewDb> db;
private final BatchUpdate.Factory updateFactory;
@@ -46,7 +44,8 @@
private final boolean allowDrafts;
@Inject
- public DeleteChange(Provider<ReviewDb> db,
+ public DeleteChange(
+ Provider<ReviewDb> db,
BatchUpdate.Factory updateFactory,
Provider<DeleteChangeOp> opProvider,
@GerritServerConfig Config cfg) {
@@ -59,8 +58,8 @@
@Override
public Response<?> apply(ChangeResource rsrc, Input input)
throws RestApiException, UpdateException {
- try (BatchUpdate bu = updateFactory.create(
- db.get(), rsrc.getProject(), rsrc.getUser(), TimeUtil.nowTs())) {
+ try (BatchUpdate bu =
+ updateFactory.create(db.get(), rsrc.getProject(), rsrc.getUser(), TimeUtil.nowTs())) {
Change.Id id = rsrc.getChange().getId();
bu.setOrder(BatchUpdate.Order.DB_BEFORE_REPO);
bu.addOp(id, opProvider.get());
@@ -74,19 +73,18 @@
try {
Change.Status status = rsrc.getChange().getStatus();
ChangeControl changeControl = rsrc.getControl();
- boolean visible = isActionAllowed(changeControl, status)
- && changeControl.canDelete(db.get(), status);
+ boolean visible =
+ isActionAllowed(changeControl, status) && changeControl.canDelete(db.get(), status);
return new UiAction.Description()
- .setLabel("Delete")
- .setTitle("Delete change " + rsrc.getId())
- .setVisible(visible);
+ .setLabel("Delete")
+ .setTitle("Delete change " + rsrc.getId())
+ .setVisible(visible);
} catch (OrmException e) {
throw new IllegalStateException(e);
}
}
- private boolean isActionAllowed(ChangeControl changeControl,
- Status status) {
+ private boolean isActionAllowed(ChangeControl changeControl, Status status) {
return status != Status.DRAFT || allowDrafts || changeControl.isAdmin();
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/DeleteChangeEdit.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/DeleteChangeEdit.java
index 604b615..f196ec8 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/DeleteChangeEdit.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/DeleteChangeEdit.java
@@ -24,14 +24,12 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
import java.io.IOException;
import java.util.Optional;
@Singleton
public class DeleteChangeEdit implements RestModifyView<ChangeResource, Input> {
- public static class Input {
- }
+ public static class Input {}
private final ChangeEditUtil editUtil;
@@ -42,8 +40,7 @@
@Override
public Response<?> apply(ChangeResource rsrc, Input input)
- throws AuthException, ResourceNotFoundException, IOException,
- OrmException {
+ throws AuthException, ResourceNotFoundException, IOException, OrmException {
Optional<ChangeEdit> edit = editUtil.byChange(rsrc.getChange());
if (edit.isPresent()) {
editUtil.delete(edit.get());
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/DeleteChangeOp.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/DeleteChangeOp.java
index d1f7cac..034a669 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/DeleteChangeOp.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/DeleteChangeOp.java
@@ -35,7 +35,9 @@
import com.google.gerrit.server.project.NoSuchChangeException;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
-
+import java.io.IOException;
+import java.util.Collection;
+import java.util.Collections;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Ref;
@@ -44,10 +46,6 @@
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.transport.ReceiveCommand;
-import java.io.IOException;
-import java.util.Collection;
-import java.util.Collections;
-
class DeleteChangeOp extends BatchUpdate.Op {
static boolean allowDrafts(Config cfg) {
return cfg.getBoolean("change", "allowDrafts", true);
@@ -63,7 +61,6 @@
return ReviewDbUtil.unwrapDb(db);
}
-
private final PatchSetUtil psUtil;
private final StarredChangesUtil starredChangesUtil;
private final DynamicItem<AccountPatchReviewStore> accountPatchReviewStore;
@@ -72,7 +69,8 @@
private Change.Id id;
@Inject
- DeleteChangeOp(PatchSetUtil psUtil,
+ DeleteChangeOp(
+ PatchSetUtil psUtil,
StarredChangesUtil starredChangesUtil,
DynamicItem<AccountPatchReviewStore> accountPatchReviewStore,
@GerritServerConfig Config cfg) {
@@ -83,15 +81,15 @@
}
@Override
- public boolean updateChange(ChangeContext ctx) throws RestApiException,
- OrmException, IOException, NoSuchChangeException {
- checkState(ctx.getOrder() == BatchUpdate.Order.DB_BEFORE_REPO,
+ public boolean updateChange(ChangeContext ctx)
+ throws RestApiException, OrmException, IOException, NoSuchChangeException {
+ checkState(
+ ctx.getOrder() == BatchUpdate.Order.DB_BEFORE_REPO,
"must use DeleteChangeOp with DB_BEFORE_REPO");
checkState(id == null, "cannot reuse DeleteChangeOp");
id = ctx.getChange().getId();
- Collection<PatchSet> patchSets = psUtil.byChange(ctx.getDb(),
- ctx.getNotes());
+ Collection<PatchSet> patchSets = psUtil.byChange(ctx.getDb(), ctx.getNotes());
ensureDeletable(ctx, id, patchSets);
// Cleaning up is only possible as long as the change and its elements are
@@ -103,19 +101,19 @@
return true;
}
- private void ensureDeletable(ChangeContext ctx, Change.Id id,
- Collection<PatchSet> patchSets) throws ResourceConflictException,
- MethodNotAllowedException, OrmException, AuthException, IOException {
+ private void ensureDeletable(ChangeContext ctx, Change.Id id, Collection<PatchSet> patchSets)
+ throws ResourceConflictException, MethodNotAllowedException, OrmException, AuthException,
+ IOException {
Change.Status status = ctx.getChange().getStatus();
if (status == Change.Status.MERGED) {
- throw new MethodNotAllowedException("Deleting merged change " + id
- + " is not allowed");
+ throw new MethodNotAllowedException("Deleting merged change " + id + " is not allowed");
}
for (PatchSet patchSet : patchSets) {
if (isPatchSetMerged(ctx, patchSet)) {
- throw new ResourceConflictException(String.format(
- "Cannot delete change %s: patch set %s is already merged",
- id, patchSet.getPatchSetId()));
+ throw new ResourceConflictException(
+ String.format(
+ "Cannot delete change %s: patch set %s is already merged",
+ id, patchSet.getPatchSetId()));
}
}
@@ -129,15 +127,18 @@
}
for (PatchSet ps : patchSets) {
if (!ps.isDraft()) {
- throw new ResourceConflictException("Cannot delete draft change " + id
- + ": patch set " + ps.getPatchSetId() + " is not a draft");
+ throw new ResourceConflictException(
+ "Cannot delete draft change "
+ + id
+ + ": patch set "
+ + ps.getPatchSetId()
+ + " is not a draft");
}
}
}
}
- private boolean isPatchSetMerged(ChangeContext ctx, PatchSet patchSet)
- throws IOException {
+ private boolean isPatchSetMerged(ChangeContext ctx, PatchSet patchSet) throws IOException {
Repository repository = ctx.getRepository();
Ref destinationRef = repository.exactRef(ctx.getChange().getDest().get());
if (destinationRef == null) {
@@ -147,12 +148,11 @@
RevWalk revWalk = ctx.getRevWalk();
ObjectId objectId = ObjectId.fromString(patchSet.getRevision().get());
RevCommit revCommit = revWalk.parseCommit(objectId);
- return IncludedInResolver.includedInOne(repository, revWalk, revCommit,
- Collections.singletonList(destinationRef));
+ return IncludedInResolver.includedInOne(
+ repository, revWalk, revCommit, Collections.singletonList(destinationRef));
}
- private void deleteChangeElementsFromDb(ChangeContext ctx, Change.Id id)
- throws OrmException {
+ private void deleteChangeElementsFromDb(ChangeContext ctx, Change.Id id) throws OrmException {
// Only delete from ReviewDb here; deletion from NoteDb is handled in
// BatchUpdate.
ReviewDb db = unwrap(ctx.getDb());
@@ -162,9 +162,8 @@
db.changeMessages().delete(db.changeMessages().byChange(id));
}
- private void cleanUpReferences(ChangeContext ctx, Change.Id id,
- Collection<PatchSet> patchSets) throws OrmException,
- NoSuchChangeException {
+ private void cleanUpReferences(ChangeContext ctx, Change.Id id, Collection<PatchSet> patchSets)
+ throws OrmException, NoSuchChangeException {
for (PatchSet ps : patchSets) {
accountPatchReviewStore.get().clearReviewed(ps.getId());
}
@@ -178,11 +177,8 @@
public void updateRepo(RepoContext ctx) throws IOException {
String prefix = new PatchSet.Id(id, 1).toRefName();
prefix = prefix.substring(0, prefix.length() - 1);
- for (Ref ref
- : ctx.getRepository().getRefDatabase().getRefs(prefix).values()) {
- ctx.addRefUpdate(
- new ReceiveCommand(
- ref.getObjectId(), ObjectId.zeroId(), ref.getName()));
+ for (Ref ref : ctx.getRepository().getRefDatabase().getRefs(prefix).values()) {
+ ctx.addRefUpdate(new ReceiveCommand(ref.getObjectId(), ObjectId.zeroId(), ref.getName()));
}
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/DeleteDraftComment.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/DeleteDraftComment.java
index 37930dd..645238b 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/DeleteDraftComment.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/DeleteDraftComment.java
@@ -36,15 +36,12 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.util.Collections;
import java.util.Optional;
@Singleton
-public class DeleteDraftComment
- implements RestModifyView<DraftCommentResource, Input> {
- static class Input {
- }
+public class DeleteDraftComment implements RestModifyView<DraftCommentResource, Input> {
+ static class Input {}
private final Provider<ReviewDb> db;
private final CommentsUtil commentsUtil;
@@ -53,7 +50,8 @@
private final PatchListCache patchListCache;
@Inject
- DeleteDraftComment(Provider<ReviewDb> db,
+ DeleteDraftComment(
+ Provider<ReviewDb> db,
CommentsUtil commentsUtil,
PatchSetUtil psUtil,
BatchUpdate.Factory updateFactory,
@@ -68,9 +66,12 @@
@Override
public Response<CommentInfo> apply(DraftCommentResource rsrc, Input input)
throws RestApiException, UpdateException {
- try (BatchUpdate bu = updateFactory.create(
- db.get(), rsrc.getChange().getProject(), rsrc.getControl().getUser(),
- TimeUtil.nowTs())) {
+ try (BatchUpdate bu =
+ updateFactory.create(
+ db.get(),
+ rsrc.getChange().getProject(),
+ rsrc.getControl().getUser(),
+ TimeUtil.nowTs())) {
Op op = new Op(rsrc.getComment().key);
bu.addOp(rsrc.getChange().getId(), op);
bu.execute();
@@ -86,23 +87,19 @@
}
@Override
- public boolean updateChange(ChangeContext ctx)
- throws ResourceNotFoundException, OrmException {
- Optional<Comment> maybeComment =
- commentsUtil.get(ctx.getDb(), ctx.getNotes(), key);
+ public boolean updateChange(ChangeContext ctx) throws ResourceNotFoundException, OrmException {
+ Optional<Comment> maybeComment = commentsUtil.get(ctx.getDb(), ctx.getNotes(), key);
if (!maybeComment.isPresent()) {
return false; // Nothing to do.
}
- PatchSet.Id psId =
- new PatchSet.Id(ctx.getChange().getId(), key.patchSetId);
+ PatchSet.Id psId = new PatchSet.Id(ctx.getChange().getId(), key.patchSetId);
PatchSet ps = psUtil.get(ctx.getDb(), ctx.getNotes(), psId);
if (ps == null) {
throw new ResourceNotFoundException("patch set not found: " + psId);
}
Comment c = maybeComment.get();
setCommentRevId(c, patchListCache, ctx.getChange(), ps);
- commentsUtil.deleteComments(
- ctx.getDb(), ctx.getUpdate(psId), Collections.singleton(c));
+ commentsUtil.deleteComments(ctx.getDb(), ctx.getUpdate(psId), Collections.singleton(c));
ctx.bumpLastUpdatedOn(false);
return true;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/DeleteDraftPatchSet.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/DeleteDraftPatchSet.java
index e473e39..76d366e 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/DeleteDraftPatchSet.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/DeleteDraftPatchSet.java
@@ -41,19 +41,16 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
+import java.io.IOException;
+import java.util.Collection;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.transport.ReceiveCommand;
-import java.io.IOException;
-import java.util.Collection;
-
@Singleton
-public class DeleteDraftPatchSet implements RestModifyView<RevisionResource, Input>,
- UiAction<RevisionResource> {
- public static class Input {
- }
+public class DeleteDraftPatchSet
+ implements RestModifyView<RevisionResource, Input>, UiAction<RevisionResource> {
+ public static class Input {}
private final Provider<ReviewDb> db;
private final BatchUpdate.Factory updateFactory;
@@ -64,7 +61,8 @@
private final boolean allowDrafts;
@Inject
- public DeleteDraftPatchSet(Provider<ReviewDb> db,
+ public DeleteDraftPatchSet(
+ Provider<ReviewDb> db,
BatchUpdate.Factory updateFactory,
PatchSetInfoFactory patchSetInfoFactory,
PatchSetUtil psUtil,
@@ -83,8 +81,8 @@
@Override
public Response<?> apply(RevisionResource rsrc, Input input)
throws RestApiException, UpdateException {
- try (BatchUpdate bu = updateFactory.create(
- db.get(), rsrc.getProject(), rsrc.getUser(), TimeUtil.nowTs())) {
+ try (BatchUpdate bu =
+ updateFactory.create(db.get(), rsrc.getProject(), rsrc.getUser(), TimeUtil.nowTs())) {
bu.setOrder(BatchUpdate.Order.DB_BEFORE_REPO);
bu.addOp(rsrc.getChange().getId(), new Op(rsrc.getPatchSet().getId()));
bu.execute();
@@ -104,8 +102,8 @@
}
@Override
- public boolean updateChange(ChangeContext ctx) throws RestApiException,
- OrmException, IOException, NoSuchChangeException {
+ public boolean updateChange(ChangeContext ctx)
+ throws RestApiException, OrmException, IOException, NoSuchChangeException {
patchSet = psUtil.get(ctx.getDb(), ctx.getNotes(), psId);
if (patchSet == null) {
return false; // Nothing to do.
@@ -139,8 +137,7 @@
patchSet.getRefName()));
}
- private void deleteDraftPatchSet(PatchSet patchSet, ChangeContext ctx)
- throws OrmException {
+ private void deleteDraftPatchSet(PatchSet patchSet, ChangeContext ctx) throws OrmException {
// For NoteDb itself, no need to delete these entities, as they are
// automatically filtered out when patch sets are deleted.
psUtil.delete(ctx.getDb(), ctx.getUpdate(patchSet.getId()), patchSet);
@@ -154,8 +151,7 @@
}
private void deleteOrUpdateDraftChange(ChangeContext ctx)
- throws OrmException, RestApiException, IOException,
- NoSuchChangeException {
+ throws OrmException, RestApiException, IOException, NoSuchChangeException {
Change c = ctx.getChange();
if (deletedOnlyPatchSet()) {
deleteChangeOp = deleteChangeOpProvider.get();
@@ -172,13 +168,12 @@
&& patchSetsBeforeDeletion.iterator().next().getId().equals(psId);
}
- private PatchSetInfo previousPatchSetInfo(ChangeContext ctx)
- throws OrmException {
+ private PatchSetInfo previousPatchSetInfo(ChangeContext ctx) throws OrmException {
try {
// TODO(dborowitz): Get this in a way that doesn't involve re-opening
// the repo after the updateRepo phase.
- return patchSetInfoFactory.get(ctx.getDb(), ctx.getNotes(),
- new PatchSet.Id(psId.getParentKey(), psId.get() - 1));
+ return patchSetInfoFactory.get(
+ ctx.getDb(), ctx.getNotes(), new PatchSet.Id(psId.getParentKey(), psId.get() - 1));
} catch (PatchSetInfoNotAvailableException e) {
throw new OrmException(e);
}
@@ -190,13 +185,13 @@
try {
int psCount = psUtil.byChange(db.get(), rsrc.getNotes()).size();
return new UiAction.Description()
- .setLabel("Delete")
- .setTitle(String.format("Delete draft revision %d",
- rsrc.getPatchSet().getPatchSetId()))
- .setVisible(allowDrafts
- && rsrc.getPatchSet().isDraft()
- && rsrc.getControl().canDelete(db.get(), Change.Status.DRAFT)
- && psCount > 1);
+ .setLabel("Delete")
+ .setTitle(String.format("Delete draft revision %d", rsrc.getPatchSet().getPatchSetId()))
+ .setVisible(
+ allowDrafts
+ && rsrc.getPatchSet().isDraft()
+ && rsrc.getControl().canDelete(db.get(), Change.Status.DRAFT)
+ && psCount > 1);
} catch (OrmException e) {
throw new IllegalStateException(e);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/DeleteReviewer.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/DeleteReviewer.java
index 3c5aeb5..71e2aa4 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/DeleteReviewer.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/DeleteReviewer.java
@@ -51,21 +51,17 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
@Singleton
-public class DeleteReviewer
- implements RestModifyView<ReviewerResource, DeleteReviewerInput> {
- private static final Logger log = LoggerFactory
- .getLogger(DeleteReviewer.class);
+public class DeleteReviewer implements RestModifyView<ReviewerResource, DeleteReviewerInput> {
+ private static final Logger log = LoggerFactory.getLogger(DeleteReviewer.class);
private final Provider<ReviewDb> dbProvider;
private final ApprovalsUtil approvalsUtil;
@@ -80,7 +76,8 @@
private final NotifyUtil notifyUtil;
@Inject
- DeleteReviewer(Provider<ReviewDb> dbProvider,
+ DeleteReviewer(
+ Provider<ReviewDb> dbProvider,
ApprovalsUtil approvalsUtil,
PatchSetUtil psUtil,
ChangeMessagesUtil cmUtil,
@@ -114,9 +111,12 @@
input.notify = NotifyHandling.ALL;
}
- try (BatchUpdate bu = batchUpdateFactory.create(dbProvider.get(),
- rsrc.getChangeResource().getProject(),
- rsrc.getChangeResource().getUser(), TimeUtil.nowTs())) {
+ try (BatchUpdate bu =
+ batchUpdateFactory.create(
+ dbProvider.get(),
+ rsrc.getChangeResource().getProject(),
+ rsrc.getChangeResource().getUser(),
+ TimeUtil.nowTs())) {
Op op = new Op(rsrc.getReviewerUser().getAccount(), input);
bu.addOp(rsrc.getChange().getId(), op);
bu.execute();
@@ -143,8 +143,7 @@
public boolean updateChange(ChangeContext ctx)
throws AuthException, ResourceNotFoundException, OrmException {
Account.Id reviewerId = reviewer.getId();
- if (!approvalsUtil.getReviewers(ctx.getDb(), ctx.getNotes()).all()
- .contains(reviewerId)) {
+ if (!approvalsUtil.getReviewers(ctx.getDb(), ctx.getNotes()).all().contains(reviewerId)) {
throw new ResourceNotFoundException();
}
currChange = ctx.getChange();
@@ -167,8 +166,11 @@
del.add(a);
if (a.getPatchSetId().equals(currPs.getId()) && a.getValue() != 0) {
oldApprovals.put(a.getLabel(), a.getValue());
- removedVotesMsg.append("* ").append(a.getLabel())
- .append(formatLabelValue(a.getValue())).append(" by ")
+ removedVotesMsg
+ .append("* ")
+ .append(a.getLabel())
+ .append(formatLabelValue(a.getValue()))
+ .append(" by ")
.append(userFactory.create(a.getAccountId()).getNameEmail())
.append("\n");
votesRemoved = true;
@@ -187,8 +189,9 @@
ChangeUpdate update = ctx.getUpdate(currPs.getId());
update.removeReviewer(reviewerId);
- changeMessage = ChangeMessagesUtil.newMessage(ctx, msg.toString(),
- ChangeMessagesUtil.TAG_DELETE_REVIEWER);
+ changeMessage =
+ ChangeMessagesUtil.newMessage(
+ ctx, msg.toString(), ChangeMessagesUtil.TAG_DELETE_REVIEWER);
cmUtil.addChangeMessage(ctx.getDb(), update, changeMessage);
return true;
@@ -199,22 +202,25 @@
if (NotifyUtil.shouldNotify(input.notify, input.notifyDetails)) {
emailReviewers(ctx.getProject(), currChange, changeMessage);
}
- reviewerDeleted.fire(currChange, currPs, reviewer,
+ reviewerDeleted.fire(
+ currChange,
+ currPs,
+ reviewer,
ctx.getAccount(),
changeMessage.getMessage(),
- newApprovals, oldApprovals,
+ newApprovals,
+ oldApprovals,
input.notify,
ctx.getWhen());
}
- private Iterable<PatchSetApproval> approvals(ChangeContext ctx,
- Account.Id accountId) throws OrmException {
+ private Iterable<PatchSetApproval> approvals(ChangeContext ctx, Account.Id accountId)
+ throws OrmException {
Change.Id changeId = ctx.getNotes().getChangeId();
Iterable<PatchSetApproval> approvals;
PrimaryStorage r = PrimaryStorage.of(ctx.getChange());
- if (migration.readChanges()
- && r == PrimaryStorage.REVIEW_DB) {
+ if (migration.readChanges() && r == PrimaryStorage.REVIEW_DB) {
// Because NoteDb and ReviewDb have different semantics for zero-value
// approvals, we must fall back to ReviewDb as the source of truth here.
ReviewDb db = ctx.getDb();
@@ -225,12 +231,10 @@
db = ReviewDbUtil.unwrapDb(db);
approvals = db.patchSetApprovals().byChange(changeId);
} else {
- approvals =
- approvalsUtil.byChange(ctx.getDb(), ctx.getNotes()).values();
+ approvals = approvalsUtil.byChange(ctx.getDb(), ctx.getNotes()).values();
}
- return Iterables.filter(
- approvals, psa -> accountId.equals(psa.getAccountId()));
+ return Iterables.filter(approvals, psa -> accountId.equals(psa.getAccountId()));
}
private String formatLabelValue(short value) {
@@ -240,23 +244,20 @@
return Short.toString(value);
}
- private void emailReviewers(Project.NameKey projectName, Change change,
- ChangeMessage changeMessage) {
+ private void emailReviewers(
+ Project.NameKey projectName, Change change, ChangeMessage changeMessage) {
Account.Id userId = user.get().getAccountId();
if (userId.equals(reviewer.getId())) {
// The user knows they removed themselves, don't bother emailing them.
return;
}
try {
- DeleteReviewerSender cm =
- deleteReviewerSenderFactory.create(projectName, change.getId());
+ DeleteReviewerSender cm = deleteReviewerSenderFactory.create(projectName, change.getId());
cm.setFrom(userId);
cm.addReviewers(Collections.singleton(reviewer.getId()));
- cm.setChangeMessage(changeMessage.getMessage(),
- changeMessage.getWrittenOn());
+ cm.setChangeMessage(changeMessage.getMessage(), changeMessage.getWrittenOn());
cm.setNotify(input.notify);
- cm.setAccountsToNotify(
- notifyUtil.resolveAccounts(input.notifyDetails));
+ cm.setAccountsToNotify(notifyUtil.resolveAccounts(input.notifyDetails));
cm.send();
} catch (Exception err) {
log.error("Cannot email update for change " + change.getId(), err);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/DeleteVote.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/DeleteVote.java
index 9a0807d2..6232528 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/DeleteVote.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/DeleteVote.java
@@ -51,17 +51,14 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
@Singleton
-public class DeleteVote
- implements RestModifyView<VoteResource, DeleteVoteInput> {
+public class DeleteVote implements RestModifyView<VoteResource, DeleteVoteInput> {
private static final Logger log = LoggerFactory.getLogger(DeleteVote.class);
private final Provider<ReviewDb> db;
@@ -75,7 +72,8 @@
private final NotifyUtil notifyUtil;
@Inject
- DeleteVote(Provider<ReviewDb> db,
+ DeleteVote(
+ Provider<ReviewDb> db,
BatchUpdate.Factory batchUpdateFactory,
ApprovalsUtil approvalsUtil,
PatchSetUtil psUtil,
@@ -110,16 +108,14 @@
ReviewerResource r = rsrc.getReviewer();
Change change = r.getChange();
- if (r.getRevisionResource() != null
- && !r.getRevisionResource().isCurrent()) {
- throw new MethodNotAllowedException(
- "Cannot delete vote on non-current patch set");
+ if (r.getRevisionResource() != null && !r.getRevisionResource().isCurrent()) {
+ throw new MethodNotAllowedException("Cannot delete vote on non-current patch set");
}
- try (BatchUpdate bu = batchUpdateFactory.create(db.get(),
- change.getProject(), r.getControl().getUser(), TimeUtil.nowTs())) {
- bu.addOp(change.getId(),
- new Op(r.getReviewerUser().getAccountId(), rsrc.getLabel(), input));
+ try (BatchUpdate bu =
+ batchUpdateFactory.create(
+ db.get(), change.getProject(), r.getControl().getUser(), TimeUtil.nowTs())) {
+ bu.addOp(change.getId(), new Op(r.getReviewerUser().getAccountId(), rsrc.getLabel(), input));
bu.execute();
}
@@ -153,8 +149,7 @@
boolean found = false;
LabelTypes labelTypes = ctx.getControl().getLabelTypes();
- for (PatchSetApproval a : approvalsUtil.byPatchSetUser(
- ctx.getDb(), ctl, psId, accountId)) {
+ for (PatchSetApproval a : approvalsUtil.byPatchSetUser(ctx.getDb(), ctl, psId, accountId)) {
if (labelTypes.byLabel(a.getLabelId()) == null) {
continue; // Ignore undefined labels.
} else if (!a.getLabel().equals(label)) {
@@ -177,19 +172,15 @@
}
ctx.getUpdate(psId).removeApprovalFor(accountId, label);
- ctx.getDb().patchSetApprovals().upsert(
- Collections.singleton(deletedApproval(ctx)));
+ ctx.getDb().patchSetApprovals().upsert(Collections.singleton(deletedApproval(ctx)));
StringBuilder msg = new StringBuilder();
msg.append("Removed ");
LabelVote.appendTo(msg, label, checkNotNull(oldApprovals.get(label)));
- msg.append(" by ")
- .append(userFactory.create(accountId).getNameEmail())
- .append("\n");
- changeMessage = ChangeMessagesUtil.newMessage(ctx, msg.toString(),
- ChangeMessagesUtil.TAG_DELETE_VOTE);
- cmUtil.addChangeMessage(ctx.getDb(), ctx.getUpdate(psId),
- changeMessage);
+ msg.append(" by ").append(userFactory.create(accountId).getNameEmail()).append("\n");
+ changeMessage =
+ ChangeMessagesUtil.newMessage(ctx, msg.toString(), ChangeMessagesUtil.TAG_DELETE_VOTE);
+ cmUtil.addChangeMessage(ctx.getDb(), ctx.getUpdate(psId), changeMessage);
return true;
}
@@ -199,10 +190,7 @@
// set the real user; this preserves the calling user as the NoteDb
// committer.
return new PatchSetApproval(
- new PatchSetApproval.Key(
- ps.getId(),
- accountId,
- new LabelId(label)),
+ new PatchSetApproval.Key(ps.getId(), accountId, new LabelId(label)),
(short) 0,
ctx.getWhen());
}
@@ -216,22 +204,26 @@
IdentifiedUser user = ctx.getIdentifiedUser();
if (NotifyUtil.shouldNotify(input.notify, input.notifyDetails)) {
try {
- ReplyToChangeSender cm = deleteVoteSenderFactory.create(
- ctx.getProject(), change.getId());
+ ReplyToChangeSender cm = deleteVoteSenderFactory.create(ctx.getProject(), change.getId());
cm.setFrom(user.getAccountId());
cm.setChangeMessage(changeMessage.getMessage(), ctx.getWhen());
cm.setNotify(input.notify);
- cm.setAccountsToNotify(
- notifyUtil.resolveAccounts(input.notifyDetails));
+ cm.setAccountsToNotify(notifyUtil.resolveAccounts(input.notifyDetails));
cm.send();
} catch (Exception e) {
log.error("Cannot email update for change " + change.getId(), e);
}
}
- voteDeleted.fire(change, ps,
- newApprovals, oldApprovals, input.notify, changeMessage.getMessage(),
- user.getAccount(), ctx.getWhen());
+ voteDeleted.fire(
+ change,
+ ps,
+ newApprovals,
+ oldApprovals,
+ input.notify,
+ changeMessage.getMessage(),
+ user.getAccount(),
+ ctx.getWhen());
}
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/DownloadContent.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/DownloadContent.java
index 24c2f0e..827dfcd 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/DownloadContent.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/DownloadContent.java
@@ -21,12 +21,10 @@
import com.google.gerrit.server.project.ProjectState;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
-
+import java.io.IOException;
import org.eclipse.jgit.lib.ObjectId;
import org.kohsuke.args4j.Option;
-import java.io.IOException;
-
public class DownloadContent implements RestReadView<FileResource> {
private final FileContentUtil fileContentUtil;
@@ -40,13 +38,11 @@
@Override
public BinaryResult apply(FileResource rsrc)
- throws ResourceNotFoundException, IOException, NoSuchChangeException,
- OrmException {
+ throws ResourceNotFoundException, IOException, NoSuchChangeException, OrmException {
String path = rsrc.getPatchKey().get();
ProjectState projectState =
rsrc.getRevision().getControl().getProjectControl().getProjectState();
- ObjectId revstr = ObjectId.fromString(
- rsrc.getRevision().getPatchSet().getRevision().get());
+ ObjectId revstr = ObjectId.fromString(rsrc.getRevision().getPatchSet().getRevision().get());
return fileContentUtil.downloadContent(projectState, revstr, path, parent);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/DraftComments.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/DraftComments.java
index fe82d66..4befc5b 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/DraftComments.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/DraftComments.java
@@ -38,7 +38,8 @@
private final CommentsUtil commentsUtil;
@Inject
- DraftComments(DynamicMap<RestView<DraftCommentResource>> views,
+ DraftComments(
+ DynamicMap<RestView<DraftCommentResource>> views,
Provider<CurrentUser> user,
ListRevisionDrafts list,
Provider<ReviewDb> dbProvider,
@@ -66,8 +67,9 @@
throws ResourceNotFoundException, OrmException, AuthException {
checkIdentifiedUser();
String uuid = id.get();
- for (Comment c : commentsUtil.draftByPatchSetAuthor(dbProvider.get(),
- rev.getPatchSet().getId(), rev.getAccountId(), rev.getNotes())) {
+ for (Comment c :
+ commentsUtil.draftByPatchSetAuthor(
+ dbProvider.get(), rev.getPatchSet().getId(), rev.getAccountId(), rev.getNotes())) {
if (uuid.equals(c.key.uuid)) {
return new DraftCommentResource(rev, c);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/EmailReviewComments.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/EmailReviewComments.java
index efa853a..8313b0a 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/EmailReviewComments.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/EmailReviewComments.java
@@ -40,12 +40,10 @@
import com.google.inject.Provider;
import com.google.inject.ProvisionException;
import com.google.inject.assistedinject.Assisted;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.util.List;
import java.util.concurrent.ExecutorService;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class EmailReviewComments implements Runnable, RequestContext {
private static final Logger log = LoggerFactory.getLogger(EmailReviewComments.class);
@@ -121,11 +119,9 @@
RequestContext old = requestContext.setContext(this);
try {
- CommentSender cm = commentSenderFactory.create(notes.getProjectName(),
- notes.getChangeId());
+ CommentSender cm = commentSenderFactory.create(notes.getProjectName(), notes.getChangeId());
cm.setFrom(user.getAccountId());
- cm.setPatchSet(patchSet,
- patchSetInfoFactory.get(notes.getProjectName(), patchSet));
+ cm.setPatchSet(patchSet, patchSetInfoFactory.get(notes.getProjectName(), patchSet));
cm.setChangeMessage(message.getMessage(), message.getWrittenOn());
cm.setComments(comments);
cm.setPatchSetComment(patchSetComment);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/FileContentUtil.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/FileContentUtil.java
index d617a70..732848e 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/FileContentUtil.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/FileContentUtil.java
@@ -30,9 +30,12 @@
import com.google.gerrit.server.project.ProjectState;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
import eu.medsea.mimeutil.MimeType;
-
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.Random;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
import org.eclipse.jgit.errors.LargeObjectException;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
import org.eclipse.jgit.lib.Constants;
@@ -45,12 +48,6 @@
import org.eclipse.jgit.treewalk.TreeWalk;
import org.eclipse.jgit.util.NB;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.util.Random;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipOutputStream;
-
@Singleton
public class FileContentUtil {
public static final String TEXT_X_GERRIT_COMMIT_MESSAGE = "text/x-gerrit-commit-message";
@@ -65,14 +62,13 @@
private final FileTypeRegistry registry;
@Inject
- FileContentUtil(GitRepositoryManager repoManager,
- FileTypeRegistry ftr) {
+ FileContentUtil(GitRepositoryManager repoManager, FileTypeRegistry ftr) {
this.repoManager = repoManager;
this.registry = ftr;
}
- public BinaryResult getContent(ProjectState project, ObjectId revstr,
- String path) throws ResourceNotFoundException, IOException {
+ public BinaryResult getContent(ProjectState project, ObjectId revstr, String path)
+ throws ResourceNotFoundException, IOException {
try (Repository repo = openRepository(project);
RevWalk rw = new RevWalk(repo)) {
RevCommit commit = rw.parseCommit(revstr);
@@ -85,9 +81,7 @@
org.eclipse.jgit.lib.FileMode mode = tw.getFileMode(0);
ObjectId id = tw.getObjectId(0);
if (mode == org.eclipse.jgit.lib.FileMode.GITLINK) {
- return BinaryResult.create(id.name())
- .setContentType(X_GIT_GITLINK)
- .base64();
+ return BinaryResult.create(id.name()).setContentType(X_GIT_GITLINK).base64();
}
ObjectLoader obj = repo.open(id, OBJ_BLOB);
@@ -110,24 +104,24 @@
}
}
- private static BinaryResult asBinaryResult(byte[] raw,
- final ObjectLoader obj) {
+ private static BinaryResult asBinaryResult(byte[] raw, final ObjectLoader obj) {
if (raw != null) {
return BinaryResult.create(raw);
}
- BinaryResult result = new BinaryResult() {
- @Override
- public void writeTo(OutputStream os) throws IOException {
- obj.copyTo(os);
- }
- };
+ BinaryResult result =
+ new BinaryResult() {
+ @Override
+ public void writeTo(OutputStream os) throws IOException {
+ obj.copyTo(os);
+ }
+ };
result.setContentLength(obj.getSize());
return result;
}
- public BinaryResult downloadContent(ProjectState project, ObjectId revstr,
- String path, @Nullable Integer parent)
- throws ResourceNotFoundException, IOException {
+ public BinaryResult downloadContent(
+ ProjectState project, ObjectId revstr, String path, @Nullable Integer parent)
+ throws ResourceNotFoundException, IOException {
try (Repository repo = openRepository(project);
RevWalk rw = new RevWalk(repo)) {
String suffix = "new";
@@ -167,16 +161,20 @@
}
}
- private BinaryResult wrapBlob(String path, final ObjectLoader obj, byte[] raw,
- MimeType contentType, @Nullable String suffix) {
+ private BinaryResult wrapBlob(
+ String path,
+ final ObjectLoader obj,
+ byte[] raw,
+ MimeType contentType,
+ @Nullable String suffix) {
return asBinaryResult(raw, obj)
.setContentType(contentType.toString())
.setAttachmentName(safeFileName(path, suffix));
}
@SuppressWarnings("resource")
- private BinaryResult zipBlob(final String path, final ObjectLoader obj,
- RevCommit commit, @Nullable final String suffix) {
+ private BinaryResult zipBlob(
+ final String path, final ObjectLoader obj, RevCommit commit, @Nullable final String suffix) {
final String commitName = commit.getName();
final long when = commit.getCommitTime() * 1000L;
return new BinaryResult() {
@@ -196,9 +194,7 @@
zipOut.closeEntry();
}
}
- }.setContentType(ZIP_TYPE)
- .setAttachmentName(safeFileName(path, suffix) + ".zip")
- .disableGzip();
+ }.setContentType(ZIP_TYPE).setAttachmentName(safeFileName(path, suffix) + ".zip").disableGzip();
}
private static String safeFileName(String fileName, @Nullable String suffix) {
@@ -235,8 +231,7 @@
} else if (ext <= 0) {
return fileName + "_" + suffix;
} else {
- return fileName.substring(0, ext) + "_" + suffix
- + fileName.substring(ext);
+ return fileName.substring(0, ext) + "_" + suffix + fileName.substring(ext);
}
}
@@ -258,8 +253,8 @@
return h.hash().toString();
}
- public static String resolveContentType(ProjectState project, String path,
- FileMode fileMode, String mimeType) {
+ public static String resolveContentType(
+ ProjectState project, String path, FileMode fileMode, String mimeType) {
switch (fileMode) {
case FILE:
if (Patch.COMMIT_MSG.equals(path)) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/FileInfoJson.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/FileInfoJson.java
index 8e55df5..60a4daf 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/FileInfoJson.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/FileInfoJson.java
@@ -28,19 +28,16 @@
import com.google.gerrit.server.patch.PatchListNotAvailableException;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.lib.ObjectId;
-
import java.util.Map;
import java.util.TreeMap;
+import org.eclipse.jgit.lib.ObjectId;
@Singleton
public class FileInfoJson {
private final PatchListCache patchListCache;
@Inject
- FileInfoJson(
- PatchListCache patchListCache) {
+ FileInfoJson(PatchListCache patchListCache) {
this.patchListCache = patchListCache;
}
@@ -51,9 +48,7 @@
Map<String, FileInfo> toFileInfoMap(Change change, RevId revision, @Nullable PatchSet base)
throws PatchListNotAvailableException {
- ObjectId a = (base == null)
- ? null
- : ObjectId.fromString(base.getRevision().get());
+ ObjectId a = (base == null) ? null : ObjectId.fromString(base.getRevision().get());
ObjectId b = ObjectId.fromString(revision.get());
return toFileInfoMap(change, new PatchListKey(a, b, Whitespace.IGNORE_NONE));
}
@@ -61,19 +56,19 @@
Map<String, FileInfo> toFileInfoMap(Change change, RevId revision, int parent)
throws PatchListNotAvailableException {
ObjectId b = ObjectId.fromString(revision.get());
- return toFileInfoMap(change,
- PatchListKey.againstParentNum(parent + 1, b, Whitespace.IGNORE_NONE));
+ return toFileInfoMap(
+ change, PatchListKey.againstParentNum(parent + 1, b, Whitespace.IGNORE_NONE));
}
- private Map<String, FileInfo> toFileInfoMap(Change change,
- PatchListKey key) throws PatchListNotAvailableException {
+ private Map<String, FileInfo> toFileInfoMap(Change change, PatchListKey key)
+ throws PatchListNotAvailableException {
PatchList list = patchListCache.get(key, change.getProject());
Map<String, FileInfo> files = new TreeMap<>();
for (PatchListEntry e : list.getPatches()) {
FileInfo d = new FileInfo();
- d.status = e.getChangeType() != Patch.ChangeType.MODIFIED
- ? e.getChangeType().getCode() : null;
+ d.status =
+ e.getChangeType() != Patch.ChangeType.MODIFIED ? e.getChangeType().getCode() : null;
d.oldPath = e.getOldName();
d.sizeDelta = e.getSizeDelta();
d.size = e.getSize();
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/Files.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/Files.java
index c077bbb..b7bd75a7 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/Files.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/Files.java
@@ -42,7 +42,13 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.ObjectReader;
@@ -55,14 +61,6 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.TimeUnit;
-
@Singleton
public class Files implements ChildCollection<RevisionResource, FileResource> {
private final DynamicMap<RestView<FileResource>> views;
@@ -114,7 +112,8 @@
private final DynamicItem<AccountPatchReviewStore> accountPatchReviewStore;
@Inject
- ListFiles(Provider<ReviewDb> db,
+ ListFiles(
+ Provider<ReviewDb> db,
Provider<CurrentUser> self,
FileInfoJson fileInfoJson,
Revisions revisions,
@@ -139,9 +138,8 @@
@Override
public Response<?> apply(RevisionResource resource)
- throws AuthException, BadRequestException, ResourceNotFoundException,
- OrmException, RepositoryNotFoundException, IOException,
- PatchListNotAvailableException {
+ throws AuthException, BadRequestException, ResourceNotFoundException, OrmException,
+ RepositoryNotFoundException, IOException, PatchListNotAvailableException {
checkOptions();
if (reviewed) {
return Response.ok(reviewed(resource));
@@ -151,21 +149,21 @@
Response<Map<String, FileInfo>> r;
if (base != null) {
- RevisionResource baseResource = revisions.parse(
- resource.getChangeResource(), IdString.fromDecoded(base));
- r = Response.ok(fileInfoJson.toFileInfoMap(
- resource.getChange(),
- resource.getPatchSet().getRevision(),
- baseResource.getPatchSet()));
+ RevisionResource baseResource =
+ revisions.parse(resource.getChangeResource(), IdString.fromDecoded(base));
+ r =
+ Response.ok(
+ fileInfoJson.toFileInfoMap(
+ resource.getChange(),
+ resource.getPatchSet().getRevision(),
+ baseResource.getPatchSet()));
} else if (parentNum > 0) {
- r = Response.ok(fileInfoJson.toFileInfoMap(
- resource.getChange(),
- resource.getPatchSet().getRevision(),
- parentNum - 1));
+ r =
+ Response.ok(
+ fileInfoJson.toFileInfoMap(
+ resource.getChange(), resource.getPatchSet().getRevision(), parentNum - 1));
} else {
- r = Response.ok(fileInfoJson.toFileInfoMap(
- resource.getChange(),
- resource.getPatchSet()));
+ r = Response.ok(fileInfoJson.toFileInfoMap(resource.getChange(), resource.getPatchSet()));
}
if (resource.isCacheable()) {
@@ -189,8 +187,7 @@
supplied++;
}
if (supplied > 1) {
- throw new BadRequestException(
- "cannot combine base, parent, reviewed, query");
+ throw new BadRequestException("cannot combine base, parent, reviewed, query");
}
}
@@ -201,8 +198,8 @@
ObjectReader or = git.newObjectReader();
RevWalk rw = new RevWalk(or);
TreeWalk tw = new TreeWalk(or)) {
- RevCommit c = rw.parseCommit(
- ObjectId.fromString(resource.getPatchSet().getRevision().get()));
+ RevCommit c =
+ rw.parseCommit(ObjectId.fromString(resource.getPatchSet().getRevision().get()));
tw.addTree(c.getTree());
tw.setRecursive(true);
@@ -225,13 +222,12 @@
}
Account.Id userId = user.getAccountId();
- Collection<String> r = accountPatchReviewStore.get()
- .findReviewed(resource.getPatchSet().getId(), userId);
+ Collection<String> r =
+ accountPatchReviewStore.get().findReviewed(resource.getPatchSet().getId(), userId);
if (r.isEmpty() && 1 < resource.getPatchSet().getPatchSetId()) {
for (PatchSet ps : reversePatchSets(resource)) {
- Collection<String> o =
- accountPatchReviewStore.get().findReviewed(ps.getId(), userId);
+ Collection<String> o = accountPatchReviewStore.get().findReviewed(ps.getId(), userId);
if (!o.isEmpty()) {
try {
r = copy(Sets.newHashSet(o), ps.getId(), resource, userId);
@@ -246,31 +242,26 @@
return r;
}
- private List<PatchSet> reversePatchSets(RevisionResource resource)
- throws OrmException {
- Collection<PatchSet> patchSets =
- psUtil.byChange(db.get(), resource.getNotes());
- List<PatchSet> list = (patchSets instanceof List) ?
- (List<PatchSet>) patchSets
- : new ArrayList<>(patchSets);
+ private List<PatchSet> reversePatchSets(RevisionResource resource) throws OrmException {
+ Collection<PatchSet> patchSets = psUtil.byChange(db.get(), resource.getNotes());
+ List<PatchSet> list =
+ (patchSets instanceof List) ? (List<PatchSet>) patchSets : new ArrayList<>(patchSets);
return Lists.reverse(list);
}
- private List<String> copy(Set<String> paths, PatchSet.Id old,
- RevisionResource resource, Account.Id userId) throws IOException,
- PatchListNotAvailableException, OrmException {
+ private List<String> copy(
+ Set<String> paths, PatchSet.Id old, RevisionResource resource, Account.Id userId)
+ throws IOException, PatchListNotAvailableException, OrmException {
Project.NameKey project = resource.getChange().getProject();
try (Repository git = gitManager.openRepository(project);
ObjectReader reader = git.newObjectReader();
RevWalk rw = new RevWalk(reader);
TreeWalk tw = new TreeWalk(reader)) {
- PatchList oldList = patchListCache.get(
- resource.getChange(),
- psUtil.get(db.get(), resource.getNotes(), old));
+ PatchList oldList =
+ patchListCache.get(
+ resource.getChange(), psUtil.get(db.get(), resource.getNotes(), old));
- PatchList curList = patchListCache.get(
- resource.getChange(),
- resource.getPatchSet());
+ PatchList curList = patchListCache.get(resource.getChange(), resource.getPatchSet());
int sz = paths.size();
List<String> pathList = Lists.newArrayListWithCapacity(sz);
@@ -292,15 +283,19 @@
while (tw.next()) {
String path = tw.getPathString();
- if (tw.getRawMode(o) != 0 && tw.getRawMode(c) != 0
+ if (tw.getRawMode(o) != 0
+ && tw.getRawMode(c) != 0
&& tw.idEqual(o, c)
&& paths.contains(path)) {
// File exists in previously reviewed oldList and in curList.
// File content is identical.
pathList.add(path);
- } else if (op >= 0 && cp >= 0
- && tw.getRawMode(o) == 0 && tw.getRawMode(c) == 0
- && tw.getRawMode(op) != 0 && tw.getRawMode(cp) != 0
+ } else if (op >= 0
+ && cp >= 0
+ && tw.getRawMode(o) == 0
+ && tw.getRawMode(c) == 0
+ && tw.getRawMode(op) != 0
+ && tw.getRawMode(cp) != 0
&& tw.idEqual(op, cp)
&& paths.contains(path)) {
// File was deleted in previously reviewed oldList and curList.
@@ -309,7 +304,8 @@
pathList.add(path);
}
}
- accountPatchReviewStore.get()
+ accountPatchReviewStore
+ .get()
.markReviewed(resource.getPatchSet().getId(), userId, pathList);
return pathList;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/GetArchive.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/GetArchive.java
index e99eb87..371127ba 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/GetArchive.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/GetArchive.java
@@ -21,7 +21,8 @@
import com.google.gerrit.extensions.restapi.RestReadView;
import com.google.gerrit.server.git.GitRepositoryManager;
import com.google.inject.Inject;
-
+import java.io.IOException;
+import java.io.OutputStream;
import org.eclipse.jgit.api.ArchiveCommand;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.lib.ObjectId;
@@ -30,9 +31,6 @@
import org.eclipse.jgit.revwalk.RevWalk;
import org.kohsuke.args4j.Option;
-import java.io.IOException;
-import java.io.OutputStream;
-
public class GetArchive implements RestReadView<RevisionResource> {
private final GitRepositoryManager repoManager;
private final AllowedFormats allowedFormats;
@@ -47,8 +45,8 @@
}
@Override
- public BinaryResult apply(RevisionResource rsrc) throws BadRequestException,
- IOException, MethodNotAllowedException {
+ public BinaryResult apply(RevisionResource rsrc)
+ throws BadRequestException, IOException, MethodNotAllowedException {
if (Strings.isNullOrEmpty(format)) {
throw new BadRequestException("format is not specified");
}
@@ -60,40 +58,37 @@
throw new MethodNotAllowedException("zip format is disabled");
}
boolean close = true;
- final Repository repo = repoManager
- .openRepository(rsrc.getControl().getProject().getNameKey());
+ final Repository repo = repoManager.openRepository(rsrc.getControl().getProject().getNameKey());
try {
final RevCommit commit;
String name;
try (RevWalk rw = new RevWalk(repo)) {
- commit = rw.parseCommit(ObjectId.fromString(
- rsrc.getPatchSet().getRevision().get()));
+ commit = rw.parseCommit(ObjectId.fromString(rsrc.getPatchSet().getRevision().get()));
name = name(f, rw, commit);
}
- BinaryResult bin = new BinaryResult() {
- @Override
- public void writeTo(OutputStream out) throws IOException {
- try {
- new ArchiveCommand(repo)
- .setFormat(f.name())
- .setTree(commit.getTree())
- .setOutputStream(out)
- .call();
- } catch (GitAPIException e) {
- throw new IOException(e);
- }
- }
+ BinaryResult bin =
+ new BinaryResult() {
+ @Override
+ public void writeTo(OutputStream out) throws IOException {
+ try {
+ new ArchiveCommand(repo)
+ .setFormat(f.name())
+ .setTree(commit.getTree())
+ .setOutputStream(out)
+ .call();
+ } catch (GitAPIException e) {
+ throw new IOException(e);
+ }
+ }
- @Override
- public void close() throws IOException {
- repo.close();
- }
- };
+ @Override
+ public void close() throws IOException {
+ repo.close();
+ }
+ };
- bin.disableGzip()
- .setContentType(f.getMimeType())
- .setAttachmentName(name);
+ bin.disableGzip().setContentType(f.getMimeType()).setAttachmentName(name);
close = false;
return bin;
@@ -106,8 +101,7 @@
private static String name(ArchiveFormat format, RevWalk rw, RevCommit commit)
throws IOException {
- return String.format("%s%s",
- rw.getObjectReader().abbreviate(commit,7).name(),
- format.getDefaultSuffix());
+ return String.format(
+ "%s%s", rw.getObjectReader().abbreviate(commit, 7).name(), format.getDefaultSuffix());
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/GetAssignee.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/GetAssignee.java
index ea81ad3..d491b91 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/GetAssignee.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/GetAssignee.java
@@ -22,7 +22,6 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
import java.util.Optional;
@Singleton
@@ -36,11 +35,9 @@
@Override
public Response<AccountInfo> apply(ChangeResource rsrc) throws OrmException {
- Optional<Account.Id> assignee =
- Optional.ofNullable(rsrc.getChange().getAssignee());
+ Optional<Account.Id> assignee = Optional.ofNullable(rsrc.getChange().getAssignee());
if (assignee.isPresent()) {
- return Response.ok(
- accountLoaderFactory.create(true).fillOne(assignee.get()));
+ return Response.ok(accountLoaderFactory.create(true).fillOne(assignee.get()));
}
return Response.none();
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/GetBlame.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/GetBlame.java
index 408a1ae..7abddcf 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/GetBlame.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/GetBlame.java
@@ -34,7 +34,10 @@
import com.google.gitiles.blame.Region;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
-
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.ObjectInserter;
@@ -46,11 +49,6 @@
import org.eclipse.jgit.revwalk.RevWalk;
import org.kohsuke.args4j.Option;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.TimeUnit;
-
public class GetBlame implements RestReadView<FileResource> {
private final GitRepositoryManager repoManager;
@@ -59,13 +57,18 @@
private final ThreeWayMergeStrategy mergeStrategy;
private final AutoMerger autoMerger;
- @Option(name = "--base", aliases = {"-b"},
- usage = "whether to load the blame of the base revision (the direct"
- + " parent of the change) instead of the change")
+ @Option(
+ name = "--base",
+ aliases = {"-b"},
+ usage =
+ "whether to load the blame of the base revision (the direct"
+ + " parent of the change) instead of the change"
+ )
private boolean base;
@Inject
- GetBlame(GitRepositoryManager repoManager,
+ GetBlame(
+ GitRepositoryManager repoManager,
BlameCache blameCache,
@GerritServerConfig Config cfg,
AutoMerger autoMerger) {
@@ -78,8 +81,7 @@
@Override
public Response<List<BlameInfo>> apply(FileResource resource)
- throws RestApiException, OrmException, IOException,
- InvalidChangeOperationException {
+ throws RestApiException, OrmException, IOException, InvalidChangeOperationException {
if (!allowBlame) {
throw new BadRequestException("blame is disabled");
}
@@ -88,9 +90,10 @@
try (Repository repository = repoManager.openRepository(project);
ObjectInserter ins = repository.newObjectInserter();
RevWalk revWalk = new RevWalk(ins.newReader())) {
- String refName = resource.getRevision().getEdit().isPresent()
- ? resource.getRevision().getEdit().get().getRefName()
- : resource.getRevision().getPatchSet().getRefName();
+ String refName =
+ resource.getRevision().getEdit().isPresent()
+ ? resource.getRevision().getEdit().get().getRefName()
+ : resource.getRevision().getPatchSet().getRefName();
Ref ref = repository.findRef(refName);
if (ref == null) {
@@ -113,8 +116,7 @@
result = blame(parents[0], path, repository, revWalk);
} else if (parents.length == 2) {
- ObjectId automerge = autoMerger.merge(repository, revWalk, ins,
- revCommit, mergeStrategy);
+ ObjectId automerge = autoMerger.merge(repository, revWalk, ins, revCommit, mergeStrategy);
result = blame(automerge, path, repository, revWalk);
} else {
@@ -130,8 +132,8 @@
}
}
- private List<BlameInfo> blame(ObjectId id, String path,
- Repository repository, RevWalk revWalk) throws IOException {
+ private List<BlameInfo> blame(ObjectId id, String path, Repository repository, RevWalk revWalk)
+ throws IOException {
ListMultimap<BlameInfo, RangeInfo> ranges =
MultimapBuilder.hashKeys().arrayListValues().build();
List<BlameInfo> result = new ArrayList<>();
@@ -155,8 +157,7 @@
return result;
}
- private static BlameInfo toBlameInfo(RevCommit commit,
- PersonIdent sourceAuthor) {
+ private static BlameInfo toBlameInfo(RevCommit commit, PersonIdent sourceAuthor) {
BlameInfo blameInfo = new BlameInfo();
blameInfo.author = sourceAuthor.getName();
blameInfo.id = commit.getName();
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/GetChange.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/GetChange.java
index b66a18b..22b0b1c 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/GetChange.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/GetChange.java
@@ -20,15 +20,12 @@
import com.google.gerrit.extensions.restapi.RestReadView;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
-
-import org.kohsuke.args4j.Option;
-
import java.util.EnumSet;
+import org.kohsuke.args4j.Option;
public class GetChange implements RestReadView<ChangeResource> {
private final ChangeJson.Factory json;
- private final EnumSet<ListChangesOption> options =
- EnumSet.noneOf(ListChangesOption.class);
+ private final EnumSet<ListChangesOption> options = EnumSet.noneOf(ListChangesOption.class);
@Option(name = "-o", usage = "Output options")
void addOption(ListChangesOption o) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/GetCommit.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/GetCommit.java
index e51d37b..832e08d 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/GetCommit.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/GetCommit.java
@@ -21,16 +21,14 @@
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.server.git.GitRepositoryManager;
import com.google.inject.Inject;
-
+import java.io.IOException;
+import java.util.concurrent.TimeUnit;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;
import org.kohsuke.args4j.Option;
-import java.io.IOException;
-import java.util.concurrent.TimeUnit;
-
public class GetCommit implements RestReadView<RevisionResource> {
private final GitRepositoryManager repoManager;
private final ChangeJson.Factory json;
@@ -52,8 +50,9 @@
String rev = rsrc.getPatchSet().getRevision().get();
RevCommit commit = rw.parseCommit(ObjectId.fromString(rev));
rw.parseBody(commit);
- CommitInfo info = json.create(ChangeJson.NO_OPTIONS)
- .toCommit(rsrc.getControl(), rw, commit, addLinks, true);
+ CommitInfo info =
+ json.create(ChangeJson.NO_OPTIONS)
+ .toCommit(rsrc.getControl(), rw, commit, addLinks, true);
Response<CommitInfo> r = Response.ok(info);
if (rsrc.isCacheable()) {
r.caching(CacheControl.PRIVATE(7, TimeUnit.DAYS));
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/GetContent.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/GetContent.java
index d8216f0..abb9e66 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/GetContent.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/GetContent.java
@@ -31,15 +31,13 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
+import java.io.IOException;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;
-import java.io.IOException;
-
@Singleton
public class GetContent implements RestReadView<FileResource> {
private final Provider<ReviewDb> db;
@@ -61,18 +59,15 @@
@Override
public BinaryResult apply(FileResource rsrc)
- throws ResourceNotFoundException, IOException, NoSuchChangeException,
- OrmException {
+ throws ResourceNotFoundException, IOException, NoSuchChangeException, OrmException {
String path = rsrc.getPatchKey().get();
if (Patch.COMMIT_MSG.equals(path)) {
- String msg = getMessage(
- rsrc.getRevision().getChangeResource().getNotes());
+ String msg = getMessage(rsrc.getRevision().getChangeResource().getNotes());
return BinaryResult.create(msg)
.setContentType(FileContentUtil.TEXT_X_GERRIT_COMMIT_MESSAGE)
.base64();
} else if (Patch.MERGE_LIST.equals(path)) {
- byte[] mergeList = getMergeList(
- rsrc.getRevision().getChangeResource().getNotes());
+ byte[] mergeList = getMergeList(rsrc.getRevision().getChangeResource().getNotes());
return BinaryResult.create(mergeList)
.setContentType(FileContentUtil.TEXT_X_GERRIT_MERGE_LIST)
.base64();
@@ -83,8 +78,7 @@
path);
}
- private String getMessage(ChangeNotes notes)
- throws OrmException, IOException {
+ private String getMessage(ChangeNotes notes) throws OrmException, IOException {
Change.Id changeId = notes.getChangeId();
PatchSet ps = psUtil.current(db.get(), notes);
if (ps == null) {
@@ -93,16 +87,14 @@
try (Repository git = gitManager.openRepository(notes.getProjectName());
RevWalk revWalk = new RevWalk(git)) {
- RevCommit commit = revWalk.parseCommit(
- ObjectId.fromString(ps.getRevision().get()));
+ RevCommit commit = revWalk.parseCommit(ObjectId.fromString(ps.getRevision().get()));
return commit.getFullMessage();
} catch (RepositoryNotFoundException e) {
throw new NoSuchChangeException(changeId, e);
}
}
- private byte[] getMergeList(ChangeNotes notes)
- throws OrmException, IOException {
+ private byte[] getMergeList(ChangeNotes notes) throws OrmException, IOException {
Change.Id changeId = notes.getChangeId();
PatchSet ps = psUtil.current(db.get(), notes);
if (ps == null) {
@@ -111,9 +103,11 @@
try (Repository git = gitManager.openRepository(notes.getProjectName());
RevWalk revWalk = new RevWalk(git)) {
- return Text.forMergeList(ComparisonType.againstAutoMerge(),
- revWalk.getObjectReader(),
- ObjectId.fromString(ps.getRevision().get())).getContent();
+ return Text.forMergeList(
+ ComparisonType.againstAutoMerge(),
+ revWalk.getObjectReader(),
+ ObjectId.fromString(ps.getRevision().get()))
+ .getContent();
} catch (RepositoryNotFoundException e) {
throw new NoSuchChangeException(changeId, e);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/GetDetail.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/GetDetail.java
index 48bd2f4..8213193 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/GetDetail.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/GetDetail.java
@@ -20,7 +20,6 @@
import com.google.gerrit.extensions.restapi.RestReadView;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
-
import org.kohsuke.args4j.Option;
public class GetDetail implements RestReadView<ChangeResource> {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/GetDiff.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/GetDiff.java
index c688f3a..5daf69a 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/GetDiff.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/GetDiff.java
@@ -52,7 +52,9 @@
import com.google.gerrit.server.project.ProjectState;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
-
+import java.io.IOException;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
import org.eclipse.jgit.diff.Edit;
import org.eclipse.jgit.diff.ReplaceEdit;
import org.kohsuke.args4j.CmdLineException;
@@ -64,10 +66,6 @@
import org.kohsuke.args4j.spi.Parameters;
import org.kohsuke.args4j.spi.Setter;
-import java.io.IOException;
-import java.util.List;
-import java.util.concurrent.TimeUnit;
-
public class GetDiff implements RestReadView<FileResource> {
private static final ImmutableMap<Patch.ChangeType, ChangeType> CHANGE_TYPE =
Maps.immutableEnumMap(
@@ -108,7 +106,8 @@
boolean webLinksOnly;
@Inject
- GetDiff(ProjectCache projectCache,
+ GetDiff(
+ ProjectCache projectCache,
PatchScriptFactory.Factory patchScriptFactoryFactory,
Revisions revisions,
WebLinks webLinks) {
@@ -120,8 +119,8 @@
@Override
public Response<DiffInfo> apply(FileResource resource)
- throws ResourceConflictException, ResourceNotFoundException,
- OrmException, AuthException, InvalidChangeOperationException, IOException {
+ throws ResourceConflictException, ResourceNotFoundException, OrmException, AuthException,
+ InvalidChangeOperationException, IOException {
DiffPreferencesInfo prefs = new DiffPreferencesInfo();
if (whitespace != null) {
prefs.ignoreWhitespace = whitespace;
@@ -136,29 +135,32 @@
PatchScriptFactory psf;
PatchSet basePatchSet = null;
if (base != null) {
- RevisionResource baseResource = revisions.parse(
- resource.getRevision().getChangeResource(), IdString.fromDecoded(base));
+ RevisionResource baseResource =
+ revisions.parse(resource.getRevision().getChangeResource(), IdString.fromDecoded(base));
basePatchSet = baseResource.getPatchSet();
- psf = patchScriptFactoryFactory.create(
- resource.getRevision().getControl(),
- resource.getPatchKey().getFileName(),
- basePatchSet.getId(),
- resource.getPatchKey().getParentKey(),
- prefs);
+ psf =
+ patchScriptFactoryFactory.create(
+ resource.getRevision().getControl(),
+ resource.getPatchKey().getFileName(),
+ basePatchSet.getId(),
+ resource.getPatchKey().getParentKey(),
+ prefs);
} else if (parentNum > 0) {
- psf = patchScriptFactoryFactory.create(
- resource.getRevision().getControl(),
- resource.getPatchKey().getFileName(),
- parentNum - 1,
- resource.getPatchKey().getParentKey(),
- prefs);
+ psf =
+ patchScriptFactoryFactory.create(
+ resource.getRevision().getControl(),
+ resource.getPatchKey().getFileName(),
+ parentNum - 1,
+ resource.getPatchKey().getParentKey(),
+ prefs);
} else {
- psf = patchScriptFactoryFactory.create(
- resource.getRevision().getControl(),
- resource.getPatchKey().getFileName(),
- null,
- resource.getPatchKey().getParentKey(),
- prefs);
+ psf =
+ patchScriptFactoryFactory.create(
+ resource.getRevision().getControl(),
+ resource.getPatchKey().getFileName(),
+ null,
+ resource.getPatchKey().getParentKey(),
+ prefs);
}
try {
@@ -172,17 +174,22 @@
}
content.addCommon(edit.getBeginA());
- checkState(content.nextA == edit.getBeginA(),
- "nextA = %s; want %s", content.nextA, edit.getBeginA());
- checkState(content.nextB == edit.getBeginB(),
- "nextB = %s; want %s", content.nextB, edit.getBeginB());
+ checkState(
+ content.nextA == edit.getBeginA(),
+ "nextA = %s; want %s",
+ content.nextA,
+ edit.getBeginA());
+ checkState(
+ content.nextB == edit.getBeginB(),
+ "nextB = %s; want %s",
+ content.nextB,
+ edit.getBeginB());
switch (edit.getType()) {
case DELETE:
case INSERT:
case REPLACE:
- List<Edit> internalEdit = edit instanceof ReplaceEdit
- ? ((ReplaceEdit) edit).getInternalEdits()
- : null;
+ List<Edit> internalEdit =
+ edit instanceof ReplaceEdit ? ((ReplaceEdit) edit).getInternalEdits() : null;
content.addDiff(edit.getEndA(), edit.getEndB(), internalEdit);
break;
case EMPTY:
@@ -192,21 +199,23 @@
}
content.addCommon(ps.getA().size());
- ProjectState state =
- projectCache.get(resource.getRevision().getChange().getProject());
+ ProjectState state = projectCache.get(resource.getRevision().getChange().getProject());
DiffInfo result = new DiffInfo();
// TODO referring to the parent commit by refs/changes/12/60012/1^1
// will likely not work for inline edits
- String revA = basePatchSet != null
- ? basePatchSet.getRefName()
- : resource.getRevision().getPatchSet().getRefName() + "^1";
- String revB = resource.getRevision().getEdit().isPresent()
- ? resource.getRevision().getEdit().get().getRefName()
- : resource.getRevision().getPatchSet().getRefName();
+ String revA =
+ basePatchSet != null
+ ? basePatchSet.getRefName()
+ : resource.getRevision().getPatchSet().getRefName() + "^1";
+ String revB =
+ resource.getRevision().getEdit().isPresent()
+ ? resource.getRevision().getEdit().get().getRefName()
+ : resource.getRevision().getPatchSet().getRefName();
List<DiffWebLinkInfo> links =
- webLinks.getDiffLinks(state.getProject().getName(),
+ webLinks.getDiffLinks(
+ state.getProject().getName(),
resource.getPatchKey().getParentKey().getParentKey().get(),
basePatchSet != null ? basePatchSet.getId().get() : null,
revA,
@@ -222,24 +231,23 @@
}
if (ps.getDisplayMethodA() != DisplayMethod.NONE) {
result.metaA = new FileMeta();
- result.metaA.name = MoreObjects.firstNonNull(ps.getOldName(),
- ps.getNewName());
- result.metaA.contentType = FileContentUtil.resolveContentType(
- state, result.metaA.name, ps.getFileModeA(), ps.getMimeTypeA());
+ result.metaA.name = MoreObjects.firstNonNull(ps.getOldName(), ps.getNewName());
+ result.metaA.contentType =
+ FileContentUtil.resolveContentType(
+ state, result.metaA.name, ps.getFileModeA(), ps.getMimeTypeA());
result.metaA.lines = ps.getA().size();
- result.metaA.webLinks =
- getFileWebLinks(state.getProject(), revA, result.metaA.name);
+ result.metaA.webLinks = getFileWebLinks(state.getProject(), revA, result.metaA.name);
result.metaA.commitId = content.commitIdA;
}
if (ps.getDisplayMethodB() != DisplayMethod.NONE) {
result.metaB = new FileMeta();
result.metaB.name = ps.getNewName();
- result.metaB.contentType = FileContentUtil.resolveContentType(
- state, result.metaB.name, ps.getFileModeB(), ps.getMimeTypeB());
+ result.metaB.contentType =
+ FileContentUtil.resolveContentType(
+ state, result.metaB.name, ps.getFileModeB(), ps.getMimeTypeB());
result.metaB.lines = ps.getB().size();
- result.metaB.webLinks =
- getFileWebLinks(state.getProject(), revB, result.metaB.name);
+ result.metaB.webLinks = getFileWebLinks(state.getProject(), revB, result.metaB.name);
result.metaB.commitId = content.commitIdB;
}
@@ -255,8 +263,7 @@
result.changeType = CHANGE_TYPE.get(ps.getChangeType());
if (result.changeType == null) {
- throw new IllegalStateException(
- "unknown change type: " + ps.getChangeType());
+ throw new IllegalStateException("unknown change type: " + ps.getChangeType());
}
if (ps.getPatchHeader().size() > 0) {
@@ -277,10 +284,8 @@
}
}
- private List<WebLinkInfo> getFileWebLinks(Project project, String rev,
- String file) {
- List<WebLinkInfo> links =
- webLinks.getFileLinks(project.getName(), rev, file);
+ private List<WebLinkInfo> getFileWebLinks(Project project, String rev, String file) {
+ List<WebLinkInfo> links = webLinks.getFileLinks(project.getName(), rev, file);
return links.isEmpty() ? null : links;
}
@@ -337,9 +342,7 @@
while (nextA < end) {
if (!fileA.contains(nextA)) {
- int endRegion = Math.min(
- end,
- nextA == 0 ? fileA.first() : fileA.next(nextA - 1));
+ int endRegion = Math.min(end, nextA == 0 ? fileA.first() : fileA.next(nextA - 1));
int len = endRegion - nextA;
entry().skip = len;
nextA = endRegion;
@@ -348,9 +351,7 @@
}
ContentEntry e = null;
- for (int i = nextA;
- i == nextA && i < end;
- i = fileA.next(i), nextA++, nextB++) {
+ for (int i = nextA; i == nextA && i < end; i = fileA.next(i), nextA++, nextB++) {
if (ignoreWS && fileB.contains(nextB)) {
if (e == null || e.common == null) {
e = entry();
@@ -396,13 +397,13 @@
int lastB = 0;
for (Edit edit : internalEdit) {
if (edit.getBeginA() != edit.getEndA()) {
- e.editA.add(ImmutableList.of(
- edit.getBeginA() - lastA, edit.getEndA() - edit.getBeginA()));
+ e.editA.add(
+ ImmutableList.of(edit.getBeginA() - lastA, edit.getEndA() - edit.getBeginA()));
lastA = edit.getEndA();
}
if (edit.getBeginB() != edit.getEndB()) {
- e.editB.add(ImmutableList.of(
- edit.getBeginB() - lastB, edit.getEndB() - edit.getBeginB()));
+ e.editB.add(
+ ImmutableList.of(edit.getBeginB() - lastB, edit.getEndB() - edit.getBeginB()));
lastB = edit.getEndB();
}
}
@@ -431,14 +432,12 @@
}
public static class ContextOptionHandler extends OptionHandler<Short> {
- public ContextOptionHandler(
- CmdLineParser parser, OptionDef option, Setter<Short> setter) {
+ public ContextOptionHandler(CmdLineParser parser, OptionDef option, Setter<Short> setter) {
super(parser, option, setter);
}
@Override
- public final int parseArguments(final Parameters params)
- throws CmdLineException {
+ public final int parseArguments(final Parameters params) throws CmdLineException {
final String value = params.getParameter(0);
short context;
if ("all".equalsIgnoreCase(value)) {
@@ -450,8 +449,10 @@
throw new NumberFormatException();
}
} catch (NumberFormatException e) {
- throw new CmdLineException(owner,
- String.format("\"%s\" is not a valid value for \"%s\"",
+ throw new CmdLineException(
+ owner,
+ String.format(
+ "\"%s\" is not a valid value for \"%s\"",
value, ((NamedOptionDef) option).name()));
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/GetHashtags.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/GetHashtags.java
index d0c1e83..4ea1c02 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/GetHashtags.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/GetHashtags.java
@@ -22,7 +22,6 @@
import com.google.gerrit.server.project.ChangeControl;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Singleton;
-
import java.io.IOException;
import java.util.Collections;
import java.util.Set;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/GetMergeList.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/GetMergeList.java
index b15810c..eed4c71 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/GetMergeList.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/GetMergeList.java
@@ -24,18 +24,16 @@
import com.google.gerrit.server.git.GitRepositoryManager;
import com.google.gerrit.server.patch.MergeListBuilder;
import com.google.inject.Inject;
-
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;
import org.kohsuke.args4j.Option;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.TimeUnit;
-
public class GetMergeList implements RestReadView<RevisionResource> {
private final GitRepositoryManager repoManager;
private final ChangeJson.Factory json;
@@ -47,8 +45,7 @@
private boolean addLinks;
@Inject
- GetMergeList(GitRepositoryManager repoManager,
- ChangeJson.Factory json) {
+ GetMergeList(GitRepositoryManager repoManager, ChangeJson.Factory json) {
this.repoManager = repoManager;
this.json = json;
}
@@ -71,17 +68,15 @@
RevCommit commit = rw.parseCommit(ObjectId.fromString(rev));
rw.parseBody(commit);
- if (uninterestingParent < 1
- || uninterestingParent > commit.getParentCount()) {
+ if (uninterestingParent < 1 || uninterestingParent > commit.getParentCount()) {
throw new BadRequestException("No such parent: " + uninterestingParent);
}
if (commit.getParentCount() < 2) {
- return createResponse(rsrc, ImmutableList.<CommitInfo> of());
+ return createResponse(rsrc, ImmutableList.<CommitInfo>of());
}
- List<RevCommit> commits =
- MergeListBuilder.build(rw, commit, uninterestingParent);
+ List<RevCommit> commits = MergeListBuilder.build(rw, commit, uninterestingParent);
List<CommitInfo> result = new ArrayList<>(commits.size());
ChangeJson changeJson = json.create(ChangeJson.NO_OPTIONS);
for (RevCommit c : commits) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/GetPastAssignees.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/GetPastAssignees.java
index c37efed..eaa3a28 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/GetPastAssignees.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/GetPastAssignees.java
@@ -24,7 +24,6 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
import java.util.Collections;
import java.util.List;
import java.util.Set;
@@ -39,18 +38,15 @@
}
@Override
- public Response<List<AccountInfo>> apply(ChangeResource rsrc)
- throws OrmException {
+ public Response<List<AccountInfo>> apply(ChangeResource rsrc) throws OrmException {
- Set<Account.Id> pastAssignees =
- rsrc.getControl().getNotes().load().getPastAssignees();
+ Set<Account.Id> pastAssignees = rsrc.getControl().getNotes().load().getPastAssignees();
if (pastAssignees == null) {
return Response.ok(Collections.emptyList());
}
AccountLoader accountLoader = accountLoaderFactory.create(true);
- List<AccountInfo> infos =
- pastAssignees.stream().map(accountLoader::get).collect(toList());
+ List<AccountInfo> infos = pastAssignees.stream().map(accountLoader::get).collect(toList());
accountLoader.fill();
return Response.ok(infos);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/GetPatch.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/GetPatch.java
index 365b204..2275e06 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/GetPatch.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/GetPatch.java
@@ -23,7 +23,13 @@
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.server.git.GitRepositoryManager;
import com.google.inject.Inject;
-
+import java.io.IOException;
+import java.io.OutputStream;
+import java.text.SimpleDateFormat;
+import java.util.Calendar;
+import java.util.Locale;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
import org.eclipse.jgit.diff.DiffFormatter;
import org.eclipse.jgit.lib.AbbreviatedObjectId;
import org.eclipse.jgit.lib.ObjectId;
@@ -34,14 +40,6 @@
import org.eclipse.jgit.treewalk.filter.PathFilter;
import org.kohsuke.args4j.Option;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.text.SimpleDateFormat;
-import java.util.Calendar;
-import java.util.Locale;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipOutputStream;
-
public class GetPatch implements RestReadView<RevisionResource> {
private final GitRepositoryManager repoManager;
@@ -62,8 +60,8 @@
}
@Override
- public BinaryResult apply(RevisionResource rsrc) throws
- ResourceConflictException, IOException, ResourceNotFoundException {
+ public BinaryResult apply(RevisionResource rsrc)
+ throws ResourceConflictException, IOException, ResourceNotFoundException {
Project.NameKey project = rsrc.getControl().getProject().getNameKey();
final Repository repo = repoManager.openRepository(project);
boolean close = true;
@@ -71,71 +69,67 @@
final RevWalk rw = new RevWalk(repo);
try {
final RevCommit commit =
- rw.parseCommit(ObjectId.fromString(rsrc.getPatchSet()
- .getRevision().get()));
+ rw.parseCommit(ObjectId.fromString(rsrc.getPatchSet().getRevision().get()));
RevCommit[] parents = commit.getParents();
if (parents.length > 1) {
- throw new ResourceConflictException(
- "Revision has more than 1 parent.");
+ throw new ResourceConflictException("Revision has more than 1 parent.");
} else if (parents.length == 0) {
throw new ResourceConflictException("Revision has no parent.");
}
final RevCommit base = parents[0];
rw.parseBody(base);
- BinaryResult bin = new BinaryResult() {
- @Override
- public void writeTo(OutputStream out) throws IOException {
- if (zip) {
- ZipOutputStream zos = new ZipOutputStream(out);
- ZipEntry e = new ZipEntry(fileName(rw, commit));
- e.setTime(commit.getCommitTime() * 1000L);
- zos.putNextEntry(e);
- format(zos);
- zos.closeEntry();
- zos.finish();
- } else {
- format(out);
- }
- }
-
- private void format(OutputStream out) throws IOException {
- // Only add header if no path is specified
- if (path == null) {
- out.write(formatEmailHeader(commit).getBytes(UTF_8));
- }
- try (DiffFormatter fmt = new DiffFormatter(out)) {
- fmt.setRepository(repo);
- if (path != null) {
- fmt.setPathFilter(PathFilter.create(path));
+ BinaryResult bin =
+ new BinaryResult() {
+ @Override
+ public void writeTo(OutputStream out) throws IOException {
+ if (zip) {
+ ZipOutputStream zos = new ZipOutputStream(out);
+ ZipEntry e = new ZipEntry(fileName(rw, commit));
+ e.setTime(commit.getCommitTime() * 1000L);
+ zos.putNextEntry(e);
+ format(zos);
+ zos.closeEntry();
+ zos.finish();
+ } else {
+ format(out);
+ }
}
- fmt.format(base.getTree(), commit.getTree());
- fmt.flush();
- }
- }
- @Override
- public void close() throws IOException {
- rw.close();
- repo.close();
- }
- };
+ private void format(OutputStream out) throws IOException {
+ // Only add header if no path is specified
+ if (path == null) {
+ out.write(formatEmailHeader(commit).getBytes(UTF_8));
+ }
+ try (DiffFormatter fmt = new DiffFormatter(out)) {
+ fmt.setRepository(repo);
+ if (path != null) {
+ fmt.setPathFilter(PathFilter.create(path));
+ }
+ fmt.format(base.getTree(), commit.getTree());
+ fmt.flush();
+ }
+ }
+
+ @Override
+ public void close() throws IOException {
+ rw.close();
+ repo.close();
+ }
+ };
if (path != null && bin.asString().isEmpty()) {
- throw new ResourceNotFoundException(
- String.format(FILE_NOT_FOUND, path));
+ throw new ResourceNotFoundException(String.format(FILE_NOT_FOUND, path));
}
if (zip) {
bin.disableGzip()
- .setContentType("application/zip")
- .setAttachmentName(fileName(rw, commit) + ".zip");
+ .setContentType("application/zip")
+ .setAttachmentName(fileName(rw, commit) + ".zip");
} else {
bin.base64()
- .setContentType("application/mbox")
- .setAttachmentName(download
- ? fileName(rw, commit) + ".base64"
- : null);
+ .setContentType("application/mbox")
+ .setAttachmentName(download ? fileName(rw, commit) + ".base64" : null);
}
close = false;
@@ -165,31 +159,37 @@
if (msg.startsWith("\n\n")) {
msg = msg.substring(2);
}
- b.append("From ").append(commit.getName())
- .append(' ')
- .append("Mon Sep 17 00:00:00 2001\n") // Fixed timestamp to match output of C Git's format-patch
- .append("From: ").append(author.getName())
- .append(" <").append(author.getEmailAddress()).append(">\n")
- .append("Date: ").append(formatDate(author)).append('\n')
- .append("Subject: [PATCH] ").append(subject).append('\n')
- .append('\n')
- .append(msg);
+ b.append("From ")
+ .append(commit.getName())
+ .append(' ')
+ .append(
+ "Mon Sep 17 00:00:00 2001\n") // Fixed timestamp to match output of C Git's format-patch
+ .append("From: ")
+ .append(author.getName())
+ .append(" <")
+ .append(author.getEmailAddress())
+ .append(">\n")
+ .append("Date: ")
+ .append(formatDate(author))
+ .append('\n')
+ .append("Subject: [PATCH] ")
+ .append(subject)
+ .append('\n')
+ .append('\n')
+ .append(msg);
if (!msg.endsWith("\n")) {
- b.append('\n');
+ b.append('\n');
}
return b.append("---\n\n").toString();
}
private static String formatDate(PersonIdent author) {
- SimpleDateFormat df = new SimpleDateFormat(
- "EEE, dd MMM yyyy HH:mm:ss Z",
- Locale.US);
+ SimpleDateFormat df = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.US);
df.setCalendar(Calendar.getInstance(author.getTimeZone(), Locale.US));
return df.format(author.getWhen());
}
- private static String fileName(RevWalk rw, RevCommit commit)
- throws IOException {
+ private static String fileName(RevWalk rw, RevCommit commit) throws IOException {
AbbreviatedObjectId id = rw.getObjectReader().abbreviate(commit, 7);
return id.name() + ".diff";
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/GetRelated.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/GetRelated.java
index 0a7452b..10c7a5a 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/GetRelated.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/GetRelated.java
@@ -32,16 +32,14 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.errors.RepositoryNotFoundException;
-import org.eclipse.jgit.revwalk.RevCommit;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
+import org.eclipse.jgit.errors.RepositoryNotFoundException;
+import org.eclipse.jgit.revwalk.RevCommit;
@Singleton
public class GetRelated implements RestReadView<RevisionResource> {
@@ -51,7 +49,8 @@
private final RelatedChangesSorter sorter;
@Inject
- GetRelated(Provider<ReviewDb> db,
+ GetRelated(
+ Provider<ReviewDb> db,
Provider<InternalChangeQuery> queryProvider,
PatchSetUtil psUtil,
RelatedChangesSorter sorter) {
@@ -69,29 +68,27 @@
return relatedInfo;
}
- private List<ChangeAndCommit> getRelated(RevisionResource rsrc)
- throws OrmException, IOException {
+ private List<ChangeAndCommit> getRelated(RevisionResource rsrc) throws OrmException, IOException {
Set<String> groups = getAllGroups(rsrc.getNotes());
if (groups.isEmpty()) {
return Collections.emptyList();
}
- List<ChangeData> cds = queryProvider.get()
- .enforceVisibility(true)
- .byProjectGroups(rsrc.getChange().getProject(), groups);
+ List<ChangeData> cds =
+ queryProvider
+ .get()
+ .enforceVisibility(true)
+ .byProjectGroups(rsrc.getChange().getProject(), groups);
if (cds.isEmpty()) {
return Collections.emptyList();
}
- if (cds.size() == 1
- && cds.get(0).getId().equals(rsrc.getChange().getId())) {
+ if (cds.size() == 1 && cds.get(0).getId().equals(rsrc.getChange().getId())) {
return Collections.emptyList();
}
List<ChangeAndCommit> result = new ArrayList<>(cds.size());
boolean isEdit = rsrc.getEdit().isPresent();
- PatchSet basePs = isEdit
- ? rsrc.getEdit().get().getBasePatchSet()
- : rsrc.getPatchSet();
+ PatchSet basePs = isEdit ? rsrc.getEdit().get().getBasePatchSet() : rsrc.getPatchSet();
reloadChangeIfStale(cds, basePs);
@@ -110,8 +107,7 @@
if (result.size() == 1) {
ChangeAndCommit r = result.get(0);
- if (r.commit != null
- && r.commit.commit.equals(rsrc.getPatchSet().getRevision().get())) {
+ if (r.commit != null && r.commit.commit.equals(rsrc.getPatchSet().getRevision().get())) {
return Collections.emptyList();
}
}
@@ -126,8 +122,7 @@
return result;
}
- private void reloadChangeIfStale(List<ChangeData> cds, PatchSet wantedPs)
- throws OrmException {
+ private void reloadChangeIfStale(List<ChangeData> cds, PatchSet wantedPs) throws OrmException {
for (ChangeData cd : cds) {
if (cd.getId().equals(wantedPs.getId().getParentKey())) {
if (cd.patchSet(wantedPs.getId()) == null) {
@@ -149,8 +144,7 @@
public Integer _currentRevisionNumber;
public String status;
- public ChangeAndCommit() {
- }
+ public ChangeAndCommit() {}
ChangeAndCommit(@Nullable Change change, @Nullable PatchSet ps, RevCommit c) {
if (change != null) {
@@ -188,14 +182,14 @@
private static String toString(CommitInfo commit) {
return MoreObjects.toStringHelper(commit)
- .add("commit", commit.commit)
- .add("parent", commit.parents)
- .add("author", commit.author)
- .add("committer", commit.committer)
- .add("subject", commit.subject)
- .add("message", commit.message)
- .add("webLinks", commit.webLinks)
- .toString();
+ .add("commit", commit.commit)
+ .add("parent", commit.parents)
+ .add("author", commit.author)
+ .add("committer", commit.committer)
+ .add("subject", commit.subject)
+ .add("message", commit.message)
+ .add("webLinks", commit.webLinks)
+ .toString();
}
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/GetReviewer.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/GetReviewer.java
index 533468d..aa0b339 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/GetReviewer.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/GetReviewer.java
@@ -19,7 +19,6 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
import java.util.List;
@Singleton
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/GetRevisionActions.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/GetRevisionActions.java
index 57e5cea..e476e73 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/GetRevisionActions.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/GetRevisionActions.java
@@ -30,11 +30,9 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.lib.Config;
-
import java.io.IOException;
import java.util.Map;
+import org.eclipse.jgit.lib.Config;
@Singleton
public class GetRevisionActions implements ETagView<RevisionResource> {
@@ -59,8 +57,7 @@
}
@Override
- public Response<Map<String, ActionInfo>> apply(RevisionResource rsrc)
- throws OrmException {
+ public Response<Map<String, ActionInfo>> apply(RevisionResource rsrc) throws OrmException {
return Response.withMustRevalidate(delegate.format(rsrc));
}
@@ -72,8 +69,7 @@
rsrc.getChangeResource().prepareETag(h, user);
h.putBoolean(Submit.wholeTopicEnabled(config));
ReviewDb db = dbProvider.get();
- ChangeSet cs =
- mergeSuperSet.get().completeChangeSet(db, rsrc.getChange(), user);
+ ChangeSet cs = mergeSuperSet.get().completeChangeSet(db, rsrc.getChange(), user);
for (ChangeData cd : cs.changes()) {
changeResourceFactory.create(cd.changeControl()).prepareETag(h, user);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/GetRobotComment.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/GetRobotComment.java
index c10cd2e..d4d53ad 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/GetRobotComment.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/GetRobotComment.java
@@ -33,7 +33,6 @@
@Override
public RobotCommentInfo apply(RobotCommentResource rsrc) throws OrmException {
- return commentJson.get().newRobotCommentFormatter()
- .format(rsrc.getComment());
+ return commentJson.get().newRobotCommentFormatter().format(rsrc.getComment());
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/HashtagsUtil.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/HashtagsUtil.java
index 39fdf3e..e9b0af2 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/HashtagsUtil.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/HashtagsUtil.java
@@ -16,7 +16,6 @@
import com.google.common.base.CharMatcher;
import com.google.common.base.Strings;
-
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
@@ -24,8 +23,7 @@
import java.util.regex.Pattern;
public class HashtagsUtil {
- private static final CharMatcher LEADER =
- CharMatcher.whitespace().or(CharMatcher.is('#'));
+ private static final CharMatcher LEADER = CharMatcher.whitespace().or(CharMatcher.is('#'));
private static final String PATTERN = "(?:\\s|\\A)#[\\p{L}[0-9]-_]+";
public static String cleanupHashtag(String hashtag) {
@@ -45,8 +43,7 @@
return result;
}
- static Set<String> extractTags(Set<String> input)
- throws IllegalArgumentException {
+ static Set<String> extractTags(Set<String> input) throws IllegalArgumentException {
if (input == null) {
return Collections.emptySet();
}
@@ -63,6 +60,5 @@
return result;
}
- private HashtagsUtil() {
- }
+ private HashtagsUtil() {}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/IncludedIn.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/IncludedIn.java
index 0c2d079..8f8925a 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/IncludedIn.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/IncludedIn.java
@@ -26,7 +26,7 @@
import com.google.gerrit.server.git.GitRepositoryManager;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
+import java.io.IOException;
import org.eclipse.jgit.errors.IncorrectObjectTypeException;
import org.eclipse.jgit.errors.MissingObjectException;
import org.eclipse.jgit.lib.ObjectId;
@@ -34,16 +34,13 @@
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;
-import java.io.IOException;
-
@Singleton
public class IncludedIn {
private final GitRepositoryManager repoManager;
private final DynamicSet<ExternalIncludedIn> externalIncludedIn;
@Inject
- IncludedIn(GitRepositoryManager repoManager,
- DynamicSet<ExternalIncludedIn> externalIncludedIn) {
+ IncludedIn(GitRepositoryManager repoManager, DynamicSet<ExternalIncludedIn> externalIncludedIn) {
this.repoManager = repoManager;
this.externalIncludedIn = externalIncludedIn;
}
@@ -63,17 +60,16 @@
}
IncludedInResolver.Result d = IncludedInResolver.resolve(r, rw, rev);
- ListMultimap<String, String> external =
- MultimapBuilder.hashKeys().arrayListValues().build();
+ ListMultimap<String, String> external = MultimapBuilder.hashKeys().arrayListValues().build();
for (ExternalIncludedIn ext : externalIncludedIn) {
- ListMultimap<String, String> extIncludedIns = ext.getIncludedIn(
- project.get(), rev.name(), d.getTags(), d.getBranches());
+ ListMultimap<String, String> extIncludedIns =
+ ext.getIncludedIn(project.get(), rev.name(), d.getTags(), d.getBranches());
if (extIncludedIns != null) {
external.putAll(extIncludedIns);
}
}
- return new IncludedInInfo(d.getBranches(), d.getTags(),
- (!external.isEmpty() ? external.asMap() : null));
+ return new IncludedInInfo(
+ d.getBranches(), d.getTags(), (!external.isEmpty() ? external.asMap() : null));
}
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/IncludedInResolver.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/IncludedInResolver.java
index 7843b15..14e1f92 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/IncludedInResolver.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/IncludedInResolver.java
@@ -17,7 +17,14 @@
import com.google.common.collect.LinkedListMultimap;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Lists;
-
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
import org.eclipse.jgit.errors.IncorrectObjectTypeException;
import org.eclipse.jgit.errors.MissingObjectException;
import org.eclipse.jgit.lib.Constants;
@@ -30,25 +37,13 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-/**
- * Resolve in which tags and branches a commit is included.
- */
+/** Resolve in which tags and branches a commit is included. */
public class IncludedInResolver {
- private static final Logger log = LoggerFactory
- .getLogger(IncludedInResolver.class);
+ private static final Logger log = LoggerFactory.getLogger(IncludedInResolver.class);
- public static Result resolve(final Repository repo,
- final RevWalk rw, final RevCommit commit) throws IOException {
+ public static Result resolve(final Repository repo, final RevWalk rw, final RevCommit commit)
+ throws IOException {
RevFlag flag = newFlag(rw);
try {
return new IncludedInResolver(repo, rw, commit, flag).resolve();
@@ -57,8 +52,9 @@
}
}
- public static boolean includedInOne(final Repository repo, final RevWalk rw,
- final RevCommit commit, final Collection<Ref> refs) throws IOException {
+ public static boolean includedInOne(
+ final Repository repo, final RevWalk rw, final RevCommit commit, final Collection<Ref> refs)
+ throws IOException {
RevFlag flag = newFlag(rw);
try {
return new IncludedInResolver(repo, rw, commit, flag).includedInOne(refs);
@@ -79,8 +75,8 @@
private ListMultimap<RevCommit, String> commitToRef;
private List<RevCommit> tipsByCommitTime;
- private IncludedInResolver(Repository repo, RevWalk rw, RevCommit target,
- RevFlag containsTarget) {
+ private IncludedInResolver(
+ Repository repo, RevWalk rw, RevCommit target, RevFlag containsTarget) {
this.repo = repo;
this.rw = rw;
this.target = target;
@@ -91,16 +87,14 @@
RefDatabase refDb = repo.getRefDatabase();
Collection<Ref> tags = refDb.getRefs(Constants.R_TAGS).values();
Collection<Ref> branches = refDb.getRefs(Constants.R_HEADS).values();
- List<Ref> allTagsAndBranches = Lists.newArrayListWithCapacity(
- tags.size() + branches.size());
+ List<Ref> allTagsAndBranches = Lists.newArrayListWithCapacity(tags.size() + branches.size());
allTagsAndBranches.addAll(tags);
allTagsAndBranches.addAll(branches);
parseCommits(allTagsAndBranches);
Set<String> allMatchingTagsAndBranches = includedIn(tipsByCommitTime, 0);
Result detail = new Result();
- detail
- .setBranches(getMatchingRefNames(allMatchingTagsAndBranches, branches));
+ detail.setBranches(getMatchingRefNames(allMatchingTagsAndBranches, branches));
detail.setTags(getMatchingRefNames(allMatchingTagsAndBranches, tags));
return detail;
@@ -117,9 +111,7 @@
return !includedIn(after, 1).isEmpty() || !includedIn(before, 1).isEmpty();
}
- /**
- * Resolves which tip refs include the target commit.
- */
+ /** Resolves which tip refs include the target commit. */
private Set<String> includedIn(final Collection<RevCommit> tips, int limit)
throws IOException, MissingObjectException, IncorrectObjectTypeException {
Set<String> result = new HashSet<>();
@@ -146,9 +138,10 @@
/**
* Partition the reference tips into two sets:
+ *
* <ul>
- * <li> before = commits with time < target.getCommitTime()
- * <li> after = commits with time >= target.getCommitTime()
+ * <li> before = commits with time < target.getCommitTime()
+ * <li> after = commits with time >= target.getCommitTime()
* </ul>
*
* Each of the before/after lists is sorted by the the commit time.
@@ -156,17 +149,19 @@
* @param before
* @param after
*/
- private void partition(final List<RevCommit> before,
- final List<RevCommit> after) {
- int insertionPoint = Collections.binarySearch(tipsByCommitTime, target,
- new Comparator<RevCommit>() {
- @Override
- public int compare(RevCommit c1, RevCommit c2) {
- return c1.getCommitTime() - c2.getCommitTime();
- }
- });
+ private void partition(final List<RevCommit> before, final List<RevCommit> after) {
+ int insertionPoint =
+ Collections.binarySearch(
+ tipsByCommitTime,
+ target,
+ new Comparator<RevCommit>() {
+ @Override
+ public int compare(RevCommit c1, RevCommit c2) {
+ return c1.getCommitTime() - c2.getCommitTime();
+ }
+ });
if (insertionPoint < 0) {
- insertionPoint = - (insertionPoint + 1);
+ insertionPoint = -(insertionPoint + 1);
}
if (0 < insertionPoint) {
before.addAll(tipsByCommitTime.subList(0, insertionPoint));
@@ -177,11 +172,11 @@
}
/**
- * Returns the short names of refs which are as well in the matchingRefs list
- * as well as in the allRef list.
+ * Returns the short names of refs which are as well in the matchingRefs list as well as in the
+ * allRef list.
*/
- private static List<String> getMatchingRefNames(Set<String> matchingRefs,
- Collection<Ref> allRefs) {
+ private static List<String> getMatchingRefNames(
+ Set<String> matchingRefs, Collection<Ref> allRefs) {
List<String> refNames = Lists.newArrayListWithCapacity(matchingRefs.size());
for (Ref r : allRefs) {
if (matchingRefs.contains(r.getName())) {
@@ -191,9 +186,7 @@
return refNames;
}
- /**
- * Parse commit of ref and store the relation between ref and commit.
- */
+ /** Parse commit of ref and store the relation between ref and commit. */
private void parseCommits(final Collection<Ref> refs) throws IOException {
if (commitToRef != null) {
return;
@@ -211,8 +204,13 @@
} catch (MissingObjectException notHere) {
// Log the problem with this branch, but keep processing.
//
- log.warn("Reference " + ref.getName() + " in " + repo.getDirectory()
- + " points to dangling object " + ref.getObjectId());
+ log.warn(
+ "Reference "
+ + ref.getName()
+ + " in "
+ + repo.getDirectory()
+ + " points to dangling object "
+ + ref.getObjectId());
continue;
}
commitToRef.put(commit, ref.getName());
@@ -222,20 +220,21 @@
}
private void sortOlderFirst(final List<RevCommit> tips) {
- Collections.sort(tips, new Comparator<RevCommit>() {
- @Override
- public int compare(RevCommit c1, RevCommit c2) {
- return c1.getCommitTime() - c2.getCommitTime();
- }
- });
+ Collections.sort(
+ tips,
+ new Comparator<RevCommit>() {
+ @Override
+ public int compare(RevCommit c1, RevCommit c2) {
+ return c1.getCommitTime() - c2.getCommitTime();
+ }
+ });
}
public static class Result {
private List<String> branches;
private List<String> tags;
- public Result() {
- }
+ public Result() {}
public void setBranches(final List<String> b) {
Collections.sort(b);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/Index.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/Index.java
index 44a9975..9257445 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/Index.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/Index.java
@@ -25,20 +25,17 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.io.IOException;
@Singleton
public class Index implements RestModifyView<ChangeResource, Input> {
- public static class Input {
- }
+ public static class Input {}
private final Provider<ReviewDb> db;
private final ChangeIndexer indexer;
@Inject
- Index(Provider<ReviewDb> db,
- ChangeIndexer indexer) {
+ Index(Provider<ReviewDb> db, ChangeIndexer indexer) {
this.db = db;
this.indexer = indexer;
}
@@ -47,10 +44,8 @@
public Response<?> apply(ChangeResource rsrc, Input input)
throws IOException, AuthException, OrmException {
ChangeControl ctl = rsrc.getControl();
- if (!ctl.isOwner()
- && !ctl.getUser().getCapabilities().canMaintainServer()) {
- throw new AuthException(
- "Only change owner or server maintainer can reindex");
+ if (!ctl.isOwner() && !ctl.getUser().getCapabilities().canMaintainServer()) {
+ throw new AuthException("Only change owner or server maintainer can reindex");
}
indexer.index(db.get(), rsrc.getChange());
return Response.none();
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/LimitedByteArrayOutputStream.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/LimitedByteArrayOutputStream.java
index b34404f..facc03c 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/LimitedByteArrayOutputStream.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/LimitedByteArrayOutputStream.java
@@ -26,9 +26,8 @@
private final ByteArrayOutputStream buffer;
/**
- * Constructs a LimitedByteArrayOutputStream, which stores output
- * in memory up to a certain specified size. When the output exceeds
- * the specified size a LimitExceededException is thrown.
+ * Constructs a LimitedByteArrayOutputStream, which stores output in memory up to a certain
+ * specified size. When the output exceeds the specified size a LimitExceededException is thrown.
*
* @param max the maximum size in bytes which may be stored.
* @param initial the initial size. It must be smaller than the max size.
@@ -46,7 +45,7 @@
}
@Override
- public void write(int b) throws IOException{
+ public void write(int b) throws IOException {
checkOversize(1);
buffer.write(b);
}
@@ -57,9 +56,7 @@
buffer.write(b, off, len);
}
- /**
- * @return a newly allocated byte array with contents of the buffer.
- */
+ /** @return a newly allocated byte array with contents of the buffer. */
public byte[] toByteArray() {
return buffer.toByteArray();
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/ListChangeComments.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/ListChangeComments.java
index 32b5ae8..942c3b4 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/ListChangeComments.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/ListChangeComments.java
@@ -24,7 +24,6 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.util.List;
import java.util.Map;
@@ -36,7 +35,8 @@
private final CommentsUtil commentsUtil;
@Inject
- ListChangeComments(Provider<ReviewDb> db,
+ ListChangeComments(
+ Provider<ReviewDb> db,
ChangeData.Factory changeDataFactory,
Provider<CommentJson> commentJson,
CommentsUtil commentsUtil) {
@@ -47,10 +47,11 @@
}
@Override
- public Map<String, List<CommentInfo>> apply(
- ChangeResource rsrc) throws AuthException, OrmException {
+ public Map<String, List<CommentInfo>> apply(ChangeResource rsrc)
+ throws AuthException, OrmException {
ChangeData cd = changeDataFactory.create(db.get(), rsrc.getControl());
- return commentJson.get()
+ return commentJson
+ .get()
.setFillAccounts(true)
.setFillPatchSet(true)
.newCommentFormatter()
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/ListChangeDrafts.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/ListChangeDrafts.java
index 6a3e237..2bf7aa0 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/ListChangeDrafts.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/ListChangeDrafts.java
@@ -25,7 +25,6 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.util.List;
import java.util.Map;
@@ -37,7 +36,8 @@
private final CommentsUtil commentsUtil;
@Inject
- ListChangeDrafts(Provider<ReviewDb> db,
+ ListChangeDrafts(
+ Provider<ReviewDb> db,
ChangeData.Factory changeDataFactory,
Provider<CommentJson> commentJson,
CommentsUtil commentsUtil) {
@@ -48,17 +48,20 @@
}
@Override
- public Map<String, List<CommentInfo>> apply(
- ChangeResource rsrc) throws AuthException, OrmException {
+ public Map<String, List<CommentInfo>> apply(ChangeResource rsrc)
+ throws AuthException, OrmException {
if (!rsrc.getControl().getUser().isIdentifiedUser()) {
throw new AuthException("Authentication required");
}
ChangeData cd = changeDataFactory.create(db.get(), rsrc.getControl());
- List<Comment> drafts = commentsUtil.draftByChangeAuthor(
- db.get(), cd.notes(), rsrc.getControl().getUser().getAccountId());
- return commentJson.get()
+ List<Comment> drafts =
+ commentsUtil.draftByChangeAuthor(
+ db.get(), cd.notes(), rsrc.getControl().getUser().getAccountId());
+ return commentJson
+ .get()
.setFillAccounts(false)
.setFillPatchSet(true)
- .newCommentFormatter().format(drafts);
+ .newCommentFormatter()
+ .format(drafts);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/ListChangeRobotComments.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/ListChangeRobotComments.java
index abfe869..881c6f53 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/ListChangeRobotComments.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/ListChangeRobotComments.java
@@ -23,7 +23,6 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
-
import java.util.List;
import java.util.Map;
@@ -34,7 +33,8 @@
private final CommentsUtil commentsUtil;
@Inject
- ListChangeRobotComments(Provider<ReviewDb> db,
+ ListChangeRobotComments(
+ Provider<ReviewDb> db,
ChangeData.Factory changeDataFactory,
Provider<CommentJson> commentJson,
CommentsUtil commentsUtil) {
@@ -45,14 +45,14 @@
}
@Override
- public Map<String, List<RobotCommentInfo>> apply(
- ChangeResource rsrc) throws AuthException, OrmException {
+ public Map<String, List<RobotCommentInfo>> apply(ChangeResource rsrc)
+ throws AuthException, OrmException {
ChangeData cd = changeDataFactory.create(db.get(), rsrc.getControl());
- return commentJson.get()
+ return commentJson
+ .get()
.setFillAccounts(true)
.setFillPatchSet(true)
.newRobotCommentFormatter()
.format(commentsUtil.robotCommentsByChange(cd.notes()));
}
}
-
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/ListReviewers.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/ListReviewers.java
index ccbd552..27ec89d 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/ListReviewers.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/ListReviewers.java
@@ -23,7 +23,6 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -36,7 +35,8 @@
private final ReviewerResource.Factory resourceFactory;
@Inject
- ListReviewers(Provider<ReviewDb> dbProvider,
+ ListReviewers(
+ Provider<ReviewDb> dbProvider,
ApprovalsUtil approvalsUtil,
ReviewerResource.Factory resourceFactory,
ReviewerJson json) {
@@ -50,8 +50,7 @@
public List<ReviewerInfo> apply(ChangeResource rsrc) throws OrmException {
Map<Account.Id, ReviewerResource> reviewers = new LinkedHashMap<>();
ReviewDb db = dbProvider.get();
- for (Account.Id accountId
- : approvalsUtil.getReviewers(db, rsrc.getNotes()).all()) {
+ for (Account.Id accountId : approvalsUtil.getReviewers(db, rsrc.getNotes()).all()) {
if (!reviewers.containsKey(accountId)) {
reviewers.put(accountId, resourceFactory.create(rsrc, accountId));
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/ListRevisionComments.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/ListRevisionComments.java
index 8524b8e..037a856 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/ListRevisionComments.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/ListRevisionComments.java
@@ -26,9 +26,8 @@
@Singleton
public class ListRevisionComments extends ListRevisionDrafts {
@Inject
- ListRevisionComments(Provider<ReviewDb> db,
- Provider<CommentJson> commentJson,
- CommentsUtil commentsUtil) {
+ ListRevisionComments(
+ Provider<ReviewDb> db, Provider<CommentJson> commentJson, CommentsUtil commentsUtil) {
super(db, commentJson, commentsUtil);
}
@@ -38,10 +37,8 @@
}
@Override
- protected Iterable<Comment> listComments(RevisionResource rsrc)
- throws OrmException {
+ protected Iterable<Comment> listComments(RevisionResource rsrc) throws OrmException {
ChangeNotes notes = rsrc.getNotes();
- return commentsUtil.publishedByPatchSet(db.get(), notes,
- rsrc.getPatchSet().getId());
+ return commentsUtil.publishedByPatchSet(db.get(), notes, rsrc.getPatchSet().getId());
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/ListRevisionDrafts.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/ListRevisionDrafts.java
index 21d427c..0463601 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/ListRevisionDrafts.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/ListRevisionDrafts.java
@@ -23,7 +23,6 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.util.List;
import java.util.Map;
@@ -34,18 +33,16 @@
protected final CommentsUtil commentsUtil;
@Inject
- ListRevisionDrafts(Provider<ReviewDb> db,
- Provider<CommentJson> commentJson,
- CommentsUtil commentsUtil) {
+ ListRevisionDrafts(
+ Provider<ReviewDb> db, Provider<CommentJson> commentJson, CommentsUtil commentsUtil) {
this.db = db;
this.commentJson = commentJson;
this.commentsUtil = commentsUtil;
}
- protected Iterable<Comment> listComments(RevisionResource rsrc)
- throws OrmException {
- return commentsUtil.draftByPatchSetAuthor(db.get(), rsrc.getPatchSet().getId(),
- rsrc.getAccountId(), rsrc.getNotes());
+ protected Iterable<Comment> listComments(RevisionResource rsrc) throws OrmException {
+ return commentsUtil.draftByPatchSetAuthor(
+ db.get(), rsrc.getPatchSet().getId(), rsrc.getAccountId(), rsrc.getNotes());
}
protected boolean includeAuthorInfo() {
@@ -53,17 +50,19 @@
}
@Override
- public Map<String, List<CommentInfo>> apply(RevisionResource rsrc)
- throws OrmException {
- return commentJson.get()
+ public Map<String, List<CommentInfo>> apply(RevisionResource rsrc) throws OrmException {
+ return commentJson
+ .get()
.setFillAccounts(includeAuthorInfo())
- .newCommentFormatter().format(listComments(rsrc));
+ .newCommentFormatter()
+ .format(listComments(rsrc));
}
- public List<CommentInfo> getComments(RevisionResource rsrc)
- throws OrmException {
- return commentJson.get()
+ public List<CommentInfo> getComments(RevisionResource rsrc) throws OrmException {
+ return commentJson
+ .get()
.setFillAccounts(includeAuthorInfo())
- .newCommentFormatter().formatAsList(listComments(rsrc));
+ .newCommentFormatter()
+ .formatAsList(listComments(rsrc));
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/ListRevisionReviewers.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/ListRevisionReviewers.java
index 5d9819e..d0c8ca0 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/ListRevisionReviewers.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/ListRevisionReviewers.java
@@ -24,7 +24,6 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -37,7 +36,8 @@
private final ReviewerResource.Factory resourceFactory;
@Inject
- ListRevisionReviewers(Provider<ReviewDb> dbProvider,
+ ListRevisionReviewers(
+ Provider<ReviewDb> dbProvider,
ApprovalsUtil approvalsUtil,
ReviewerResource.Factory resourceFactory,
ReviewerJson json) {
@@ -48,17 +48,15 @@
}
@Override
- public List<ReviewerInfo> apply(RevisionResource rsrc) throws OrmException,
- MethodNotAllowedException {
+ public List<ReviewerInfo> apply(RevisionResource rsrc)
+ throws OrmException, MethodNotAllowedException {
if (!rsrc.isCurrent()) {
- throw new MethodNotAllowedException(
- "Cannot list reviewers on non-current patch set");
+ throw new MethodNotAllowedException("Cannot list reviewers on non-current patch set");
}
Map<Account.Id, ReviewerResource> reviewers = new LinkedHashMap<>();
ReviewDb db = dbProvider.get();
- for (Account.Id accountId
- : approvalsUtil.getReviewers(db, rsrc.getNotes()).all()) {
+ for (Account.Id accountId : approvalsUtil.getReviewers(db, rsrc.getNotes()).all()) {
if (!reviewers.containsKey(accountId)) {
reviewers.put(accountId, resourceFactory.create(rsrc, accountId));
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/ListRobotComments.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/ListRobotComments.java
index 01ad9ee..de2b91a 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/ListRobotComments.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/ListRobotComments.java
@@ -23,7 +23,6 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.util.List;
import java.util.Map;
@@ -34,34 +33,31 @@
protected final CommentsUtil commentsUtil;
@Inject
- ListRobotComments(Provider<ReviewDb> db,
- Provider<CommentJson> commentJson,
- CommentsUtil commentsUtil) {
+ ListRobotComments(
+ Provider<ReviewDb> db, Provider<CommentJson> commentJson, CommentsUtil commentsUtil) {
this.db = db;
this.commentJson = commentJson;
this.commentsUtil = commentsUtil;
}
@Override
- public Map<String, List<RobotCommentInfo>> apply(RevisionResource rsrc)
- throws OrmException {
- return commentJson.get()
+ public Map<String, List<RobotCommentInfo>> apply(RevisionResource rsrc) throws OrmException {
+ return commentJson
+ .get()
.setFillAccounts(true)
.newRobotCommentFormatter()
.format(listComments(rsrc));
}
- public List<RobotCommentInfo> getComments(RevisionResource rsrc)
- throws OrmException {
- return commentJson.get()
+ public List<RobotCommentInfo> getComments(RevisionResource rsrc) throws OrmException {
+ return commentJson
+ .get()
.setFillAccounts(true)
.newRobotCommentFormatter()
.formatAsList(listComments(rsrc));
}
- private Iterable<RobotComment> listComments(RevisionResource rsrc)
- throws OrmException {
- return commentsUtil.robotCommentsByPatchSet(
- rsrc.getNotes(), rsrc.getPatchSet().getId());
+ private Iterable<RobotComment> listComments(RevisionResource rsrc) throws OrmException {
+ return commentsUtil.robotCommentsByPatchSet(rsrc.getNotes(), rsrc.getPatchSet().getId());
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/MergeabilityCache.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/MergeabilityCache.java
index 93c4ac3..3a7f3ab 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/MergeabilityCache.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/MergeabilityCache.java
@@ -16,7 +16,6 @@
import com.google.gerrit.extensions.client.SubmitType;
import com.google.gerrit.reviewdb.client.Branch;
-
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
@@ -25,21 +24,30 @@
public interface MergeabilityCache {
class NotImplemented implements MergeabilityCache {
@Override
- public boolean get(ObjectId commit, Ref intoRef, SubmitType submitType,
- String mergeStrategy, Branch.NameKey dest, Repository repo) {
+ public boolean get(
+ ObjectId commit,
+ Ref intoRef,
+ SubmitType submitType,
+ String mergeStrategy,
+ Branch.NameKey dest,
+ Repository repo) {
throw new UnsupportedOperationException("Mergeability checking disabled");
}
@Override
- public Boolean getIfPresent(ObjectId commit, Ref intoRef,
- SubmitType submitType, String mergeStrategy) {
+ public Boolean getIfPresent(
+ ObjectId commit, Ref intoRef, SubmitType submitType, String mergeStrategy) {
throw new UnsupportedOperationException("Mergeability checking disabled");
}
}
- boolean get(ObjectId commit, Ref intoRef, SubmitType submitType,
- String mergeStrategy, Branch.NameKey dest, Repository repo);
+ boolean get(
+ ObjectId commit,
+ Ref intoRef,
+ SubmitType submitType,
+ String mergeStrategy,
+ Branch.NameKey dest,
+ Repository repo);
- Boolean getIfPresent(ObjectId commit, Ref intoRef,
- SubmitType submitType, String mergeStrategy);
+ Boolean getIfPresent(ObjectId commit, Ref intoRef, SubmitType submitType, String mergeStrategy);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/MergeabilityCacheImpl.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/MergeabilityCacheImpl.java
index a6e0935..7d01277 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/MergeabilityCacheImpl.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/MergeabilityCacheImpl.java
@@ -39,14 +39,6 @@
import com.google.inject.Module;
import com.google.inject.Singleton;
import com.google.inject.name.Named;
-
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.lib.Ref;
-import org.eclipse.jgit.lib.Repository;
-import org.eclipse.jgit.revwalk.RevCommit;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
@@ -56,11 +48,16 @@
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.lib.Ref;
+import org.eclipse.jgit.lib.Repository;
+import org.eclipse.jgit.revwalk.RevCommit;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
@Singleton
public class MergeabilityCacheImpl implements MergeabilityCache {
- private static final Logger log =
- LoggerFactory.getLogger(MergeabilityCacheImpl.class);
+ private static final Logger log = LoggerFactory.getLogger(MergeabilityCacheImpl.class);
private static final String CACHE_NAME = "mergeability";
@@ -75,7 +72,8 @@
.build();
static {
- checkState(SUBMIT_TYPES.size() == SubmitType.values().length,
+ checkState(
+ SUBMIT_TYPES.size() == SubmitType.values().length,
"SubmitType <-> char BiMap needs updating");
}
@@ -92,9 +90,7 @@
}
public static ObjectId toId(Ref ref) {
- return ref != null && ref.getObjectId() != null
- ? ref.getObjectId()
- : ObjectId.zeroId();
+ return ref != null && ref.getObjectId() != null ? ref.getObjectId() : ObjectId.zeroId();
}
public static class EntryKey implements Serializable {
@@ -105,8 +101,7 @@
private SubmitType submitType;
private String mergeStrategy;
- public EntryKey(ObjectId commit, ObjectId into, SubmitType submitType,
- String mergeStrategy) {
+ public EntryKey(ObjectId commit, ObjectId into, SubmitType submitType, String mergeStrategy) {
this.commit = checkNotNull(commit, "commit");
this.into = checkNotNull(into, "into");
this.submitType = checkNotNull(submitType, "submitType");
@@ -191,8 +186,7 @@
}
@Override
- public Boolean call()
- throws NoSuchProjectException, IntegrationException, IOException {
+ public Boolean call() throws NoSuchProjectException, IntegrationException, IOException {
if (key.into.equals(ObjectId.zeroId())) {
return true; // Assume yes on new branch.
}
@@ -200,17 +194,17 @@
Set<RevCommit> accepted = SubmitDryRun.getAlreadyAccepted(repo, rw);
accepted.add(rw.parseCommit(key.into));
accepted.addAll(Arrays.asList(rw.parseCommit(key.commit).getParents()));
- return submitDryRun.run(
- key.submitType, repo, rw, dest, key.into, key.commit, accepted);
+ return submitDryRun.run(key.submitType, repo, rw, dest, key.into, key.commit, accepted);
}
}
}
- public static class MergeabilityWeigher
- implements Weigher<EntryKey, Boolean> {
+ public static class MergeabilityWeigher implements Weigher<EntryKey, Boolean> {
@Override
public int weigh(EntryKey k, Boolean v) {
- return 16 + 2 * (16 + 20) + 3 * 8 // Size of EntryKey, 64-bit JVM.
+ return 16
+ + 2 * (16 + 20)
+ + 3 * 8 // Size of EntryKey, 64-bit JVM.
+ 8; // Size of Boolean.
}
}
@@ -220,31 +214,36 @@
@Inject
MergeabilityCacheImpl(
- SubmitDryRun submitDryRun,
- @Named(CACHE_NAME) Cache<EntryKey, Boolean> cache) {
+ SubmitDryRun submitDryRun, @Named(CACHE_NAME) Cache<EntryKey, Boolean> cache) {
this.submitDryRun = submitDryRun;
this.cache = cache;
}
@Override
- public boolean get(ObjectId commit, Ref intoRef, SubmitType submitType,
- String mergeStrategy, Branch.NameKey dest, Repository repo) {
+ public boolean get(
+ ObjectId commit,
+ Ref intoRef,
+ SubmitType submitType,
+ String mergeStrategy,
+ Branch.NameKey dest,
+ Repository repo) {
ObjectId into = intoRef != null ? intoRef.getObjectId() : ObjectId.zeroId();
EntryKey key = new EntryKey(commit, into, submitType, mergeStrategy);
try {
return cache.get(key, new Loader(key, dest, repo));
} catch (ExecutionException | UncheckedExecutionException e) {
- log.error(String.format("Error checking mergeability of %s into %s (%s)",
- key.commit.name(), key.into.name(), key.submitType.name()),
+ log.error(
+ String.format(
+ "Error checking mergeability of %s into %s (%s)",
+ key.commit.name(), key.into.name(), key.submitType.name()),
e.getCause());
return false;
}
}
@Override
- public Boolean getIfPresent(ObjectId commit, Ref intoRef,
- SubmitType submitType, String mergeStrategy) {
- return cache.getIfPresent(
- new EntryKey(commit, toId(intoRef), submitType, mergeStrategy));
+ public Boolean getIfPresent(
+ ObjectId commit, Ref intoRef, SubmitType submitType, String mergeStrategy) {
+ return cache.getIfPresent(new EntryKey(commit, toId(intoRef), submitType, mergeStrategy));
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/Mergeable.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/Mergeable.java
index 7796d18..e5f9352 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/Mergeable.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/Mergeable.java
@@ -36,7 +36,11 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
-
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Map;
+import java.util.Objects;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Ref;
@@ -45,17 +49,14 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Map;
-import java.util.Objects;
-
public class Mergeable implements RestReadView<RevisionResource> {
private static final Logger log = LoggerFactory.getLogger(Mergeable.class);
- @Option(name = "--other-branches", aliases = {"-o"},
- usage = "test mergeability for other branches too")
+ @Option(
+ name = "--other-branches",
+ aliases = {"-o"},
+ usage = "test mergeability for other branches too"
+ )
private boolean otherBranches;
private final GitRepositoryManager gitManager;
@@ -67,7 +68,8 @@
private final MergeabilityCache cache;
@Inject
- Mergeable(GitRepositoryManager gitManager,
+ Mergeable(
+ GitRepositoryManager gitManager,
ProjectCache projectCache,
MergeUtil.Factory mergeUtilFactory,
ChangeData.Factory changeDataFactory,
@@ -88,8 +90,9 @@
}
@Override
- public MergeableInfo apply(RevisionResource resource) throws AuthException,
- ResourceConflictException, BadRequestException, OrmException, IOException {
+ public MergeableInfo apply(RevisionResource resource)
+ throws AuthException, ResourceConflictException, BadRequestException, OrmException,
+ IOException {
Change change = resource.getChange();
PatchSet ps = resource.getPatchSet();
MergeableInfo result = new MergeableInfo();
@@ -108,11 +111,9 @@
ObjectId commit = toId(ps);
Ref ref = git.getRefDatabase().exactRef(change.getDest().get());
ProjectState projectState = projectCache.get(change.getProject());
- String strategy = mergeUtilFactory.create(projectState)
- .mergeStrategyName();
+ String strategy = mergeUtilFactory.create(projectState).mergeStrategyName();
result.strategy = strategy;
- result.mergeable =
- isMergable(git, change, commit, ref, result.submitType, strategy);
+ result.mergeable = isMergable(git, change, commit, ref, result.submitType, strategy);
if (otherBranches) {
result.mergeableInto = new ArrayList<>();
@@ -126,8 +127,7 @@
if (other == null) {
continue;
}
- if (cache.get(commit, other, SubmitType.CHERRY_PICK, strategy,
- change.getDest(), git)) {
+ if (cache.get(commit, other, SubmitType.CHERRY_PICK, strategy, change.getDest(), git)) {
result.mergeableInto.add(other.getName().substring(prefixLen));
}
}
@@ -137,19 +137,22 @@
return result;
}
- private SubmitType getSubmitType(ChangeData cd, PatchSet patchSet)
- throws OrmException {
- SubmitTypeRecord rec =
- new SubmitRuleEvaluator(cd).setPatchSet(patchSet).getSubmitType();
+ private SubmitType getSubmitType(ChangeData cd, PatchSet patchSet) throws OrmException {
+ SubmitTypeRecord rec = new SubmitRuleEvaluator(cd).setPatchSet(patchSet).getSubmitType();
if (rec.status != SubmitTypeRecord.Status.OK) {
throw new OrmException("Submit type rule failed: " + rec);
}
return rec.type;
}
- private boolean isMergable(Repository git, Change change, ObjectId commit,
- Ref ref, SubmitType submitType, String strategy)
- throws IOException, OrmException {
+ private boolean isMergable(
+ Repository git,
+ Change change,
+ ObjectId commit,
+ Ref ref,
+ SubmitType submitType,
+ String strategy)
+ throws IOException, OrmException {
if (commit == null) {
return false;
}
@@ -158,8 +161,7 @@
if (old != null) {
return old;
}
- return refresh(change, commit, ref, submitType,
- strategy, git, old);
+ return refresh(change, commit, ref, submitType, strategy, git, old);
}
private static ObjectId toId(PatchSet ps) {
@@ -171,11 +173,16 @@
}
}
- private boolean refresh(final Change change, ObjectId commit,
- final Ref ref, SubmitType type, String strategy, Repository git,
- Boolean old) throws OrmException, IOException {
- final boolean mergeable =
- cache.get(commit, ref, type, strategy, change.getDest(), git);
+ private boolean refresh(
+ final Change change,
+ ObjectId commit,
+ final Ref ref,
+ SubmitType type,
+ String strategy,
+ Repository git,
+ Boolean old)
+ throws OrmException, IOException {
+ final boolean mergeable = cache.get(commit, ref, type, strategy, change.getDest(), git);
if (!Objects.equals(mergeable, old)) {
invalidateETag(change.getId(), db.get());
indexer.index(db.get(), change);
@@ -183,8 +190,7 @@
return mergeable;
}
- private static void invalidateETag(Change.Id id, ReviewDb db)
- throws OrmException {
+ private static void invalidateETag(Change.Id id, ReviewDb db) throws OrmException {
// Empty update of Change to bump rowVersion, changing its ETag.
// TODO(dborowitz): Include cache info in ETag somehow instead.
db = ReviewDbUtil.unwrapDb(db);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/Move.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/Move.java
index 4a3f45a..09e3377 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/Move.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/Move.java
@@ -45,15 +45,13 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
+import java.io.IOException;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;
-import java.io.IOException;
-
@Singleton
public class Move implements RestModifyView<ChangeResource, MoveInput> {
private final Provider<ReviewDb> dbProvider;
@@ -65,7 +63,8 @@
private final PatchSetUtil psUtil;
@Inject
- Move(Provider<ReviewDb> dbProvider,
+ Move(
+ Provider<ReviewDb> dbProvider,
ChangeJson.Factory json,
GitRepositoryManager repoManager,
Provider<InternalChangeQuery> queryProvider,
@@ -90,8 +89,9 @@
throw new AuthException("Move not permitted");
}
- try (BatchUpdate u = batchUpdateFactory.create(dbProvider.get(),
- req.getChange().getProject(), control.getUser(), TimeUtil.nowTs())) {
+ try (BatchUpdate u =
+ batchUpdateFactory.create(
+ dbProvider.get(), req.getChange().getProject(), control.getUser(), TimeUtil.nowTs())) {
u.addOp(req.getChange().getId(), new Op(input));
u.execute();
}
@@ -110,11 +110,10 @@
}
@Override
- public boolean updateChange(ChangeContext ctx) throws OrmException,
- ResourceConflictException, RepositoryNotFoundException, IOException {
+ public boolean updateChange(ChangeContext ctx)
+ throws OrmException, ResourceConflictException, RepositoryNotFoundException, IOException {
change = ctx.getChange();
- if (change.getStatus() != Status.NEW
- && change.getStatus() != Status.DRAFT) {
+ if (change.getStatus() != Status.NEW && change.getStatus() != Status.DRAFT) {
throw new ResourceConflictException("Change is " + status(change));
}
@@ -122,16 +121,16 @@
newDestKey = new Branch.NameKey(projectKey, input.destinationBranch);
Branch.NameKey changePrevDest = change.getDest();
if (changePrevDest.equals(newDestKey)) {
- throw new ResourceConflictException(
- "Change is already destined for the specified branch");
+ throw new ResourceConflictException("Change is already destined for the specified branch");
}
final PatchSet.Id patchSetId = change.currentPatchSetId();
try (Repository repo = repoManager.openRepository(projectKey);
RevWalk revWalk = new RevWalk(repo)) {
- RevCommit currPatchsetRevCommit = revWalk.parseCommit(
- ObjectId.fromString(psUtil.current(ctx.getDb(), ctx.getNotes())
- .getRevision().get()));
+ RevCommit currPatchsetRevCommit =
+ revWalk.parseCommit(
+ ObjectId.fromString(
+ psUtil.current(ctx.getDb(), ctx.getNotes()).getRevision().get()));
if (currPatchsetRevCommit.getParentCount() > 1) {
throw new ResourceConflictException("Merge commit cannot be moved");
}
@@ -145,17 +144,17 @@
RevCommit refCommit = revWalk.parseCommit(refId);
if (revWalk.isMergedInto(currPatchsetRevCommit, refCommit)) {
throw new ResourceConflictException(
- "Current patchset revision is reachable from tip of "
- + input.destinationBranch);
+ "Current patchset revision is reachable from tip of " + input.destinationBranch);
}
}
Change.Key changeKey = change.getKey();
- if (!asChanges(queryProvider.get().byBranchKey(newDestKey, changeKey))
- .isEmpty()) {
+ if (!asChanges(queryProvider.get().byBranchKey(newDestKey, changeKey)).isEmpty()) {
throw new ResourceConflictException(
- "Destination " + newDestKey.getShortName()
- + " has a different change with same change key " + changeKey);
+ "Destination "
+ + newDestKey.getShortName()
+ + " has a different change with same change key "
+ + changeKey);
}
if (!change.currentPatchSetId().equals(patchSetId)) {
@@ -176,8 +175,7 @@
msgBuf.append(input.message);
}
ChangeMessage cmsg =
- ChangeMessagesUtil.newMessage(
- ctx, msgBuf.toString(), ChangeMessagesUtil.TAG_MOVE);
+ ChangeMessagesUtil.newMessage(ctx, msgBuf.toString(), ChangeMessagesUtil.TAG_MOVE);
cmUtil.addChangeMessage(ctx.getDb(), update, cmsg);
return true;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/NotifyUtil.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/NotifyUtil.java
index e5633cd..8516615 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/NotifyUtil.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/NotifyUtil.java
@@ -31,7 +31,6 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@@ -43,14 +42,13 @@
private final AccountResolver accountResolver;
@Inject
- NotifyUtil(Provider<ReviewDb> dbProvider,
- AccountResolver accountResolver) {
+ NotifyUtil(Provider<ReviewDb> dbProvider, AccountResolver accountResolver) {
this.dbProvider = dbProvider;
this.accountResolver = accountResolver;
}
- public static boolean shouldNotify(NotifyHandling notify,
- @Nullable Map<RecipientType, NotifyInfo> notifyDetails) {
+ public static boolean shouldNotify(
+ NotifyHandling notify, @Nullable Map<RecipientType, NotifyInfo> notifyDetails) {
if (!isNullOrEmpty(notifyDetails)) {
return true;
}
@@ -58,8 +56,7 @@
return notify.compareTo(NotifyHandling.NONE) > 0;
}
- private static boolean isNullOrEmpty(
- @Nullable Map<RecipientType, NotifyInfo> notifyDetails) {
+ private static boolean isNullOrEmpty(@Nullable Map<RecipientType, NotifyInfo> notifyDetails) {
if (notifyDetails == null || notifyDetails.isEmpty()) {
return true;
}
@@ -79,7 +76,7 @@
public ListMultimap<RecipientType, Account.Id> resolveAccounts(
@Nullable Map<RecipientType, NotifyInfo> notifyDetails)
- throws OrmException, BadRequestException {
+ throws OrmException, BadRequestException {
if (isNullOrEmpty(notifyDetails)) {
return ImmutableListMultimap.of();
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/PatchSetInserter.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/PatchSetInserter.java
index c9b4df2..d7a043f 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/PatchSetInserter.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/PatchSetInserter.java
@@ -52,24 +52,20 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
-
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.transport.ReceiveCommand;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.util.Collections;
-import java.util.List;
-
public class PatchSetInserter extends BatchUpdate.Op {
- private static final Logger log =
- LoggerFactory.getLogger(PatchSetInserter.class);
+ private static final Logger log = LoggerFactory.getLogger(PatchSetInserter.class);
public interface Factory {
- PatchSetInserter create(ChangeControl ctl, PatchSet.Id psId,
- RevCommit commit);
+ PatchSetInserter create(ChangeControl ctl, PatchSet.Id psId, RevCommit commit);
}
// Injected fields.
@@ -93,15 +89,13 @@
// Fields exposed as setters.
private String message;
private String description;
- private CommitValidators.Policy validatePolicy =
- CommitValidators.Policy.GERRIT;
+ private CommitValidators.Policy validatePolicy = CommitValidators.Policy.GERRIT;
private boolean checkAddPatchSetPermission = true;
private boolean draft;
private List<String> groups = Collections.emptyList();
private boolean fireRevisionCreated = true;
private NotifyHandling notify = NotifyHandling.ALL;
- private ListMultimap<RecipientType, Account.Id> accountsToNotify =
- ImmutableListMultimap.of();
+ private ListMultimap<RecipientType, Account.Id> accountsToNotify = ImmutableListMultimap.of();
private boolean allowClosed;
private boolean copyApprovals = true;
@@ -113,7 +107,8 @@
private ReviewerSet oldReviewers;
@AssistedInject
- public PatchSetInserter(ApprovalsUtil approvalsUtil,
+ public PatchSetInserter(
+ ApprovalsUtil approvalsUtil,
ApprovalCopier approvalCopier,
ChangeMessagesUtil cmUtil,
PatchSetInfoFactory patchSetInfoFactory,
@@ -157,8 +152,7 @@
return this;
}
- public PatchSetInserter setCheckAddPatchSetPermission(
- boolean checkAddPatchSetPermission) {
+ public PatchSetInserter setCheckAddPatchSetPermission(boolean checkAddPatchSetPermission) {
this.checkAddPatchSetPermission = checkAddPatchSetPermission;
return this;
}
@@ -214,8 +208,9 @@
public void updateRepo(RepoContext ctx)
throws AuthException, ResourceConflictException, IOException, OrmException {
validate(ctx);
- ctx.addRefUpdate(new ReceiveCommand(ObjectId.zeroId(),
- commit, getPatchSetId().toRefName(), ReceiveCommand.Type.CREATE));
+ ctx.addRefUpdate(
+ new ReceiveCommand(
+ ObjectId.zeroId(), commit, getPatchSetId().toRefName(), ReceiveCommand.Type.CREATE));
}
@Override
@@ -229,9 +224,10 @@
update.setSubjectForCommit("Create patch set " + psId.get());
if (!change.getStatus().isOpen() && !allowClosed) {
- throw new ResourceConflictException(String.format(
- "Cannot create new patch set of change %s because it is %s",
- change.getId(), change.getStatus().name().toLowerCase()));
+ throw new ResourceConflictException(
+ String.format(
+ "Cannot create new patch set of change %s because it is %s",
+ change.getId(), change.getStatus().name().toLowerCase()));
}
List<String> newGroups = groups;
@@ -241,17 +237,30 @@
newGroups = prevPs.getGroups();
}
}
- patchSet = psUtil.insert(db, ctx.getRevWalk(), ctx.getUpdate(psId),
- psId, commit, draft, newGroups, null, description);
+ patchSet =
+ psUtil.insert(
+ db,
+ ctx.getRevWalk(),
+ ctx.getUpdate(psId),
+ psId,
+ commit,
+ draft,
+ newGroups,
+ null,
+ description);
if (notify != NotifyHandling.NONE) {
oldReviewers = approvalsUtil.getReviewers(db, ctl.getNotes());
}
if (message != null) {
- changeMessage = ChangeMessagesUtil.newMessage(
- patchSet.getId(), ctx.getUser(), ctx.getWhen(), message,
- ChangeMessagesUtil.TAG_UPLOADED_PATCH_SET);
+ changeMessage =
+ ChangeMessagesUtil.newMessage(
+ patchSet.getId(),
+ ctx.getUser(),
+ ctx.getWhen(),
+ message,
+ ChangeMessagesUtil.TAG_UPLOADED_PATCH_SET);
changeMessage.setMessage(message);
}
@@ -273,8 +282,7 @@
public void postUpdate(Context ctx) throws OrmException {
if (notify != NotifyHandling.NONE || !accountsToNotify.isEmpty()) {
try {
- ReplacePatchSetSender cm = replacePatchSetFactory.create(
- ctx.getProject(), change.getId());
+ ReplacePatchSetSender cm = replacePatchSetFactory.create(ctx.getProject(), change.getId());
cm.setFrom(ctx.getAccountId());
cm.setPatchSet(patchSet, patchSetInfo);
cm.setChangeMessage(changeMessage.getMessage(), ctx.getWhen());
@@ -284,20 +292,17 @@
cm.setAccountsToNotify(accountsToNotify);
cm.send();
} catch (Exception err) {
- log.error("Cannot send email for new patch set on change "
- + change.getId(), err);
+ log.error("Cannot send email for new patch set on change " + change.getId(), err);
}
}
if (fireRevisionCreated) {
- revisionCreated.fire(change, patchSet, ctx.getAccount(),
- ctx.getWhen(), notify);
+ revisionCreated.fire(change, patchSet, ctx.getAccount(), ctx.getWhen(), notify);
}
}
private void validate(RepoContext ctx)
- throws AuthException, ResourceConflictException, IOException,
- OrmException {
+ throws AuthException, ResourceConflictException, IOException, OrmException {
if (checkAddPatchSetPermission && !origCtl.canAddPatchSet(ctx.getDb())) {
throw new AuthException("cannot add patch set");
}
@@ -306,20 +311,20 @@
}
String refName = getPatchSetId().toRefName();
- CommitReceivedEvent event = new CommitReceivedEvent(
- new ReceiveCommand(
- ObjectId.zeroId(),
- commit.getId(),
- refName.substring(0, refName.lastIndexOf('/') + 1) + "new"),
- origCtl.getProjectControl().getProject(),
- origCtl.getRefControl().getRefName(),
- commit, ctx.getIdentifiedUser());
+ CommitReceivedEvent event =
+ new CommitReceivedEvent(
+ new ReceiveCommand(
+ ObjectId.zeroId(),
+ commit.getId(),
+ refName.substring(0, refName.lastIndexOf('/') + 1) + "new"),
+ origCtl.getProjectControl().getProject(),
+ origCtl.getRefControl().getRefName(),
+ commit,
+ ctx.getIdentifiedUser());
try {
commitValidatorsFactory
- .create(
- validatePolicy, origCtl.getRefControl(), new NoSshInfo(),
- ctx.getRepository())
+ .create(validatePolicy, origCtl.getRefControl(), new NoSshInfo(), ctx.getRepository())
.validate(event);
} catch (CommitValidationException e) {
throw new ResourceConflictException(e.getFullMessage());
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/PostHashtags.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/PostHashtags.java
index 6d7720d..55e476b 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/PostHashtags.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/PostHashtags.java
@@ -30,14 +30,14 @@
@Singleton
public class PostHashtags
- implements RestModifyView<ChangeResource, HashtagsInput>,
- UiAction<ChangeResource> {
+ implements RestModifyView<ChangeResource, HashtagsInput>, UiAction<ChangeResource> {
private final Provider<ReviewDb> db;
private final BatchUpdate.Factory batchUpdateFactory;
private final SetHashtagsOp.Factory hashtagsFactory;
@Inject
- PostHashtags(Provider<ReviewDb> db,
+ PostHashtags(
+ Provider<ReviewDb> db,
BatchUpdate.Factory batchUpdateFactory,
SetHashtagsOp.Factory hashtagsFactory) {
this.db = db;
@@ -46,22 +46,22 @@
}
@Override
- public Response<ImmutableSortedSet<String>> apply(ChangeResource req,
- HashtagsInput input) throws RestApiException, UpdateException {
- try (BatchUpdate bu = batchUpdateFactory.create(db.get(),
- req.getChange().getProject(), req.getControl().getUser(),
- TimeUtil.nowTs())) {
+ public Response<ImmutableSortedSet<String>> apply(ChangeResource req, HashtagsInput input)
+ throws RestApiException, UpdateException {
+ try (BatchUpdate bu =
+ batchUpdateFactory.create(
+ db.get(), req.getChange().getProject(), req.getControl().getUser(), TimeUtil.nowTs())) {
SetHashtagsOp op = hashtagsFactory.create(input);
bu.addOp(req.getId(), op);
bu.execute();
- return Response.<ImmutableSortedSet<String>> ok(op.getUpdatedHashtags());
+ return Response.<ImmutableSortedSet<String>>ok(op.getUpdatedHashtags());
}
}
@Override
public UiAction.Description getDescription(ChangeResource resource) {
return new UiAction.Description()
- .setLabel("Edit Hashtags")
- .setVisible(resource.getControl().canEditHashtags());
+ .setLabel("Edit Hashtags")
+ .setVisible(resource.getControl().canEditHashtags());
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/PostReview.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/PostReview.java
index aaea82c..790c241 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/PostReview.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/PostReview.java
@@ -100,10 +100,6 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
@@ -117,6 +113,8 @@
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
@Singleton
public class PostReview implements RestModifyView<RevisionResource, ReviewInput> {
@@ -139,7 +137,8 @@
private final NotifyUtil notifyUtil;
@Inject
- PostReview(Provider<ReviewDb> db,
+ PostReview(
+ Provider<ReviewDb> db,
BatchUpdate.Factory batchUpdateFactory,
ChangesCollection changes,
ChangeData.Factory changeDataFactory,
@@ -177,8 +176,7 @@
return apply(revision, input, TimeUtil.nowTs());
}
- public Response<ReviewResult> apply(RevisionResource revision, ReviewInput input,
- Timestamp ts)
+ public Response<ReviewResult> apply(RevisionResource revision, ReviewInput input, Timestamp ts)
throws RestApiException, UpdateException, OrmException, IOException {
// Respect timestamp, but truncate at change created-on time.
ts = Ordering.natural().max(ts, revision.getChange().getCreatedOn());
@@ -220,8 +218,8 @@
// Prevent notifications because setting reviewers is batched.
reviewerInput.notify = NotifyHandling.NONE;
- PostReviewers.Addition result = postReviewers.prepareApplication(
- revision.getChangeResource(), reviewerInput, true);
+ PostReviewers.Addition result =
+ postReviewers.prepareApplication(revision.getChangeResource(), reviewerInput, true);
reviewerJsonResults.put(reviewerInput.reviewer, result.result);
if (result.result.error != null) {
hasError = true;
@@ -242,15 +240,16 @@
}
output.labels = input.labels;
- try (BatchUpdate bu = batchUpdateFactory.create(db.get(),
- revision.getChange().getProject(), revision.getUser(), ts)) {
+ try (BatchUpdate bu =
+ batchUpdateFactory.create(
+ db.get(), revision.getChange().getProject(), revision.getUser(), ts)) {
Account.Id id = bu.getUser().getAccountId();
boolean ccOrReviewer = input.labels != null && !input.labels.isEmpty();
if (!ccOrReviewer) {
// Check if user was already CCed or reviewing prior to this review.
- ReviewerSet currentReviewers = approvalsUtil.getReviewers(
- db.get(), revision.getChangeResource().getNotes());
+ ReviewerSet currentReviewers =
+ approvalsUtil.getReviewers(db.get(), revision.getChangeResource().getNotes());
ccOrReviewer = currentReviewers.all().contains(id);
}
@@ -281,29 +280,29 @@
// User posting this review isn't currently in the reviewer or CC list,
// isn't being explicitly added, and isn't voting on any label.
// Automatically CC them on this change so they receive replies.
- PostReviewers.Addition selfAddition =
- postReviewers.ccCurrentUser(bu.getUser(), revision);
+ PostReviewers.Addition selfAddition = postReviewers.ccCurrentUser(bu.getUser(), revision);
bu.addOp(revision.getChange().getId(), selfAddition.op);
}
- bu.addOp(revision.getChange().getId(),
- new Op(revision.getPatchSet().getId(), input, accountsToNotify,
- reviewerResults));
+ bu.addOp(
+ revision.getChange().getId(),
+ new Op(revision.getPatchSet().getId(), input, accountsToNotify, reviewerResults));
bu.execute();
for (PostReviewers.Addition reviewerResult : reviewerResults) {
reviewerResult.gatherResults();
}
- emailReviewers(revision.getChange(), reviewerResults, input.notify,
- accountsToNotify);
+ emailReviewers(revision.getChange(), reviewerResults, input.notify, accountsToNotify);
}
return Response.ok(output);
}
- private void emailReviewers(Change change,
- List<PostReviewers.Addition> reviewerAdditions, NotifyHandling notify,
+ private void emailReviewers(
+ Change change,
+ List<PostReviewers.Addition> reviewerAdditions,
+ NotifyHandling notify,
ListMultimap<RecipientType, Account.Id> accountsToNotify) {
List<Account.Id> to = new ArrayList<>();
List<Account.Id> cc = new ArrayList<>();
@@ -318,12 +317,10 @@
}
private RevisionResource onBehalfOf(RevisionResource rev, ReviewInput in)
- throws BadRequestException, AuthException, UnprocessableEntityException,
- OrmException {
+ throws BadRequestException, AuthException, UnprocessableEntityException, OrmException {
if (in.labels == null || in.labels.isEmpty()) {
- throw new AuthException(String.format(
- "label required to post review on behalf of \"%s\"",
- in.onBehalfOf));
+ throw new AuthException(
+ String.format("label required to post review on behalf of \"%s\"", in.onBehalfOf));
}
if (in.drafts == null) {
in.drafts = DraftHandling.KEEP;
@@ -332,15 +329,14 @@
throw new AuthException("not allowed to modify other user's drafts");
}
-
ChangeControl caller = rev.getControl();
Iterator<Map.Entry<String, Short>> itr = in.labels.entrySet().iterator();
while (itr.hasNext()) {
Map.Entry<String, Short> ent = itr.next();
LabelType type = caller.getLabelTypes().byLabel(ent.getKey());
if (type == null && in.strictLabels) {
- throw new BadRequestException(String.format(
- "label \"%s\" is not a configured label", ent.getKey()));
+ throw new BadRequestException(
+ String.format("label \"%s\" is not a configured label", ent.getKey()));
} else if (type == null) {
itr.remove();
continue;
@@ -352,40 +348,40 @@
PermissionRange r = caller.getRange(Permission.forLabelAs(type.getName()));
if (r == null || r.isEmpty() || !r.contains(ent.getValue())) {
- throw new AuthException(String.format(
- "not permitted to modify label \"%s\" on behalf of \"%s\"",
- ent.getKey(), in.onBehalfOf));
+ throw new AuthException(
+ String.format(
+ "not permitted to modify label \"%s\" on behalf of \"%s\"",
+ ent.getKey(), in.onBehalfOf));
}
}
if (in.labels.isEmpty()) {
- throw new AuthException(String.format(
- "label required to post review on behalf of \"%s\"",
- in.onBehalfOf));
+ throw new AuthException(
+ String.format("label required to post review on behalf of \"%s\"", in.onBehalfOf));
}
- ChangeControl target = caller.forUser(
- accounts.parseOnBehalfOf(caller.getUser(), in.onBehalfOf));
+ ChangeControl target =
+ caller.forUser(accounts.parseOnBehalfOf(caller.getUser(), in.onBehalfOf));
if (!target.getRefControl().isVisible()) {
- throw new UnprocessableEntityException(String.format(
- "on_behalf_of account %s cannot see destination ref",
- target.getUser().getAccountId()));
+ throw new UnprocessableEntityException(
+ String.format(
+ "on_behalf_of account %s cannot see destination ref",
+ target.getUser().getAccountId()));
}
return new RevisionResource(changes.parse(target), rev.getPatchSet());
}
- private void checkLabels(RevisionResource revision, boolean strict,
- Map<String, Short> labels) throws BadRequestException, AuthException {
+ private void checkLabels(RevisionResource revision, boolean strict, Map<String, Short> labels)
+ throws BadRequestException, AuthException {
ChangeControl ctl = revision.getControl();
Iterator<Map.Entry<String, Short>> itr = labels.entrySet().iterator();
while (itr.hasNext()) {
Map.Entry<String, Short> ent = itr.next();
- LabelType lt = revision.getControl().getLabelTypes()
- .byLabel(ent.getKey());
+ LabelType lt = revision.getControl().getLabelTypes().byLabel(ent.getKey());
if (lt == null) {
if (strict) {
- throw new BadRequestException(String.format(
- "label \"%s\" is not a configured label", ent.getKey()));
+ throw new BadRequestException(
+ String.format("label \"%s\" is not a configured label", ent.getKey()));
}
itr.remove();
continue;
@@ -399,9 +395,8 @@
if (lt.getValue(ent.getValue()) == null) {
if (strict) {
- throw new BadRequestException(String.format(
- "label \"%s\": %d is not a valid value",
- ent.getKey(), ent.getValue()));
+ throw new BadRequestException(
+ String.format("label \"%s\": %d is not a valid value", ent.getKey(), ent.getValue()));
}
itr.remove();
continue;
@@ -411,9 +406,9 @@
PermissionRange range = ctl.getRange(Permission.forLabel(name));
if (range == null || !range.contains(ent.getValue())) {
if (strict) {
- throw new AuthException(String.format(
- "Applying label \"%s\": %d is restricted",
- ent.getKey(), ent.getValue()));
+ throw new AuthException(
+ String.format(
+ "Applying label \"%s\": %d is restricted", ent.getKey(), ent.getValue()));
} else if (range == null || range.isEmpty()) {
ent.setValue((short) 0);
} else {
@@ -423,15 +418,14 @@
}
}
- private <T extends CommentInput> void checkComments(RevisionResource revision,
- Map<String, List<T>> commentsPerPath)
+ private <T extends CommentInput> void checkComments(
+ RevisionResource revision, Map<String, List<T>> commentsPerPath)
throws BadRequestException, OrmException {
cleanUpComments(commentsPerPath);
ensureCommentsAreAddable(revision, commentsPerPath);
}
- private <T extends CommentInput> void cleanUpComments(
- Map<String, List<T>> commentsPerPath) {
+ private <T extends CommentInput> void cleanUpComments(Map<String, List<T>> commentsPerPath) {
Iterator<List<T>> mapValueIterator = commentsPerPath.values().iterator();
while (mapValueIterator.hasNext()) {
List<T> comments = mapValueIterator.next();
@@ -471,8 +465,7 @@
for (Map.Entry<String, List<T>> entry : commentsPerPath.entrySet()) {
String path = entry.getKey();
PatchSet.Id patchSetId = revision.getChange().currentPatchSetId();
- ensurePathRefersToAvailableOrMagicFile(path, revisionFilePaths,
- patchSetId);
+ ensurePathRefersToAvailableOrMagicFile(path, revisionFilePaths, patchSetId);
List<T> comments = entry.getValue();
for (T comment : comments) {
@@ -482,42 +475,37 @@
}
}
- private Set<String> getAffectedFilePaths(RevisionResource revision)
- throws OrmException {
- ChangeData changeData = changeDataFactory.create(db.get(),
- revision.getControl());
+ private Set<String> getAffectedFilePaths(RevisionResource revision) throws OrmException {
+ ChangeData changeData = changeDataFactory.create(db.get(), revision.getControl());
return new HashSet<>(changeData.filePaths(revision.getPatchSet()));
}
- private void ensurePathRefersToAvailableOrMagicFile(String path,
- Set<String> availableFilePaths, PatchSet.Id patchSetId)
+ private void ensurePathRefersToAvailableOrMagicFile(
+ String path, Set<String> availableFilePaths, PatchSet.Id patchSetId)
throws BadRequestException {
if (!availableFilePaths.contains(path) && !Patch.isMagic(path)) {
- throw new BadRequestException(String.format(
- "file %s not found in revision %s", path, patchSetId));
+ throw new BadRequestException(
+ String.format("file %s not found in revision %s", path, patchSetId));
}
}
- private void ensureLineIsNonNegative(Integer line, String path)
- throws BadRequestException {
+ private void ensureLineIsNonNegative(Integer line, String path) throws BadRequestException {
if (line != null && line < 0) {
- throw new BadRequestException(String.format(
- "negative line number %d not allowed on %s", line, path));
+ throw new BadRequestException(
+ String.format("negative line number %d not allowed on %s", line, path));
}
}
private <T extends CommentInput> void ensureCommentNotOnMagicFilesOfAutoMerge(
String path, T comment) throws BadRequestException {
- if (Patch.isMagic(path) && comment.side == Side.PARENT
- && comment.parent == null) {
- throw new BadRequestException(
- String.format("cannot comment on %s on auto-merge", path));
+ if (Patch.isMagic(path) && comment.side == Side.PARENT && comment.parent == null) {
+ throw new BadRequestException(String.format("cannot comment on %s on auto-merge", path));
}
}
- private void checkRobotComments(RevisionResource revision,
- Map<String, List<RobotCommentInput>> in)
- throws BadRequestException, OrmException {
+ private void checkRobotComments(
+ RevisionResource revision, Map<String, List<RobotCommentInput>> in)
+ throws BadRequestException, OrmException {
for (Map.Entry<String, List<RobotCommentInput>> e : in.entrySet()) {
String commentPath = e.getKey();
for (RobotCommentInput c : e.getValue()) {
@@ -529,130 +517,146 @@
checkComments(revision, in);
}
- private void ensureRobotIdIsSet(String robotId, String commentPath)
- throws BadRequestException {
+ private void ensureRobotIdIsSet(String robotId, String commentPath) throws BadRequestException {
if (robotId == null) {
- throw new BadRequestException(String
- .format("robotId is missing for robot comment on %s", commentPath));
+ throw new BadRequestException(
+ String.format("robotId is missing for robot comment on %s", commentPath));
}
}
private void ensureRobotRunIdIsSet(String robotRunId, String commentPath)
throws BadRequestException {
if (robotRunId == null) {
- throw new BadRequestException(String
- .format("robotRunId is missing for robot comment on %s",
- commentPath));
+ throw new BadRequestException(
+ String.format("robotRunId is missing for robot comment on %s", commentPath));
}
}
private void ensureFixSuggestionsAreAddable(
- List<FixSuggestionInfo> fixSuggestionInfos, String commentPath)
- throws BadRequestException {
+ List<FixSuggestionInfo> fixSuggestionInfos, String commentPath) throws BadRequestException {
if (fixSuggestionInfos == null) {
return;
}
for (FixSuggestionInfo fixSuggestionInfo : fixSuggestionInfos) {
ensureDescriptionIsSet(commentPath, fixSuggestionInfo.description);
- ensureFixReplacementsAreAddable(commentPath,
- fixSuggestionInfo.replacements);
+ ensureFixReplacementsAreAddable(commentPath, fixSuggestionInfo.replacements);
}
}
private void ensureDescriptionIsSet(String commentPath, String description)
throws BadRequestException {
if (description == null) {
- throw new BadRequestException(String.format("A description is required "
- + "for the suggested fix of the robot comment on %s", commentPath));
+ throw new BadRequestException(
+ String.format(
+ "A description is required " + "for the suggested fix of the robot comment on %s",
+ commentPath));
}
}
- private void ensureFixReplacementsAreAddable(String commentPath,
- List<FixReplacementInfo> fixReplacementInfos) throws BadRequestException {
+ private void ensureFixReplacementsAreAddable(
+ String commentPath, List<FixReplacementInfo> fixReplacementInfos) throws BadRequestException {
ensureReplacementsArePresent(commentPath, fixReplacementInfos);
for (FixReplacementInfo fixReplacementInfo : fixReplacementInfos) {
ensureReplacementPathIsSet(commentPath, fixReplacementInfo.path);
- ensureReplacementPathRefersToFileOfComment(commentPath,
- fixReplacementInfo.path);
+ ensureReplacementPathRefersToFileOfComment(commentPath, fixReplacementInfo.path);
ensureRangeIsSet(commentPath, fixReplacementInfo.range);
ensureRangeIsValid(commentPath, fixReplacementInfo.range);
ensureReplacementStringIsSet(commentPath, fixReplacementInfo.replacement);
}
}
- private void ensureReplacementsArePresent(String commentPath,
- List<FixReplacementInfo> fixReplacementInfos) throws BadRequestException {
+ private void ensureReplacementsArePresent(
+ String commentPath, List<FixReplacementInfo> fixReplacementInfos) throws BadRequestException {
if (fixReplacementInfos == null || fixReplacementInfos.isEmpty()) {
- throw new BadRequestException(String.format("At least one replacement is "
- + "required for the suggested fix of the robot comment on %s",
- commentPath));
+ throw new BadRequestException(
+ String.format(
+ "At least one replacement is "
+ + "required for the suggested fix of the robot comment on %s",
+ commentPath));
}
}
- private void ensureReplacementPathIsSet(String commentPath,
- String replacementPath) throws BadRequestException {
+ private void ensureReplacementPathIsSet(String commentPath, String replacementPath)
+ throws BadRequestException {
if (replacementPath == null) {
- throw new BadRequestException(String.format("A file path must be given "
- + "for the replacement of the robot comment on %s", commentPath));
+ throw new BadRequestException(
+ String.format(
+ "A file path must be given " + "for the replacement of the robot comment on %s",
+ commentPath));
}
}
- private void ensureReplacementPathRefersToFileOfComment(String commentPath,
- String replacementPath) throws BadRequestException {
+ private void ensureReplacementPathRefersToFileOfComment(
+ String commentPath, String replacementPath) throws BadRequestException {
if (!Objects.equals(commentPath, replacementPath)) {
- throw new BadRequestException(String.format("Replacements may only be "
- + "specified for the file %s on which the robot comment was added",
- commentPath));
+ throw new BadRequestException(
+ String.format(
+ "Replacements may only be "
+ + "specified for the file %s on which the robot comment was added",
+ commentPath));
}
}
- private void ensureRangeIsSet(String commentPath,
- com.google.gerrit.extensions.client.Comment.Range range)
+ private void ensureRangeIsSet(
+ String commentPath, com.google.gerrit.extensions.client.Comment.Range range)
throws BadRequestException {
if (range == null) {
- throw new BadRequestException(String.format("A range must be given "
- + "for the replacement of the robot comment on %s", commentPath));
+ throw new BadRequestException(
+ String.format(
+ "A range must be given " + "for the replacement of the robot comment on %s",
+ commentPath));
}
}
- private void ensureRangeIsValid(String commentPath,
- com.google.gerrit.extensions.client.Comment.Range range)
+ private void ensureRangeIsValid(
+ String commentPath, com.google.gerrit.extensions.client.Comment.Range range)
throws BadRequestException {
if (range == null) {
return;
}
if (!range.isValid()) {
- throw new BadRequestException(String.format("Range (%s:%s - %s:%s) is not"
- + " valid for the replacement of the robot comment on %s",
- range.startLine, range.startCharacter, range.endLine,
- range.endCharacter, commentPath));
+ throw new BadRequestException(
+ String.format(
+ "Range (%s:%s - %s:%s) is not"
+ + " valid for the replacement of the robot comment on %s",
+ range.startLine,
+ range.startCharacter,
+ range.endLine,
+ range.endCharacter,
+ commentPath));
}
}
- private void ensureReplacementStringIsSet(String commentPath,
- String replacement) throws BadRequestException {
+ private void ensureReplacementStringIsSet(String commentPath, String replacement)
+ throws BadRequestException {
if (replacement == null) {
- throw new BadRequestException(String.format("A content for replacement "
- + "must be indicated for the replacement of the robot comment on %s",
- commentPath));
+ throw new BadRequestException(
+ String.format(
+ "A content for replacement "
+ + "must be indicated for the replacement of the robot comment on %s",
+ commentPath));
}
}
- /**
- * Used to compare Comments with CommentInput comments.
- */
+ /** Used to compare Comments with CommentInput comments. */
@AutoValue
abstract static class CommentSetEntry {
- private static CommentSetEntry create(String filename, int patchSetId,
- Integer line, Side side, HashCode message, Comment.Range range) {
- return new AutoValue_PostReview_CommentSetEntry(filename, patchSetId,
- line, side, message, range);
+ private static CommentSetEntry create(
+ String filename,
+ int patchSetId,
+ Integer line,
+ Side side,
+ HashCode message,
+ Comment.Range range) {
+ return new AutoValue_PostReview_CommentSetEntry(
+ filename, patchSetId, line, side, message, range);
}
public static CommentSetEntry create(Comment comment) {
- return create(comment.key.filename,
+ return create(
+ comment.key.filename,
comment.key.patchSetId,
comment.lineNbr,
Side.fromShort(comment.side),
@@ -661,11 +665,18 @@
}
abstract String filename();
+
abstract int patchSetId();
- @Nullable abstract Integer line();
+
+ @Nullable
+ abstract Integer line();
+
abstract Side side();
+
abstract HashCode message();
- @Nullable abstract Comment.Range range();
+
+ @Nullable
+ abstract Comment.Range range();
}
private class Op extends BatchUpdate.Op {
@@ -683,7 +694,9 @@
private Map<String, Short> approvals = new HashMap<>();
private Map<String, Short> oldApprovals = new HashMap<>();
- private Op(PatchSet.Id psId, ReviewInput in,
+ private Op(
+ PatchSet.Id psId,
+ ReviewInput in,
ListMultimap<RecipientType, Account.Id> accountsToNotify,
List<PostReviewers.Addition> reviewerResults) {
this.psId = psId;
@@ -694,8 +707,7 @@
@Override
public boolean updateChange(ChangeContext ctx)
- throws OrmException, ResourceConflictException,
- UnprocessableEntityException {
+ throws OrmException, ResourceConflictException, UnprocessableEntityException {
user = ctx.getIdentifiedUser();
notes = ctx.getNotes();
ps = psUtil.get(ctx.getDb(), ctx.getNotes(), psId);
@@ -712,22 +724,28 @@
if (message == null) {
return;
}
- if (in.notify.compareTo(NotifyHandling.NONE) > 0
- || !accountsToNotify.isEmpty()) {
- email.create(
- in.notify,
- accountsToNotify,
- notes,
- ps,
- user,
- message,
- comments,
- in.message,
- labelDelta).sendAsync();
+ if (in.notify.compareTo(NotifyHandling.NONE) > 0 || !accountsToNotify.isEmpty()) {
+ email
+ .create(
+ in.notify,
+ accountsToNotify,
+ notes,
+ ps,
+ user,
+ message,
+ comments,
+ in.message,
+ labelDelta)
+ .sendAsync();
}
commentAdded.fire(
- notes.getChange(), ps, user.getAccount(), message.getMessage(),
- approvals, oldApprovals, ctx.getWhen());
+ notes.getChange(),
+ ps,
+ user.getAccount(),
+ message.getMessage(),
+ approvals,
+ oldApprovals,
+ ctx.getWhen());
}
private boolean insertComments(ChangeContext ctx)
@@ -749,9 +767,8 @@
List<Comment> toDel = new ArrayList<>();
List<Comment> toPublish = new ArrayList<>();
- Set<CommentSetEntry> existingIds = in.omitDuplicateComments
- ? readExistingComments(ctx)
- : Collections.emptySet();
+ Set<CommentSetEntry> existingIds =
+ in.omitDuplicateComments ? readExistingComments(ctx) : Collections.emptySet();
for (Map.Entry<String, List<CommentInput>> ent : map.entrySet()) {
String path = ent.getKey();
@@ -759,8 +776,7 @@
String parent = Url.decode(c.inReplyTo);
Comment e = drafts.remove(Url.decode(c.id));
if (e == null) {
- e = commentsUtil.newComment(ctx, path, psId, c.side(), c.message,
- c.unresolved, parent);
+ e = commentsUtil.newComment(ctx, path, psId, c.side(), c.message, c.unresolved, parent);
} else {
e.writtenOn = ctx.getWhen();
e.side = c.side();
@@ -812,16 +828,13 @@
return !newRobotComments.isEmpty();
}
- private List<RobotComment> getNewRobotComments(ChangeContext ctx)
- throws OrmException {
+ private List<RobotComment> getNewRobotComments(ChangeContext ctx) throws OrmException {
List<RobotComment> toAdd = new ArrayList<>(in.robotComments.size());
- Set<CommentSetEntry> existingIds = in.omitDuplicateComments
- ? readExistingRobotComments(ctx)
- : Collections.emptySet();
+ Set<CommentSetEntry> existingIds =
+ in.omitDuplicateComments ? readExistingRobotComments(ctx) : Collections.emptySet();
- for (Map.Entry<String, List<RobotCommentInput>> ent :
- in.robotComments.entrySet()) {
+ for (Map.Entry<String, List<RobotCommentInput>> ent : in.robotComments.entrySet()) {
String path = ent.getKey();
for (RobotCommentInput c : ent.getValue()) {
RobotComment e = createRobotCommentFromInput(ctx, path, c);
@@ -834,20 +847,24 @@
return toAdd;
}
- private RobotComment createRobotCommentFromInput(ChangeContext ctx,
- String path, RobotCommentInput robotCommentInput) throws OrmException {
- RobotComment robotComment = commentsUtil.newRobotComment(
- ctx, path, psId, robotCommentInput.side(), robotCommentInput.message,
- robotCommentInput.robotId, robotCommentInput.robotRunId);
+ private RobotComment createRobotCommentFromInput(
+ ChangeContext ctx, String path, RobotCommentInput robotCommentInput) throws OrmException {
+ RobotComment robotComment =
+ commentsUtil.newRobotComment(
+ ctx,
+ path,
+ psId,
+ robotCommentInput.side(),
+ robotCommentInput.message,
+ robotCommentInput.robotId,
+ robotCommentInput.robotRunId);
robotComment.parentUuid = Url.decode(robotCommentInput.inReplyTo);
robotComment.url = robotCommentInput.url;
robotComment.properties = robotCommentInput.properties;
- robotComment.setLineNbrAndRange(robotCommentInput.line,
- robotCommentInput.range);
+ robotComment.setLineNbrAndRange(robotCommentInput.line, robotCommentInput.range);
robotComment.tag = in.tag;
setCommentRevId(robotComment, patchListCache, ctx.getChange(), ps);
- robotComment.fixSuggestions =
- createFixSuggestionsFromInput(robotCommentInput.fixSuggestions);
+ robotComment.fixSuggestions = createFixSuggestionsFromInput(robotCommentInput.fixSuggestions);
return robotComment;
}
@@ -857,72 +874,65 @@
return Collections.emptyList();
}
- List<FixSuggestion> fixSuggestions =
- new ArrayList<>(fixSuggestionInfos.size());
+ List<FixSuggestion> fixSuggestions = new ArrayList<>(fixSuggestionInfos.size());
for (FixSuggestionInfo fixSuggestionInfo : fixSuggestionInfos) {
fixSuggestions.add(createFixSuggestionFromInput(fixSuggestionInfo));
}
return fixSuggestions;
}
- private FixSuggestion createFixSuggestionFromInput(
- FixSuggestionInfo fixSuggestionInfo) {
- List<FixReplacement> fixReplacements =
- toFixReplacements(fixSuggestionInfo.replacements);
+ private FixSuggestion createFixSuggestionFromInput(FixSuggestionInfo fixSuggestionInfo) {
+ List<FixReplacement> fixReplacements = toFixReplacements(fixSuggestionInfo.replacements);
String fixId = ChangeUtil.messageUuid();
- return new FixSuggestion(fixId, fixSuggestionInfo.description,
- fixReplacements);
+ return new FixSuggestion(fixId, fixSuggestionInfo.description, fixReplacements);
}
- private List<FixReplacement> toFixReplacements(
- List<FixReplacementInfo> fixReplacementInfos) {
- return fixReplacementInfos.stream()
- .map(this::toFixReplacement)
- .collect(Collectors.toList());
+ private List<FixReplacement> toFixReplacements(List<FixReplacementInfo> fixReplacementInfos) {
+ return fixReplacementInfos.stream().map(this::toFixReplacement).collect(Collectors.toList());
}
- private FixReplacement toFixReplacement(
- FixReplacementInfo fixReplacementInfo) {
+ private FixReplacement toFixReplacement(FixReplacementInfo fixReplacementInfo) {
Comment.Range range = new Comment.Range(fixReplacementInfo.range);
- return new FixReplacement(fixReplacementInfo.path, range,
- fixReplacementInfo.replacement);
+ return new FixReplacement(fixReplacementInfo.path, range, fixReplacementInfo.replacement);
}
- private Set<CommentSetEntry> readExistingComments(ChangeContext ctx)
- throws OrmException {
- return commentsUtil.publishedByChange(ctx.getDb(), ctx.getNotes())
- .stream().map(CommentSetEntry::create).collect(toSet());
+ private Set<CommentSetEntry> readExistingComments(ChangeContext ctx) throws OrmException {
+ return commentsUtil
+ .publishedByChange(ctx.getDb(), ctx.getNotes())
+ .stream()
+ .map(CommentSetEntry::create)
+ .collect(toSet());
}
- private Set<CommentSetEntry> readExistingRobotComments(ChangeContext ctx)
- throws OrmException {
- return commentsUtil.robotCommentsByChange(ctx.getNotes())
- .stream().map(CommentSetEntry::create).collect(toSet());
+ private Set<CommentSetEntry> readExistingRobotComments(ChangeContext ctx) throws OrmException {
+ return commentsUtil
+ .robotCommentsByChange(ctx.getNotes())
+ .stream()
+ .map(CommentSetEntry::create)
+ .collect(toSet());
}
- private Map<String, Comment> changeDrafts(ChangeContext ctx)
- throws OrmException {
+ private Map<String, Comment> changeDrafts(ChangeContext ctx) throws OrmException {
Map<String, Comment> drafts = new HashMap<>();
- for (Comment c : commentsUtil.draftByChangeAuthor(
- ctx.getDb(), ctx.getNotes(), user.getAccountId())) {
+ for (Comment c :
+ commentsUtil.draftByChangeAuthor(ctx.getDb(), ctx.getNotes(), user.getAccountId())) {
c.tag = in.tag;
drafts.put(c.key.uuid, c);
}
return drafts;
}
- private Map<String, Comment> patchSetDrafts(ChangeContext ctx)
- throws OrmException {
+ private Map<String, Comment> patchSetDrafts(ChangeContext ctx) throws OrmException {
Map<String, Comment> drafts = new HashMap<>();
- for (Comment c : commentsUtil.draftByPatchSetAuthor(ctx.getDb(),
- psId, user.getAccountId(), ctx.getNotes())) {
+ for (Comment c :
+ commentsUtil.draftByPatchSetAuthor(
+ ctx.getDb(), psId, user.getAccountId(), ctx.getNotes())) {
drafts.put(c.key.uuid, c);
}
return drafts;
}
- private Map<String, Short> approvalsByKey(
- Collection<PatchSetApproval> patchsetApprovals) {
+ private Map<String, Short> approvalsByKey(Collection<PatchSetApproval> patchsetApprovals) {
Map<String, Short> labels = new HashMap<>();
for (PatchSetApproval psa : patchsetApprovals) {
labels.put(psa.getLabel(), psa.getValue());
@@ -930,8 +940,7 @@
return labels;
}
- private Comment publishComment(ChangeContext ctx,
- Comment c, PatchSet ps) throws OrmException {
+ private Comment publishComment(ChangeContext ctx, Comment c, PatchSet ps) throws OrmException {
c.writtenOn = ctx.getWhen();
c.tag = in.tag;
// Draft may have been created by a different real user; copy the current
@@ -942,9 +951,8 @@
return c;
}
- private void publishAllRevisions(ChangeContext ctx,
- Map<String, Comment> drafts, List<Comment> ups)
- throws OrmException {
+ private void publishAllRevisions(
+ ChangeContext ctx, Map<String, Comment> drafts, List<Comment> ups) throws OrmException {
boolean needOtherPatchSets = false;
for (Comment c : drafts.values()) {
if (c.key.patchSetId != psId.get()) {
@@ -952,17 +960,19 @@
break;
}
}
- Map<PatchSet.Id, PatchSet> patchSets = needOtherPatchSets
- ? psUtil.byChangeAsMap(ctx.getDb(), ctx.getNotes())
- : ImmutableMap.of(psId, ps);
+ Map<PatchSet.Id, PatchSet> patchSets =
+ needOtherPatchSets
+ ? psUtil.byChangeAsMap(ctx.getDb(), ctx.getNotes())
+ : ImmutableMap.of(psId, ps);
for (Comment e : drafts.values()) {
- ups.add(publishComment(ctx, e, patchSets
- .get(new PatchSet.Id(ctx.getChange().getId(), e.key.patchSetId))));
+ ups.add(
+ publishComment(
+ ctx, e, patchSets.get(new PatchSet.Id(ctx.getChange().getId(), e.key.patchSetId))));
}
}
- private Map<String, Short> getAllApprovals(LabelTypes labelTypes,
- Map<String, Short> current, Map<String, Short> input) {
+ private Map<String, Short> getAllApprovals(
+ LabelTypes labelTypes, Map<String, Short> current, Map<String, Short> input) {
Map<String, Short> allApprovals = new HashMap<>();
for (LabelType lt : labelTypes.getLabelTypes()) {
allApprovals.put(lt.getName(), (short) 0);
@@ -1014,10 +1024,9 @@
return false;
}
- private boolean updateLabels(ChangeContext ctx)
- throws OrmException, ResourceConflictException {
- Map<String, Short> inLabels = MoreObjects.firstNonNull(in.labels,
- Collections.<String, Short> emptyMap());
+ private boolean updateLabels(ChangeContext ctx) throws OrmException, ResourceConflictException {
+ Map<String, Short> inLabels =
+ MoreObjects.firstNonNull(in.labels, Collections.<String, Short>emptyMap());
// If no labels were modified and change is closed, abort early.
// This avoids trying to record a modified label caused by a user
@@ -1030,10 +1039,10 @@
List<PatchSetApproval> ups = new ArrayList<>();
Map<String, PatchSetApproval> current = scanLabels(ctx, del);
LabelTypes labelTypes = ctx.getControl().getLabelTypes();
- Map<String, Short> allApprovals = getAllApprovals(labelTypes,
- approvalsByKey(current.values()), inLabels);
- Map<String, Short> previous = getPreviousApprovals(allApprovals,
- approvalsByKey(current.values()));
+ Map<String, Short> allApprovals =
+ getAllApprovals(labelTypes, approvalsByKey(current.values()), inLabels);
+ Map<String, Short> previous =
+ getPreviousApprovals(allApprovals, approvalsByKey(current.values()));
ChangeUpdate update = ctx.getUpdate(psId);
for (Map.Entry<String, Short> ent : allApprovals.entrySet()) {
@@ -1069,8 +1078,7 @@
oldApprovals.put(normName, null);
approvals.put(normName, c.getValue());
} else if (c == null) {
- c = ApprovalsUtil.newApproval(
- psId, user, lt.getLabelId(), ent.getValue(), ctx.getWhen());
+ c = ApprovalsUtil.newApproval(psId, user, lt.getLabelId(), ent.getValue(), ctx.getWhen());
c.setTag(in.tag);
c.setGranted(ctx.getWhen());
ups.add(c);
@@ -1086,8 +1094,7 @@
// Return early if user is not a reviewer and not posting any labels.
// This allows us to preserve their CC status.
- if (current.isEmpty() && del.isEmpty() && ups.isEmpty() &&
- !isReviewer(ctx)) {
+ if (current.isEmpty() && del.isEmpty() && ups.isEmpty() && !isReviewer(ctx)) {
return false;
}
@@ -1097,9 +1104,12 @@
return !del.isEmpty() || !ups.isEmpty();
}
- private void validatePostSubmitLabels(ChangeContext ctx,
- LabelTypes labelTypes, Map<String, Short> previous,
- List<PatchSetApproval> ups, List<PatchSetApproval> del)
+ private void validatePostSubmitLabels(
+ ChangeContext ctx,
+ LabelTypes labelTypes,
+ Map<String, Short> previous,
+ List<PatchSetApproval> ups,
+ List<PatchSetApproval> del)
throws ResourceConflictException {
if (ctx.getChange().getStatus().isOpen()) {
return; // Not closed, nothing to validate.
@@ -1114,8 +1124,7 @@
// make it possible to take a merged change and make it no longer
// submittable.
List<PatchSetApproval> reduced = new ArrayList<>(ups.size() + del.size());
- List<String> disallowed =
- new ArrayList<>(labelTypes.getLabelTypes().size());
+ List<String> disallowed = new ArrayList<>(labelTypes.getLabelTypes().size());
for (PatchSetApproval psa : del) {
LabelType lt = checkNotNull(labelTypes.byLabel(psa.getLabel()));
@@ -1152,29 +1161,32 @@
if (!disallowed.isEmpty()) {
throw new ResourceConflictException(
"Voting on labels disallowed after submit: "
- + disallowed.stream().distinct().sorted()
- .collect(joining(", ")));
+ + disallowed.stream().distinct().sorted().collect(joining(", ")));
}
if (!reduced.isEmpty()) {
throw new ResourceConflictException(
"Cannot reduce vote on labels for closed change: "
- + reduced.stream().map(p -> p.getLabel()).distinct().sorted()
+ + reduced
+ .stream()
+ .map(p -> p.getLabel())
+ .distinct()
+ .sorted()
.collect(joining(", ")));
}
}
- private void forceCallerAsReviewer(ChangeContext ctx,
- Map<String, PatchSetApproval> current, List<PatchSetApproval> ups,
+ private void forceCallerAsReviewer(
+ ChangeContext ctx,
+ Map<String, PatchSetApproval> current,
+ List<PatchSetApproval> ups,
List<PatchSetApproval> del) {
if (current.isEmpty() && ups.isEmpty()) {
// TODO Find another way to link reviewers to changes.
if (del.isEmpty()) {
// If no existing label is being set to 0, hack in the caller
// as a reviewer by picking the first server-wide LabelType.
- LabelId labelId = ctx.getControl().getLabelTypes().getLabelTypes()
- .get(0).getLabelId();
- PatchSetApproval c = ApprovalsUtil.newApproval(
- psId, user, labelId, 0, ctx.getWhen());
+ LabelId labelId = ctx.getControl().getLabelTypes().getLabelTypes().get(0).getLabelId();
+ PatchSetApproval c = ApprovalsUtil.newApproval(psId, user, labelId, 0, ctx.getWhen());
c.setTag(in.tag);
c.setGranted(ctx.getWhen());
ups.add(c);
@@ -1188,17 +1200,16 @@
ups.add(c);
}
}
- ctx.getUpdate(ctx.getChange().currentPatchSetId())
- .putReviewer(user.getAccountId(), REVIEWER);
+ ctx.getUpdate(ctx.getChange().currentPatchSetId()).putReviewer(user.getAccountId(), REVIEWER);
}
- private Map<String, PatchSetApproval> scanLabels(ChangeContext ctx,
- List<PatchSetApproval> del) throws OrmException {
+ private Map<String, PatchSetApproval> scanLabels(ChangeContext ctx, List<PatchSetApproval> del)
+ throws OrmException {
LabelTypes labelTypes = ctx.getControl().getLabelTypes();
Map<String, PatchSetApproval> current = new HashMap<>();
- for (PatchSetApproval a : approvalsUtil.byPatchSetUser(
- ctx.getDb(), ctx.getControl(), psId, user.getAccountId())) {
+ for (PatchSetApproval a :
+ approvalsUtil.byPatchSetUser(ctx.getDb(), ctx.getControl(), psId, user.getAccountId())) {
if (a.isLegacySubmit()) {
continue;
}
@@ -1213,8 +1224,7 @@
return current;
}
- private boolean insertMessage(ChangeContext ctx)
- throws OrmException {
+ private boolean insertMessage(ChangeContext ctx) throws OrmException {
String msg = Strings.nullToEmpty(in.message).trim();
StringBuilder buf = new StringBuilder();
@@ -1233,9 +1243,9 @@
return false;
}
- message = ChangeMessagesUtil.newMessage(
- psId, user, ctx.getWhen(),
- "Patch Set " + psId.get() + ":" + buf, in.tag);
+ message =
+ ChangeMessagesUtil.newMessage(
+ psId, user, ctx.getWhen(), "Patch Set " + psId.get() + ":" + buf, in.tag);
cmUtil.addChangeMessage(ctx.getDb(), ctx.getUpdate(psId), message);
return true;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/PostReviewers.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/PostReviewers.java
index 116f84e..2873bd9 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/PostReviewers.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/PostReviewers.java
@@ -66,11 +66,6 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.lib.Config;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
@@ -79,12 +74,13 @@
import java.util.List;
import java.util.Map;
import java.util.Set;
+import org.eclipse.jgit.lib.Config;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
@Singleton
-public class PostReviewers
- implements RestModifyView<ChangeResource, AddReviewerInput> {
- private static final Logger log =
- LoggerFactory.getLogger(PostReviewers.class);
+public class PostReviewers implements RestModifyView<ChangeResource, AddReviewerInput> {
+ private static final Logger log = LoggerFactory.getLogger(PostReviewers.class);
public static final int DEFAULT_MAX_REVIEWERS_WITHOUT_CHECK = 10;
public static final int DEFAULT_MAX_REVIEWERS = 20;
@@ -109,7 +105,8 @@
private final NotifyUtil notifyUtil;
@Inject
- PostReviewers(AccountsCollection accounts,
+ PostReviewers(
+ AccountsCollection accounts,
ReviewerResource.Factory reviewerFactory,
ApprovalsUtil approvalsUtil,
PatchSetUtil psUtil,
@@ -158,8 +155,9 @@
if (addition.op == null) {
return addition.result;
}
- try (BatchUpdate bu = batchUpdateFactory.create(dbProvider.get(),
- rsrc.getProject(), rsrc.getUser(), TimeUtil.nowTs())) {
+ try (BatchUpdate bu =
+ batchUpdateFactory.create(
+ dbProvider.get(), rsrc.getProject(), rsrc.getUser(), TimeUtil.nowTs())) {
Change.Id id = rsrc.getChange().getId();
bu.addOp(id, addition.op);
bu.execute();
@@ -168,9 +166,9 @@
return addition.result;
}
- public Addition prepareApplication(ChangeResource rsrc,
- AddReviewerInput input, boolean allowGroup)
- throws OrmException, RestApiException, IOException {
+ public Addition prepareApplication(
+ ChangeResource rsrc, AddReviewerInput input, boolean allowGroup)
+ throws OrmException, RestApiException, IOException {
Account.Id accountId;
try {
accountId = accounts.parse(input.reviewer).getAccountId();
@@ -179,60 +177,73 @@
try {
return putGroup(rsrc, input);
} catch (UnprocessableEntityException e2) {
- throw new UnprocessableEntityException(MessageFormat.format(
- ChangeMessages.get().reviewerNotFoundUserOrGroup,
- input.reviewer));
+ throw new UnprocessableEntityException(
+ MessageFormat.format(
+ ChangeMessages.get().reviewerNotFoundUserOrGroup, input.reviewer));
}
}
- throw new UnprocessableEntityException(MessageFormat
- .format(ChangeMessages.get().reviewerNotFoundUser, input.reviewer));
+ throw new UnprocessableEntityException(
+ MessageFormat.format(ChangeMessages.get().reviewerNotFoundUser, input.reviewer));
}
- return putAccount(input.reviewer, reviewerFactory.create(rsrc, accountId),
- input.state(), input.notify,
+ return putAccount(
+ input.reviewer,
+ reviewerFactory.create(rsrc, accountId),
+ input.state(),
+ input.notify,
notifyUtil.resolveAccounts(input.notifyDetails));
}
Addition ccCurrentUser(CurrentUser user, RevisionResource revision) {
return new Addition(
- user.getUserName(), revision.getChangeResource(),
+ user.getUserName(),
+ revision.getChangeResource(),
ImmutableMap.of(user.getAccountId(), revision.getControl()),
- CC, NotifyHandling.NONE, ImmutableListMultimap.of());
+ CC,
+ NotifyHandling.NONE,
+ ImmutableListMultimap.of());
}
- private Addition putAccount(String reviewer, ReviewerResource rsrc,
- ReviewerState state, NotifyHandling notify,
+ private Addition putAccount(
+ String reviewer,
+ ReviewerResource rsrc,
+ ReviewerState state,
+ NotifyHandling notify,
ListMultimap<RecipientType, Account.Id> accountsToNotify)
- throws UnprocessableEntityException {
+ throws UnprocessableEntityException {
Account member = rsrc.getReviewerUser().getAccount();
ChangeControl control = rsrc.getReviewerControl();
if (isValidReviewer(member, control)) {
- return new Addition(reviewer, rsrc.getChangeResource(),
- ImmutableMap.of(member.getId(), control), state, notify,
+ return new Addition(
+ reviewer,
+ rsrc.getChangeResource(),
+ ImmutableMap.of(member.getId(), control),
+ state,
+ notify,
accountsToNotify);
}
if (member.isActive()) {
- throw new UnprocessableEntityException(
- String.format("Change not visible to %s", reviewer));
+ throw new UnprocessableEntityException(String.format("Change not visible to %s", reviewer));
}
- throw new UnprocessableEntityException(
- String.format("Account of %s is inactive.", reviewer));
+ throw new UnprocessableEntityException(String.format("Account of %s is inactive.", reviewer));
}
private Addition putGroup(ChangeResource rsrc, AddReviewerInput input)
throws RestApiException, OrmException, IOException {
- GroupDescription.Basic group =
- groupsCollection.parseInternal(input.reviewer);
+ GroupDescription.Basic group = groupsCollection.parseInternal(input.reviewer);
if (!isLegalReviewerGroup(group.getGroupUUID())) {
- return fail(input.reviewer, MessageFormat.format(ChangeMessages.get().groupIsNotAllowed,
- group.getName()));
+ return fail(
+ input.reviewer,
+ MessageFormat.format(ChangeMessages.get().groupIsNotAllowed, group.getName()));
}
Map<Account.Id, ChangeControl> reviewers = new HashMap<>();
ChangeControl control = rsrc.getControl();
Set<Account> members;
try {
- members = groupMembersFactory.create(control.getUser()).listAccounts(
- group.getGroupUUID(), control.getProject().getNameKey());
+ members =
+ groupMembersFactory
+ .create(control.getUser())
+ .listAccounts(group.getGroupUUID(), control.getProject().getNameKey());
} catch (NoSuchGroupException e) {
throw new UnprocessableEntityException(e.getMessage());
} catch (NoSuchProjectException e) {
@@ -241,22 +252,24 @@
// if maxAllowed is set to 0, it is allowed to add any number of
// reviewers
- int maxAllowed =
- cfg.getInt("addreviewer", "maxAllowed", DEFAULT_MAX_REVIEWERS);
+ int maxAllowed = cfg.getInt("addreviewer", "maxAllowed", DEFAULT_MAX_REVIEWERS);
if (maxAllowed > 0 && members.size() > maxAllowed) {
- return fail(input.reviewer, MessageFormat.format(
- ChangeMessages.get().groupHasTooManyMembers, group.getName()));
+ return fail(
+ input.reviewer,
+ MessageFormat.format(ChangeMessages.get().groupHasTooManyMembers, group.getName()));
}
// if maxWithoutCheck is set to 0, we never ask for confirmation
- int maxWithoutConfirmation = cfg.getInt("addreviewer",
- "maxWithoutConfirmation", DEFAULT_MAX_REVIEWERS_WITHOUT_CHECK);
- if (!input.confirmed() && maxWithoutConfirmation > 0
+ int maxWithoutConfirmation =
+ cfg.getInt("addreviewer", "maxWithoutConfirmation", DEFAULT_MAX_REVIEWERS_WITHOUT_CHECK);
+ if (!input.confirmed()
+ && maxWithoutConfirmation > 0
&& members.size() > maxWithoutConfirmation) {
- return fail(input.reviewer, true,
+ return fail(
+ input.reviewer,
+ true,
MessageFormat.format(
- ChangeMessages.get().groupManyMembersConfirmation,
- group.getName(), members.size()));
+ ChangeMessages.get().groupManyMembersConfirmation, group.getName(), members.size()));
}
for (Account member : members) {
@@ -265,8 +278,13 @@
}
}
- return new Addition(input.reviewer, rsrc, reviewers, input.state(),
- input.notify, notifyUtil.resolveAccounts(input.notifyDetails));
+ return new Addition(
+ input.reviewer,
+ rsrc,
+ reviewers,
+ input.state(),
+ input.notify,
+ notifyUtil.resolveAccounts(input.notifyDetails));
}
private boolean isValidReviewer(Account member, ChangeControl control) {
@@ -300,8 +318,11 @@
this(reviewer, null, null, REVIEWER, null, ImmutableListMultimap.of());
}
- protected Addition(String reviewer, ChangeResource rsrc,
- Map<Account.Id, ChangeControl> reviewers, ReviewerState state,
+ protected Addition(
+ String reviewer,
+ ChangeResource rsrc,
+ Map<Account.Id, ChangeControl> reviewers,
+ ReviewerState state,
NotifyHandling notify,
ListMultimap<RecipientType, Account.Id> accountsToNotify) {
result = new AddReviewerResult(reviewer);
@@ -320,8 +341,7 @@
if (migration.readChanges() && op.state == CC) {
result.ccs = Lists.newArrayListWithCapacity(op.addedCCs.size());
for (Account.Id accountId : op.addedCCs) {
- result.ccs.add(
- json.format(new ReviewerInfo(accountId.get()), reviewers.get(accountId)));
+ result.ccs.add(json.format(new ReviewerInfo(accountId.get()), reviewers.get(accountId)));
}
accountLoaderFactory.create(true).fill(result.ccs);
} else {
@@ -329,9 +349,10 @@
for (PatchSetApproval psa : op.addedReviewers) {
// New reviewers have value 0, don't bother normalizing.
result.reviewers.add(
- json.format(new ReviewerInfo(psa.getAccountId().get()),
- reviewers.get(psa.getAccountId()),
- ImmutableList.of(psa)));
+ json.format(
+ new ReviewerInfo(psa.getAccountId().get()),
+ reviewers.get(psa.getAccountId()),
+ ImmutableList.of(psa)));
}
accountLoaderFactory.create(true).fill(result.reviewers);
}
@@ -349,8 +370,11 @@
private final ChangeResource rsrc;
private PatchSet patchSet;
- Op(ChangeResource rsrc, Map<Account.Id, ChangeControl> reviewers,
- ReviewerState state, NotifyHandling notify,
+ Op(
+ ChangeResource rsrc,
+ Map<Account.Id, ChangeControl> reviewers,
+ ReviewerState state,
+ NotifyHandling notify,
ListMultimap<RecipientType, Account.Id> accountsToNotify) {
this.rsrc = rsrc;
this.reviewers = reviewers;
@@ -363,17 +387,23 @@
public boolean updateChange(ChangeContext ctx)
throws RestApiException, OrmException, IOException {
if (migration.readChanges() && state == CC) {
- addedCCs = approvalsUtil.addCcs(ctx.getNotes(),
- ctx.getUpdate(ctx.getChange().currentPatchSetId()),
- reviewers.keySet());
+ addedCCs =
+ approvalsUtil.addCcs(
+ ctx.getNotes(),
+ ctx.getUpdate(ctx.getChange().currentPatchSetId()),
+ reviewers.keySet());
if (addedCCs.isEmpty()) {
return false;
}
} else {
- addedReviewers = approvalsUtil.addReviewers(ctx.getDb(), ctx.getNotes(),
- ctx.getUpdate(ctx.getChange().currentPatchSetId()),
- rsrc.getControl().getLabelTypes(), rsrc.getChange(),
- reviewers.keySet());
+ addedReviewers =
+ approvalsUtil.addReviewers(
+ ctx.getDb(),
+ ctx.getNotes(),
+ ctx.getUpdate(ctx.getChange().currentPatchSetId()),
+ rsrc.getControl().getLabelTypes(),
+ rsrc.getChange(),
+ reviewers.keySet());
if (addedReviewers.isEmpty()) {
return false;
}
@@ -392,21 +422,28 @@
if (addedCCs == null) {
addedCCs = new ArrayList<>();
}
- emailReviewers(rsrc.getChange(),
- Lists.transform(addedReviewers, r -> r.getAccountId()), addedCCs,
- notify, accountsToNotify);
+ emailReviewers(
+ rsrc.getChange(),
+ Lists.transform(addedReviewers, r -> r.getAccountId()),
+ addedCCs,
+ notify,
+ accountsToNotify);
if (!addedReviewers.isEmpty()) {
- List<Account> reviewers = Lists.transform(addedReviewers,
- psa -> accountCache.get(psa.getAccountId()).getAccount());
- reviewerAdded.fire(rsrc.getChange(), patchSet, reviewers,
- ctx.getAccount(), ctx.getWhen());
+ List<Account> reviewers =
+ Lists.transform(
+ addedReviewers, psa -> accountCache.get(psa.getAccountId()).getAccount());
+ reviewerAdded.fire(
+ rsrc.getChange(), patchSet, reviewers, ctx.getAccount(), ctx.getWhen());
}
}
}
}
- public void emailReviewers(Change change, Collection<Account.Id> added,
- Collection<Account.Id> copied, NotifyHandling notify,
+ public void emailReviewers(
+ Change change,
+ Collection<Account.Id> added,
+ Collection<Account.Id> copied,
+ NotifyHandling notify,
ListMultimap<RecipientType, Account.Id> accountsToNotify) {
if (added.isEmpty() && copied.isEmpty()) {
return;
@@ -433,8 +470,7 @@
}
try {
- AddReviewerSender cm = addReviewerSenderFactory
- .create(change.getProject(), change.getId());
+ AddReviewerSender cm = addReviewerSenderFactory.create(change.getProject(), change.getId());
if (notify != null) {
cm.setNotify(notify);
}
@@ -444,8 +480,7 @@
cm.addExtraCC(toCopy);
cm.send();
} catch (Exception err) {
- log.error("Cannot send email to new reviewers of change "
- + change.getId(), err);
+ log.error("Cannot send email to new reviewers of change " + change.getId(), err);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/PreviewSubmit.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/PreviewSubmit.java
index b783447..8b71eca 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/PreviewSubmit.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/PreviewSubmit.java
@@ -37,7 +37,10 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.Collection;
+import java.util.Set;
import org.apache.commons.compress.archivers.ArchiveOutputStream;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.lib.NullProgressMonitor;
@@ -46,11 +49,6 @@
import org.eclipse.jgit.transport.ReceiveCommand;
import org.kohsuke.args4j.Option;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.util.Collection;
-import java.util.Set;
-
@Singleton
public class PreviewSubmit implements RestReadView<RevisionResource> {
private static int MAX_DEFAULT_BUNDLE_SIZE = 100 * 1024 * 1024;
@@ -67,15 +65,15 @@
}
@Inject
- PreviewSubmit(Provider<ReviewDb> dbProvider,
+ PreviewSubmit(
+ Provider<ReviewDb> dbProvider,
Provider<MergeOp> mergeOpProvider,
AllowedFormats allowedFormats,
@GerritServerConfig Config cfg) {
this.dbProvider = dbProvider;
this.mergeOpProvider = mergeOpProvider;
this.allowedFormats = allowedFormats;
- this.maxBundleSize = cfg.getInt("download", "maxBundleSize",
- MAX_DEFAULT_BUNDLE_SIZE);
+ this.maxBundleSize = cfg.getInt("download", "maxBundleSize", MAX_DEFAULT_BUNDLE_SIZE);
}
@Override
@@ -105,8 +103,7 @@
try (BinaryResult b = getBundles(rsrc, f)) {
b.disableGzip()
.setContentType(f.getMimeType())
- .setAttachmentName("submit-preview-"
- + change.getChangeId() + "." + format);
+ .setAttachmentName("submit-preview-" + change.getChangeId() + "." + format);
return b;
} catch (OrmException | IOException e) {
throw new RestApiException("Error generating submit preview");
@@ -126,38 +123,39 @@
final MergeOpRepoManager orm = op.getMergeOpRepoManager();
final Set<Project.NameKey> projects = op.getAllProjects();
- bin = new BinaryResult() {
- @Override
- public void writeTo(OutputStream out) throws IOException {
- try (ArchiveOutputStream aos = f.createArchiveOutputStream(out)) {
- for (Project.NameKey p : projects) {
- OpenRepo or = orm.getRepo(p);
- BundleWriter bw = new BundleWriter(or.getRepo());
- bw.setObjectCountCallback(null);
- bw.setPackConfig(null);
- Collection<ReceiveCommand> refs = or.getUpdate().getRefUpdates();
- for (ReceiveCommand r : refs) {
- bw.include(r.getRefName(), r.getNewId());
- ObjectId oldId = r.getOldId();
- if (!oldId.equals(ObjectId.zeroId())) {
- bw.assume(or.getCodeReviewRevWalk().parseCommit(oldId));
- }
- }
- // This naming scheme cannot produce directory/file conflicts
- // as no projects contains ".git/":
- String path = p.get() + ".git";
+ bin =
+ new BinaryResult() {
+ @Override
+ public void writeTo(OutputStream out) throws IOException {
+ try (ArchiveOutputStream aos = f.createArchiveOutputStream(out)) {
+ for (Project.NameKey p : projects) {
+ OpenRepo or = orm.getRepo(p);
+ BundleWriter bw = new BundleWriter(or.getRepo());
+ bw.setObjectCountCallback(null);
+ bw.setPackConfig(null);
+ Collection<ReceiveCommand> refs = or.getUpdate().getRefUpdates();
+ for (ReceiveCommand r : refs) {
+ bw.include(r.getRefName(), r.getNewId());
+ ObjectId oldId = r.getOldId();
+ if (!oldId.equals(ObjectId.zeroId())) {
+ bw.assume(or.getCodeReviewRevWalk().parseCommit(oldId));
+ }
+ }
+ // This naming scheme cannot produce directory/file conflicts
+ // as no projects contains ".git/":
+ String path = p.get() + ".git";
- LimitedByteArrayOutputStream bos =
- new LimitedByteArrayOutputStream(maxBundleSize, 1024);
- bw.writeBundle(NullProgressMonitor.INSTANCE, bos);
- f.putEntry(aos, path, bos.toByteArray());
+ LimitedByteArrayOutputStream bos =
+ new LimitedByteArrayOutputStream(maxBundleSize, 1024);
+ bw.writeBundle(NullProgressMonitor.INSTANCE, bos);
+ f.putEntry(aos, path, bos.toByteArray());
+ }
+ } catch (LimitExceededException e) {
+ throw new NotImplementedException(
+ "The bundle is too big to " + "generate at the server");
+ }
}
- } catch (LimitExceededException e) {
- throw new NotImplementedException("The bundle is too big to "
- + "generate at the server");
- }
- }
- };
+ };
}
return bin;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/PublishChangeEdit.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/PublishChangeEdit.java
index 9f61e65..89079fc 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/PublishChangeEdit.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/PublishChangeEdit.java
@@ -33,14 +33,12 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
import java.io.IOException;
import java.util.Optional;
@Singleton
-public class PublishChangeEdit implements
- ChildCollection<ChangeResource, ChangeEditResource>,
- AcceptsPost<ChangeResource> {
+public class PublishChangeEdit
+ implements ChildCollection<ChangeResource, ChangeEditResource>, AcceptsPost<ChangeResource> {
private final Publish publish;
@@ -71,15 +69,13 @@
}
@Singleton
- public static class Publish
- implements RestModifyView<ChangeResource, PublishChangeEditInput> {
+ public static class Publish implements RestModifyView<ChangeResource, PublishChangeEditInput> {
private final ChangeEditUtil editUtil;
private final NotifyUtil notifyUtil;
@Inject
- Publish(ChangeEditUtil editUtil,
- NotifyUtil notifyUtil) {
+ Publish(ChangeEditUtil editUtil, NotifyUtil notifyUtil) {
this.editUtil = editUtil;
this.notifyUtil = notifyUtil;
}
@@ -87,23 +83,20 @@
@Override
public Response<?> apply(ChangeResource rsrc, PublishChangeEditInput in)
throws IOException, OrmException, RestApiException, UpdateException {
- Capable r =
- rsrc.getControl().getProjectControl().canPushToAtLeastOneRef();
+ Capable r = rsrc.getControl().getProjectControl().canPushToAtLeastOneRef();
if (r != Capable.OK) {
throw new AuthException(r.getMessage());
}
Optional<ChangeEdit> edit = editUtil.byChange(rsrc.getChange());
if (!edit.isPresent()) {
- throw new ResourceConflictException(String.format(
- "no edit exists for change %s",
- rsrc.getChange().getChangeId()));
+ throw new ResourceConflictException(
+ String.format("no edit exists for change %s", rsrc.getChange().getChangeId()));
}
if (in == null) {
in = new PublishChangeEditInput();
}
- editUtil.publish(edit.get(), in.notify,
- notifyUtil.resolveAccounts(in.notifyDetails));
+ editUtil.publish(edit.get(), in.notify, notifyUtil.resolveAccounts(in.notifyDetails));
return Response.none();
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/PublishDraftPatchSet.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/PublishDraftPatchSet.java
index 5a9a1e5..5dbc757 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/PublishDraftPatchSet.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/PublishDraftPatchSet.java
@@ -53,25 +53,21 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
+import java.io.IOException;
+import java.util.Collection;
+import java.util.List;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.revwalk.FooterLine;
import org.eclipse.jgit.revwalk.RevCommit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.util.Collection;
-import java.util.List;
-
@Singleton
-public class PublishDraftPatchSet implements RestModifyView<RevisionResource, Input>,
- UiAction<RevisionResource> {
- private static final Logger log =
- LoggerFactory.getLogger(PublishDraftPatchSet.class);
+public class PublishDraftPatchSet
+ implements RestModifyView<RevisionResource, Input>, UiAction<RevisionResource> {
+ private static final Logger log = LoggerFactory.getLogger(PublishDraftPatchSet.class);
- public static class Input {
- }
+ public static class Input {}
private final AccountResolver accountResolver;
private final ApprovalsUtil approvalsUtil;
@@ -108,14 +104,13 @@
@Override
public Response<?> apply(RevisionResource rsrc, Input input)
throws RestApiException, UpdateException {
- return apply(rsrc.getUser(), rsrc.getChange(), rsrc.getPatchSet().getId(),
- rsrc.getPatchSet());
+ return apply(rsrc.getUser(), rsrc.getChange(), rsrc.getPatchSet().getId(), rsrc.getPatchSet());
}
- private Response<?> apply(CurrentUser u, Change c, PatchSet.Id psId,
- PatchSet ps) throws RestApiException, UpdateException {
- try (BatchUpdate bu = updateFactory.create(
- dbProvider.get(), c.getProject(), u, TimeUtil.nowTs())) {
+ private Response<?> apply(CurrentUser u, Change c, PatchSet.Id psId, PatchSet ps)
+ throws RestApiException, UpdateException {
+ try (BatchUpdate bu =
+ updateFactory.create(dbProvider.get(), c.getProject(), u, TimeUtil.nowTs())) {
bu.addOp(c.getId(), new Op(psId, ps));
bu.execute();
}
@@ -126,18 +121,16 @@
public UiAction.Description getDescription(RevisionResource rsrc) {
try {
return new UiAction.Description()
- .setLabel("Publish")
- .setTitle(String.format("Publish revision %d",
- rsrc.getPatchSet().getPatchSetId()))
- .setVisible(rsrc.getPatchSet().isDraft()
- && rsrc.getControl().canPublish(dbProvider.get()));
+ .setLabel("Publish")
+ .setTitle(String.format("Publish revision %d", rsrc.getPatchSet().getPatchSetId()))
+ .setVisible(
+ rsrc.getPatchSet().isDraft() && rsrc.getControl().canPublish(dbProvider.get()));
} catch (OrmException e) {
throw new IllegalStateException(e);
}
}
- public static class CurrentRevision implements
- RestModifyView<ChangeResource, Input> {
+ public static class CurrentRevision implements RestModifyView<ChangeResource, Input> {
private final PublishDraftPatchSet publish;
@Inject
@@ -148,8 +141,11 @@
@Override
public Response<?> apply(ChangeResource rsrc, Input input)
throws RestApiException, UpdateException {
- return publish.apply(rsrc.getControl().getUser(), rsrc.getChange(),
- rsrc.getChange().currentPatchSetId(), null);
+ return publish.apply(
+ rsrc.getControl().getUser(),
+ rsrc.getChange(),
+ rsrc.getChange().currentPatchSetId(),
+ null);
}
}
@@ -195,36 +191,39 @@
}
}
- private void savePatchSet(ChangeContext ctx)
- throws RestApiException, OrmException {
+ private void savePatchSet(ChangeContext ctx) throws RestApiException, OrmException {
if (!patchSet.isDraft()) {
throw new ResourceConflictException("Patch set is not a draft");
}
psUtil.publish(ctx.getDb(), ctx.getUpdate(psId), patchSet);
}
- private void addReviewers(ChangeContext ctx)
- throws OrmException, IOException {
+ private void addReviewers(ChangeContext ctx) throws OrmException, IOException {
LabelTypes labelTypes = ctx.getControl().getLabelTypes();
- Collection<Account.Id> oldReviewers = approvalsUtil.getReviewers(
- ctx.getDb(), ctx.getNotes()).all();
- RevCommit commit = ctx.getRevWalk().parseCommit(
- ObjectId.fromString(patchSet.getRevision().get()));
+ Collection<Account.Id> oldReviewers =
+ approvalsUtil.getReviewers(ctx.getDb(), ctx.getNotes()).all();
+ RevCommit commit =
+ ctx.getRevWalk().parseCommit(ObjectId.fromString(patchSet.getRevision().get()));
patchSetInfo = patchSetInfoFactory.get(ctx.getRevWalk(), commit, psId);
List<FooterLine> footerLines = commit.getFooterLines();
- recipients = getRecipientsFromFooters(
- ctx.getDb(), accountResolver, patchSet.isDraft(), footerLines);
+ recipients =
+ getRecipientsFromFooters(ctx.getDb(), accountResolver, patchSet.isDraft(), footerLines);
recipients.remove(ctx.getAccountId());
- approvalsUtil.addReviewers(ctx.getDb(), ctx.getUpdate(psId), labelTypes,
- change, patchSet, patchSetInfo, recipients.getReviewers(),
+ approvalsUtil.addReviewers(
+ ctx.getDb(),
+ ctx.getUpdate(psId),
+ labelTypes,
+ change,
+ patchSet,
+ patchSetInfo,
+ recipients.getReviewers(),
oldReviewers);
}
@Override
public void postUpdate(Context ctx) throws OrmException {
- draftPublished.fire(change, patchSet, ctx.getAccount(),
- ctx.getWhen());
+ draftPublished.fire(change, patchSet, ctx.getAccount(), ctx.getWhen());
if (patchSet.isDraft() && change.getStatus() == Change.Status.DRAFT) {
// Skip emails if the patch set is still a draft.
return;
@@ -241,8 +240,7 @@
}
private void sendCreateChange(Context ctx) throws EmailException {
- CreateChangeSender cm =
- createChangeSenderFactory.create(ctx.getProject(), change.getId());
+ CreateChangeSender cm = createChangeSenderFactory.create(ctx.getProject(), change.getId());
cm.setFrom(ctx.getAccountId());
cm.setPatchSet(patchSet, patchSetInfo);
cm.addReviewers(recipients.getReviewers());
@@ -251,12 +249,14 @@
}
private void sendReplacePatchSet(Context ctx) throws EmailException {
- ChangeMessage msg = ChangeMessagesUtil.newMessage(
- psId, ctx.getUser(), ctx.getWhen(),
- "Uploaded patch set " + psId.get() + ".",
- ChangeMessagesUtil.TAG_UPLOADED_PATCH_SET);
- ReplacePatchSetSender cm =
- replacePatchSetFactory.create(ctx.getProject(), change.getId());
+ ChangeMessage msg =
+ ChangeMessagesUtil.newMessage(
+ psId,
+ ctx.getUser(),
+ ctx.getWhen(),
+ "Uploaded patch set " + psId.get() + ".",
+ ChangeMessagesUtil.TAG_UPLOADED_PATCH_SET);
+ ReplacePatchSetSender cm = replacePatchSetFactory.create(ctx.getProject(), change.getId());
cm.setFrom(ctx.getAccountId());
cm.setPatchSet(patchSet, patchSetInfo);
cm.setChangeMessage(msg.getMessage(), ctx.getWhen());
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/PutAssignee.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/PutAssignee.java
index 8afb0e6..ce2be83 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/PutAssignee.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/PutAssignee.java
@@ -35,12 +35,11 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.io.IOException;
@Singleton
-public class PutAssignee implements
- RestModifyView<ChangeResource, AssigneeInput>, UiAction<ChangeResource> {
+public class PutAssignee
+ implements RestModifyView<ChangeResource, AssigneeInput>, UiAction<ChangeResource> {
private final SetAssigneeOp.Factory assigneeFactory;
private final BatchUpdate.Factory batchUpdateFactory;
@@ -49,7 +48,8 @@
private final AccountLoader.Factory accountLoaderFactory;
@Inject
- PutAssignee(SetAssigneeOp.Factory assigneeFactory,
+ PutAssignee(
+ SetAssigneeOp.Factory assigneeFactory,
BatchUpdate.Factory batchUpdateFactory,
Provider<ReviewDb> db,
PostReviewers postReviewers,
@@ -71,19 +71,20 @@
throw new BadRequestException("missing assignee field");
}
- try (BatchUpdate bu = batchUpdateFactory.create(db.get(),
- rsrc.getChange().getProject(), rsrc.getControl().getUser(),
- TimeUtil.nowTs())) {
+ try (BatchUpdate bu =
+ batchUpdateFactory.create(
+ db.get(),
+ rsrc.getChange().getProject(),
+ rsrc.getControl().getUser(),
+ TimeUtil.nowTs())) {
SetAssigneeOp op = assigneeFactory.create(input.assignee);
bu.addOp(rsrc.getId(), op);
- PostReviewers.Addition reviewersAddition =
- addAssigneeAsCC(rsrc, input.assignee);
+ PostReviewers.Addition reviewersAddition = addAssigneeAsCC(rsrc, input.assignee);
bu.addOp(rsrc.getId(), reviewersAddition.op);
bu.execute();
- return Response.ok(
- accountLoaderFactory.create(true).fillOne(op.getNewAssignee()));
+ return Response.ok(accountLoaderFactory.create(true).fillOne(op.getNewAssignee()));
}
}
@@ -100,7 +101,7 @@
@Override
public UiAction.Description getDescription(ChangeResource resource) {
return new UiAction.Description()
- .setLabel("Edit Assignee")
- .setVisible(resource.getControl().canEditAssignee());
+ .setLabel("Edit Assignee")
+ .setVisible(resource.getControl().canEditAssignee());
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/PutDescription.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/PutDescription.java
index 5480fb4..4ce3ccb 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/PutDescription.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/PutDescription.java
@@ -36,24 +36,23 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.util.Collections;
@Singleton
-public class PutDescription implements RestModifyView<RevisionResource,
- PutDescription.Input>, UiAction<RevisionResource> {
+public class PutDescription
+ implements RestModifyView<RevisionResource, PutDescription.Input>, UiAction<RevisionResource> {
private final Provider<ReviewDb> dbProvider;
private final ChangeMessagesUtil cmUtil;
private final BatchUpdate.Factory batchUpdateFactory;
private final PatchSetUtil psUtil;
public static class Input {
- @DefaultInput
- public String description;
+ @DefaultInput public String description;
}
@Inject
- PutDescription(Provider<ReviewDb> dbProvider,
+ PutDescription(
+ Provider<ReviewDb> dbProvider,
ChangeMessagesUtil cmUtil,
BatchUpdate.Factory batchUpdateFactory,
PatchSetUtil psUtil) {
@@ -70,14 +69,15 @@
if (!ctl.canEditDescription()) {
throw new AuthException("changing description not permitted");
}
- Op op =
- new Op(input != null ? input : new Input(), rsrc.getPatchSet().getId());
- try (BatchUpdate u = batchUpdateFactory.create(dbProvider.get(),
- rsrc.getChange().getProject(), ctl.getUser(), TimeUtil.nowTs())) {
+ Op op = new Op(input != null ? input : new Input(), rsrc.getPatchSet().getId());
+ try (BatchUpdate u =
+ batchUpdateFactory.create(
+ dbProvider.get(), rsrc.getChange().getProject(), ctl.getUser(), TimeUtil.nowTs())) {
u.addOp(rsrc.getChange().getId(), op);
u.execute();
}
- return Strings.isNullOrEmpty(op.newDescription) ? Response.none()
+ return Strings.isNullOrEmpty(op.newDescription)
+ ? Response.none()
: Response.ok(op.newDescription);
}
@@ -117,8 +117,8 @@
ctx.getDb().patchSets().update(Collections.singleton(ps));
ChangeMessage cmsg =
- ChangeMessagesUtil.newMessage(psId, ctx.getUser(),
- ctx.getWhen(), summary, ChangeMessagesUtil.TAG_SET_DESCRIPTION);
+ ChangeMessagesUtil.newMessage(
+ psId, ctx.getUser(), ctx.getWhen(), summary, ChangeMessagesUtil.TAG_SET_DESCRIPTION);
cmUtil.addChangeMessage(ctx.getDb(), update, cmsg);
return true;
}
@@ -126,7 +126,8 @@
@Override
public UiAction.Description getDescription(RevisionResource rsrc) {
- return new UiAction.Description().setLabel("Edit Description")
+ return new UiAction.Description()
+ .setLabel("Edit Description")
.setVisible(rsrc.getControl().canEditDescription());
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/PutDraftComment.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/PutDraftComment.java
index 46bf6a9..1d7125f 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/PutDraftComment.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/PutDraftComment.java
@@ -40,7 +40,6 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.sql.Timestamp;
import java.util.Collections;
import java.util.Optional;
@@ -57,7 +56,8 @@
private final PatchListCache patchListCache;
@Inject
- PutDraftComment(Provider<ReviewDb> db,
+ PutDraftComment(
+ Provider<ReviewDb> db,
DeleteDraftComment delete,
CommentsUtil commentsUtil,
PatchSetUtil psUtil,
@@ -74,8 +74,8 @@
}
@Override
- public Response<CommentInfo> apply(DraftCommentResource rsrc, DraftInput in) throws
- RestApiException, UpdateException, OrmException {
+ public Response<CommentInfo> apply(DraftCommentResource rsrc, DraftInput in)
+ throws RestApiException, UpdateException, OrmException {
if (in == null || in.message == null || in.message.trim().isEmpty()) {
return delete.apply(rsrc, null);
} else if (in.id != null && !rsrc.getId().equals(in.id)) {
@@ -86,15 +86,17 @@
throw new BadRequestException("range endLine must be on the same line as the comment");
}
- try (BatchUpdate bu = updateFactory.create(
- db.get(), rsrc.getChange().getProject(), rsrc.getControl().getUser(),
- TimeUtil.nowTs())) {
+ try (BatchUpdate bu =
+ updateFactory.create(
+ db.get(),
+ rsrc.getChange().getProject(),
+ rsrc.getControl().getUser(),
+ TimeUtil.nowTs())) {
Op op = new Op(rsrc.getComment().key, in);
bu.addOp(rsrc.getChange().getId(), op);
bu.execute();
- return Response.ok(commentJson.get()
- .setFillAccounts(false)
- .newCommentFormatter().format(op.comment));
+ return Response.ok(
+ commentJson.get().setFillAccounts(false).newCommentFormatter().format(op.comment));
}
}
@@ -110,10 +112,8 @@
}
@Override
- public boolean updateChange(ChangeContext ctx)
- throws ResourceNotFoundException, OrmException {
- Optional<Comment> maybeComment =
- commentsUtil.get(ctx.getDb(), ctx.getNotes(), key);
+ public boolean updateChange(ChangeContext ctx) throws ResourceNotFoundException, OrmException {
+ Optional<Comment> maybeComment = commentsUtil.get(ctx.getDb(), ctx.getNotes(), key);
if (!maybeComment.isPresent()) {
// Disappeared out from under us. Can't easily fall back to insert,
// because the input might be missing required fields. Just give up.
@@ -125,25 +125,25 @@
// user.
ctx.getUser().updateRealAccountId(comment::setRealAuthor);
- PatchSet.Id psId =
- new PatchSet.Id(ctx.getChange().getId(), origComment.key.patchSetId);
+ PatchSet.Id psId = new PatchSet.Id(ctx.getChange().getId(), origComment.key.patchSetId);
ChangeUpdate update = ctx.getUpdate(psId);
PatchSet ps = psUtil.get(ctx.getDb(), ctx.getNotes(), psId);
if (ps == null) {
throw new ResourceNotFoundException("patch set not found: " + psId);
}
- if (in.path != null
- && !in.path.equals(origComment.key.filename)) {
+ if (in.path != null && !in.path.equals(origComment.key.filename)) {
// Updating the path alters the primary key, which isn't possible.
// Delete then recreate the comment instead of an update.
- commentsUtil.deleteComments(
- ctx.getDb(), update, Collections.singleton(origComment));
+ commentsUtil.deleteComments(ctx.getDb(), update, Collections.singleton(origComment));
comment.key.filename = in.path;
}
setCommentRevId(comment, patchListCache, ctx.getChange(), ps);
- commentsUtil.putComments(ctx.getDb(), update, Status.DRAFT,
+ commentsUtil.putComments(
+ ctx.getDb(),
+ update,
+ Status.DRAFT,
Collections.singleton(update(comment, in, ctx.getWhen())));
ctx.bumpLastUpdatedOn(false);
return true;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/PutTopic.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/PutTopic.java
index 62ef261..d3f5c77 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/PutTopic.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/PutTopic.java
@@ -40,20 +40,19 @@
import com.google.inject.Singleton;
@Singleton
-public class PutTopic implements RestModifyView<ChangeResource, Input>,
- UiAction<ChangeResource> {
+public class PutTopic implements RestModifyView<ChangeResource, Input>, UiAction<ChangeResource> {
private final Provider<ReviewDb> dbProvider;
private final ChangeMessagesUtil cmUtil;
private final BatchUpdate.Factory batchUpdateFactory;
private final TopicEdited topicEdited;
public static class Input {
- @DefaultInput
- public String topic;
+ @DefaultInput public String topic;
}
@Inject
- PutTopic(Provider<ReviewDb> dbProvider,
+ PutTopic(
+ Provider<ReviewDb> dbProvider,
ChangeMessagesUtil cmUtil,
BatchUpdate.Factory batchUpdateFactory,
TopicEdited topicEdited) {
@@ -72,13 +71,14 @@
}
Op op = new Op(input != null ? input : new Input());
- try (BatchUpdate u = batchUpdateFactory.create(dbProvider.get(),
- req.getChange().getProject(), ctl.getUser(), TimeUtil.nowTs())) {
+ try (BatchUpdate u =
+ batchUpdateFactory.create(
+ dbProvider.get(), req.getChange().getProject(), ctl.getUser(), TimeUtil.nowTs())) {
u.addOp(req.getId(), op);
u.execute();
}
return Strings.isNullOrEmpty(op.newTopicName)
- ? Response.<String> none()
+ ? Response.<String>none()
: Response.ok(op.newTopicName);
}
@@ -108,14 +108,13 @@
} else if (newTopicName.isEmpty()) {
summary = "Topic " + oldTopicName + " removed";
} else {
- summary = String.format("Topic changed from %s to %s",
- oldTopicName, newTopicName);
+ summary = String.format("Topic changed from %s to %s", oldTopicName, newTopicName);
}
change.setTopic(Strings.emptyToNull(newTopicName));
update.setTopic(change.getTopic());
- ChangeMessage cmsg = ChangeMessagesUtil.newMessage(ctx, summary,
- ChangeMessagesUtil.TAG_SET_TOPIC);
+ ChangeMessage cmsg =
+ ChangeMessagesUtil.newMessage(ctx, summary, ChangeMessagesUtil.TAG_SET_TOPIC);
cmUtil.addChangeMessage(ctx.getDb(), update, cmsg);
return true;
}
@@ -123,10 +122,7 @@
@Override
public void postUpdate(Context ctx) {
if (change != null) {
- topicEdited.fire(change,
- ctx.getAccount(),
- oldTopicName,
- ctx.getWhen());
+ topicEdited.fire(change, ctx.getAccount(), oldTopicName, ctx.getWhen());
}
}
}
@@ -134,7 +130,7 @@
@Override
public UiAction.Description getDescription(ChangeResource resource) {
return new UiAction.Description()
- .setLabel("Edit Topic")
- .setVisible(resource.getControl().canEditTopicName());
+ .setLabel("Edit Topic")
+ .setVisible(resource.getControl().canEditTopicName());
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/Rebase.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/Rebase.java
index 4b81c31..046712d 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/Rebase.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/Rebase.java
@@ -40,7 +40,8 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
+import java.io.IOException;
+import java.util.EnumSet;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.ObjectInserter;
import org.eclipse.jgit.lib.Repository;
@@ -49,16 +50,12 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.util.EnumSet;
-
@Singleton
-public class Rebase implements RestModifyView<RevisionResource, RebaseInput>,
- UiAction<RevisionResource> {
+public class Rebase
+ implements RestModifyView<RevisionResource, RebaseInput>, UiAction<RevisionResource> {
private static final Logger log = LoggerFactory.getLogger(Rebase.class);
- private static final EnumSet<ListChangesOption> OPTIONS = EnumSet.of(
- ListChangesOption.CURRENT_REVISION,
- ListChangesOption.CURRENT_COMMIT);
+ private static final EnumSet<ListChangesOption> OPTIONS =
+ EnumSet.of(ListChangesOption.CURRENT_REVISION, ListChangesOption.CURRENT_COMMIT);
private final BatchUpdate.Factory updateFactory;
private final GitRepositoryManager repoManager;
@@ -68,7 +65,8 @@
private final Provider<ReviewDb> dbProvider;
@Inject
- public Rebase(BatchUpdate.Factory updateFactory,
+ public Rebase(
+ BatchUpdate.Factory updateFactory,
GitRepositoryManager repoManager,
RebaseChangeOp.Factory rebaseFactory,
RebaseUtil rebaseUtil,
@@ -84,39 +82,40 @@
@Override
public ChangeInfo apply(RevisionResource rsrc, RebaseInput input)
- throws EmailException, OrmException, UpdateException, RestApiException,
- IOException, NoSuchChangeException {
+ throws EmailException, OrmException, UpdateException, RestApiException, IOException,
+ NoSuchChangeException {
ChangeControl control = rsrc.getControl();
Change change = rsrc.getChange();
try (Repository repo = repoManager.openRepository(change.getProject());
RevWalk rw = new RevWalk(repo);
ObjectInserter oi = repo.newObjectInserter();
- BatchUpdate bu = updateFactory.create(dbProvider.get(),
- change.getProject(), rsrc.getUser(), TimeUtil.nowTs())) {
+ BatchUpdate bu =
+ updateFactory.create(
+ dbProvider.get(), change.getProject(), rsrc.getUser(), TimeUtil.nowTs())) {
if (!control.canRebase(dbProvider.get())) {
throw new AuthException("rebase not permitted");
} else if (!change.getStatus().isOpen()) {
- throw new ResourceConflictException("change is "
- + change.getStatus().name().toLowerCase());
+ throw new ResourceConflictException("change is " + change.getStatus().name().toLowerCase());
} else if (!hasOneParent(rw, rsrc.getPatchSet())) {
throw new ResourceConflictException(
"cannot rebase merge commits or commit with no ancestor");
}
bu.setRepository(repo, rw, oi);
- bu.addOp(change.getId(), rebaseFactory.create(
- control, rsrc.getPatchSet(),
- findBaseRev(rw, rsrc, input))
- .setForceContentMerge(true)
- .setFireRevisionCreated(true)
- .setValidatePolicy(CommitValidators.Policy.GERRIT));
+ bu.addOp(
+ change.getId(),
+ rebaseFactory
+ .create(control, rsrc.getPatchSet(), findBaseRev(rw, rsrc, input))
+ .setForceContentMerge(true)
+ .setFireRevisionCreated(true)
+ .setValidatePolicy(CommitValidators.Policy.GERRIT));
bu.execute();
}
return json.create(OPTIONS).format(change.getProject(), change.getId());
}
- private String findBaseRev(RevWalk rw, RevisionResource rsrc,
- RebaseInput input) throws AuthException, ResourceConflictException,
- OrmException, IOException, NoSuchChangeException {
+ private String findBaseRev(RevWalk rw, RevisionResource rsrc, RebaseInput input)
+ throws AuthException, ResourceConflictException, OrmException, IOException,
+ NoSuchChangeException {
if (input == null || input.base == null) {
return null;
}
@@ -149,18 +148,17 @@
throw new ResourceConflictException(
"base change is targeting wrong branch: " + baseChange.getDest());
} else if (baseChange.getStatus() == Status.ABANDONED) {
- throw new ResourceConflictException(
- "base change is abandoned: " + baseChange.getKey());
+ throw new ResourceConflictException("base change is abandoned: " + baseChange.getKey());
} else if (isMergedInto(rw, rsrc.getPatchSet(), base.patchSet())) {
throw new ResourceConflictException(
- "base change " + baseChange.getKey()
- + " is a descendant of the current change - recursion not allowed");
+ "base change "
+ + baseChange.getKey()
+ + " is a descendant of the current change - recursion not allowed");
}
return base.patchSet().getRevision().get();
}
- private boolean isMergedInto(RevWalk rw, PatchSet base, PatchSet tip)
- throws IOException {
+ private boolean isMergedInto(RevWalk rw, PatchSet base, PatchSet tip) throws IOException {
ObjectId baseId = ObjectId.fromString(base.getRevision().get());
ObjectId tipId = ObjectId.fromString(tip.getRevision().get());
return rw.isMergedInto(rw.parseCommit(baseId), rw.parseCommit(tipId));
@@ -182,9 +180,8 @@
} catch (OrmException e) {
log.error("Cannot check canRebase status. Assuming false.", e);
}
- boolean visible = resource.getChange().getStatus().isOpen()
- && resource.isCurrent()
- && canRebase;
+ boolean visible =
+ resource.getChange().getStatus().isOpen() && resource.isCurrent() && canRebase;
boolean enabled = true;
if (visible) {
@@ -193,21 +190,20 @@
visible = hasOneParent(rw, resource.getPatchSet());
enabled = rebaseUtil.canRebase(patchSet, dest, repo, rw);
} catch (IOException e) {
- log.error("Failed to check if patch set can be rebased: "
- + resource.getPatchSet(), e);
+ log.error("Failed to check if patch set can be rebased: " + resource.getPatchSet(), e);
visible = false;
}
}
- UiAction.Description descr = new UiAction.Description()
- .setLabel("Rebase")
- .setTitle("Rebase onto tip of branch or parent change")
- .setVisible(visible)
- .setEnabled(enabled);
+ UiAction.Description descr =
+ new UiAction.Description()
+ .setLabel("Rebase")
+ .setTitle("Rebase onto tip of branch or parent change")
+ .setVisible(visible)
+ .setEnabled(enabled);
return descr;
}
- public static class CurrentRevision implements
- RestModifyView<ChangeResource, RebaseInput> {
+ public static class CurrentRevision implements RestModifyView<ChangeResource, RebaseInput> {
private final Rebase rebase;
@Inject
@@ -217,11 +213,9 @@
@Override
public ChangeInfo apply(ChangeResource rsrc, RebaseInput input)
- throws EmailException, OrmException, UpdateException, RestApiException,
- IOException, NoSuchChangeException {
- PatchSet ps =
- rebase.dbProvider.get().patchSets()
- .get(rsrc.getChange().currentPatchSetId());
+ throws EmailException, OrmException, UpdateException, RestApiException, IOException,
+ NoSuchChangeException {
+ PatchSet ps = rebase.dbProvider.get().patchSets().get(rsrc.getChange().currentPatchSetId());
if (ps == null) {
throw new ResourceConflictException("current revision is missing");
} else if (!rsrc.getControl().isPatchVisible(ps, rebase.dbProvider.get())) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/RebaseChangeEdit.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/RebaseChangeEdit.java
index db125eb..7b673dd 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/RebaseChangeEdit.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/RebaseChangeEdit.java
@@ -32,15 +32,12 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
+import java.io.IOException;
import org.eclipse.jgit.lib.Repository;
-import java.io.IOException;
-
@Singleton
-public class RebaseChangeEdit implements
- ChildCollection<ChangeResource, ChangeEditResource>,
- AcceptsPost<ChangeResource> {
+public class RebaseChangeEdit
+ implements ChildCollection<ChangeResource, ChangeEditResource>, AcceptsPost<ChangeResource> {
private final Rebase rebase;
@@ -72,23 +69,20 @@
@Singleton
public static class Rebase implements RestModifyView<ChangeResource, Rebase.Input> {
- public static class Input {
- }
+ public static class Input {}
private final GitRepositoryManager repositoryManager;
private final ChangeEditModifier editModifier;
@Inject
- Rebase(GitRepositoryManager repositoryManager,
- ChangeEditModifier editModifier) {
+ Rebase(GitRepositoryManager repositoryManager, ChangeEditModifier editModifier) {
this.repositoryManager = repositoryManager;
this.editModifier = editModifier;
}
@Override
public Response<?> apply(ChangeResource rsrc, Rebase.Input in)
- throws AuthException, ResourceConflictException, IOException,
- OrmException {
+ throws AuthException, ResourceConflictException, IOException, OrmException {
Project.NameKey project = rsrc.getProject();
try (Repository repository = repositoryManager.openRepository(project)) {
editModifier.rebaseEdit(repository, rsrc.getControl());
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/RebaseChangeOp.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/RebaseChangeOp.java
index 91734ff..89b1c6b 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/RebaseChangeOp.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/RebaseChangeOp.java
@@ -38,7 +38,7 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
-
+import java.io.IOException;
import org.eclipse.jgit.lib.CommitBuilder;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.PersonIdent;
@@ -46,12 +46,10 @@
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;
-import java.io.IOException;
-
public class RebaseChangeOp extends BatchUpdate.Op {
public interface Factory {
- RebaseChangeOp create(ChangeControl ctl, PatchSet originalPatchSet,
- @Nullable String baseCommitish);
+ RebaseChangeOp create(
+ ChangeControl ctl, PatchSet originalPatchSet, @Nullable String baseCommitish);
}
private final PatchSetInserter.Factory patchSetInserterFactory;
@@ -105,8 +103,7 @@
return this;
}
- public RebaseChangeOp setCheckAddPatchSetPermission(
- boolean checkAddPatchSetPermission) {
+ public RebaseChangeOp setCheckAddPatchSetPermission(boolean checkAddPatchSetPermission) {
this.checkAddPatchSetPermission = checkAddPatchSetPermission;
return this;
}
@@ -126,8 +123,7 @@
return this;
}
- public RebaseChangeOp setDetailedCommitMessage(
- boolean detailedCommitMessage) {
+ public RebaseChangeOp setDetailedCommitMessage(boolean detailedCommitMessage) {
this.detailedCommitMessage = detailedCommitMessage;
return this;
}
@@ -138,9 +134,9 @@
}
@Override
- public void updateRepo(RepoContext ctx) throws MergeConflictException,
- InvalidChangeOperationException, RestApiException, IOException,
- OrmException, NoSuchChangeException {
+ public void updateRepo(RepoContext ctx)
+ throws MergeConflictException, InvalidChangeOperationException, RestApiException, IOException,
+ OrmException, NoSuchChangeException {
// Ok that originalPatchSet was not read in a transaction, since we just
// need its revision.
RevId oldRev = originalPatchSet.getRevision();
@@ -151,44 +147,54 @@
RevCommit baseCommit;
if (baseCommitish != null) {
- baseCommit = rw.parseCommit(ctx.getRepository().resolve(baseCommitish));
+ baseCommit = rw.parseCommit(ctx.getRepository().resolve(baseCommitish));
} else {
- baseCommit = rw.parseCommit(rebaseUtil.findBaseRevision(
- originalPatchSet, ctl.getChange().getDest(),
- ctx.getRepository(), ctx.getRevWalk()));
+ baseCommit =
+ rw.parseCommit(
+ rebaseUtil.findBaseRevision(
+ originalPatchSet,
+ ctl.getChange().getDest(),
+ ctx.getRepository(),
+ ctx.getRevWalk()));
}
String newCommitMessage;
if (detailedCommitMessage) {
rw.parseBody(baseCommit);
- newCommitMessage = newMergeUtil().createCommitMessageOnSubmit(original,
- baseCommit, ctl, originalPatchSet.getId());
+ newCommitMessage =
+ newMergeUtil()
+ .createCommitMessageOnSubmit(original, baseCommit, ctl, originalPatchSet.getId());
} else {
newCommitMessage = original.getFullMessage();
}
rebasedCommit = rebaseCommit(ctx, original, baseCommit, newCommitMessage);
- RevId baseRevId = new RevId((baseCommitish != null) ? baseCommitish
- : ObjectId.toString(baseCommit.getId()));
- Base base = rebaseUtil.parseBase(
- new RevisionResource(
- changeResourceFactory.create(ctl), originalPatchSet),
- baseRevId.get());
+ RevId baseRevId =
+ new RevId((baseCommitish != null) ? baseCommitish : ObjectId.toString(baseCommit.getId()));
+ Base base =
+ rebaseUtil.parseBase(
+ new RevisionResource(changeResourceFactory.create(ctl), originalPatchSet),
+ baseRevId.get());
- rebasedPatchSetId = ChangeUtil.nextPatchSetId(
- ctx.getRepository(), ctl.getChange().currentPatchSetId());
- patchSetInserter = patchSetInserterFactory
- .create(ctl, rebasedPatchSetId, rebasedCommit)
- .setDescription("Rebase")
- .setDraft(originalPatchSet.isDraft())
- .setNotify(NotifyHandling.NONE)
- .setFireRevisionCreated(fireRevisionCreated)
- .setCopyApprovals(copyApprovals)
- .setCheckAddPatchSetPermission(checkAddPatchSetPermission);
+ rebasedPatchSetId =
+ ChangeUtil.nextPatchSetId(ctx.getRepository(), ctl.getChange().currentPatchSetId());
+ patchSetInserter =
+ patchSetInserterFactory
+ .create(ctl, rebasedPatchSetId, rebasedCommit)
+ .setDescription("Rebase")
+ .setDraft(originalPatchSet.isDraft())
+ .setNotify(NotifyHandling.NONE)
+ .setFireRevisionCreated(fireRevisionCreated)
+ .setCopyApprovals(copyApprovals)
+ .setCheckAddPatchSetPermission(checkAddPatchSetPermission);
if (postMessage) {
- patchSetInserter.setMessage("Patch Set " + rebasedPatchSetId.get()
- + ": Patch Set " + originalPatchSet.getId().get() + " was rebased");
+ patchSetInserter.setMessage(
+ "Patch Set "
+ + rebasedPatchSetId.get()
+ + ": Patch Set "
+ + originalPatchSet.getId().get()
+ + " was rebased");
}
if (base != null) {
@@ -214,20 +220,17 @@
}
public RevCommit getRebasedCommit() {
- checkState(rebasedCommit != null,
- "getRebasedCommit() only valid after updateRepo");
+ checkState(rebasedCommit != null, "getRebasedCommit() only valid after updateRepo");
return rebasedCommit;
}
public PatchSet.Id getPatchSetId() {
- checkState(rebasedPatchSetId != null,
- "getPatchSetId() only valid after updateRepo");
+ checkState(rebasedPatchSetId != null, "getPatchSetId() only valid after updateRepo");
return rebasedPatchSetId;
}
public PatchSet getPatchSet() {
- checkState(rebasedPatchSet != null,
- "getPatchSet() only valid after executing update");
+ checkState(rebasedPatchSet != null, "getPatchSet() only valid after executing update");
return rebasedPatchSet;
}
@@ -257,8 +260,8 @@
throw new ResourceConflictException("Change is already up to date.");
}
- ThreeWayMerger merger = newMergeUtil().newThreeWayMerger(
- ctx.getRepository(), ctx.getInserter());
+ ThreeWayMerger merger =
+ newMergeUtil().newThreeWayMerger(ctx.getRepository(), ctx.getInserter());
merger.setBase(parentCommit);
merger.merge(original, base);
@@ -275,8 +278,7 @@
if (committerIdent != null) {
cb.setCommitter(committerIdent);
} else {
- cb.setCommitter(ctx.getIdentifiedUser()
- .newCommitterIdent(ctx.getWhen(), ctx.getTimeZone()));
+ cb.setCommitter(ctx.getIdentifiedUser().newCommitterIdent(ctx.getWhen(), ctx.getTimeZone()));
}
ObjectId objectId = ctx.getInserter().insert(cb);
ctx.getInserter().flush();
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/RebaseUtil.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/RebaseUtil.java
index 4a9d19c..88fc1b3 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/RebaseUtil.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/RebaseUtil.java
@@ -33,7 +33,7 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
-
+import java.io.IOException;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
@@ -42,8 +42,6 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-
/** Utility methods related to rebasing changes. */
public class RebaseUtil {
private static final Logger log = LoggerFactory.getLogger(RebaseUtil.class);
@@ -54,7 +52,8 @@
private final PatchSetUtil psUtil;
@Inject
- RebaseUtil(Provider<InternalChangeQuery> queryProvider,
+ RebaseUtil(
+ Provider<InternalChangeQuery> queryProvider,
ChangeNotes.Factory notesFactory,
Provider<ReviewDb> dbProvider,
PatchSetUtil psUtil) {
@@ -64,17 +63,17 @@
this.psUtil = psUtil;
}
- public boolean canRebase(PatchSet patchSet, Branch.NameKey dest,
- Repository git, RevWalk rw) {
+ public boolean canRebase(PatchSet patchSet, Branch.NameKey dest, Repository git, RevWalk rw) {
try {
findBaseRevision(patchSet, dest, git, rw);
return true;
} catch (RestApiException e) {
return false;
} catch (OrmException | IOException e) {
- log.warn(String.format(
- "Error checking if patch set %s on %s can be rebased",
- patchSet.getId(), dest), e);
+ log.warn(
+ String.format(
+ "Error checking if patch set %s on %s can be rebased", patchSet.getId(), dest),
+ e);
return false;
}
}
@@ -89,6 +88,7 @@
}
abstract ChangeControl control();
+
abstract PatchSet patchSet();
}
@@ -118,38 +118,32 @@
// Try parsing as SHA-1.
Base ret = null;
- for (ChangeData cd : queryProvider.get()
- .byProjectCommit(rsrc.getProject(), base)) {
+ for (ChangeData cd : queryProvider.get().byProjectCommit(rsrc.getProject(), base)) {
for (PatchSet ps : cd.patchSets()) {
if (!ps.getRevision().matches(base)) {
continue;
}
if (ret == null || ret.patchSet().getId().get() < ps.getId().get()) {
- ret = Base.create(
- rsrc.getControl().getProjectControl().controlFor(cd.notes()),
- ps);
+ ret = Base.create(rsrc.getControl().getProjectControl().controlFor(cd.notes()), ps);
}
}
}
return ret;
}
- private ChangeControl controlFor(RevisionResource rsrc, Change.Id id)
- throws OrmException {
+ private ChangeControl controlFor(RevisionResource rsrc, Change.Id id) throws OrmException {
if (rsrc.getChange().getId().equals(id)) {
return rsrc.getControl();
}
- ChangeNotes notes =
- notesFactory.createChecked(dbProvider.get(), rsrc.getProject(), id);
+ ChangeNotes notes = notesFactory.createChecked(dbProvider.get(), rsrc.getProject(), id);
return rsrc.getControl().getProjectControl().controlFor(notes);
}
/**
* Find the commit onto which a patch set should be rebased.
- * <p>
- * This is defined as the latest patch set of the change corresponding to
- * this commit's parent, or the destination branch tip in the case where the
- * parent's change is merged.
+ *
+ * <p>This is defined as the latest patch set of the change corresponding to this commit's parent,
+ * or the destination branch tip in the case where the parent's change is merged.
*
* @param patchSet patch set for which the new base commit should be found.
* @param destBranch the destination branch.
@@ -160,26 +154,23 @@
* @throws IOException if accessing the repository fails.
* @throws OrmException if accessing the database fails.
*/
- ObjectId findBaseRevision(PatchSet patchSet, Branch.NameKey destBranch,
- Repository git, RevWalk rw)
+ ObjectId findBaseRevision(
+ PatchSet patchSet, Branch.NameKey destBranch, Repository git, RevWalk rw)
throws RestApiException, IOException, OrmException {
String baseRev = null;
- RevCommit commit = rw.parseCommit(
- ObjectId.fromString(patchSet.getRevision().get()));
+ RevCommit commit = rw.parseCommit(ObjectId.fromString(patchSet.getRevision().get()));
if (commit.getParentCount() > 1) {
- throw new UnprocessableEntityException(
- "Cannot rebase a change with multiple parents.");
+ throw new UnprocessableEntityException("Cannot rebase a change with multiple parents.");
} else if (commit.getParentCount() == 0) {
throw new UnprocessableEntityException(
- "Cannot rebase a change without any parents"
- + " (is this the initial commit?).");
+ "Cannot rebase a change without any parents" + " (is this the initial commit?).");
}
RevId parentRev = new RevId(commit.getParent(0).name());
- CHANGES: for (ChangeData cd : queryProvider.get()
- .byBranchCommit(destBranch, parentRev.get())) {
+ CHANGES:
+ for (ChangeData cd : queryProvider.get().byBranchCommit(destBranch, parentRev.get())) {
for (PatchSet depPatchSet : cd.patchSets()) {
if (!depPatchSet.getRevision().equals(parentRev)) {
continue;
@@ -187,15 +178,13 @@
Change depChange = cd.change();
if (depChange.getStatus() == Status.ABANDONED) {
throw new ResourceConflictException(
- "Cannot rebase a change with an abandoned parent: "
- + depChange.getKey());
+ "Cannot rebase a change with an abandoned parent: " + depChange.getKey());
}
if (depChange.getStatus().isOpen()) {
if (depPatchSet.getId().equals(depChange.currentPatchSetId())) {
throw new ResourceConflictException(
- "Change is already based on the latest patch set of the"
- + " dependent change.");
+ "Change is already based on the latest patch set of the" + " dependent change.");
}
baseRev = cd.currentPatchSet().getRevision().get();
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/Rebuild.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/Rebuild.java
index b9f4483..682b45f 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/Rebuild.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/Rebuild.java
@@ -34,16 +34,13 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.errors.ConfigInvalidException;
-
import java.io.IOException;
import java.util.List;
+import org.eclipse.jgit.errors.ConfigInvalidException;
@Singleton
public class Rebuild implements RestModifyView<ChangeResource, Input> {
- public static class Input {
- }
+ public static class Input {}
private final Provider<ReviewDb> db;
private final NotesMigration migration;
@@ -53,7 +50,8 @@
private final ChangeNotes.Factory notesFactory;
@Inject
- Rebuild(Provider<ReviewDb> db,
+ Rebuild(
+ Provider<ReviewDb> db,
NotesMigration migration,
ChangeRebuilder rebuilder,
ChangeBundleReader bundleReader,
@@ -69,11 +67,11 @@
@Override
public BinaryResult apply(ChangeResource rsrc, Input input)
- throws ResourceNotFoundException, IOException, OrmException,
- ConfigInvalidException {
+ throws ResourceNotFoundException, IOException, OrmException, ConfigInvalidException {
if (!migration.commitChangeWrites()) {
throw new ResourceNotFoundException();
- } if (!migration.readChanges()) {
+ }
+ if (!migration.readChanges()) {
// ChangeBundle#fromNotes currently doesn't work if reading isn't enabled,
// so don't attempt a diff.
rebuild(rsrc);
@@ -82,29 +80,25 @@
// Not the same transaction as the rebuild, so may result in spurious diffs
// in the case of races. This should be easy enough to detect by rerunning.
- ChangeBundle reviewDbBundle = bundleReader.fromReviewDb(
- ReviewDbUtil.unwrapDb(db.get()), rsrc.getId());
+ ChangeBundle reviewDbBundle =
+ bundleReader.fromReviewDb(ReviewDbUtil.unwrapDb(db.get()), rsrc.getId());
rebuild(rsrc);
- ChangeNotes notes = notesFactory.create(
- db.get(), rsrc.getChange().getProject(), rsrc.getId());
+ ChangeNotes notes = notesFactory.create(db.get(), rsrc.getChange().getProject(), rsrc.getId());
ChangeBundle noteDbBundle = ChangeBundle.fromNotes(commentsUtil, notes);
List<String> diffs = reviewDbBundle.differencesFrom(noteDbBundle);
if (diffs.isEmpty()) {
return BinaryResult.create("No differences between ReviewDb and NoteDb");
}
return BinaryResult.create(
- diffs.stream()
- .collect(joining(
- "\n", "Differences between ReviewDb and NoteDb:\n", "\n")));
+ diffs.stream().collect(joining("\n", "Differences between ReviewDb and NoteDb:\n", "\n")));
}
- private void rebuild(ChangeResource rsrc) throws ResourceNotFoundException,
- OrmException, IOException {
+ private void rebuild(ChangeResource rsrc)
+ throws ResourceNotFoundException, OrmException, IOException {
try {
rebuilder.rebuild(db.get(), rsrc.getId());
} catch (NoSuchChangeException e) {
- throw new ResourceNotFoundException(
- IdString.fromDecoded(rsrc.getId().toString()));
+ throw new ResourceNotFoundException(IdString.fromDecoded(rsrc.getId().toString()));
}
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/RelatedChangesSorter.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/RelatedChangesSorter.java
index e7a346f..4810a02 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/RelatedChangesSorter.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/RelatedChangesSorter.java
@@ -33,12 +33,6 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.lib.Repository;
-import org.eclipse.jgit.revwalk.RevCommit;
-import org.eclipse.jgit.revwalk.RevWalk;
-
import java.io.IOException;
import java.util.ArrayDeque;
import java.util.ArrayList;
@@ -51,6 +45,10 @@
import java.util.Map;
import java.util.Objects;
import java.util.Set;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.lib.Repository;
+import org.eclipse.jgit.revwalk.RevCommit;
+import org.eclipse.jgit.revwalk.RevWalk;
@Singleton
class RelatedChangesSorter {
@@ -98,8 +96,7 @@
Collection<PatchSetData> ancestors = walkAncestors(ctl, parents, start);
List<PatchSetData> descendants =
walkDescendants(ctl, children, start, otherPatchSetsOfStart, ancestors);
- List<PatchSetData> result =
- new ArrayList<>(ancestors.size() + descendants.size() - 1);
+ List<PatchSetData> result = new ArrayList<>(ancestors.size() + descendants.size() - 1);
result.addAll(Lists.reverse(descendants));
result.addAll(ancestors);
return result;
@@ -108,15 +105,17 @@
private Map<String, PatchSetData> collectById(List<ChangeData> in)
throws OrmException, IOException {
Project.NameKey project = in.get(0).change().getProject();
- Map<String, PatchSetData> result =
- Maps.newHashMapWithExpectedSize(in.size() * 3);
+ Map<String, PatchSetData> result = Maps.newHashMapWithExpectedSize(in.size() * 3);
try (Repository repo = repoManager.openRepository(project);
RevWalk rw = new RevWalk(repo)) {
rw.setRetainBody(true);
for (ChangeData cd : in) {
- checkArgument(cd.change().getProject().equals(project),
+ checkArgument(
+ cd.change().getProject().equals(project),
"Expected change %s in project %s, found %s",
- cd.getId(), project, cd.change().getProject());
+ cd.getId(),
+ project,
+ cd.change().getProject());
for (PatchSet ps : cd.patchSets()) {
String id = ps.getRevision().get();
RevCommit c = rw.parseCommit(ObjectId.fromString(id));
@@ -128,8 +127,8 @@
return result;
}
- private static Collection<PatchSetData> walkAncestors(ProjectControl ctl,
- ListMultimap<PatchSetData, PatchSetData> parents, PatchSetData start)
+ private static Collection<PatchSetData> walkAncestors(
+ ProjectControl ctl, ListMultimap<PatchSetData, PatchSetData> parents, PatchSetData start)
throws OrmException {
LinkedHashSet<PatchSetData> result = new LinkedHashSet<>();
Deque<PatchSetData> pending = new ArrayDeque<>();
@@ -145,38 +144,41 @@
return result;
}
- private static List<PatchSetData> walkDescendants(ProjectControl ctl,
+ private static List<PatchSetData> walkDescendants(
+ ProjectControl ctl,
ListMultimap<PatchSetData, PatchSetData> children,
- PatchSetData start, List<PatchSetData> otherPatchSetsOfStart,
+ PatchSetData start,
+ List<PatchSetData> otherPatchSetsOfStart,
Iterable<PatchSetData> ancestors)
throws OrmException {
Set<Change.Id> alreadyEmittedChanges = new HashSet<>();
addAllChangeIds(alreadyEmittedChanges, ancestors);
// Prefer descendants found by following the original patch set passed in.
- List<PatchSetData> result = walkDescendentsImpl(
- ctl, alreadyEmittedChanges, children, ImmutableList.of(start));
+ List<PatchSetData> result =
+ walkDescendentsImpl(ctl, alreadyEmittedChanges, children, ImmutableList.of(start));
addAllChangeIds(alreadyEmittedChanges, result);
// Then, go back and add new indirect descendants found by following any
// other patch sets of start. These show up after all direct descendants,
// because we wouldn't know where in the walk to insert them.
- result.addAll(walkDescendentsImpl(
- ctl, alreadyEmittedChanges, children, otherPatchSetsOfStart));
+ result.addAll(walkDescendentsImpl(ctl, alreadyEmittedChanges, children, otherPatchSetsOfStart));
return result;
}
- private static void addAllChangeIds(Collection<Change.Id> changeIds,
- Iterable<PatchSetData> psds) {
+ private static void addAllChangeIds(
+ Collection<Change.Id> changeIds, Iterable<PatchSetData> psds) {
for (PatchSetData psd : psds) {
changeIds.add(psd.id());
}
}
- private static List<PatchSetData> walkDescendentsImpl(ProjectControl ctl,
+ private static List<PatchSetData> walkDescendentsImpl(
+ ProjectControl ctl,
Set<Change.Id> alreadyEmittedChanges,
ListMultimap<PatchSetData, PatchSetData> children,
- List<PatchSetData> start) throws OrmException {
+ List<PatchSetData> start)
+ throws OrmException {
if (start.isEmpty()) {
return ImmutableList.of();
}
@@ -218,12 +220,10 @@
return result;
}
- private static boolean isVisible(PatchSetData psd, ProjectControl ctl)
- throws OrmException {
+ private static boolean isVisible(PatchSetData psd, ProjectControl ctl) throws OrmException {
// Reuse existing project control rather than lazily creating a new one for
// each ChangeData.
- return ctl.controlFor(psd.data().notes())
- .isPatchVisible(psd.patchSet(), psd.data());
+ return ctl.controlFor(psd.data().notes()).isPatchVisible(psd.patchSet(), psd.data());
}
@AutoValue
@@ -234,7 +234,9 @@
}
abstract ChangeData data();
+
abstract PatchSet patchSet();
+
abstract RevCommit commit();
PatchSet.Id psId() {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/Restore.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/Restore.java
index b1d9c0d..2c373be 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/Restore.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/Restore.java
@@ -43,13 +43,12 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Singleton
-public class Restore implements RestModifyView<ChangeResource, RestoreInput>,
- UiAction<ChangeResource> {
+public class Restore
+ implements RestModifyView<ChangeResource, RestoreInput>, UiAction<ChangeResource> {
private static final Logger log = LoggerFactory.getLogger(Restore.class);
private final RestoredSender.Factory restoredSenderFactory;
@@ -61,7 +60,8 @@
private final ChangeRestored changeRestored;
@Inject
- Restore(RestoredSender.Factory restoredSenderFactory,
+ Restore(
+ RestoredSender.Factory restoredSenderFactory,
Provider<ReviewDb> dbProvider,
ChangeJson.Factory json,
ChangeMessagesUtil cmUtil,
@@ -86,8 +86,9 @@
}
Op op = new Op(input);
- try (BatchUpdate u = batchUpdateFactory.create(dbProvider.get(),
- req.getChange().getProject(), ctl.getUser(), TimeUtil.nowTs())) {
+ try (BatchUpdate u =
+ batchUpdateFactory.create(
+ dbProvider.get(), req.getChange().getProject(), ctl.getUser(), TimeUtil.nowTs())) {
u.addOp(req.getId(), op).execute();
}
return json.create(ChangeJson.NO_OPTIONS).format(op.change);
@@ -105,8 +106,7 @@
}
@Override
- public boolean updateChange(ChangeContext ctx) throws OrmException,
- ResourceConflictException {
+ public boolean updateChange(ChangeContext ctx) throws OrmException, ResourceConflictException {
change = ctx.getChange();
if (change == null || change.getStatus() != Status.ABANDONED) {
throw new ResourceConflictException("change is " + status(change));
@@ -130,25 +130,21 @@
msg.append("\n\n");
msg.append(input.message.trim());
}
- return ChangeMessagesUtil.newMessage(ctx, msg.toString(),
- ChangeMessagesUtil.TAG_RESTORE);
+ return ChangeMessagesUtil.newMessage(ctx, msg.toString(), ChangeMessagesUtil.TAG_RESTORE);
}
@Override
public void postUpdate(Context ctx) throws OrmException {
try {
- ReplyToChangeSender cm =
- restoredSenderFactory.create(ctx.getProject(), change.getId());
+ ReplyToChangeSender cm = restoredSenderFactory.create(ctx.getProject(), change.getId());
cm.setFrom(ctx.getAccountId());
cm.setChangeMessage(message.getMessage(), ctx.getWhen());
cm.send();
} catch (Exception e) {
log.error("Cannot email update for change " + change.getId(), e);
}
- changeRestored.fire(change, patchSet,
- ctx.getAccount(),
- Strings.emptyToNull(input.message),
- ctx.getWhen());
+ changeRestored.fire(
+ change, patchSet, ctx.getAccount(), Strings.emptyToNull(input.message), ctx.getWhen());
}
}
@@ -161,10 +157,9 @@
log.error("Cannot check canRestore status. Assuming false.", e);
}
return new UiAction.Description()
- .setLabel("Restore")
- .setTitle("Restore the change")
- .setVisible(resource.getChange().getStatus() == Status.ABANDONED
- && canRestore);
+ .setLabel("Restore")
+ .setTitle("Restore the change")
+ .setVisible(resource.getChange().getStatus() == Status.ABANDONED && canRestore);
}
private static String status(Change change) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/Revert.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/Revert.java
index ab318c1..95f64b7 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/Revert.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/Revert.java
@@ -54,7 +54,11 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
+import java.io.IOException;
+import java.sql.Timestamp;
+import java.text.MessageFormat;
+import java.util.HashSet;
+import java.util.Set;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
import org.eclipse.jgit.lib.CommitBuilder;
import org.eclipse.jgit.lib.ObjectId;
@@ -67,15 +71,9 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.sql.Timestamp;
-import java.text.MessageFormat;
-import java.util.HashSet;
-import java.util.Set;
-
@Singleton
-public class Revert implements RestModifyView<ChangeResource, RevertInput>,
- UiAction<ChangeResource> {
+public class Revert
+ implements RestModifyView<ChangeResource, RevertInput>, UiAction<ChangeResource> {
private static final Logger log = LoggerFactory.getLogger(Revert.class);
private final Provider<ReviewDb> db;
@@ -92,7 +90,8 @@
private final ChangeReverted changeReverted;
@Inject
- Revert(Provider<ReviewDb> db,
+ Revert(
+ Provider<ReviewDb> db,
GitRepositoryManager repoManager,
ChangeInserter.Factory changeInserterFactory,
ChangeMessagesUtil cmUtil,
@@ -120,8 +119,7 @@
@Override
public ChangeInfo apply(ChangeResource req, RevertInput input)
- throws IOException, OrmException, RestApiException,
- UpdateException, NoSuchChangeException {
+ throws IOException, OrmException, RestApiException, UpdateException, NoSuchChangeException {
RefControl refControl = req.getControl().getRefControl();
ProjectControl projectControl = req.getControl().getProjectControl();
@@ -137,10 +135,8 @@
throw new ResourceConflictException("change is " + status(change));
}
- Change.Id revertedChangeId =
- revert(req.getControl(), Strings.emptyToNull(input.message));
- return json.create(ChangeJson.NO_OPTIONS).format(req.getProject(),
- revertedChangeId);
+ Change.Id revertedChangeId = revert(req.getControl(), Strings.emptyToNull(input.message));
+ return json.create(ChangeJson.NO_OPTIONS).format(req.getProject(), revertedChangeId);
}
private Change.Id revert(ChangeControl ctl, String message)
@@ -164,8 +160,8 @@
Timestamp now = TimeUtil.nowTs();
PersonIdent committerIdent = new PersonIdent(serverIdent, now);
- PersonIdent authorIdent = user.asIdentifiedUser()
- .newCommitterIdent(now, committerIdent.getTimeZone());
+ PersonIdent authorIdent =
+ user.asIdentifiedUser().newCommitterIdent(now, committerIdent.getTimeZone());
RevCommit parentToCommitToRevert = commitToRevert.getParent(0);
revWalk.parseHeaders(parentToCommitToRevert);
@@ -178,16 +174,21 @@
Change changeToRevert = ctl.getChange();
if (message == null) {
- message = MessageFormat.format(
- ChangeMessages.get().revertChangeDefaultMessage,
- changeToRevert.getSubject(), patch.getRevision().get());
+ message =
+ MessageFormat.format(
+ ChangeMessages.get().revertChangeDefaultMessage,
+ changeToRevert.getSubject(),
+ patch.getRevision().get());
}
ObjectId computedChangeId =
- ChangeIdUtil.computeChangeId(parentToCommitToRevert.getTree(),
- commitToRevert, authorIdent, committerIdent, message);
- revertCommitBuilder.setMessage(
- ChangeIdUtil.insertId(message, computedChangeId, true));
+ ChangeIdUtil.computeChangeId(
+ parentToCommitToRevert.getTree(),
+ commitToRevert,
+ authorIdent,
+ committerIdent,
+ message);
+ revertCommitBuilder.setMessage(ChangeIdUtil.insertId(message, computedChangeId, true));
Change.Id changeId = new Change.Id(seq.nextChangeId());
try (ObjectInserter oi = git.newObjectInserter()) {
@@ -195,26 +196,24 @@
oi.flush();
RevCommit revertCommit = revWalk.parseCommit(id);
- ChangeInserter ins = changeInserterFactory.create(
- changeId, revertCommit, ctl.getChange().getDest().get())
- .setValidatePolicy(CommitValidators.Policy.GERRIT)
- .setTopic(changeToRevert.getTopic());
+ ChangeInserter ins =
+ changeInserterFactory
+ .create(changeId, revertCommit, ctl.getChange().getDest().get())
+ .setValidatePolicy(CommitValidators.Policy.GERRIT)
+ .setTopic(changeToRevert.getTopic());
ins.setMessage("Uploaded patch set 1.");
Set<Account.Id> reviewers = new HashSet<>();
reviewers.add(changeToRevert.getOwner());
- reviewers.addAll(
- approvalsUtil.getReviewers(db.get(), ctl.getNotes()).all());
+ reviewers.addAll(approvalsUtil.getReviewers(db.get(), ctl.getNotes()).all());
reviewers.remove(user.getAccountId());
ins.setReviewers(reviewers);
- try (BatchUpdate bu = updateFactory.create(
- db.get(), project, user, now)) {
+ try (BatchUpdate bu = updateFactory.create(db.get(), project, user, now)) {
bu.setRepository(git, revWalk, oi);
bu.insertChange(ins);
bu.addOp(changeId, new NotifyOp(ctl.getChange(), ins));
- bu.addOp(changeToRevert.getId(),
- new PostRevertedMessageOp(computedChangeId));
+ bu.addOp(changeToRevert.getId(), new PostRevertedMessageOp(computedChangeId));
bu.execute();
}
}
@@ -227,10 +226,11 @@
@Override
public UiAction.Description getDescription(ChangeResource resource) {
return new UiAction.Description()
- .setLabel("Revert")
- .setTitle("Revert the change")
- .setVisible(resource.getChange().getStatus() == Status.MERGED
- && resource.getControl().getRefControl().canUpload());
+ .setLabel("Revert")
+ .setTitle("Revert the change")
+ .setVisible(
+ resource.getChange().getStatus() == Status.MERGED
+ && resource.getControl().getRefControl().canUpload());
}
private static String status(Change change) {
@@ -251,8 +251,7 @@
changeReverted.fire(change, ins.getChange(), ctx.getWhen());
Change.Id changeId = ins.getChange().getId();
try {
- RevertedSender cm =
- revertedSenderFactory.create(ctx.getProject(), changeId);
+ RevertedSender cm = revertedSenderFactory.create(ctx.getProject(), changeId);
cm.setFrom(ctx.getAccountId());
cm.setChangeMessage(ins.getChangeMessage().getMessage(), ctx.getWhen());
cm.send();
@@ -273,11 +272,12 @@
public boolean updateChange(ChangeContext ctx) throws Exception {
Change change = ctx.getChange();
PatchSet.Id patchSetId = change.currentPatchSetId();
- ChangeMessage changeMessage = ChangeMessagesUtil.newMessage(ctx,
- "Created a revert of this change as I" + computedChangeId.name(),
- ChangeMessagesUtil.TAG_REVERT);
- cmUtil.addChangeMessage(ctx.getDb(), ctx.getUpdate(patchSetId),
- changeMessage);
+ ChangeMessage changeMessage =
+ ChangeMessagesUtil.newMessage(
+ ctx,
+ "Created a revert of this change as I" + computedChangeId.name(),
+ ChangeMessagesUtil.TAG_REVERT);
+ cmUtil.addChangeMessage(ctx.getDb(), ctx.getUpdate(patchSetId), changeMessage);
return true;
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/Reviewed.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/Reviewed.java
index 997a8f9..0d25d35 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/Reviewed.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/Reviewed.java
@@ -22,12 +22,10 @@
import com.google.inject.Singleton;
public class Reviewed {
- public static class Input {
- }
+ public static class Input {}
@Singleton
- public static class PutReviewed
- implements RestModifyView<FileResource, Input> {
+ public static class PutReviewed implements RestModifyView<FileResource, Input> {
private final DynamicItem<AccountPatchReviewStore> accountPatchReviewStore;
@Inject
@@ -36,11 +34,13 @@
}
@Override
- public Response<String> apply(FileResource resource, Input input)
- throws OrmException {
- if (accountPatchReviewStore.get().markReviewed(
- resource.getPatchKey().getParentKey(), resource.getAccountId(),
- resource.getPatchKey().getFileName())) {
+ public Response<String> apply(FileResource resource, Input input) throws OrmException {
+ if (accountPatchReviewStore
+ .get()
+ .markReviewed(
+ resource.getPatchKey().getParentKey(),
+ resource.getAccountId(),
+ resource.getPatchKey().getFileName())) {
return Response.created("");
}
return Response.ok("");
@@ -48,26 +48,25 @@
}
@Singleton
- public static class DeleteReviewed
- implements RestModifyView<FileResource, Input> {
+ public static class DeleteReviewed implements RestModifyView<FileResource, Input> {
private final DynamicItem<AccountPatchReviewStore> accountPatchReviewStore;
@Inject
- DeleteReviewed(
- DynamicItem<AccountPatchReviewStore> accountPatchReviewStore) {
+ DeleteReviewed(DynamicItem<AccountPatchReviewStore> accountPatchReviewStore) {
this.accountPatchReviewStore = accountPatchReviewStore;
}
@Override
- public Response<?> apply(FileResource resource, Input input)
- throws OrmException {
- accountPatchReviewStore.get().clearReviewed(
- resource.getPatchKey().getParentKey(), resource.getAccountId(),
- resource.getPatchKey().getFileName());
+ public Response<?> apply(FileResource resource, Input input) throws OrmException {
+ accountPatchReviewStore
+ .get()
+ .clearReviewed(
+ resource.getPatchKey().getParentKey(),
+ resource.getAccountId(),
+ resource.getPatchKey().getFileName());
return Response.none();
}
}
- private Reviewed() {
- }
+ private Reviewed() {}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/ReviewerJson.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/ReviewerJson.java
index 69cd439..ac7f15e 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/ReviewerJson.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/ReviewerJson.java
@@ -37,7 +37,6 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.util.Collection;
import java.util.List;
import java.util.TreeMap;
@@ -50,7 +49,8 @@
private final AccountLoader.Factory accountLoaderFactory;
@Inject
- ReviewerJson(Provider<ReviewDb> db,
+ ReviewerJson(
+ Provider<ReviewDb> db,
ChangeData.Factory changeDataFactory,
ApprovalsUtil approvalsUtil,
AccountLoader.Factory accountLoaderFactory) {
@@ -60,14 +60,14 @@
this.accountLoaderFactory = accountLoaderFactory;
}
- public List<ReviewerInfo> format(Collection<ReviewerResource> rsrcs)
- throws OrmException {
+ public List<ReviewerInfo> format(Collection<ReviewerResource> rsrcs) throws OrmException {
List<ReviewerInfo> infos = Lists.newArrayListWithCapacity(rsrcs.size());
AccountLoader loader = accountLoaderFactory.create(true);
for (ReviewerResource rsrc : rsrcs) {
- ReviewerInfo info = format(new ReviewerInfo(
- rsrc.getReviewerUser().getAccountId().get()),
- rsrc.getReviewerControl());
+ ReviewerInfo info =
+ format(
+ new ReviewerInfo(rsrc.getReviewerUser().getAccountId().get()),
+ rsrc.getReviewerControl());
loader.put(info);
infos.add(info);
}
@@ -76,18 +76,20 @@
}
public List<ReviewerInfo> format(ReviewerResource rsrc) throws OrmException {
- return format(ImmutableList.<ReviewerResource> of(rsrc));
+ return format(ImmutableList.<ReviewerResource>of(rsrc));
}
public ReviewerInfo format(ReviewerInfo out, ChangeControl ctl) throws OrmException {
PatchSet.Id psId = ctl.getChange().currentPatchSetId();
- return format(out, ctl,
- approvalsUtil.byPatchSetUser(db.get(), ctl, psId,
- new Account.Id(out._accountId)));
+ return format(
+ out,
+ ctl,
+ approvalsUtil.byPatchSetUser(db.get(), ctl, psId, new Account.Id(out._accountId)));
}
- public ReviewerInfo format(ReviewerInfo out, ChangeControl ctl,
- Iterable<PatchSetApproval> approvals) throws OrmException {
+ public ReviewerInfo format(
+ ReviewerInfo out, ChangeControl ctl, Iterable<PatchSetApproval> approvals)
+ throws OrmException {
LabelTypes labelTypes = ctl.getLabelTypes();
// Don't use Maps.newTreeMap(Comparator) due to OpenJDK bug 100167.
@@ -108,10 +110,8 @@
ChangeData cd = changeDataFactory.create(db.get(), ctl);
PatchSet ps = cd.currentPatchSet();
if (ps != null) {
- for (SubmitRecord rec : new SubmitRuleEvaluator(cd)
- .setFastEvalLabels(true)
- .setAllowDraft(true)
- .evaluate()) {
+ for (SubmitRecord rec :
+ new SubmitRuleEvaluator(cd).setFastEvalLabels(true).setAllowDraft(true).evaluate()) {
if (rec.labels == null) {
continue;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/ReviewerResource.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/ReviewerResource.java
index f362a49..6ff4a50 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/ReviewerResource.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/ReviewerResource.java
@@ -30,6 +30,7 @@
public interface Factory {
ReviewerResource create(ChangeResource change, Account.Id id);
+
ReviewerResource create(RevisionResource revision, Account.Id id);
}
@@ -38,7 +39,8 @@
private final IdentifiedUser user;
@AssistedInject
- ReviewerResource(IdentifiedUser.GenericFactory userFactory,
+ ReviewerResource(
+ IdentifiedUser.GenericFactory userFactory,
@Assisted ChangeResource change,
@Assisted Account.Id id) {
this.change = change;
@@ -47,7 +49,8 @@
}
@AssistedInject
- ReviewerResource(IdentifiedUser.GenericFactory userFactory,
+ ReviewerResource(
+ IdentifiedUser.GenericFactory userFactory,
@Assisted RevisionResource revision,
@Assisted Account.Id id) {
this.revision = revision;
@@ -76,16 +79,16 @@
}
/**
- * @return the control for the caller's user (as opposed to the reviewer's
- * user as returned by {@link #getReviewerControl()}).
+ * @return the control for the caller's user (as opposed to the reviewer's user as returned by
+ * {@link #getReviewerControl()}).
*/
public ChangeControl getControl() {
return change.getControl();
}
/**
- * @return the control for the reviewer's user (as opposed to the caller's
- * user as returned by {@link #getControl()}).
+ * @return the control for the reviewer's user (as opposed to the caller's user as returned by
+ * {@link #getControl()}).
*/
public ChangeControl getReviewerControl() {
return change.getControl().forUser(user);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/ReviewerSuggestion.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/ReviewerSuggestion.java
index 6affd9f..a2dd8b5 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/ReviewerSuggestion.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/ReviewerSuggestion.java
@@ -19,13 +19,12 @@
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.reviewdb.client.Change;
import com.google.gerrit.reviewdb.client.Project;
-
import java.util.Set;
/**
* Listener to provide reviewer suggestions.
- * <p>
- * Invoked by Gerrit a user who is searching for a reviewer to add to a change.
+ *
+ * <p>Invoked by Gerrit a user who is searching for a reviewer to add to a change.
*/
@ExtensionPoint
public interface ReviewerSuggestion {
@@ -36,10 +35,12 @@
* @param changeId The changeId that the suggestion is for. Can be an {@code null}.
* @param query The query as typed by the user. Can be an {@code null}.
* @param candidates A set of candidates for the ranking. Can be empty.
- * @return Set of suggested reviewers as a tuple of account id and score.
- * The account ids listed here don't have to be a part of candidates.
+ * @return Set of suggested reviewers as a tuple of account id and score. The account ids listed
+ * here don't have to be a part of candidates.
*/
- Set<SuggestedReviewer> suggestReviewers(Project.NameKey project,
- @Nullable Change.Id changeId, @Nullable String query,
+ Set<SuggestedReviewer> suggestReviewers(
+ Project.NameKey project,
+ @Nullable Change.Id changeId,
+ @Nullable String query,
Set<Account.Id> candidates);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/Reviewers.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/Reviewers.java
index d45d260..14c74bc 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/Reviewers.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/Reviewers.java
@@ -29,12 +29,10 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.util.Collection;
@Singleton
-public class Reviewers implements
- ChildCollection<ChangeResource, ReviewerResource> {
+public class Reviewers implements ChildCollection<ChangeResource, ReviewerResource> {
private final DynamicMap<RestView<ReviewerResource>> views;
private final Provider<ReviewDb> dbProvider;
private final ApprovalsUtil approvalsUtil;
@@ -43,7 +41,8 @@
private final ListReviewers list;
@Inject
- Reviewers(Provider<ReviewDb> dbProvider,
+ Reviewers(
+ Provider<ReviewDb> dbProvider,
ApprovalsUtil approvalsUtil,
AccountsCollection accounts,
ReviewerResource.Factory resourceFactory,
@@ -70,8 +69,7 @@
@Override
public ReviewerResource parse(ChangeResource rsrc, IdString id)
throws OrmException, ResourceNotFoundException, AuthException {
- Account.Id accountId =
- accounts.parse(TopLevelResource.INSTANCE, id).getUser().getAccountId();
+ Account.Id accountId = accounts.parse(TopLevelResource.INSTANCE, id).getUser().getAccountId();
// See if the id exists as a reviewer for this change
if (fetchAccountIds(rsrc).contains(accountId)) {
@@ -80,9 +78,7 @@
throw new ResourceNotFoundException(id);
}
- private Collection<Account.Id> fetchAccountIds(ChangeResource rsrc)
- throws OrmException {
- return approvalsUtil.getReviewers(
- dbProvider.get(), rsrc.getNotes()).all();
+ private Collection<Account.Id> fetchAccountIds(ChangeResource rsrc) throws OrmException {
+ return approvalsUtil.getReviewers(dbProvider.get(), rsrc.getNotes()).all();
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/RevisionResource.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/RevisionResource.java
index 152563b..4d35f9e 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/RevisionResource.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/RevisionResource.java
@@ -26,7 +26,6 @@
import com.google.gerrit.server.notedb.ChangeNotes;
import com.google.gerrit.server.project.ChangeControl;
import com.google.inject.TypeLiteral;
-
import java.util.Optional;
public class RevisionResource implements RestResource, HasETag {
@@ -42,8 +41,7 @@
this(change, ps, Optional.empty());
}
- public RevisionResource(ChangeResource change, PatchSet ps,
- Optional<ChangeEdit> edit) {
+ public RevisionResource(ChangeResource change, PatchSet ps, Optional<ChangeEdit> edit) {
this.change = change;
this.ps = ps;
this.edit = edit;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/RevisionReviewers.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/RevisionReviewers.java
index 3ad860c..d3623cf 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/RevisionReviewers.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/RevisionReviewers.java
@@ -30,12 +30,10 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.util.Collection;
@Singleton
-public class RevisionReviewers implements
- ChildCollection<RevisionResource, ReviewerResource> {
+public class RevisionReviewers implements ChildCollection<RevisionResource, ReviewerResource> {
private final DynamicMap<RestView<ReviewerResource>> views;
private final Provider<ReviewDb> dbProvider;
private final ApprovalsUtil approvalsUtil;
@@ -44,7 +42,8 @@
private final ListRevisionReviewers list;
@Inject
- RevisionReviewers(Provider<ReviewDb> dbProvider,
+ RevisionReviewers(
+ Provider<ReviewDb> dbProvider,
ApprovalsUtil approvalsUtil,
AccountsCollection accounts,
ReviewerResource.Factory resourceFactory,
@@ -70,18 +69,15 @@
@Override
public ReviewerResource parse(RevisionResource rsrc, IdString id)
- throws OrmException, ResourceNotFoundException, AuthException,
- MethodNotAllowedException {
+ throws OrmException, ResourceNotFoundException, AuthException, MethodNotAllowedException {
if (!rsrc.isCurrent()) {
- throw new MethodNotAllowedException(
- "Cannot access on non-current patch set");
+ throw new MethodNotAllowedException("Cannot access on non-current patch set");
}
- Account.Id accountId =
- accounts.parse(TopLevelResource.INSTANCE, id).getUser().getAccountId();
+ Account.Id accountId = accounts.parse(TopLevelResource.INSTANCE, id).getUser().getAccountId();
- Collection<Account.Id> reviewers = approvalsUtil.getReviewers(
- dbProvider.get(), rsrc.getNotes()).all();
+ Collection<Account.Id> reviewers =
+ approvalsUtil.getReviewers(dbProvider.get(), rsrc.getNotes()).all();
if (reviewers.contains(accountId)) {
return resourceFactory.create(rsrc, accountId);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/Revisions.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/Revisions.java
index 4572994..a16f2f9 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/Revisions.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/Revisions.java
@@ -32,7 +32,6 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
@@ -47,7 +46,8 @@
private final PatchSetUtil psUtil;
@Inject
- Revisions(DynamicMap<RestView<RevisionResource>> views,
+ Revisions(
+ DynamicMap<RestView<RevisionResource>> views,
Provider<ReviewDb> dbProvider,
ChangeEditUtil editUtil,
PatchSetUtil psUtil) {
@@ -69,8 +69,7 @@
@Override
public RevisionResource parse(ChangeResource change, IdString id)
- throws ResourceNotFoundException, AuthException, OrmException,
- IOException {
+ throws ResourceNotFoundException, AuthException, OrmException, IOException {
if (id.equals("current")) {
PatchSet ps = psUtil.current(dbProvider.get(), change.getNotes());
if (ps != null && visible(change, ps)) {
@@ -92,13 +91,11 @@
return match.get(0);
default:
throw new ResourceNotFoundException(
- "Multiple patch sets for \"" + id.get() + "\": "
- + Joiner.on("; ").join(match));
+ "Multiple patch sets for \"" + id.get() + "\": " + Joiner.on("; ").join(match));
}
}
- private boolean visible(ChangeResource change, PatchSet ps)
- throws OrmException {
+ private boolean visible(ChangeResource change, PatchSet ps) throws OrmException {
return change.getControl().isPatchVisible(ps, dbProvider.get());
}
@@ -128,10 +125,13 @@
}
}
- private List<RevisionResource> byLegacyPatchSetId(ChangeResource change,
- String id) throws OrmException {
- PatchSet ps = psUtil.get(dbProvider.get(), change.getNotes(),
- new PatchSet.Id(change.getId(), Integer.parseInt(id)));
+ private List<RevisionResource> byLegacyPatchSetId(ChangeResource change, String id)
+ throws OrmException {
+ PatchSet ps =
+ psUtil.get(
+ dbProvider.get(),
+ change.getNotes(),
+ new PatchSet.Id(change.getId(), Integer.parseInt(id)));
if (ps != null) {
return Collections.singletonList(new RevisionResource(change, ps));
}
@@ -145,8 +145,7 @@
PatchSet ps = new PatchSet(new PatchSet.Id(change.getId(), 0));
ps.setRevision(edit.get().getRevision());
if (revid == null || edit.get().getRevision().equals(revid)) {
- return Collections.singletonList(
- new RevisionResource(change, ps, edit));
+ return Collections.singletonList(new RevisionResource(change, ps, edit));
}
}
return Collections.emptyList();
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/RobotComments.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/RobotComments.java
index 886af1d..d1443af 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/RobotComments.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/RobotComments.java
@@ -27,14 +27,14 @@
import com.google.inject.Singleton;
@Singleton
-public class RobotComments
- implements ChildCollection<RevisionResource, RobotCommentResource> {
+public class RobotComments implements ChildCollection<RevisionResource, RobotCommentResource> {
private final DynamicMap<RestView<RobotCommentResource>> views;
private final ListRobotComments list;
private final CommentsUtil commentsUtil;
@Inject
- RobotComments(DynamicMap<RestView<RobotCommentResource>> views,
+ RobotComments(
+ DynamicMap<RestView<RobotCommentResource>> views,
ListRobotComments list,
CommentsUtil commentsUtil) {
this.views = views;
@@ -58,8 +58,7 @@
String uuid = id.get();
ChangeNotes notes = rev.getNotes();
- for (RobotComment c : commentsUtil.robotCommentsByPatchSet(
- notes, rev.getPatchSet().getId())) {
+ for (RobotComment c : commentsUtil.robotCommentsByPatchSet(notes, rev.getPatchSet().getId())) {
if (uuid.equals(c.key.uuid)) {
return new RobotCommentResource(rev, c);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/SetAssigneeOp.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/SetAssigneeOp.java
index f687400..80e0017 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/SetAssigneeOp.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/SetAssigneeOp.java
@@ -38,13 +38,11 @@
import com.google.inject.Provider;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SetAssigneeOp extends BatchUpdate.Op {
- private static final Logger log =
- LoggerFactory.getLogger(SetAssigneeOp.class);
+ private static final Logger log = LoggerFactory.getLogger(SetAssigneeOp.class);
public interface Factory {
SetAssigneeOp create(String assignee);
@@ -64,7 +62,8 @@
private Account oldAssignee;
@AssistedInject
- SetAssigneeOp(AccountsCollection accounts,
+ SetAssigneeOp(
+ AccountsCollection accounts,
ChangeMessagesUtil cmUtil,
DynamicSet<AssigneeValidationListener> validationListeners,
AssigneeChanged assigneeChanged,
@@ -83,8 +82,7 @@
}
@Override
- public boolean updateChange(BatchUpdate.ChangeContext ctx)
- throws OrmException, RestApiException {
+ public boolean updateChange(BatchUpdate.ChangeContext ctx) throws OrmException, RestApiException {
change = ctx.getChange();
ChangeUpdate update = ctx.getUpdate(change.currentPatchSetId());
IdentifiedUser newAssigneeUser = accounts.parse(assignee);
@@ -98,14 +96,12 @@
}
}
if (!newAssignee.isActive()) {
- throw new UnprocessableEntityException(String.format(
- "Account of %s is not active", assignee));
+ throw new UnprocessableEntityException(
+ String.format("Account of %s is not active", assignee));
}
if (!ctx.getControl().forUser(newAssigneeUser).isRefVisible()) {
- throw new AuthException(String.format(
- "Change %s is not visible to %s.",
- change.getChangeId(),
- assignee));
+ throw new AuthException(
+ String.format("Change %s is not visible to %s.", change.getChangeId(), assignee));
}
try {
for (AssigneeValidationListener validator : validationListeners) {
@@ -122,9 +118,12 @@
return true;
}
- private void addMessage(BatchUpdate.ChangeContext ctx, ChangeUpdate update,
- IdentifiedUser previousAssignee, IdentifiedUser newAssignee)
- throws OrmException {
+ private void addMessage(
+ BatchUpdate.ChangeContext ctx,
+ ChangeUpdate update,
+ IdentifiedUser previousAssignee,
+ IdentifiedUser newAssignee)
+ throws OrmException {
StringBuilder msg = new StringBuilder();
msg.append("Assignee ");
if (previousAssignee == null) {
@@ -136,21 +135,20 @@
msg.append(" to: ");
msg.append(newAssignee.getNameEmail());
}
- ChangeMessage cmsg = ChangeMessagesUtil.newMessage(ctx, msg.toString(),
- ChangeMessagesUtil.TAG_SET_ASSIGNEE);
+ ChangeMessage cmsg =
+ ChangeMessagesUtil.newMessage(ctx, msg.toString(), ChangeMessagesUtil.TAG_SET_ASSIGNEE);
cmUtil.addChangeMessage(ctx.getDb(), update, cmsg);
}
@Override
public void postUpdate(Context ctx) throws OrmException {
try {
- SetAssigneeSender cm = setAssigneeSenderFactory
- .create(change.getProject(), change.getId(), newAssignee.getId());
+ SetAssigneeSender cm =
+ setAssigneeSenderFactory.create(change.getProject(), change.getId(), newAssignee.getId());
cm.setFrom(user.get().getAccountId());
cm.send();
} catch (Exception err) {
- log.error("Cannot send email to new assignee of change " + change.getId(),
- err);
+ log.error("Cannot send email to new assignee of change " + change.getId(), err);
}
assigneeChanged.fire(change, ctx.getAccount(), oldAssignee, ctx.getWhen());
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/SetHashtagsOp.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/SetHashtagsOp.java
index 3b2117d..c266d7e 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/SetHashtagsOp.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/SetHashtagsOp.java
@@ -41,7 +41,6 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
-
import java.io.IOException;
import java.util.Collection;
import java.util.HashSet;
@@ -86,14 +85,12 @@
@Override
public boolean updateChange(ChangeContext ctx)
- throws AuthException, BadRequestException, MethodNotAllowedException,
- OrmException, IOException {
+ throws AuthException, BadRequestException, MethodNotAllowedException, OrmException,
+ IOException {
if (!notesMigration.readChanges()) {
- throw new MethodNotAllowedException(
- "Cannot add hashtags; NoteDb is disabled");
+ throw new MethodNotAllowedException("Cannot add hashtags; NoteDb is disabled");
}
- if (input == null
- || (input.add == null && input.remove == null)) {
+ if (input == null || (input.add == null && input.remove == null)) {
updatedHashtags = ImmutableSortedSet.of();
return false;
}
@@ -131,18 +128,16 @@
return true;
}
- private void addMessage(ChangeContext ctx, ChangeUpdate update)
- throws OrmException {
+ private void addMessage(ChangeContext ctx, ChangeUpdate update) throws OrmException {
StringBuilder msg = new StringBuilder();
appendHashtagMessage(msg, "added", toAdd);
appendHashtagMessage(msg, "removed", toRemove);
- ChangeMessage cmsg = ChangeMessagesUtil.newMessage(ctx, msg.toString(),
- ChangeMessagesUtil.TAG_SET_HASHTAGS);
+ ChangeMessage cmsg =
+ ChangeMessagesUtil.newMessage(ctx, msg.toString(), ChangeMessagesUtil.TAG_SET_HASHTAGS);
cmUtil.addChangeMessage(ctx.getDb(), update, cmsg);
}
- private void appendHashtagMessage(StringBuilder b, String action,
- Set<String> hashtags) {
+ private void appendHashtagMessage(StringBuilder b, String action, Set<String> hashtags) {
if (isNullOrEmpty(hashtags)) {
return;
}
@@ -163,14 +158,13 @@
@Override
public void postUpdate(Context ctx) throws OrmException {
if (updated() && fireEvent) {
- hashtagsEdited.fire(change, ctx.getAccount(), updatedHashtags,
- toAdd, toRemove, ctx.getWhen());
+ hashtagsEdited.fire(
+ change, ctx.getAccount(), updatedHashtags, toAdd, toRemove, ctx.getWhen());
}
}
public ImmutableSortedSet<String> getUpdatedHashtags() {
- checkState(updatedHashtags != null,
- "getUpdatedHashtags() only valid after executing op");
+ checkState(updatedHashtags != null, "getUpdatedHashtags() only valid after executing op");
return updatedHashtags;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/Submit.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/Submit.java
index 654471f..8013d87 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/Submit.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/Submit.java
@@ -60,7 +60,13 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
+import java.io.IOException;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.lib.ObjectId;
@@ -70,38 +76,26 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
@Singleton
-public class Submit implements RestModifyView<RevisionResource, SubmitInput>,
- UiAction<RevisionResource> {
+public class Submit
+ implements RestModifyView<RevisionResource, SubmitInput>, UiAction<RevisionResource> {
private static final Logger log = LoggerFactory.getLogger(Submit.class);
- private static final String DEFAULT_TOOLTIP =
- "Submit patch set ${patchSet} into ${branch}";
+ private static final String DEFAULT_TOOLTIP = "Submit patch set ${patchSet} into ${branch}";
private static final String DEFAULT_TOOLTIP_ANCESTORS =
- "Submit patch set ${patchSet} and ancestors (${submitSize} changes " +
- "altogether) into ${branch}";
+ "Submit patch set ${patchSet} and ancestors (${submitSize} changes "
+ + "altogether) into ${branch}";
private static final String DEFAULT_TOPIC_TOOLTIP =
- "Submit all ${topicSize} changes of the same topic " +
- "(${submitSize} changes including ancestors and other " +
- "changes related by topic)";
+ "Submit all ${topicSize} changes of the same topic "
+ + "(${submitSize} changes including ancestors and other "
+ + "changes related by topic)";
private static final String BLOCKED_SUBMIT_TOOLTIP =
"This change depends on other changes which are not ready";
private static final String BLOCKED_HIDDEN_SUBMIT_TOOLTIP =
"This change depends on other hidden changes which are not ready";
- private static final String CLICK_FAILURE_TOOLTIP =
- "Clicking the button would fail";
- private static final String CHANGE_UNMERGEABLE =
- "Problems with integrating this change";
- private static final String CHANGES_NOT_MERGEABLE =
- "Problems with change(s): ";
+ private static final String CLICK_FAILURE_TOOLTIP = "Clicking the button would fail";
+ private static final String CHANGE_UNMERGEABLE = "Problems with integrating this change";
+ private static final String CHANGES_NOT_MERGEABLE = "Problems with change(s): ";
public static class Output {
transient Change change;
@@ -112,8 +106,8 @@
}
/**
- * Subclass of {@link SubmitInput} with special bits that may be flipped for
- * testing purposes only.
+ * Subclass of {@link SubmitInput} with special bits that may be flipped for testing purposes
+ * only.
*/
@VisibleForTesting
public static class TestSubmitInput extends SubmitInput {
@@ -146,7 +140,8 @@
private final PatchSetUtil psUtil;
@Inject
- Submit(Provider<ReviewDb> dbProvider,
+ Submit(
+ Provider<ReviewDb> dbProvider,
GitRepositoryManager repoManager,
ChangeData.Factory changeDataFactory,
ChangeMessagesUtil cmUtil,
@@ -167,35 +162,38 @@
this.mergeSuperSet = mergeSuperSet;
this.accounts = accounts;
this.changes = changes;
- this.label = MoreObjects.firstNonNull(
- Strings.emptyToNull(cfg.getString("change", null, "submitLabel")),
- "Submit");
- this.labelWithParents = MoreObjects.firstNonNull(
- Strings.emptyToNull(
- cfg.getString("change", null, "submitLabelWithParents")),
- "Submit including parents");
- this.titlePattern = new ParameterizedString(MoreObjects.firstNonNull(
- cfg.getString("change", null, "submitTooltip"),
- DEFAULT_TOOLTIP));
- this.titlePatternWithAncestors = new ParameterizedString(
+ this.label =
MoreObjects.firstNonNull(
- cfg.getString("change", null, "submitTooltipAncestors"),
- DEFAULT_TOOLTIP_ANCESTORS));
+ Strings.emptyToNull(cfg.getString("change", null, "submitLabel")), "Submit");
+ this.labelWithParents =
+ MoreObjects.firstNonNull(
+ Strings.emptyToNull(cfg.getString("change", null, "submitLabelWithParents")),
+ "Submit including parents");
+ this.titlePattern =
+ new ParameterizedString(
+ MoreObjects.firstNonNull(
+ cfg.getString("change", null, "submitTooltip"), DEFAULT_TOOLTIP));
+ this.titlePatternWithAncestors =
+ new ParameterizedString(
+ MoreObjects.firstNonNull(
+ cfg.getString("change", null, "submitTooltipAncestors"),
+ DEFAULT_TOOLTIP_ANCESTORS));
submitWholeTopic = wholeTopicEnabled(cfg);
- this.submitTopicLabel = MoreObjects.firstNonNull(
- Strings.emptyToNull(cfg.getString("change", null, "submitTopicLabel")),
- "Submit whole topic");
- this.submitTopicTooltip = new ParameterizedString(MoreObjects.firstNonNull(
- cfg.getString("change", null, "submitTopicTooltip"),
- DEFAULT_TOPIC_TOOLTIP));
+ this.submitTopicLabel =
+ MoreObjects.firstNonNull(
+ Strings.emptyToNull(cfg.getString("change", null, "submitTopicLabel")),
+ "Submit whole topic");
+ this.submitTopicTooltip =
+ new ParameterizedString(
+ MoreObjects.firstNonNull(
+ cfg.getString("change", null, "submitTopicTooltip"), DEFAULT_TOPIC_TOOLTIP));
this.queryProvider = queryProvider;
this.psUtil = psUtil;
}
@Override
public Output apply(RevisionResource rsrc, SubmitInput input)
- throws RestApiException, RepositoryNotFoundException, IOException,
- OrmException {
+ throws RestApiException, RepositoryNotFoundException, IOException, OrmException {
input.onBehalfOf = Strings.emptyToNull(input.onBehalfOf);
if (input.onBehalfOf != null) {
rsrc = onBehalfOf(rsrc, input);
@@ -208,22 +206,21 @@
} else if (!change.getStatus().isOpen()) {
throw new ResourceConflictException("change is " + status(change));
} else if (!ProjectUtil.branchExists(repoManager, change.getDest())) {
- throw new ResourceConflictException(String.format(
- "destination branch \"%s\" not found.",
- change.getDest().get()));
+ throw new ResourceConflictException(
+ String.format("destination branch \"%s\" not found.", change.getDest().get()));
} else if (!rsrc.getPatchSet().getId().equals(change.currentPatchSetId())) {
// TODO Allow submitting non-current revision by changing the current.
- throw new ResourceConflictException(String.format(
- "revision %s is not current revision",
- rsrc.getPatchSet().getRevision().get()));
+ throw new ResourceConflictException(
+ String.format(
+ "revision %s is not current revision", rsrc.getPatchSet().getRevision().get()));
}
try (MergeOp op = mergeOpProvider.get()) {
ReviewDb db = dbProvider.get();
op.merge(db, change, caller, true, input, false);
try {
- change = changeNotesFactory
- .createChecked(db, change.getProject(), change.getId()).getChange();
+ change =
+ changeNotesFactory.createChecked(db, change.getProject(), change.getId()).getChange();
} catch (NoSuchChangeException e) {
throw new ResourceConflictException("change is deleted");
}
@@ -251,8 +248,7 @@
* @param user the user who is checking to submit
* @return a reason why any of the changes is not submittable or null
*/
- private String problemsForSubmittingChangeset(ChangeData cd, ChangeSet cs,
- CurrentUser user) {
+ private String problemsForSubmittingChangeset(ChangeData cd, ChangeSet cs, CurrentUser user) {
try {
@SuppressWarnings("resource")
ReviewDb db = dbProvider.get();
@@ -280,10 +276,8 @@
return CHANGE_UNMERGEABLE;
}
}
- return CHANGES_NOT_MERGEABLE +
- unmergeable.stream()
- .map(c -> c.getId().toString())
- .collect(joining(", "));
+ return CHANGES_NOT_MERGEABLE
+ + unmergeable.stream().map(c -> c.getId().toString()).collect(joining(", "));
}
} catch (ResourceConflictException e) {
return BLOCKED_SUBMIT_TOOLTIP;
@@ -298,10 +292,11 @@
public UiAction.Description getDescription(RevisionResource resource) {
PatchSet.Id current = resource.getChange().currentPatchSetId();
String topic = resource.getChange().getTopic();
- boolean visible = !resource.getPatchSet().isDraft()
- && resource.getChange().getStatus().isOpen()
- && resource.getPatchSet().getId().equals(current)
- && resource.getControl().canSubmit();
+ boolean visible =
+ !resource.getPatchSet().isDraft()
+ && resource.getChange().getStatus().isOpen()
+ && resource.getPatchSet().getId().equals(current)
+ && resource.getControl().canSubmit();
ReviewDb db = dbProvider.get();
ChangeData cd = changeDataFactory.create(db, resource.getControl());
@@ -315,31 +310,24 @@
}
if (!visible) {
- return new UiAction.Description()
- .setLabel("")
- .setTitle("")
- .setVisible(false);
+ return new UiAction.Description().setLabel("").setTitle("").setVisible(false);
}
ChangeSet cs;
try {
- cs = mergeSuperSet.get().completeChangeSet(
- db, cd.change(), resource.getControl().getUser());
+ cs = mergeSuperSet.get().completeChangeSet(db, cd.change(), resource.getControl().getUser());
} catch (OrmException | IOException e) {
- throw new OrmRuntimeException("Could not determine complete set of " +
- "changes to be submitted", e);
+ throw new OrmRuntimeException(
+ "Could not determine complete set of " + "changes to be submitted", e);
}
int topicSize = 0;
if (!Strings.isNullOrEmpty(topic)) {
topicSize = getChangesByTopic(topic).size();
}
- boolean treatWithTopic = submitWholeTopic
- && !Strings.isNullOrEmpty(topic)
- && topicSize > 1;
+ boolean treatWithTopic = submitWholeTopic && !Strings.isNullOrEmpty(topic) && topicSize > 1;
- String submitProblems =
- problemsForSubmittingChangeset(cd, cs, resource.getUser());
+ String submitProblems = problemsForSubmittingChangeset(cd, cs, resource.getUser());
Boolean enabled;
try {
@@ -358,50 +346,45 @@
if (submitProblems != null) {
return new UiAction.Description()
- .setLabel(treatWithTopic
- ? submitTopicLabel : (cs.size() > 1)
- ? labelWithParents : label)
- .setTitle(submitProblems)
- .setVisible(true)
- .setEnabled(false);
+ .setLabel(treatWithTopic ? submitTopicLabel : (cs.size() > 1) ? labelWithParents : label)
+ .setTitle(submitProblems)
+ .setVisible(true)
+ .setEnabled(false);
}
if (treatWithTopic) {
- Map<String, String> params = ImmutableMap.of(
- "topicSize", String.valueOf(topicSize),
- "submitSize", String.valueOf(cs.size()));
+ Map<String, String> params =
+ ImmutableMap.of(
+ "topicSize", String.valueOf(topicSize),
+ "submitSize", String.valueOf(cs.size()));
return new UiAction.Description()
.setLabel(submitTopicLabel)
- .setTitle(Strings.emptyToNull(
- submitTopicTooltip.replace(params)))
+ .setTitle(Strings.emptyToNull(submitTopicTooltip.replace(params)))
.setVisible(true)
.setEnabled(Boolean.TRUE.equals(enabled));
}
RevId revId = resource.getPatchSet().getRevision();
- Map<String, String> params = ImmutableMap.of(
- "patchSet", String.valueOf(resource.getPatchSet().getPatchSetId()),
- "branch", resource.getChange().getDest().getShortName(),
- "commit", ObjectId.fromString(revId.get()).abbreviate(7).name(),
- "submitSize", String.valueOf(cs.size()));
- ParameterizedString tp = cs.size() > 1 ? titlePatternWithAncestors :
- titlePattern;
+ Map<String, String> params =
+ ImmutableMap.of(
+ "patchSet", String.valueOf(resource.getPatchSet().getPatchSetId()),
+ "branch", resource.getChange().getDest().getShortName(),
+ "commit", ObjectId.fromString(revId.get()).abbreviate(7).name(),
+ "submitSize", String.valueOf(cs.size()));
+ ParameterizedString tp = cs.size() > 1 ? titlePatternWithAncestors : titlePattern;
return new UiAction.Description()
- .setLabel(cs.size() > 1 ? labelWithParents : label)
- .setTitle(Strings.emptyToNull(tp.replace(params)))
- .setVisible(true)
- .setEnabled(Boolean.TRUE.equals(enabled));
+ .setLabel(cs.size() > 1 ? labelWithParents : label)
+ .setTitle(Strings.emptyToNull(tp.replace(params)))
+ .setVisible(true)
+ .setEnabled(Boolean.TRUE.equals(enabled));
}
/**
- * If the merge was attempted and it failed the system usually writes a
- * comment as a ChangeMessage and sets status to NEW. Find the relevant
- * message and return it.
+ * If the merge was attempted and it failed the system usually writes a comment as a ChangeMessage
+ * and sets status to NEW. Find the relevant message and return it.
*/
- public ChangeMessage getConflictMessage(RevisionResource rsrc)
- throws OrmException {
+ public ChangeMessage getConflictMessage(RevisionResource rsrc) throws OrmException {
return FluentIterable.from(
- cmUtil.byPatchSet(
- dbProvider.get(), rsrc.getNotes(), rsrc.getPatchSet().getId()))
+ cmUtil.byPatchSet(dbProvider.get(), rsrc.getNotes(), rsrc.getPatchSet().getId()))
.filter(cm -> cm.getAuthor() == null)
.last()
.orNull();
@@ -411,8 +394,7 @@
return change != null ? change.getStatus().name().toLowerCase() : "deleted";
}
- public Collection<ChangeData> unmergeableChanges(ChangeSet cs)
- throws OrmException, IOException {
+ public Collection<ChangeData> unmergeableChanges(ChangeSet cs) throws OrmException, IOException {
Set<ChangeData> mergeabilityMap = new HashSet<>();
for (ChangeData change : cs.changes()) {
mergeabilityMap.add(change);
@@ -421,8 +403,7 @@
ListMultimap<Branch.NameKey, ChangeData> cbb = cs.changesByBranch();
for (Branch.NameKey branch : cbb.keySet()) {
Collection<ChangeData> targetBranch = cbb.get(branch);
- HashMap<Change.Id, RevCommit> commits =
- findCommits(targetBranch, branch.getParentKey());
+ HashMap<Change.Id, RevCommit> commits = findCommits(targetBranch, branch.getParentKey());
Set<ObjectId> allParents = Sets.newHashSetWithExpectedSize(cs.size());
for (RevCommit commit : commits.values()) {
@@ -462,14 +443,15 @@
}
private HashMap<Change.Id, RevCommit> findCommits(
- Collection<ChangeData> changes, Project.NameKey project)
- throws IOException, OrmException {
+ Collection<ChangeData> changes, Project.NameKey project) throws IOException, OrmException {
HashMap<Change.Id, RevCommit> commits = new HashMap<>();
try (Repository repo = repoManager.openRepository(project);
RevWalk walk = new RevWalk(repo)) {
for (ChangeData change : changes) {
- RevCommit commit = walk.parseCommit(ObjectId.fromString(
- psUtil.current(dbProvider.get(), change.notes()).getRevision().get()));
+ RevCommit commit =
+ walk.parseCommit(
+ ObjectId.fromString(
+ psUtil.current(dbProvider.get(), change.notes()).getRevision().get()));
commits.put(change.getId(), commit);
}
}
@@ -485,18 +467,19 @@
if (!caller.canSubmitAs()) {
throw new AuthException("submit on behalf of not permitted");
}
- ChangeControl target = caller.forUser(
- accounts.parseOnBehalfOf(caller.getUser(), in.onBehalfOf));
+ ChangeControl target =
+ caller.forUser(accounts.parseOnBehalfOf(caller.getUser(), in.onBehalfOf));
if (!target.getRefControl().isVisible()) {
- throw new UnprocessableEntityException(String.format(
- "on_behalf_of account %s cannot see destination ref",
- target.getUser().getAccountId()));
+ throw new UnprocessableEntityException(
+ String.format(
+ "on_behalf_of account %s cannot see destination ref",
+ target.getUser().getAccountId()));
}
return new RevisionResource(changes.parse(target), rsrc.getPatchSet());
}
public static boolean wholeTopicEnabled(Config config) {
- return config.getBoolean("change", null, "submitWholeTopic" , false);
+ return config.getBoolean("change", null, "submitWholeTopic", false);
}
private List<ChangeData> getChangesByTopic(String topic) {
@@ -507,15 +490,15 @@
}
}
- public static class CurrentRevision implements
- RestModifyView<ChangeResource, SubmitInput> {
+ public static class CurrentRevision implements RestModifyView<ChangeResource, SubmitInput> {
private final Provider<ReviewDb> dbProvider;
private final Submit submit;
private final ChangeJson.Factory json;
private final PatchSetUtil psUtil;
@Inject
- CurrentRevision(Provider<ReviewDb> dbProvider,
+ CurrentRevision(
+ Provider<ReviewDb> dbProvider,
Submit submit,
ChangeJson.Factory json,
PatchSetUtil psUtil) {
@@ -527,8 +510,7 @@
@Override
public ChangeInfo apply(ChangeResource rsrc, SubmitInput input)
- throws RestApiException, RepositoryNotFoundException, IOException,
- OrmException {
+ throws RestApiException, RepositoryNotFoundException, IOException, OrmException {
PatchSet ps = psUtil.current(dbProvider.get(), rsrc.getNotes());
if (ps == null) {
throw new ResourceConflictException("current revision is missing");
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/SubmittedTogether.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/SubmittedTogether.java
index 23e7d8b..568b50a 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/SubmittedTogether.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/SubmittedTogether.java
@@ -34,28 +34,26 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
-
-import org.kohsuke.args4j.Option;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
+import org.kohsuke.args4j.Option;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class SubmittedTogether implements RestReadView<ChangeResource> {
- private static final Logger log = LoggerFactory.getLogger(
- SubmittedTogether.class);
+ private static final Logger log = LoggerFactory.getLogger(SubmittedTogether.class);
private final EnumSet<SubmittedTogetherOption> options =
EnumSet.noneOf(SubmittedTogetherOption.class);
- private final EnumSet<ListChangesOption> jsonOpt = EnumSet.of(
- ListChangesOption.CURRENT_REVISION,
- ListChangesOption.CURRENT_COMMIT,
- ListChangesOption.SUBMITTABLE);
+ private final EnumSet<ListChangesOption> jsonOpt =
+ EnumSet.of(
+ ListChangesOption.CURRENT_REVISION,
+ ListChangesOption.CURRENT_COMMIT,
+ ListChangesOption.SUBMITTABLE);
private final ChangeJson.Factory json;
private final Provider<ReviewDb> dbProvider;
@@ -83,7 +81,8 @@
}
@Inject
- SubmittedTogether(ChangeJson.Factory json,
+ SubmittedTogether(
+ ChangeJson.Factory json,
Provider<ReviewDb> dbProvider,
Provider<InternalChangeQuery> queryProvider,
Provider<MergeSuperSet> mergeSuperSet,
@@ -100,16 +99,15 @@
return this;
}
- public SubmittedTogether addSubmittedTogetherOption(
- EnumSet<SubmittedTogetherOption> o) {
+ public SubmittedTogether addSubmittedTogetherOption(EnumSet<SubmittedTogetherOption> o) {
options.addAll(o);
return this;
}
@Override
public Object apply(ChangeResource resource)
- throws AuthException, BadRequestException,
- ResourceConflictException, IOException, OrmException {
+ throws AuthException, BadRequestException, ResourceConflictException, IOException,
+ OrmException {
SubmittedTogetherInfo info = applyInfo(resource);
if (options.isEmpty()) {
return info.changes;
@@ -126,8 +124,9 @@
if (c.getStatus().isOpen()) {
ChangeSet cs =
- mergeSuperSet.get().completeChangeSet(
- dbProvider.get(), c, resource.getControl().getUser());
+ mergeSuperSet
+ .get()
+ .completeChangeSet(dbProvider.get(), c, resource.getControl().getUser());
cds = cs.changes().asList();
hidden = cs.nonVisibleChanges().size();
} else if (c.getStatus().asChangeStatus() == ChangeStatus.MERGED) {
@@ -138,10 +137,8 @@
hidden = 0;
}
- if (hidden != 0
- && !options.contains(NON_VISIBLE_CHANGES)) {
- throw new AuthException(
- "change would be submitted with a change that you cannot see");
+ if (hidden != 0 && !options.contains(NON_VISIBLE_CHANGES)) {
+ throw new AuthException("change would be submitted with a change that you cannot see");
}
if (cds.size() <= 1 && hidden == 0) {
@@ -162,8 +159,7 @@
}
}
- private List<ChangeData> sort(List<ChangeData> cds)
- throws OrmException, IOException {
+ private List<ChangeData> sort(List<ChangeData> cds) throws OrmException, IOException {
List<ChangeData> sorted = new ArrayList<>(cds.size());
for (PatchSetData psd : sorter.get().sort(cds)) {
sorted.add(psd.data());
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/SuggestChangeReviewers.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/SuggestChangeReviewers.java
index 0753769..5260730 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/SuggestChangeReviewers.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/SuggestChangeReviewers.java
@@ -30,24 +30,26 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
-
-import org.eclipse.jgit.lib.Config;
-import org.kohsuke.args4j.Option;
-
import java.io.IOException;
import java.util.List;
+import org.eclipse.jgit.lib.Config;
+import org.kohsuke.args4j.Option;
public class SuggestChangeReviewers extends SuggestReviewers
implements RestReadView<ChangeResource> {
- @Option(name = "--exclude-groups", aliases = {"-e"},
- usage = "exclude groups from query")
+ @Option(
+ name = "--exclude-groups",
+ aliases = {"-e"},
+ usage = "exclude groups from query"
+ )
boolean excludeGroups;
private final Provider<CurrentUser> self;
@Inject
- SuggestChangeReviewers(AccountVisibility av,
+ SuggestChangeReviewers(
+ AccountVisibility av,
GenericFactory identifiedUserFactory,
Provider<ReviewDb> dbProvider,
Provider<CurrentUser> self,
@@ -63,8 +65,12 @@
if (!self.get().isIdentifiedUser()) {
throw new AuthException("Authentication required");
}
- return reviewersUtil.suggestReviewers(rsrc.getNotes(), this,
- rsrc.getControl().getProjectControl(), getVisibility(rsrc), excludeGroups);
+ return reviewersUtil.suggestReviewers(
+ rsrc.getNotes(),
+ this,
+ rsrc.getControl().getProjectControl(),
+ getVisibility(rsrc),
+ excludeGroups);
}
private VisibilityControl getVisibility(final ChangeResource rsrc) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/SuggestReviewers.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/SuggestReviewers.java
index 2af1f6b..47fb513 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/SuggestReviewers.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/SuggestReviewers.java
@@ -21,7 +21,6 @@
import com.google.gerrit.server.config.GerritServerConfig;
import com.google.inject.Inject;
import com.google.inject.Provider;
-
import org.eclipse.jgit.lib.Config;
import org.kohsuke.args4j.Option;
@@ -39,16 +38,22 @@
protected String query;
protected final int maxSuggestedReviewers;
- @Option(name = "--limit", aliases = {"-n"}, metaVar = "CNT",
- usage = "maximum number of reviewers to list")
+ @Option(
+ name = "--limit",
+ aliases = {"-n"},
+ metaVar = "CNT",
+ usage = "maximum number of reviewers to list"
+ )
public void setLimit(int l) {
- this.limit =
- l <= 0 ? maxSuggestedReviewers : Math.min(l,
- maxSuggestedReviewers);
+ this.limit = l <= 0 ? maxSuggestedReviewers : Math.min(l, maxSuggestedReviewers);
}
- @Option(name = "--query", aliases = {"-q"}, metaVar = "QUERY",
- usage = "match reviewers query")
+ @Option(
+ name = "--query",
+ aliases = {"-q"},
+ metaVar = "QUERY",
+ usage = "match reviewers query"
+ )
public void setQuery(String q) {
this.query = q;
}
@@ -74,7 +79,8 @@
}
@Inject
- public SuggestReviewers(AccountVisibility av,
+ public SuggestReviewers(
+ AccountVisibility av,
IdentifiedUser.GenericFactory identifiedUserFactory,
Provider<ReviewDb> dbProvider,
@GerritServerConfig Config cfg,
@@ -86,17 +92,17 @@
cfg.getInt("suggest", "maxSuggestedReviewers", DEFAULT_MAX_SUGGESTED);
this.limit = this.maxSuggestedReviewers;
String suggest = cfg.getString("suggest", null, "accounts");
- if ("OFF".equalsIgnoreCase(suggest)
- || "false".equalsIgnoreCase(suggest)) {
+ if ("OFF".equalsIgnoreCase(suggest) || "false".equalsIgnoreCase(suggest)) {
this.suggestAccounts = false;
} else {
this.suggestAccounts = (av != AccountVisibility.NONE);
}
- this.maxAllowed = cfg.getInt("addreviewer", "maxAllowed",
- PostReviewers.DEFAULT_MAX_REVIEWERS);
- this.maxAllowedWithoutConfirmation = cfg.getInt(
- "addreviewer", "maxWithoutConfirmation",
- PostReviewers.DEFAULT_MAX_REVIEWERS_WITHOUT_CHECK);
+ this.maxAllowed = cfg.getInt("addreviewer", "maxAllowed", PostReviewers.DEFAULT_MAX_REVIEWERS);
+ this.maxAllowedWithoutConfirmation =
+ cfg.getInt(
+ "addreviewer",
+ "maxWithoutConfirmation",
+ PostReviewers.DEFAULT_MAX_REVIEWERS_WITHOUT_CHECK);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/TestSubmitRule.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/TestSubmitRule.java
index 45d9669..524f4d6 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/TestSubmitRule.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/TestSubmitRule.java
@@ -30,15 +30,12 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
-
-import org.kohsuke.args4j.Option;
-
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
+import org.kohsuke.args4j.Option;
-public class TestSubmitRule
- implements RestModifyView<RevisionResource, TestSubmitRuleInput> {
+public class TestSubmitRule implements RestModifyView<RevisionResource, TestSubmitRuleInput> {
private final Provider<ReviewDb> db;
private final ChangeData.Factory changeDataFactory;
private final RulesCache rules;
@@ -48,7 +45,8 @@
private Filters filters = Filters.RUN;
@Inject
- TestSubmitRule(Provider<ReviewDb> db,
+ TestSubmitRule(
+ Provider<ReviewDb> db,
ChangeData.Factory changeDataFactory,
RulesCache rules,
AccountLoader.Factory infoFactory) {
@@ -68,14 +66,16 @@
throw new AuthException("project rules are disabled");
}
input.filters = MoreObjects.firstNonNull(input.filters, filters);
- SubmitRuleEvaluator evaluator = new SubmitRuleEvaluator(
- changeDataFactory.create(db.get(), rsrc.getControl()));
+ SubmitRuleEvaluator evaluator =
+ new SubmitRuleEvaluator(changeDataFactory.create(db.get(), rsrc.getControl()));
- List<SubmitRecord> records = evaluator.setPatchSet(rsrc.getPatchSet())
- .setLogErrors(false)
- .setSkipSubmitFilters(input.filters == Filters.SKIP)
- .setRule(input.rule)
- .evaluate();
+ List<SubmitRecord> records =
+ evaluator
+ .setPatchSet(rsrc.getPatchSet())
+ .setLogErrors(false)
+ .setSkipSubmitFilters(input.filters == Filters.SKIP)
+ .setRule(input.rule)
+ .evaluate();
List<Record> out = Lists.newArrayListWithCapacity(records.size());
AccountLoader accounts = accountInfoFactory.create(true);
for (SubmitRecord r : records) {
@@ -104,9 +104,7 @@
if (r.labels != null) {
for (SubmitRecord.Label n : r.labels) {
- AccountInfo who = n.appliedBy != null
- ? accounts.get(n.appliedBy)
- : new AccountInfo(null);
+ AccountInfo who = n.appliedBy != null ? accounts.get(n.appliedBy) : new AccountInfo(null);
label(n, who);
}
}
@@ -148,6 +146,5 @@
}
}
- static class None {
- }
+ static class None {}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/TestSubmitType.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/TestSubmitType.java
index 4855012..b19f1d1 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/TestSubmitType.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/TestSubmitType.java
@@ -30,11 +30,9 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
-
import org.kohsuke.args4j.Option;
-public class TestSubmitType
- implements RestModifyView<RevisionResource, TestSubmitRuleInput> {
+public class TestSubmitType implements RestModifyView<RevisionResource, TestSubmitRuleInput> {
private final Provider<ReviewDb> db;
private final ChangeData.Factory changeDataFactory;
private final RulesCache rules;
@@ -43,9 +41,7 @@
private Filters filters = Filters.RUN;
@Inject
- TestSubmitType(Provider<ReviewDb> db,
- ChangeData.Factory changeDataFactory,
- RulesCache rules) {
+ TestSubmitType(Provider<ReviewDb> db, ChangeData.Factory changeDataFactory, RulesCache rules) {
this.db = db;
this.changeDataFactory = changeDataFactory;
this.rules = rules;
@@ -61,18 +57,19 @@
throw new AuthException("project rules are disabled");
}
input.filters = MoreObjects.firstNonNull(input.filters, filters);
- SubmitRuleEvaluator evaluator = new SubmitRuleEvaluator(
- changeDataFactory.create(db.get(), rsrc.getControl()));
+ SubmitRuleEvaluator evaluator =
+ new SubmitRuleEvaluator(changeDataFactory.create(db.get(), rsrc.getControl()));
- SubmitTypeRecord rec = evaluator.setPatchSet(rsrc.getPatchSet())
- .setLogErrors(false)
- .setSkipSubmitFilters(input.filters == Filters.SKIP)
- .setRule(input.rule)
- .getSubmitType();
+ SubmitTypeRecord rec =
+ evaluator
+ .setPatchSet(rsrc.getPatchSet())
+ .setLogErrors(false)
+ .setSkipSubmitFilters(input.filters == Filters.SKIP)
+ .setRule(input.rule)
+ .getSubmitType();
if (rec.status != SubmitTypeRecord.Status.OK) {
- throw new BadRequestException(String.format(
- "rule %s produced invalid result: %s",
- evaluator.getSubmitRuleName(), rec));
+ throw new BadRequestException(
+ String.format("rule %s produced invalid result: %s", evaluator.getSubmitRuleName(), rec));
}
return rec.type;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/Votes.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/Votes.java
index 78cdf75..b2ca405 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/Votes.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/Votes.java
@@ -29,7 +29,6 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.util.Map;
import java.util.TreeMap;
@@ -39,8 +38,7 @@
private final List list;
@Inject
- Votes(DynamicMap<RestView<VoteResource>> views,
- List list) {
+ Votes(DynamicMap<RestView<VoteResource>> views, List list) {
this.views = views;
this.list = list;
}
@@ -57,12 +55,9 @@
@Override
public VoteResource parse(ReviewerResource reviewer, IdString id)
- throws ResourceNotFoundException, OrmException, AuthException,
- MethodNotAllowedException {
- if (reviewer.getRevisionResource() != null
- && !reviewer.getRevisionResource().isCurrent()) {
- throw new MethodNotAllowedException(
- "Cannot access on non-current patch set");
+ throws ResourceNotFoundException, OrmException, AuthException, MethodNotAllowedException {
+ if (reviewer.getRevisionResource() != null && !reviewer.getRevisionResource().isCurrent()) {
+ throw new MethodNotAllowedException("Cannot access on non-current patch set");
}
return new VoteResource(reviewer, id.get());
}
@@ -73,8 +68,7 @@
private final ApprovalsUtil approvalsUtil;
@Inject
- List(Provider<ReviewDb> db,
- ApprovalsUtil approvalsUtil) {
+ List(Provider<ReviewDb> db, ApprovalsUtil approvalsUtil) {
this.db = db;
this.approvalsUtil = approvalsUtil;
}
@@ -82,18 +76,17 @@
@Override
public Map<String, Short> apply(ReviewerResource rsrc)
throws OrmException, MethodNotAllowedException {
- if (rsrc.getRevisionResource() != null
- && !rsrc.getRevisionResource().isCurrent()) {
- throw new MethodNotAllowedException(
- "Cannot list votes on non-current patch set");
+ if (rsrc.getRevisionResource() != null && !rsrc.getRevisionResource().isCurrent()) {
+ throw new MethodNotAllowedException("Cannot list votes on non-current patch set");
}
Map<String, Short> votes = new TreeMap<>();
- Iterable<PatchSetApproval> byPatchSetUser = approvalsUtil.byPatchSetUser(
- db.get(),
- rsrc.getControl(),
- rsrc.getChange().currentPatchSetId(),
- rsrc.getReviewerUser().getAccountId());
+ Iterable<PatchSetApproval> byPatchSetUser =
+ approvalsUtil.byPatchSetUser(
+ db.get(),
+ rsrc.getControl(),
+ rsrc.getChange().currentPatchSetId(),
+ rsrc.getReviewerUser().getAccountId());
for (PatchSetApproval psa : byPatchSetUser) {
votes.put(psa.getLabel(), psa.getValue());
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/WalkSorter.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/WalkSorter.java
index e0113b2..56d7ec0 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/WalkSorter.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/WalkSorter.java
@@ -29,17 +29,6 @@
import com.google.gerrit.server.query.change.ChangeData;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
-
-import org.eclipse.jgit.errors.IncorrectObjectTypeException;
-import org.eclipse.jgit.errors.MissingObjectException;
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.lib.Repository;
-import org.eclipse.jgit.revwalk.RevCommit;
-import org.eclipse.jgit.revwalk.RevFlag;
-import org.eclipse.jgit.revwalk.RevWalk;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.io.IOException;
import java.util.ArrayDeque;
import java.util.ArrayList;
@@ -50,38 +39,46 @@
import java.util.List;
import java.util.Map;
import java.util.Set;
+import org.eclipse.jgit.errors.IncorrectObjectTypeException;
+import org.eclipse.jgit.errors.MissingObjectException;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.lib.Repository;
+import org.eclipse.jgit.revwalk.RevCommit;
+import org.eclipse.jgit.revwalk.RevFlag;
+import org.eclipse.jgit.revwalk.RevWalk;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* Helper to sort {@link ChangeData}s based on {@link RevWalk} ordering.
- * <p>
- * Split changes by project, and map each change to a single commit based on the
- * latest patch set. The set of patch sets considered may be limited by calling
- * {@link #includePatchSets(Iterable)}. Perform a standard {@link RevWalk} on
- * each project repository, do an approximate topo sort, and record the order in
- * which each change's commit is seen.
- * <p>
- * Once an order within each project is determined, groups of changes are sorted
- * based on the project name. This is slightly more stable than sorting on
- * something like the commit or change timestamp, as it will not unexpectedly
- * reorder large groups of changes on subsequent calls if one of the changes was
- * updated.
+ *
+ * <p>Split changes by project, and map each change to a single commit based on the latest patch
+ * set. The set of patch sets considered may be limited by calling {@link
+ * #includePatchSets(Iterable)}. Perform a standard {@link RevWalk} on each project repository, do
+ * an approximate topo sort, and record the order in which each change's commit is seen.
+ *
+ * <p>Once an order within each project is determined, groups of changes are sorted based on the
+ * project name. This is slightly more stable than sorting on something like the commit or change
+ * timestamp, as it will not unexpectedly reorder large groups of changes on subsequent calls if one
+ * of the changes was updated.
*/
class WalkSorter {
- private static final Logger log =
- LoggerFactory.getLogger(WalkSorter.class);
+ private static final Logger log = LoggerFactory.getLogger(WalkSorter.class);
private static final Ordering<List<PatchSetData>> PROJECT_LIST_SORTER =
- Ordering.natural().nullsFirst().onResultOf(
- (List<PatchSetData> in) -> {
- if (in == null || in.isEmpty()) {
- return null;
- }
- try {
- return in.get(0).data().change().getProject();
- } catch (OrmException e) {
- throw new IllegalStateException(e);
- }
- });
+ Ordering.natural()
+ .nullsFirst()
+ .onResultOf(
+ (List<PatchSetData> in) -> {
+ if (in == null || in.isEmpty()) {
+ return null;
+ }
+ try {
+ return in.get(0).data().change().getProject();
+ } catch (OrmException e) {
+ throw new IllegalStateException(e);
+ }
+ });
private final GitRepositoryManager repoManager;
private final Set<PatchSet.Id> includePatchSets;
@@ -103,26 +100,23 @@
return this;
}
- public Iterable<PatchSetData> sort(Iterable<ChangeData> in)
- throws OrmException, IOException {
+ public Iterable<PatchSetData> sort(Iterable<ChangeData> in) throws OrmException, IOException {
ListMultimap<Project.NameKey, ChangeData> byProject =
MultimapBuilder.hashKeys().arrayListValues().build();
for (ChangeData cd : in) {
byProject.put(cd.change().getProject(), cd);
}
- List<List<PatchSetData>> sortedByProject =
- new ArrayList<>(byProject.keySet().size());
- for (Map.Entry<Project.NameKey, Collection<ChangeData>> e
- : byProject.asMap().entrySet()) {
+ List<List<PatchSetData>> sortedByProject = new ArrayList<>(byProject.keySet().size());
+ for (Map.Entry<Project.NameKey, Collection<ChangeData>> e : byProject.asMap().entrySet()) {
sortedByProject.add(sortProject(e.getKey(), e.getValue()));
}
Collections.sort(sortedByProject, PROJECT_LIST_SORTER);
return Iterables.concat(sortedByProject);
}
- private List<PatchSetData> sortProject(Project.NameKey project,
- Collection<ChangeData> in) throws OrmException, IOException {
+ private List<PatchSetData> sortProject(Project.NameKey project, Collection<ChangeData> in)
+ throws OrmException, IOException {
try (Repository repo = repoManager.openRepository(project);
RevWalk rw = new RevWalk(repo)) {
rw.setRetainBody(retainBody);
@@ -172,8 +166,7 @@
while (!todo.isEmpty()) {
// Sanity check: we can't pop more than N pending commits, otherwise
// we have an infinite loop due to programmer error or something.
- checkState(++i <= commits.size(),
- "Too many pending steps while sorting %s", commits);
+ checkState(++i <= commits.size(), "Too many pending steps while sorting %s", commits);
RevCommit t = todo.removeFirst();
if (t.has(done)) {
continue;
@@ -195,8 +188,7 @@
}
}
- private static ListMultimap<RevCommit, RevCommit> collectChildren(
- Set<RevCommit> commits) {
+ private static ListMultimap<RevCommit, RevCommit> collectChildren(Set<RevCommit> commits) {
ListMultimap<RevCommit, RevCommit> children =
MultimapBuilder.hashKeys().arrayListValues().build();
for (RevCommit c : commits) {
@@ -209,8 +201,10 @@
return children;
}
- private static int emit(RevCommit c,
- ListMultimap<RevCommit, PatchSetData> byCommit, List<PatchSetData> result,
+ private static int emit(
+ RevCommit c,
+ ListMultimap<RevCommit, PatchSetData> byCommit,
+ List<PatchSetData> result,
RevFlag done) {
if (c.has(done)) {
return 0;
@@ -224,29 +218,26 @@
return 0;
}
- private ListMultimap<RevCommit, PatchSetData> byCommit(RevWalk rw,
- Collection<ChangeData> in) throws OrmException, IOException {
+ private ListMultimap<RevCommit, PatchSetData> byCommit(RevWalk rw, Collection<ChangeData> in)
+ throws OrmException, IOException {
ListMultimap<RevCommit, PatchSetData> byCommit =
MultimapBuilder.hashKeys(in.size()).arrayListValues(1).build();
for (ChangeData cd : in) {
PatchSet maxPs = null;
for (PatchSet ps : cd.patchSets()) {
- if (shouldInclude(ps)
- && (maxPs == null || ps.getId().get() > maxPs.getId().get())) {
+ if (shouldInclude(ps) && (maxPs == null || ps.getId().get() > maxPs.getId().get())) {
maxPs = ps;
}
}
if (maxPs == null) {
- continue; // No patch sets matched.
+ continue; // No patch sets matched.
}
ObjectId id = ObjectId.fromString(maxPs.getRevision().get());
try {
RevCommit c = rw.parseCommit(id);
byCommit.put(c, PatchSetData.create(cd, maxPs, c));
} catch (MissingObjectException | IncorrectObjectTypeException e) {
- log.warn(
- "missing commit " + id.name() + " for patch set " + maxPs.getId(),
- e);
+ log.warn("missing commit " + id.name() + " for patch set " + maxPs.getId(), e);
}
}
return byCommit;
@@ -256,8 +247,7 @@
return includePatchSets.isEmpty() || includePatchSets.contains(ps.getId());
}
- private static void markStart(RevWalk rw, Iterable<RevCommit> commits)
- throws IOException {
+ private static void markStart(RevWalk rw, Iterable<RevCommit> commits) throws IOException {
for (RevCommit c : commits) {
rw.markStart(c);
}
@@ -271,7 +261,9 @@
}
abstract ChangeData data();
+
abstract PatchSet patchSet();
+
abstract RevCommit commit();
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/AdministrateServerGroups.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/AdministrateServerGroups.java
index caeb771..89090f4 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/AdministrateServerGroups.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/AdministrateServerGroups.java
@@ -17,7 +17,6 @@
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import com.google.inject.BindingAnnotation;
-
import java.lang.annotation.Retention;
/**
@@ -30,5 +29,4 @@
*/
@Retention(RUNTIME)
@BindingAnnotation
-public @interface AdministrateServerGroups {
-}
+public @interface AdministrateServerGroups {}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/AdministrateServerGroupsProvider.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/AdministrateServerGroupsProvider.java
index dd3b8329..29f288a 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/AdministrateServerGroupsProvider.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/AdministrateServerGroupsProvider.java
@@ -24,7 +24,6 @@
import com.google.gerrit.server.util.ThreadLocalRequestContext;
import com.google.inject.Inject;
import com.google.inject.Provider;
-
import org.eclipse.jgit.lib.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -34,7 +33,8 @@
private final ImmutableSet<GroupReference> groups;
@Inject
- public AdministrateServerGroupsProvider(GroupBackend groupBackend,
+ public AdministrateServerGroupsProvider(
+ GroupBackend groupBackend,
@GerritServerConfig Config config,
ThreadLocalRequestContext threadContext,
ServerRequestContext serverCtx) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/AgreementJson.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/AgreementJson.java
index 3ababbc..83eca9c 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/AgreementJson.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/AgreementJson.java
@@ -26,13 +26,11 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AgreementJson {
- private static final Logger log =
- LoggerFactory.getLogger(AgreementJson.class);
+ private static final Logger log = LoggerFactory.getLogger(AgreementJson.class);
private final Provider<CurrentUser> self;
private final IdentifiedUser.GenericFactory identifiedUserFactory;
@@ -40,7 +38,8 @@
private final GroupJson groupJson;
@Inject
- AgreementJson(Provider<CurrentUser> self,
+ AgreementJson(
+ Provider<CurrentUser> self,
IdentifiedUser.GenericFactory identifiedUserFactory,
GroupControl.GenericFactory genericGroupControlFactory,
GroupJson groupJson) {
@@ -57,16 +56,18 @@
info.url = ca.getAgreementUrl();
GroupReference autoVerifyGroup = ca.getAutoVerify();
if (autoVerifyGroup != null && self.get().isIdentifiedUser()) {
- IdentifiedUser user =
- identifiedUserFactory.create(self.get().getAccountId());
+ IdentifiedUser user = identifiedUserFactory.create(self.get().getAccountId());
try {
- GroupControl gc = genericGroupControlFactory.controlFor(
- user, autoVerifyGroup.getUUID());
+ GroupControl gc = genericGroupControlFactory.controlFor(user, autoVerifyGroup.getUUID());
GroupResource group = new GroupResource(gc);
info.autoVerifyGroup = groupJson.format(group);
} catch (NoSuchGroupException | OrmException e) {
- log.warn("autoverify group \"" + autoVerifyGroup.getName() +
- "\" does not exist, referenced in CLA \"" + ca.getName() + "\"");
+ log.warn(
+ "autoverify group \""
+ + autoVerifyGroup.getName()
+ + "\" does not exist, referenced in CLA \""
+ + ca.getName()
+ + "\"");
}
}
return info;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/AllProjectsNameProvider.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/AllProjectsNameProvider.java
index af681db..3250185 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/AllProjectsNameProvider.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/AllProjectsNameProvider.java
@@ -17,7 +17,6 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import org.eclipse.jgit.lib.Config;
@Singleton
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/AllUsersNameProvider.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/AllUsersNameProvider.java
index 09f1c50..0020d5c 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/AllUsersNameProvider.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/AllUsersNameProvider.java
@@ -17,7 +17,6 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import org.eclipse.jgit.lib.Config;
@Singleton
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/AnonymousCowardName.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/AnonymousCowardName.java
index 197d64e..3cc0a8f 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/AnonymousCowardName.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/AnonymousCowardName.java
@@ -17,11 +17,9 @@
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import com.google.inject.BindingAnnotation;
-
import java.lang.annotation.Retention;
/** Special name for a user that hasn't set a name. */
@Retention(RUNTIME)
@BindingAnnotation
-public @interface AnonymousCowardName {
-}
+public @interface AnonymousCowardName {}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/AnonymousCowardNameProvider.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/AnonymousCowardNameProvider.java
index b44affa..3f3d6fd 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/AnonymousCowardNameProvider.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/AnonymousCowardNameProvider.java
@@ -16,7 +16,6 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
-
import org.eclipse.jgit.lib.Config;
public class AnonymousCowardNameProvider implements Provider<String> {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/AuthConfig.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/AuthConfig.java
index 11a34f7..db7d567 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/AuthConfig.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/AuthConfig.java
@@ -22,15 +22,13 @@
import com.google.gwtjsonrpc.server.XsrfException;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.lib.Config;
-
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
+import org.eclipse.jgit.lib.Config;
/** Authentication related settings from {@code gerrit.config}. */
@Singleton
@@ -66,8 +64,7 @@
private GitBasicAuthPolicy gitBasicAuthPolicy;
@Inject
- AuthConfig(@GerritServerConfig final Config cfg)
- throws XsrfException {
+ AuthConfig(@GerritServerConfig final Config cfg) throws XsrfException {
authType = toType(cfg);
httpHeader = cfg.getString("auth", null, "httpheader");
httpDisplaynameHeader = cfg.getString("auth", null, "httpdisplaynameheader");
@@ -93,17 +90,21 @@
enableRunAs = cfg.getBoolean("auth", null, "enableRunAs", true);
gitBasicAuth = cfg.getBoolean("auth", "gitBasicAuth", false);
gitBasicAuthPolicy = getBasicAuthPolicy(cfg);
- useContributorAgreements =
- cfg.getBoolean("auth", "contributoragreements", false);
+ useContributorAgreements = cfg.getBoolean("auth", "contributoragreements", false);
userNameToLowerCase = cfg.getBoolean("auth", "userNameToLowerCase", false);
allowRegisterNewEmail = cfg.getBoolean("auth", "allowRegisterNewEmail", true);
String key = cfg.getString("auth", null, "registerEmailPrivateKey");
if (key != null && !key.isEmpty()) {
- int age = (int) ConfigUtil.getTimeUnit(cfg,
- "auth", null, "maxRegisterEmailTokenAge",
- TimeUnit.SECONDS.convert(12, TimeUnit.HOURS),
- TimeUnit.SECONDS);
+ int age =
+ (int)
+ ConfigUtil.getTimeUnit(
+ cfg,
+ "auth",
+ null,
+ "maxRegisterEmailTokenAge",
+ TimeUnit.SECONDS.convert(12, TimeUnit.HOURS),
+ TimeUnit.SECONDS);
emailReg = new SignedToken(age, key);
} else {
emailReg = null;
@@ -314,8 +315,7 @@
}
public boolean isLdapAuthType() {
- return authType == AuthType.LDAP ||
- authType == AuthType.LDAP_BIND;
+ return authType == AuthType.LDAP || authType == AuthType.LDAP_BIND;
}
public boolean isAllowRegisterNewEmail() {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/CacheResource.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/CacheResource.java
index 05ad33d..7b40786 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/CacheResource.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/CacheResource.java
@@ -32,12 +32,15 @@
}
public CacheResource(String pluginName, String cacheName, final Cache<?, ?> cache) {
- this(pluginName, cacheName, new Provider<Cache<?, ?>>() {
- @Override
- public Cache<?, ?> get() {
- return cache;
- }
- });
+ this(
+ pluginName,
+ cacheName,
+ new Provider<Cache<?, ?>>() {
+ @Override
+ public Cache<?, ?> get() {
+ return cache;
+ }
+ });
}
public String getName() {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/CachesCollection.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/CachesCollection.java
index 7b567e1..f002f8d 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/CachesCollection.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/CachesCollection.java
@@ -35,8 +35,8 @@
@RequiresAnyCapability({VIEW_CACHES, MAINTAIN_SERVER})
@Singleton
-public class CachesCollection implements
- ChildCollection<ConfigResource, CacheResource>, AcceptsPost<ConfigResource> {
+public class CachesCollection
+ implements ChildCollection<ConfigResource, CacheResource>, AcceptsPost<ConfigResource> {
private final DynamicMap<RestView<CacheResource>> views;
private final Provider<ListCaches> list;
@@ -45,8 +45,10 @@
private final PostCaches postCaches;
@Inject
- CachesCollection(DynamicMap<RestView<CacheResource>> views,
- Provider<ListCaches> list, Provider<CurrentUser> self,
+ CachesCollection(
+ DynamicMap<RestView<CacheResource>> views,
+ Provider<ListCaches> list,
+ Provider<CurrentUser> self,
DynamicMap<Cache<?, ?>> cacheMap,
PostCaches postCaches) {
this.views = views;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/CanonicalWebUrl.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/CanonicalWebUrl.java
index e40c6a1..c8d39b0 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/CanonicalWebUrl.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/CanonicalWebUrl.java
@@ -17,17 +17,15 @@
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import com.google.inject.BindingAnnotation;
-
import java.lang.annotation.Retention;
/**
* Marker on a {@link String} holding the canonical address for this server.
- * <p>
- * Note that the String may be null, if the administrator has not configured the
- * value and we are not in an HTTP request where the URL can be guessed from the
- * request state. Clients must handle such cases explicitly.
+ *
+ * <p>Note that the String may be null, if the administrator has not configured the value and we are
+ * not in an HTTP request where the URL can be guessed from the request state. Clients must handle
+ * such cases explicitly.
*/
@Retention(RUNTIME)
@BindingAnnotation
-public @interface CanonicalWebUrl {
-}
+public @interface CanonicalWebUrl {}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/CanonicalWebUrlModule.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/CanonicalWebUrlModule.java
index 8d66d33..646d395 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/CanonicalWebUrlModule.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/CanonicalWebUrlModule.java
@@ -29,8 +29,7 @@
// running in an HTTP environment.
//
final Class<? extends Provider<String>> provider = provider();
- bind(String.class).annotatedWith(CanonicalWebUrl.class)
- .toProvider(provider);
+ bind(String.class).annotatedWith(CanonicalWebUrl.class).toProvider(provider);
}
protected abstract Class<? extends Provider<String>> provider();
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/CanonicalWebUrlProvider.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/CanonicalWebUrlProvider.java
index 3cce4f0..e670e2c 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/CanonicalWebUrlProvider.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/CanonicalWebUrlProvider.java
@@ -16,7 +16,6 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
-
import org.eclipse.jgit.lib.Config;
/** Provides {@link CanonicalWebUrl} from {@code gerrit.canonicalWebUrl}. */
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/CapabilitiesCollection.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/CapabilitiesCollection.java
index 7ce5a88..1124048 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/CapabilitiesCollection.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/CapabilitiesCollection.java
@@ -23,14 +23,12 @@
import com.google.inject.Singleton;
@Singleton
-public class CapabilitiesCollection implements
- ChildCollection<ConfigResource, CapabilityResource> {
+public class CapabilitiesCollection implements ChildCollection<ConfigResource, CapabilityResource> {
private final DynamicMap<RestView<CapabilityResource>> views;
private final ListCapabilities list;
@Inject
- CapabilitiesCollection(DynamicMap<RestView<CapabilityResource>> views,
- ListCapabilities list) {
+ CapabilitiesCollection(DynamicMap<RestView<CapabilityResource>> views, ListCapabilities list) {
this.views = views;
this.list = list;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/ChangeCleanupConfig.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/ChangeCleanupConfig.java
index b4b1865..b2b5fab 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/ChangeCleanupConfig.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/ChangeCleanupConfig.java
@@ -18,10 +18,8 @@
import com.google.gerrit.common.Nullable;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.lib.Config;
-
import java.util.concurrent.TimeUnit;
+import org.eclipse.jgit.lib.Config;
@Singleton
public class ChangeCleanupConfig {
@@ -31,9 +29,9 @@
private static String KEY_ABANDON_MESSAGE = "abandonMessage";
private static String DEFAULT_ABANDON_MESSAGE =
"Auto-Abandoned due to inactivity, see "
- + "${URL}Documentation/user-change-cleanup.html#auto-abandon\n"
- + "\n"
- + "If this change is still wanted it should be restored.";
+ + "${URL}Documentation/user-change-cleanup.html#auto-abandon\n"
+ + "\n"
+ + "If this change is still wanted it should be restored.";
private final ScheduleConfig scheduleConfig;
private final long abandonAfter;
@@ -41,19 +39,17 @@
private final String abandonMessage;
@Inject
- ChangeCleanupConfig(@GerritServerConfig Config cfg,
- @CanonicalWebUrl @Nullable String canonicalWebUrl) {
+ ChangeCleanupConfig(
+ @GerritServerConfig Config cfg, @CanonicalWebUrl @Nullable String canonicalWebUrl) {
scheduleConfig = new ScheduleConfig(cfg, SECTION);
abandonAfter = readAbandonAfter(cfg);
- abandonIfMergeable =
- cfg.getBoolean(SECTION, null, KEY_ABANDON_IF_MERGEABLE, true);
+ abandonIfMergeable = cfg.getBoolean(SECTION, null, KEY_ABANDON_IF_MERGEABLE, true);
abandonMessage = readAbandonMessage(cfg, canonicalWebUrl);
}
private long readAbandonAfter(Config cfg) {
long abandonAfter =
- ConfigUtil.getTimeUnit(cfg, SECTION, null, KEY_ABANDON_AFTER, 0,
- TimeUnit.MILLISECONDS);
+ ConfigUtil.getTimeUnit(cfg, SECTION, null, KEY_ABANDON_AFTER, 0, TimeUnit.MILLISECONDS);
return abandonAfter >= 0 ? abandonAfter : 0;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/ConfigCollection.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/ConfigCollection.java
index 72c4f2e..d5d2960 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/ConfigCollection.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/ConfigCollection.java
@@ -24,8 +24,7 @@
import com.google.inject.Singleton;
@Singleton
-public class ConfigCollection implements
- RestCollection<TopLevelResource, ConfigResource> {
+public class ConfigCollection implements RestCollection<TopLevelResource, ConfigResource> {
private final DynamicMap<RestView<ConfigResource>> views;
@Inject
@@ -44,8 +43,7 @@
}
@Override
- public ConfigResource parse(TopLevelResource root, IdString id)
- throws ResourceNotFoundException {
+ public ConfigResource parse(TopLevelResource root, IdString id) throws ResourceNotFoundException {
if (id.equals("server")) {
return new ConfigResource();
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/ConfigUtil.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/ConfigUtil.java
index eaeb850..0da1d3b 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/ConfigUtil.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/ConfigUtil.java
@@ -15,10 +15,6 @@
package com.google.gerrit.server.config;
import com.google.common.base.Preconditions;
-
-import org.eclipse.jgit.errors.ConfigInvalidException;
-import org.eclipse.jgit.lib.Config;
-
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
@@ -29,6 +25,8 @@
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
+import org.eclipse.jgit.errors.ConfigInvalidException;
+import org.eclipse.jgit.lib.Config;
public class ConfigUtil {
@@ -36,8 +34,10 @@
private static <T> T[] allValuesOf(final T defaultValue) {
try {
return (T[]) defaultValue.getClass().getMethod("values").invoke(null);
- } catch (IllegalArgumentException | NoSuchMethodException
- | InvocationTargetException | IllegalAccessException
+ } catch (IllegalArgumentException
+ | NoSuchMethodException
+ | InvocationTargetException
+ | IllegalAccessException
| SecurityException e) {
throw new IllegalArgumentException("Cannot obtain enumeration values", e);
}
@@ -51,12 +51,15 @@
* @param subsection subsection the key is in, or null if not in a subsection.
* @param setting name of the setting to read.
* @param valueString string value from git Config
- * @param all all possible values in the enumeration which should be
- * recognized. This should be {@code EnumType.values()}.
+ * @param all all possible values in the enumeration which should be recognized. This should be
+ * {@code EnumType.values()}.
* @return the selected enumeration value, or {@code defaultValue}.
*/
- private static <T extends Enum<?>> T getEnum(final String section,
- final String subsection, final String setting, String valueString,
+ private static <T extends Enum<?>> T getEnum(
+ final String section,
+ final String subsection,
+ final String setting,
+ String valueString,
final T[] all) {
String n = valueString.replace(' ', '_').replace('-', '_');
@@ -94,12 +97,15 @@
* @param section section the key is in.
* @param subsection subsection the key is in, or null if not in a subsection.
* @param setting name of the setting to read.
- * @param defaultValue default value to return if the setting was not set.
- * Must not be null as the enumeration values are derived from this.
+ * @param defaultValue default value to return if the setting was not set. Must not be null as the
+ * enumeration values are derived from this.
* @return the selected enumeration values list, or {@code defaultValue}.
*/
- public static <T extends Enum<?>> List<T> getEnumList(final Config config,
- final String section, final String subsection, final String setting,
+ public static <T extends Enum<?>> List<T> getEnumList(
+ final Config config,
+ final String section,
+ final String subsection,
+ final String setting,
final T defaultValue) {
final T[] all = allValuesOf(defaultValue);
return getEnumList(config, section, subsection, setting, all, defaultValue);
@@ -113,15 +119,18 @@
* @param section section the key is in.
* @param subsection subsection the key is in, or null if not in a subsection.
* @param setting name of the setting to read.
- * @param all all possible values in the enumeration which should be
- * recognized. This should be {@code EnumType.values()}.
- * @param defaultValue default value to return if the setting was not set.
- * This value may be null.
+ * @param all all possible values in the enumeration which should be recognized. This should be
+ * {@code EnumType.values()}.
+ * @param defaultValue default value to return if the setting was not set. This value may be null.
* @return the selected enumeration values list, or {@code defaultValue}.
*/
- public static <T extends Enum<?>> List<T> getEnumList(final Config config,
- final String section, final String subsection, final String setting,
- final T[] all, final T defaultValue) {
+ public static <T extends Enum<?>> List<T> getEnumList(
+ final Config config,
+ final String section,
+ final String subsection,
+ final String setting,
+ final T[] all,
+ final T defaultValue) {
final List<T> list = new ArrayList<>();
final String[] values = config.getStringList(section, subsection, setting);
if (values.length == 0) {
@@ -143,16 +152,17 @@
* @param section section the key is in.
* @param subsection subsection the key is in, or null if not in a subsection.
* @param setting name of the setting to read.
- * @param defaultValue default value to return if no value was set in the
- * configuration file.
- * @param wantUnit the units of {@code defaultValue} and the return value, as
- * well as the units to assume if the value does not contain an
- * indication of the units.
- * @return the setting, or {@code defaultValue} if not set, expressed in
- * {@code units}.
+ * @param defaultValue default value to return if no value was set in the configuration file.
+ * @param wantUnit the units of {@code defaultValue} and the return value, as well as the units to
+ * assume if the value does not contain an indication of the units.
+ * @return the setting, or {@code defaultValue} if not set, expressed in {@code units}.
*/
- public static long getTimeUnit(final Config config, final String section,
- final String subsection, final String setting, final long defaultValue,
+ public static long getTimeUnit(
+ final Config config,
+ final String section,
+ final String subsection,
+ final String setting,
+ final long defaultValue,
final TimeUnit wantUnit) {
final String valueString = config.getString(section, subsection, setting);
if (valueString == null) {
@@ -164,7 +174,7 @@
return defaultValue;
}
- if (s.startsWith("-")/* negative */) {
+ if (s.startsWith("-") /* negative */) {
throw notTimeUnit(section, subsection, setting, valueString);
}
@@ -179,16 +189,12 @@
* Parse a numerical time unit, such as "1 minute", from a string.
*
* @param valueString the string to parse.
- * @param defaultValue default value to return if no value was set in the
- * configuration file.
- * @param wantUnit the units of {@code defaultValue} and the return value, as
- * well as the units to assume if the value does not contain an
- * indication of the units.
- * @return the setting, or {@code defaultValue} if not set, expressed in
- * {@code units}.
+ * @param defaultValue default value to return if no value was set in the configuration file.
+ * @param wantUnit the units of {@code defaultValue} and the return value, as well as the units to
+ * assume if the value does not contain an indication of the units.
+ * @return the setting, or {@code defaultValue} if not set, expressed in {@code units}.
*/
- public static long getTimeUnit(final String valueString, long defaultValue,
- TimeUnit wantUnit) {
+ public static long getTimeUnit(final String valueString, long defaultValue, TimeUnit wantUnit) {
Matcher m = Pattern.compile("^(0|[1-9][0-9]*)\\s*(.*)$").matcher(valueString);
if (!m.matches()) {
return defaultValue;
@@ -250,19 +256,18 @@
public static String getRequired(Config cfg, String section, String name) {
final String v = cfg.getString(section, null, name);
if (v == null || "".equals(v)) {
- throw new IllegalArgumentException("No " + section + "." + name
- + " configured");
+ throw new IllegalArgumentException("No " + section + "." + name + " configured");
}
return v;
}
/**
* Store section by inspecting Java class attributes.
- * <p>
- * Optimize the storage by unsetting a variable if it is
- * being set to default value by the server.
- * <p>
- * Fields marked with final or transient modifiers are skipped.
+ *
+ * <p>Optimize the storage by unsetting a variable if it is being set to default value by the
+ * server.
+ *
+ * <p>Fields marked with final or transient modifiers are skipped.
*
* @param cfg config in which the values should be stored
* @param section section
@@ -271,8 +276,8 @@
* @param defaults instance of class with default values
* @throws ConfigInvalidException
*/
- public static <T> void storeSection(Config cfg, String section, String sub,
- T s, T defaults) throws ConfigInvalidException {
+ public static <T> void storeSection(Config cfg, String section, String sub, T s, T defaults)
+ throws ConfigInvalidException {
try {
for (Field f : s.getClass().getDeclaredFields()) {
if (skipField(f)) {
@@ -307,32 +312,31 @@
}
}
}
- } catch (SecurityException | IllegalArgumentException
- | IllegalAccessException e) {
+ } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) {
throw new ConfigInvalidException("cannot save values", e);
}
}
/**
* Load section by inspecting Java class attributes.
- * <p>
- * Config values are stored optimized: no default values are stored.
- * The loading is performed eagerly: all values are set.
- * <p>
- * Fields marked with final or transient modifiers are skipped.
+ *
+ * <p>Config values are stored optimized: no default values are stored. The loading is performed
+ * eagerly: all values are set.
+ *
+ * <p>Fields marked with final or transient modifiers are skipped.
*
* @param cfg config from which the values are loaded
* @param section section
* @param sub subsection
* @param s instance of class in which the values are set
* @param defaults instance of class with default values
- * @param i instance to merge during the load. When present, the
- * boolean fields are not nullified when their values are false
+ * @param i instance to merge during the load. When present, the boolean fields are not nullified
+ * when their values are false
* @return loaded instance
* @throws ConfigInvalidException
*/
- public static <T> T loadSection(Config cfg, String section, String sub,
- T s, T defaults, T i) throws ConfigInvalidException {
+ public static <T> T loadSection(Config cfg, String section, String sub, T s, T defaults, T i)
+ throws ConfigInvalidException {
try {
for (Field f : s.getClass().getDeclaredFields()) {
if (skipField(f)) {
@@ -348,7 +352,7 @@
if (isString(t)) {
String v = cfg.getString(section, sub, n);
if (v == null) {
- v = (String)d;
+ v = (String) d;
}
f.set(s, v);
} else if (isInteger(t)) {
@@ -375,8 +379,7 @@
}
}
}
- } catch (SecurityException | IllegalArgumentException
- | IllegalAccessException e) {
+ } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) {
throw new ConfigInvalidException("cannot load values", e);
}
return s;
@@ -388,8 +391,7 @@
}
private static boolean isCollectionOrMap(Class<?> t) {
- return Collection.class.isAssignableFrom(t)
- || Map.class.isAssignableFrom(t);
+ return Collection.class.isAssignableFrom(t) || Map.class.isAssignableFrom(t);
}
private static boolean isString(Class<?> t) {
@@ -417,17 +419,24 @@
return false;
}
- private static IllegalArgumentException notTimeUnit(final String section,
- final String subsection, final String setting, final String valueString) {
- return new IllegalArgumentException("Invalid time unit value: " + section
- + (subsection != null ? "." + subsection : "") + "." + setting + " = "
- + valueString);
+ private static IllegalArgumentException notTimeUnit(
+ final String section,
+ final String subsection,
+ final String setting,
+ final String valueString) {
+ return new IllegalArgumentException(
+ "Invalid time unit value: "
+ + section
+ + (subsection != null ? "." + subsection : "")
+ + "."
+ + setting
+ + " = "
+ + valueString);
}
private static IllegalArgumentException notTimeUnit(final String val) {
return new IllegalArgumentException("Invalid time unit value: " + val);
}
- private ConfigUtil() {
- }
+ private ConfigUtil() {}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/ConfirmEmail.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/ConfirmEmail.java
index 81a3366..35c9012 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/ConfirmEmail.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/ConfirmEmail.java
@@ -29,14 +29,12 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.io.IOException;
@Singleton
public class ConfirmEmail implements RestModifyView<ConfigResource, Input> {
public static class Input {
- @DefaultInput
- public String token;
+ @DefaultInput public String token;
}
private final Provider<CurrentUser> self;
@@ -44,7 +42,8 @@
private final AccountManager accountManager;
@Inject
- public ConfirmEmail(Provider<CurrentUser> self,
+ public ConfirmEmail(
+ Provider<CurrentUser> self,
EmailTokenVerifier emailTokenVerifier,
AccountManager accountManager) {
this.self = self;
@@ -54,8 +53,8 @@
@Override
public Response<?> apply(ConfigResource rsrc, Input input)
- throws AuthException, UnprocessableEntityException, AccountException,
- OrmException, IOException {
+ throws AuthException, UnprocessableEntityException, AccountException, OrmException,
+ IOException {
CurrentUser user = self.get();
if (!user.isIdentifiedUser()) {
throw new AuthException("Authentication required");
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/DeleteTask.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/DeleteTask.java
index 1e8afba..29ca20f 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/DeleteTask.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/DeleteTask.java
@@ -28,14 +28,14 @@
@Singleton
@RequiresAnyCapability({KILL_TASK, MAINTAIN_SERVER})
public class DeleteTask implements RestModifyView<TaskResource, Input> {
- public static class Input {
- }
+ public static class Input {}
@Override
public Response<?> apply(TaskResource rsrc, Input input) {
Task<?> task = rsrc.getTask();
boolean taskDeleted = task.cancel(true);
- return taskDeleted ? Response.none() : Response.withStatusCode(
- SC_INTERNAL_SERVER_ERROR, "Unable to kill task " + task);
+ return taskDeleted
+ ? Response.none()
+ : Response.withStatusCode(SC_INTERNAL_SERVER_ERROR, "Unable to kill task " + task);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/DisableReverseDnsLookup.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/DisableReverseDnsLookup.java
index 04712f9..336edeb 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/DisableReverseDnsLookup.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/DisableReverseDnsLookup.java
@@ -17,10 +17,8 @@
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import com.google.inject.BindingAnnotation;
-
import java.lang.annotation.Retention;
@Retention(RUNTIME)
@BindingAnnotation
-public @interface DisableReverseDnsLookup {
-}
+public @interface DisableReverseDnsLookup {}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/DisableReverseDnsLookupProvider.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/DisableReverseDnsLookupProvider.java
index 8c42714..87d6bac2 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/DisableReverseDnsLookupProvider.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/DisableReverseDnsLookupProvider.java
@@ -16,7 +16,6 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
-
import org.eclipse.jgit.lib.Config;
public class DisableReverseDnsLookupProvider implements Provider<Boolean> {
@@ -24,8 +23,7 @@
@Inject
DisableReverseDnsLookupProvider(@GerritServerConfig Config config) {
- disableReverseDnsLookup =
- config.getBoolean("gerrit", null, "disableReverseDnsLookup", false);
+ disableReverseDnsLookup = config.getBoolean("gerrit", null, "disableReverseDnsLookup", false);
}
@Override
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/DownloadConfig.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/DownloadConfig.java
index 2db4ec9..48d4507 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/DownloadConfig.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/DownloadConfig.java
@@ -20,20 +20,18 @@
import com.google.gerrit.server.change.ArchiveFormat;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.lib.Config;
-
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
+import org.eclipse.jgit.lib.Config;
/**
* Download protocol from {@code gerrit.config}.
- * <p>
- * Only used to configure the built-in set of schemes and commands in the core
- * download-commands plugin; not used by other plugins.
+ *
+ * <p>Only used to configure the built-in set of schemes and commands in the core download-commands
+ * plugin; not used by other plugins.
*/
@Singleton
public class DownloadConfig {
@@ -45,17 +43,15 @@
DownloadConfig(@GerritServerConfig final Config cfg) {
String[] allSchemes = cfg.getStringList("download", null, "scheme");
if (allSchemes.length == 0) {
- downloadSchemes = ImmutableSet.of(
- CoreDownloadSchemes.SSH,
- CoreDownloadSchemes.HTTP,
- CoreDownloadSchemes.ANON_HTTP);
+ downloadSchemes =
+ ImmutableSet.of(
+ CoreDownloadSchemes.SSH, CoreDownloadSchemes.HTTP, CoreDownloadSchemes.ANON_HTTP);
} else {
List<String> normalized = new ArrayList<>(allSchemes.length);
for (String s : allSchemes) {
String core = toCoreScheme(s);
if (core == null) {
- throw new IllegalArgumentException(
- "not a core download scheme: " + s);
+ throw new IllegalArgumentException("not a core download scheme: " + s);
}
normalized.add(core);
}
@@ -64,8 +60,7 @@
DownloadCommand[] downloadCommandValues = DownloadCommand.values();
List<DownloadCommand> allCommands =
- ConfigUtil.getEnumList(cfg, "download", null, "command",
- downloadCommandValues, null);
+ ConfigUtil.getEnumList(cfg, "download", null, "command", downloadCommandValues, null);
if (isOnlyNull(allCommands)) {
downloadCommands = ImmutableSet.copyOf(downloadCommandValues);
} else {
@@ -78,9 +73,9 @@
} else if (v.isEmpty() || "off".equalsIgnoreCase(v)) {
archiveFormats = ImmutableSet.of();
} else {
- archiveFormats = ImmutableSet.copyOf(ConfigUtil.getEnumList(cfg,
- "download", null, "archive",
- ArchiveFormat.TGZ));
+ archiveFormats =
+ ImmutableSet.copyOf(
+ ConfigUtil.getEnumList(cfg, "download", null, "archive", ArchiveFormat.TGZ));
}
}
@@ -96,7 +91,9 @@
return (String) f.get(null);
}
return null;
- } catch (NoSuchFieldException | SecurityException | IllegalArgumentException
+ } catch (NoSuchFieldException
+ | SecurityException
+ | IllegalArgumentException
| IllegalAccessException e) {
return null;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/EmailExpanderProvider.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/EmailExpanderProvider.java
index a55ef84d..1c42c09 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/EmailExpanderProvider.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/EmailExpanderProvider.java
@@ -12,13 +12,11 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-
package com.google.gerrit.server.config;
import com.google.gerrit.server.account.EmailExpander;
import com.google.inject.Inject;
import com.google.inject.Provider;
-
import org.eclipse.jgit.lib.Config;
class EmailExpanderProvider implements Provider<EmailExpander> {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/FlushCache.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/FlushCache.java
index eb5ef22..5e19091 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/FlushCache.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/FlushCache.java
@@ -30,8 +30,7 @@
@RequiresAnyCapability({FLUSH_CACHES, MAINTAIN_SERVER})
@Singleton
public class FlushCache implements RestModifyView<CacheResource, Input> {
- public static class Input {
- }
+ public static class Input {}
public static final String WEB_SESSIONS = "web_sessions";
@@ -43,12 +42,9 @@
}
@Override
- public Response<String> apply(CacheResource rsrc, Input input)
- throws AuthException {
- if (WEB_SESSIONS.equals(rsrc.getName())
- && !self.get().getCapabilities().canMaintainServer()) {
- throw new AuthException(String.format(
- "only site maintainers can flush %s", WEB_SESSIONS));
+ public Response<String> apply(CacheResource rsrc, Input input) throws AuthException {
+ if (WEB_SESSIONS.equals(rsrc.getName()) && !self.get().getCapabilities().canMaintainServer()) {
+ throw new AuthException(String.format("only site maintainers can flush %s", WEB_SESSIONS));
}
rsrc.getCache().invalidateAll();
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/GcConfig.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/GcConfig.java
index 572b56e..36f5e29 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/GcConfig.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/GcConfig.java
@@ -16,7 +16,6 @@
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.lib.ConfigConstants;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/GerritConfig.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/GerritConfig.java
index fff29fa..fdc3b7f 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/GerritConfig.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/GerritConfig.java
@@ -15,7 +15,6 @@
package com.google.gerrit.server.config;
import com.google.gerrit.server.securestore.SecureStore;
-
import org.eclipse.jgit.lib.Config;
class GerritConfig extends Config {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/GerritGlobalModule.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/GerritGlobalModule.java
index e941de0..a0867ae 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/GerritGlobalModule.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/GerritGlobalModule.java
@@ -181,33 +181,27 @@
import com.google.inject.TypeLiteral;
import com.google.inject.internal.UniqueAnnotations;
import com.google.template.soy.tofu.SoyTofu;
-
+import java.util.List;
import org.apache.velocity.runtime.RuntimeInstance;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.transport.PostReceiveHook;
import org.eclipse.jgit.transport.PostUploadHook;
import org.eclipse.jgit.transport.PreUploadHook;
-import java.util.List;
-
-
/** Starts global state with standard dependencies. */
public class GerritGlobalModule extends FactoryModule {
private final Config cfg;
private final AuthModule authModule;
@Inject
- GerritGlobalModule(
- @GerritServerConfig Config cfg,
- AuthModule authModule) {
+ GerritGlobalModule(@GerritServerConfig Config cfg, AuthModule authModule) {
this.cfg = cfg;
this.authModule = authModule;
}
@Override
protected void configure() {
- bind(EmailExpander.class).toProvider(EmailExpanderProvider.class).in(
- SINGLETON);
+ bind(EmailExpander.class).toProvider(EmailExpanderProvider.class).in(SINGLETON);
bind(IdGenerator.class);
bind(RulesCache.class);
@@ -262,9 +256,7 @@
factory(ReplacePatchSetSender.Factory.class);
factory(SetAssigneeSender.Factory.class);
bind(PermissionCollection.Factory.class);
- bind(AccountVisibility.class)
- .toProvider(AccountVisibilityProvider.class)
- .in(SINGLETON);
+ bind(AccountVisibility.class).toProvider(AccountVisibilityProvider.class).in(SINGLETON);
factory(ProjectOwnerGroupsProvider.Factory.class);
bind(AuthBackend.class).to(UniversalAuthBackend.class).in(SINGLETON);
@@ -283,15 +275,13 @@
bind(ApprovalsUtil.class);
- bind(RuntimeInstance.class)
- .toProvider(VelocityRuntimeProvider.class);
- bind(SoyTofu.class)
- .annotatedWith(MailTemplates.class)
- .toProvider(MailSoyTofuProvider.class);
- bind(FromAddressGenerator.class).toProvider(
- FromAddressGeneratorProvider.class).in(SINGLETON);
- bind(Boolean.class).annotatedWith(DisableReverseDnsLookup.class)
- .toProvider(DisableReverseDnsLookupProvider.class).in(SINGLETON);
+ bind(RuntimeInstance.class).toProvider(VelocityRuntimeProvider.class);
+ bind(SoyTofu.class).annotatedWith(MailTemplates.class).toProvider(MailSoyTofuProvider.class);
+ bind(FromAddressGenerator.class).toProvider(FromAddressGeneratorProvider.class).in(SINGLETON);
+ bind(Boolean.class)
+ .annotatedWith(DisableReverseDnsLookup.class)
+ .toProvider(DisableReverseDnsLookupProvider.class)
+ .in(SINGLETON);
bind(PatchSetInfoFactory.class);
bind(IdentifiedUser.GenericFactory.class).in(SINGLETON);
@@ -404,7 +394,8 @@
factory(ChangeUserName.Factory.class);
bind(new TypeLiteral<List<CommentLinkInfo>>() {})
- .toProvider(CommentLinkProvider.class).in(SINGLETON);
+ .toProvider(CommentLinkProvider.class)
+ .in(SINGLETON);
bind(ReloadPluginListener.class)
.annotatedWith(UniqueAnnotations.create())
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/GerritOptions.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/GerritOptions.java
index ab4b463..725a69a 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/GerritOptions.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/GerritOptions.java
@@ -18,7 +18,6 @@
import static com.google.common.base.Preconditions.checkArgument;
import com.google.gerrit.extensions.client.UiType;
-
import org.eclipse.jgit.lib.Config;
public class GerritOptions {
@@ -29,31 +28,24 @@
private final boolean forcePolyGerritDev;
private final UiType defaultUi;
- public GerritOptions(Config cfg, boolean headless, boolean slave,
- boolean forcePolyGerritDev) {
+ public GerritOptions(Config cfg, boolean headless, boolean slave, boolean forcePolyGerritDev) {
this.slave = slave;
- this.enablePolyGerrit = forcePolyGerritDev
- || cfg.getBoolean("gerrit", null, "enablePolyGerrit", true);
+ this.enablePolyGerrit =
+ forcePolyGerritDev || cfg.getBoolean("gerrit", null, "enablePolyGerrit", true);
this.enableGwtUi = cfg.getBoolean("gerrit", null, "enableGwtUi", true);
this.forcePolyGerritDev = forcePolyGerritDev;
this.headless = headless || (!enableGwtUi && !enablePolyGerrit);
- UiType defaultUi = enablePolyGerrit && !enableGwtUi
- ? UiType.POLYGERRIT
- : UiType.GWT;
- String uiStr = firstNonNull(
- cfg.getString("gerrit", null, "ui"),
- defaultUi.name());
+ UiType defaultUi = enablePolyGerrit && !enableGwtUi ? UiType.POLYGERRIT : UiType.GWT;
+ String uiStr = firstNonNull(cfg.getString("gerrit", null, "ui"), defaultUi.name());
this.defaultUi = firstNonNull(UiType.parse(uiStr), UiType.NONE);
switch (defaultUi) {
case GWT:
- checkArgument(enableGwtUi,
- "gerrit.ui = %s but GWT UI is disabled", defaultUi);
+ checkArgument(enableGwtUi, "gerrit.ui = %s but GWT UI is disabled", defaultUi);
break;
case POLYGERRIT:
- checkArgument(enablePolyGerrit,
- "gerrit.ui = %s but PolyGerrit is disabled", defaultUi);
+ checkArgument(enablePolyGerrit, "gerrit.ui = %s but PolyGerrit is disabled", defaultUi);
break;
case NONE:
default:
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/GerritServerConfig.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/GerritServerConfig.java
index 0dc1e68..ead0d63 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/GerritServerConfig.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/GerritServerConfig.java
@@ -17,16 +17,14 @@
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import com.google.inject.BindingAnnotation;
-
import java.lang.annotation.Retention;
/**
* Marker on {@link org.eclipse.jgit.lib.Config} holding {@code gerrit.config} .
- * <p>
- * The {@code gerrit.config} file contains almost all site-wide configuration
- * settings for the Gerrit Code Review server.
+ *
+ * <p>The {@code gerrit.config} file contains almost all site-wide configuration settings for the
+ * Gerrit Code Review server.
*/
@Retention(RUNTIME)
@BindingAnnotation
-public @interface GerritServerConfig {
-}
+public @interface GerritServerConfig {}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/GerritServerConfigModule.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/GerritServerConfigModule.java
index 281600d..100a7cd 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/GerritServerConfigModule.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/GerritServerConfigModule.java
@@ -23,15 +23,13 @@
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.ProvisionException;
-
+import java.io.IOException;
+import java.nio.file.Path;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.storage.file.FileBasedConfig;
import org.eclipse.jgit.util.FS;
-import java.io.IOException;
-import java.nio.file.Path;
-
/** Creates {@link GerritServerConfig}. */
public class GerritServerConfigModule extends AbstractModule {
public static String getSecureStoreClassName(final Path sitePath) {
@@ -44,13 +42,14 @@
}
private static String getSecureStoreFromGerritConfig(final Path sitePath) {
- AbstractModule m = new AbstractModule() {
- @Override
- protected void configure() {
- bind(Path.class).annotatedWith(SitePath.class).toInstance(sitePath);
- bind(SitePaths.class);
- }
- };
+ AbstractModule m =
+ new AbstractModule() {
+ @Override
+ protected void configure() {
+ bind(Path.class).annotatedWith(SitePath.class).toInstance(sitePath);
+ bind(SitePaths.class);
+ }
+ };
Injector injector = Guice.createInjector(m);
SitePaths site = injector.getInstance(SitePaths.class);
FileBasedConfig cfg = new FileBasedConfig(site.gerrit_config.toFile(), FS.DETECTED);
@@ -74,9 +73,11 @@
@Override
protected void configure() {
bind(SitePaths.class);
- bind(TrackingFooters.class).toProvider(TrackingFootersProvider.class).in(SINGLETON) ;
- bind(Config.class).annotatedWith(GerritServerConfig.class).toProvider(
- GerritServerConfigProvider.class).in(SINGLETON);
+ bind(TrackingFooters.class).toProvider(TrackingFootersProvider.class).in(SINGLETON);
+ bind(Config.class)
+ .annotatedWith(GerritServerConfig.class)
+ .toProvider(GerritServerConfigProvider.class)
+ .in(SINGLETON);
bind(SecureStore.class).toProvider(SecureStoreProvider.class).in(SINGLETON);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/GerritServerConfigProvider.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/GerritServerConfigProvider.java
index 8be42db..494b63a 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/GerritServerConfigProvider.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/GerritServerConfigProvider.java
@@ -18,7 +18,7 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.ProvisionException;
-
+import java.io.IOException;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.storage.file.FileBasedConfig;
@@ -26,12 +26,9 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-
/** Provides {@link Config} annotated with {@link GerritServerConfig}. */
class GerritServerConfigProvider implements Provider<Config> {
- private static final Logger log =
- LoggerFactory.getLogger(GerritServerConfigProvider.class);
+ private static final Logger log = LoggerFactory.getLogger(GerritServerConfigProvider.class);
private final SitePaths site;
private final SecureStore secureStore;
@@ -44,12 +41,10 @@
@Override
public Config get() {
- FileBasedConfig cfg =
- new FileBasedConfig(site.gerrit_config.toFile(), FS.DETECTED);
+ FileBasedConfig cfg = new FileBasedConfig(site.gerrit_config.toFile(), FS.DETECTED);
if (!cfg.getFile().exists()) {
- log.info("No " + site.gerrit_config.toAbsolutePath()
- + "; assuming defaults");
+ log.info("No " + site.gerrit_config.toAbsolutePath() + "; assuming defaults");
return new GerritConfig(cfg, secureStore);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/GerritServerId.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/GerritServerId.java
index f3fa9b1..87dc44a 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/GerritServerId.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/GerritServerId.java
@@ -17,16 +17,13 @@
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import com.google.inject.BindingAnnotation;
-
import java.lang.annotation.Retention;
/**
* Marker on a string holding a unique identifier for the server.
- * <p>
- * This value is generated on first use and stored in {@code
- * $site_path/etc/uuid}.
+ *
+ * <p>This value is generated on first use and stored in {@code $site_path/etc/uuid}.
*/
@Retention(RUNTIME)
@BindingAnnotation
-public @interface GerritServerId {
-}
+public @interface GerritServerId {}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/GerritServerIdProvider.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/GerritServerIdProvider.java
index 9479438..83b60e2f1 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/GerritServerIdProvider.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/GerritServerIdProvider.java
@@ -19,16 +19,14 @@
import com.google.common.base.Strings;
import com.google.inject.Inject;
import com.google.inject.Provider;
-
+import java.io.IOException;
+import java.nio.file.Files;
+import java.util.UUID;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.storage.file.FileBasedConfig;
import org.eclipse.jgit.util.FS;
-import java.io.IOException;
-import java.nio.file.Files;
-import java.util.UUID;
-
public class GerritServerIdProvider implements Provider<String> {
public static final String SECTION = "gerrit";
public static final String KEY = "serverId";
@@ -40,8 +38,8 @@
private final String id;
@Inject
- GerritServerIdProvider(@GerritServerConfig Config cfg,
- SitePaths sitePaths) throws IOException, ConfigInvalidException {
+ GerritServerIdProvider(@GerritServerConfig Config cfg, SitePaths sitePaths)
+ throws IOException, ConfigInvalidException {
String origId = cfg.getString(SECTION, null, KEY);
if (!Strings.isNullOrEmpty(origId)) {
id = origId;
@@ -69,8 +67,7 @@
// Reread gerrit.config from disk before writing. We can't just use
// cfg.toText(), as the @GerritServerConfig only has gerrit.config as a
// fallback.
- FileBasedConfig cfg =
- new FileBasedConfig(sitePaths.gerrit_config.toFile(), FS.DETECTED);
+ FileBasedConfig cfg = new FileBasedConfig(sitePaths.gerrit_config.toFile(), FS.DETECTED);
if (!cfg.getFile().exists()) {
return new Config();
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/GetDiffPreferences.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/GetDiffPreferences.java
index 9f18fc3..8393fb4 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/GetDiffPreferences.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/GetDiffPreferences.java
@@ -24,13 +24,11 @@
import com.google.gerrit.server.git.UserConfigSections;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
+import java.io.IOException;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
import org.eclipse.jgit.lib.Repository;
-import java.io.IOException;
-
@Singleton
public class GetDiffPreferences implements RestReadView<ConfigResource> {
@@ -38,30 +36,32 @@
private final GitRepositoryManager gitManager;
@Inject
- GetDiffPreferences(GitRepositoryManager gitManager,
- AllUsersName allUsersName) {
+ GetDiffPreferences(GitRepositoryManager gitManager, AllUsersName allUsersName) {
this.allUsersName = allUsersName;
this.gitManager = gitManager;
}
@Override
public DiffPreferencesInfo apply(ConfigResource configResource)
- throws BadRequestException, ResourceConflictException, IOException,
- ConfigInvalidException {
+ throws BadRequestException, ResourceConflictException, IOException, ConfigInvalidException {
return readFromGit(gitManager, allUsersName, null);
}
- static DiffPreferencesInfo readFromGit(GitRepositoryManager gitMgr,
- AllUsersName allUsersName, DiffPreferencesInfo in)
+ static DiffPreferencesInfo readFromGit(
+ GitRepositoryManager gitMgr, AllUsersName allUsersName, DiffPreferencesInfo in)
throws IOException, ConfigInvalidException, RepositoryNotFoundException {
try (Repository git = gitMgr.openRepository(allUsersName)) {
// Load all users prefs.
- VersionedAccountPreferences dp =
- VersionedAccountPreferences.forDefault();
+ VersionedAccountPreferences dp = VersionedAccountPreferences.forDefault();
dp.load(git);
DiffPreferencesInfo allUserPrefs = new DiffPreferencesInfo();
- loadSection(dp.getConfig(), UserConfigSections.DIFF, null, allUserPrefs,
- DiffPreferencesInfo.defaults(), in);
+ loadSection(
+ dp.getConfig(),
+ UserConfigSections.DIFF,
+ null,
+ allUserPrefs,
+ DiffPreferencesInfo.defaults(),
+ in);
return allUserPrefs;
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/GetPreferences.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/GetPreferences.java
index 66e45b6..ed212f4 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/GetPreferences.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/GetPreferences.java
@@ -24,13 +24,11 @@
import com.google.gerrit.server.git.UserConfigSections;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
+import java.io.IOException;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
import org.eclipse.jgit.lib.Repository;
-import java.io.IOException;
-
@Singleton
public class GetPreferences implements RestReadView<ConfigResource> {
private final GeneralPreferencesLoader loader;
@@ -38,8 +36,8 @@
private final AllUsersName allUsersName;
@Inject
- public GetPreferences(GeneralPreferencesLoader loader,
- GitRepositoryManager gitMgr, AllUsersName allUsersName) {
+ public GetPreferences(
+ GeneralPreferencesLoader loader, GitRepositoryManager gitMgr, AllUsersName allUsersName) {
this.loader = loader;
this.gitMgr = gitMgr;
this.allUsersName = allUsersName;
@@ -51,17 +49,24 @@
return readFromGit(gitMgr, loader, allUsersName, null);
}
- static GeneralPreferencesInfo readFromGit(GitRepositoryManager gitMgr,
- GeneralPreferencesLoader loader, AllUsersName allUsersName,
- GeneralPreferencesInfo in) throws IOException, ConfigInvalidException,
- RepositoryNotFoundException {
+ static GeneralPreferencesInfo readFromGit(
+ GitRepositoryManager gitMgr,
+ GeneralPreferencesLoader loader,
+ AllUsersName allUsersName,
+ GeneralPreferencesInfo in)
+ throws IOException, ConfigInvalidException, RepositoryNotFoundException {
try (Repository git = gitMgr.openRepository(allUsersName)) {
VersionedAccountPreferences p = VersionedAccountPreferences.forDefault();
p.load(git);
- GeneralPreferencesInfo r = loadSection(p.getConfig(),
- UserConfigSections.GENERAL, null, new GeneralPreferencesInfo(),
- GeneralPreferencesInfo.defaults(), in);
+ GeneralPreferencesInfo r =
+ loadSection(
+ p.getConfig(),
+ UserConfigSections.GENERAL,
+ null,
+ new GeneralPreferencesInfo(),
+ GeneralPreferencesInfo.defaults(),
+ in);
// TODO(davido): Maintain cache of default values in AllUsers repository
return loader.loadMyMenusAndUrlAliases(r, p, null);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/GetServerInfo.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/GetServerInfo.java
index 54fc3fa..2ecbb54 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/GetServerInfo.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/GetServerInfo.java
@@ -52,9 +52,6 @@
import com.google.gerrit.server.notedb.NotesMigration;
import com.google.gerrit.server.project.ProjectCache;
import com.google.inject.Inject;
-
-import org.eclipse.jgit.lib.Config;
-
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Collection;
@@ -63,6 +60,7 @@
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
+import org.eclipse.jgit.lib.Config;
public class GetServerInfo implements RestReadView<ConfigResource> {
private static final String URL_ALIAS = "urlAlias";
@@ -137,8 +135,7 @@
info.auth = getAuthInfo(authConfig, realm);
info.change = getChangeInfo(config);
info.download =
- getDownloadInfo(downloadSchemes, downloadCommands, cloneCommands,
- archiveFormats);
+ getDownloadInfo(downloadSchemes, downloadCommands, cloneCommands, archiveFormats);
info.gerrit = getGerritInfo(config, allProjectsName, allUsersName);
info.noteDbEnabled = toBoolean(isNoteDbEnabled());
info.plugin = getPluginInfo();
@@ -166,9 +163,8 @@
Collection<ContributorAgreement> agreements =
projectCache.getAllProjects().getConfig().getContributorAgreements();
if (!agreements.isEmpty()) {
- info.contributorAgreements =
- Lists.newArrayListWithCapacity(agreements.size());
- for (ContributorAgreement agreement: agreements) {
+ info.contributorAgreements = Lists.newArrayListWithCapacity(agreements.size());
+ for (ContributorAgreement agreement : agreements) {
info.contributorAgreements.add(agreementJson.format(agreement));
}
}
@@ -209,19 +205,18 @@
ChangeConfigInfo info = new ChangeConfigInfo();
info.allowBlame = toBoolean(cfg.getBoolean("change", "allowBlame", true));
info.allowDrafts = toBoolean(cfg.getBoolean("change", "allowDrafts", true));
- info.showAssignee = toBoolean(
- cfg.getBoolean("change", "showAssignee", true)
- && indexes.getSearchIndex().getSchema()
- .hasField(ChangeField.ASSIGNEE));
+ info.showAssignee =
+ toBoolean(
+ cfg.getBoolean("change", "showAssignee", true)
+ && indexes.getSearchIndex().getSchema().hasField(ChangeField.ASSIGNEE));
info.largeChange = cfg.getInt("change", "largeChange", 500);
info.replyTooltip =
- Optional.ofNullable(cfg.getString("change", null, "replyTooltip"))
- .orElse("Reply and score") + " (Shortcut: a)";
+ Optional.ofNullable(cfg.getString("change", null, "replyTooltip")).orElse("Reply and score")
+ + " (Shortcut: a)";
info.replyLabel =
- Optional.ofNullable(cfg.getString("change", null, "replyLabel"))
- .orElse("Reply") + "\u2026";
- info.updateDelay = (int) ConfigUtil.getTimeUnit(
- cfg, "change", null, "updateDelay", 30, TimeUnit.SECONDS);
+ Optional.ofNullable(cfg.getString("change", null, "replyLabel")).orElse("Reply") + "\u2026";
+ info.updateDelay =
+ (int) ConfigUtil.getTimeUnit(cfg, "change", null, "updateDelay", 30, TimeUnit.SECONDS);
info.submitWholeTopic = Submit.wholeTopicEnabled(cfg);
return info;
}
@@ -236,16 +231,17 @@
for (DynamicMap.Entry<DownloadScheme> e : downloadSchemes) {
DownloadScheme scheme = e.getProvider().get();
if (scheme.isEnabled() && scheme.getUrl("${project}") != null) {
- info.schemes.put(e.getExportName(),
- getDownloadSchemeInfo(scheme, downloadCommands, cloneCommands));
+ info.schemes.put(
+ e.getExportName(), getDownloadSchemeInfo(scheme, downloadCommands, cloneCommands));
}
}
- info.archives = archiveFormats.getAllowed().stream()
- .map(ArchiveFormat::getShortName).collect(toList());
+ info.archives =
+ archiveFormats.getAllowed().stream().map(ArchiveFormat::getShortName).collect(toList());
return info;
}
- private DownloadSchemeInfo getDownloadSchemeInfo(DownloadScheme scheme,
+ private DownloadSchemeInfo getDownloadSchemeInfo(
+ DownloadScheme scheme,
DynamicMap<DownloadCommand> downloadCommands,
DynamicMap<CloneCommand> cloneCommands) {
DownloadSchemeInfo info = new DownloadSchemeInfo();
@@ -269,8 +265,7 @@
CloneCommand command = e.getProvider().get();
String c = command.getCommand(scheme, "${project-path}/${project-base-name}");
if (c != null) {
- c = c.replaceAll("\\$\\{project-path\\}/\\$\\{project-base-name\\}",
- "\\$\\{project\\}");
+ c = c.replaceAll("\\$\\{project-path\\}/\\$\\{project-base-name\\}", "\\$\\{project\\}");
info.cloneCommands.put(commandName, c);
}
}
@@ -278,8 +273,8 @@
return info;
}
- private GerritInfo getGerritInfo(Config cfg, AllProjectsName allProjectsName,
- AllUsersName allUsersName) {
+ private GerritInfo getGerritInfo(
+ Config cfg, AllProjectsName allProjectsName, AllUsersName allUsersName) {
GerritInfo info = new GerritInfo();
info.allProjects = allProjectsName.get();
info.allUsers = allUsersName.get();
@@ -287,8 +282,8 @@
info.reportBugText = cfg.getString("gerrit", null, "reportBugText");
info.docUrl = getDocUrl(cfg);
info.docSearch = docSearcher.isAvailable();
- info.editGpgKeys = toBoolean(enableSignedPush
- && cfg.getBoolean("gerrit", null, "editGpgKeys", true));
+ info.editGpgKeys =
+ toBoolean(enableSignedPush && cfg.getBoolean("gerrit", null, "editGpgKeys", true));
info.webUis = EnumSet.noneOf(UiType.class);
if (gerritOptions.enableGwtUi()) {
info.webUis.add(UiType.GWT);
@@ -316,9 +311,8 @@
info.hasAvatars = toBoolean(avatar.get() != null);
info.jsResourcePaths = new ArrayList<>();
for (WebUiPlugin u : plugins) {
- info.jsResourcePaths.add(String.format("plugins/%s/%s",
- u.getPluginName(),
- u.getJavaScriptResourcePath()));
+ info.jsResourcePaths.add(
+ String.format("plugins/%s/%s", u.getPluginName(), u.getJavaScriptResourcePath()));
}
return info;
}
@@ -326,8 +320,9 @@
private Map<String, String> getUrlAliasesInfo(Config cfg) {
Map<String, String> urlAliases = new HashMap<>();
for (String subsection : cfg.getSubsections(URL_ALIAS)) {
- urlAliases.put(cfg.getString(URL_ALIAS, subsection, KEY_MATCH),
- cfg.getString(URL_ALIAS, subsection, KEY_TOKEN));
+ urlAliases.put(
+ cfg.getString(URL_ALIAS, subsection, KEY_MATCH),
+ cfg.getString(URL_ALIAS, subsection, KEY_TOKEN));
}
return urlAliases;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/GetSummary.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/GetSummary.java
index 722eb91..62de688 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/GetSummary.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/GetSummary.java
@@ -20,10 +20,6 @@
import com.google.gerrit.server.git.WorkQueue;
import com.google.gerrit.server.git.WorkQueue.Task;
import com.google.inject.Inject;
-
-import org.eclipse.jgit.internal.storage.file.WindowCacheStatAccessor;
-import org.kohsuke.args4j.Option;
-
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
@@ -39,6 +35,8 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import org.eclipse.jgit.internal.storage.file.WindowCacheStatAccessor;
+import org.kohsuke.args4j.Option;
@RequiresCapability(GlobalCapability.MAINTAIN_SERVER)
public class GetSummary implements RestReadView<ConfigResource> {
@@ -69,7 +67,7 @@
}
@Override
- public SummaryInfo apply(ConfigResource rsrc) {
+ public SummaryInfo apply(ConfigResource rsrc) {
if (gc) {
System.gc();
System.runFinalization();
@@ -94,11 +92,14 @@
int tasksSleeping = 0;
for (Task<?> task : pending) {
switch (task.getState()) {
- case RUNNING: tasksRunning++;
+ case RUNNING:
+ tasksRunning++;
break;
- case READY: tasksReady++;
+ case READY:
+ tasksReady++;
break;
- case SLEEPING: tasksSleeping++;
+ case SLEEPING:
+ tasksSleeping++;
break;
case CANCELLED:
case DONE:
@@ -141,9 +142,16 @@
threadInfo.cpus = r.availableProcessors();
threadInfo.threads = toInteger(ManagementFactory.getThreadMXBean().getThreadCount());
- List<String> prefixes = Arrays.asList("HTTP", "IntraLineDiff", "ReceiveCommits",
- "SSH git-receive-pack", "SSH git-upload-pack", "SSH-Interactive-Worker",
- "SSH-Stream-Worker", "SshCommandStart");
+ List<String> prefixes =
+ Arrays.asList(
+ "HTTP",
+ "IntraLineDiff",
+ "ReceiveCommits",
+ "SSH git-receive-pack",
+ "SSH git-upload-pack",
+ "SSH-Interactive-Worker",
+ "SSH-Stream-Worker",
+ "SshCommandStart");
String other = "Other";
ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
@@ -193,8 +201,7 @@
// Ignored
}
- jvmSummary.currentWorkingDirectory =
- path(Paths.get(".").toAbsolutePath().getParent());
+ jvmSummary.currentWorkingDirectory = path(Paths.get(".").toAbsolutePath().getParent());
jvmSummary.site = path(sitePath);
return jvmSummary;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/GitReceivePackGroups.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/GitReceivePackGroups.java
index 35ea9e6..d74ce79 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/GitReceivePackGroups.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/GitReceivePackGroups.java
@@ -17,14 +17,12 @@
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import com.google.inject.BindingAnnotation;
-
import java.lang.annotation.Retention;
/**
- * Used to populate the groups of users that are allowed to run
- * receive-pack on the server.
+ * Used to populate the groups of users that are allowed to run receive-pack on the server.
*
- * Gerrit.config example:
+ * <p>Gerrit.config example:
*
* <pre>
* [receive]
@@ -33,5 +31,4 @@
*/
@Retention(RUNTIME)
@BindingAnnotation
-public @interface GitReceivePackGroups {
-}
+public @interface GitReceivePackGroups {}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/GitReceivePackGroupsProvider.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/GitReceivePackGroupsProvider.java
index 49b3467..d28f87a 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/GitReceivePackGroupsProvider.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/GitReceivePackGroupsProvider.java
@@ -20,19 +20,21 @@
import com.google.gerrit.server.util.ServerRequestContext;
import com.google.gerrit.server.util.ThreadLocalRequestContext;
import com.google.inject.Inject;
-
-import org.eclipse.jgit.lib.Config;
-
import java.util.Collections;
+import org.eclipse.jgit.lib.Config;
public class GitReceivePackGroupsProvider extends GroupSetProvider {
@Inject
- public GitReceivePackGroupsProvider(GroupBackend gb,
+ public GitReceivePackGroupsProvider(
+ GroupBackend gb,
@GerritServerConfig Config config,
ThreadLocalRequestContext threadContext,
ServerRequestContext serverCtx) {
- super(gb, threadContext, serverCtx, ImmutableList.copyOf(
- config.getStringList("receive", null, "allowGroup")));
+ super(
+ gb,
+ threadContext,
+ serverCtx,
+ ImmutableList.copyOf(config.getStringList("receive", null, "allowGroup")));
// If no group was set, default to "registered users"
//
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/GitUploadPackGroups.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/GitUploadPackGroups.java
index fa8ccb7..a41d0a9 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/GitUploadPackGroups.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/GitUploadPackGroups.java
@@ -17,14 +17,12 @@
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import com.google.inject.BindingAnnotation;
-
import java.lang.annotation.Retention;
/**
- * Used to populate the groups of users that are allowed to run
- * upload-pack on the server.
+ * Used to populate the groups of users that are allowed to run upload-pack on the server.
*
- * Gerrit.config example:
+ * <p>Gerrit.config example:
*
* <pre>
* [upload]
@@ -33,5 +31,4 @@
*/
@Retention(RUNTIME)
@BindingAnnotation
-public @interface GitUploadPackGroups {
-}
+public @interface GitUploadPackGroups {}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/GitUploadPackGroupsProvider.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/GitUploadPackGroupsProvider.java
index b772089..8d6926a 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/GitUploadPackGroupsProvider.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/GitUploadPackGroupsProvider.java
@@ -21,24 +21,26 @@
import com.google.gerrit.server.util.ServerRequestContext;
import com.google.gerrit.server.util.ThreadLocalRequestContext;
import com.google.inject.Inject;
-
import org.eclipse.jgit.lib.Config;
public class GitUploadPackGroupsProvider extends GroupSetProvider {
@Inject
- public GitUploadPackGroupsProvider(GroupBackend gb,
+ public GitUploadPackGroupsProvider(
+ GroupBackend gb,
@GerritServerConfig Config config,
ThreadLocalRequestContext threadContext,
ServerRequestContext serverCtx) {
- super(gb, threadContext, serverCtx, ImmutableList.copyOf(
- config.getStringList("upload", null, "allowGroup")));
+ super(
+ gb,
+ threadContext,
+ serverCtx,
+ ImmutableList.copyOf(config.getStringList("upload", null, "allowGroup")));
// If no group was set, default to "registered users" and "anonymous"
//
if (groupIds.isEmpty()) {
- groupIds = ImmutableSet.of(
- SystemGroupBackend.REGISTERED_USERS,
- SystemGroupBackend.ANONYMOUS_USERS);
+ groupIds =
+ ImmutableSet.of(SystemGroupBackend.REGISTERED_USERS, SystemGroupBackend.ANONYMOUS_USERS);
}
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/GitwebCgiConfig.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/GitwebCgiConfig.java
index 830579f..153cddc 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/GitwebCgiConfig.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/GitwebCgiConfig.java
@@ -19,18 +19,15 @@
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
+import java.nio.file.Path;
+import java.nio.file.Paths;
import org.eclipse.jgit.lib.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-
@Singleton
public class GitwebCgiConfig {
- private static final Logger log =
- LoggerFactory.getLogger(GitwebCgiConfig.class);
+ private static final Logger log = LoggerFactory.getLogger(GitwebCgiConfig.class);
public GitwebCgiConfig disabled() {
return new GitwebCgiConfig();
@@ -54,10 +51,7 @@
String cfgCgi = cfg.getString("gitweb", null, "cgi");
Path pkgCgi = Paths.get("/usr/lib/cgi-bin/gitweb.cgi");
String[] resourcePaths = {
- "/usr/share/gitweb/static",
- "/usr/share/gitweb",
- "/var/www/static",
- "/var/www",
+ "/usr/share/gitweb/static", "/usr/share/gitweb", "/var/www/static", "/var/www",
};
Path cgi;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/GitwebConfig.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/GitwebConfig.java
index d8fc9f8..723e9bf 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/GitwebConfig.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/GitwebConfig.java
@@ -34,7 +34,6 @@
import com.google.inject.AbstractModule;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
import org.eclipse.jgit.lib.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -65,8 +64,7 @@
DynamicSet.bind(binder(), BranchWebLink.class).to(GitwebLinks.class);
}
- if (!isNullOrEmpty(type.getFile())
- || !isNullOrEmpty(type.getRootTree())) {
+ if (!isNullOrEmpty(type.getFile()) || !isNullOrEmpty(type.getRootTree())) {
DynamicSet.bind(binder(), FileWebLink.class).to(GitwebLinks.class);
}
@@ -86,8 +84,7 @@
}
}
- private static boolean isEmptyString(Config cfg, String section,
- String subsection, String name) {
+ private static boolean isEmptyString(Config cfg, String section, String subsection, String name) {
// This is currently the only way to check for the empty string in a JGit
// config. Fun!
String[] values = cfg.getStringList(section, subsection, name);
@@ -101,43 +98,30 @@
}
GitwebType type = new GitwebType();
- type.setLinkName(firstNonNull(
- cfg.getString("gitweb", null, "linkname"),
- defaultType.getLinkName()));
- type.setBranch(firstNonNull(
- cfg.getString("gitweb", null, "branch"),
- defaultType.getBranch()));
- type.setProject(firstNonNull(
- cfg.getString("gitweb", null, "project"),
- defaultType.getProject()));
- type.setRevision(firstNonNull(
- cfg.getString("gitweb", null, "revision"),
- defaultType.getRevision()));
- type.setRootTree(firstNonNull(
- cfg.getString("gitweb", null, "roottree"),
- defaultType.getRootTree()));
- type.setFile(firstNonNull(
- cfg.getString("gitweb", null, "file"),
- defaultType.getFile()));
- type.setFileHistory(firstNonNull(
- cfg.getString("gitweb", null, "filehistory"),
- defaultType.getFileHistory()));
- type.setUrlEncode(
- cfg.getBoolean("gitweb", null, "urlencode",
- defaultType.getUrlEncode()));
+ type.setLinkName(
+ firstNonNull(cfg.getString("gitweb", null, "linkname"), defaultType.getLinkName()));
+ type.setBranch(firstNonNull(cfg.getString("gitweb", null, "branch"), defaultType.getBranch()));
+ type.setProject(
+ firstNonNull(cfg.getString("gitweb", null, "project"), defaultType.getProject()));
+ type.setRevision(
+ firstNonNull(cfg.getString("gitweb", null, "revision"), defaultType.getRevision()));
+ type.setRootTree(
+ firstNonNull(cfg.getString("gitweb", null, "roottree"), defaultType.getRootTree()));
+ type.setFile(firstNonNull(cfg.getString("gitweb", null, "file"), defaultType.getFile()));
+ type.setFileHistory(
+ firstNonNull(cfg.getString("gitweb", null, "filehistory"), defaultType.getFileHistory()));
+ type.setUrlEncode(cfg.getBoolean("gitweb", null, "urlencode", defaultType.getUrlEncode()));
String pathSeparator = cfg.getString("gitweb", null, "pathSeparator");
if (pathSeparator != null) {
if (pathSeparator.length() == 1) {
char c = pathSeparator.charAt(0);
if (isValidPathSeparator(c)) {
- type.setPathSeparator(
- firstNonNull(c, defaultType.getPathSeparator()));
+ type.setPathSeparator(firstNonNull(c, defaultType.getPathSeparator()));
} else {
log.warn("Invalid gitweb.pathSeparator: " + c);
}
} else {
- log.warn(
- "gitweb.pathSeparator is not a single character: " + pathSeparator);
+ log.warn("gitweb.pathSeparator is not a single character: " + pathSeparator);
}
}
return type;
@@ -153,8 +137,7 @@
type.setBranch("?p=${project}.git;a=shortlog;h=${branch}");
type.setRootTree("?p=${project}.git;a=tree;hb=${commit}");
type.setFile("?p=${project}.git;hb=${commit};f=${file}");
- type.setFileHistory(
- "?p=${project}.git;a=history;hb=${branch};f=${file}");
+ type.setFileHistory("?p=${project}.git;a=history;hb=${branch};f=${file}");
break;
case "cgit":
type.setLinkName("cgit");
@@ -205,36 +188,35 @@
}
}
- /** @return GitwebType for gitweb viewer. */
- @Nullable
- public GitwebType getGitwebType() {
- return type;
- }
+ /** @return GitwebType for gitweb viewer. */
+ @Nullable
+ public GitwebType getGitwebType() {
+ return type;
+ }
/**
- * @return URL of the entry point into gitweb. This URL may be relative to our
- * context if gitweb is hosted by ourselves; or absolute if its hosted
- * elsewhere; or null if gitweb has not been configured.
+ * @return URL of the entry point into gitweb. This URL may be relative to our context if gitweb
+ * is hosted by ourselves; or absolute if its hosted elsewhere; or null if gitweb has not been
+ * configured.
*/
public String getUrl() {
return url;
}
/**
- * Determines if a given character can be used unencoded in an URL as a
- * replacement for the path separator '/'.
+ * Determines if a given character can be used unencoded in an URL as a replacement for the path
+ * separator '/'.
*
- * Reasoning: http://www.ietf.org/rfc/rfc1738.txt § 2.2:
+ * <p>Reasoning: http://www.ietf.org/rfc/rfc1738.txt § 2.2:
*
- * ... only alphanumerics, the special characters "$-_.+!*'(),", and
- * reserved characters used for their reserved purposes may be used
- * unencoded within a URL.
+ * <p>... only alphanumerics, the special characters "$-_.+!*'(),", and reserved characters used
+ * for their reserved purposes may be used unencoded within a URL.
*
- * The following characters might occur in file names, however:
+ * <p>The following characters might occur in file names, however:
*
- * alphanumeric characters,
+ * <p>alphanumeric characters,
*
- * "$-_.+!',"
+ * <p>"$-_.+!',"
*/
static boolean isValidPathSeparator(char c) {
switch (c) {
@@ -248,8 +230,13 @@
}
@Singleton
- static class GitwebLinks implements BranchWebLink, FileHistoryWebLink,
- FileWebLink, PatchSetWebLink, ParentWebLink, ProjectWebLink {
+ static class GitwebLinks
+ implements BranchWebLink,
+ FileHistoryWebLink,
+ FileWebLink,
+ PatchSetWebLink,
+ ParentWebLink,
+ ProjectWebLink {
private final String url;
private final GitwebType type;
private final ParameterizedString branch;
@@ -263,9 +250,7 @@
this.url = config.getUrl();
this.type = type;
this.branch = parse(type.getBranch());
- this.file = parse(firstNonNull(
- emptyToNull(type.getFile()),
- nullToEmpty(type.getRootTree())));
+ this.file = parse(firstNonNull(emptyToNull(type.getFile()), nullToEmpty(type.getRootTree())));
this.fileHistory = parse(type.getFileHistory());
this.project = parse(type.getProject());
this.revision = parse(type.getRevision());
@@ -274,36 +259,36 @@
@Override
public WebLinkInfo getBranchWebLink(String projectName, String branchName) {
if (branch != null) {
- return link(branch
- .replace("project", encode(projectName))
- .replace("branch", encode(branchName))
- .toString());
+ return link(
+ branch
+ .replace("project", encode(projectName))
+ .replace("branch", encode(branchName))
+ .toString());
}
return null;
}
@Override
- public WebLinkInfo getFileHistoryWebLink(String projectName,
- String revision, String fileName) {
+ public WebLinkInfo getFileHistoryWebLink(String projectName, String revision, String fileName) {
if (fileHistory != null) {
- return link(fileHistory
- .replace("project", encode(projectName))
- .replace("branch", encode(revision))
- .replace("file", encode(fileName))
- .toString());
+ return link(
+ fileHistory
+ .replace("project", encode(projectName))
+ .replace("branch", encode(revision))
+ .replace("file", encode(fileName))
+ .toString());
}
return null;
}
@Override
- public WebLinkInfo getFileWebLink(String projectName, String revision,
- String fileName) {
+ public WebLinkInfo getFileWebLink(String projectName, String revision, String fileName) {
if (file != null) {
- return link(file
- .replace("project", encode(projectName))
- .replace("commit", encode(revision))
- .replace("file", encode(fileName))
- .toString());
+ return link(
+ file.replace("project", encode(projectName))
+ .replace("commit", encode(revision))
+ .replace("file", encode(fileName))
+ .toString());
}
return null;
}
@@ -311,10 +296,11 @@
@Override
public WebLinkInfo getPatchSetWebLink(String projectName, String commit) {
if (revision != null) {
- return link(revision
- .replace("project", encode(projectName))
- .replace("commit", encode(commit))
- .toString());
+ return link(
+ revision
+ .replace("project", encode(projectName))
+ .replace("commit", encode(commit))
+ .toString());
}
return null;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/GlobalPluginConfig.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/GlobalPluginConfig.java
index 2a2c316..19ceaa1 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/GlobalPluginConfig.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/GlobalPluginConfig.java
@@ -15,18 +15,14 @@
package com.google.gerrit.server.config;
import com.google.gerrit.server.securestore.SecureStore;
-
import org.eclipse.jgit.lib.Config;
-/**
- * Plugin configuration in etc/$PLUGIN.config and etc/$PLUGIN.secure.config.
- */
+/** Plugin configuration in etc/$PLUGIN.config and etc/$PLUGIN.secure.config. */
public class GlobalPluginConfig extends Config {
private final SecureStore secureStore;
private final String pluginName;
- GlobalPluginConfig(String pluginName, Config baseConfig,
- SecureStore secureStore) {
+ GlobalPluginConfig(String pluginName, Config baseConfig, SecureStore secureStore) {
super(baseConfig);
this.pluginName = pluginName;
this.secureStore = secureStore;
@@ -34,8 +30,7 @@
@Override
public String getString(String section, String subsection, String name) {
- String secure = secureStore.getForPlugin(
- pluginName, section, subsection, name);
+ String secure = secureStore.getForPlugin(pluginName, section, subsection, name);
if (secure != null) {
return secure;
}
@@ -44,8 +39,7 @@
@Override
public String[] getStringList(String section, String subsection, String name) {
- String[] secure = secureStore.getListForPlugin(
- pluginName, section, subsection, name);
+ String[] secure = secureStore.getListForPlugin(pluginName, section, subsection, name);
if (secure != null && secure.length > 0) {
return secure;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/GroupSetProvider.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/GroupSetProvider.java
index 78af1ae..a8c1674 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/GroupSetProvider.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/GroupSetProvider.java
@@ -23,22 +23,21 @@
import com.google.gerrit.server.util.ServerRequestContext;
import com.google.gerrit.server.util.ThreadLocalRequestContext;
import com.google.inject.Provider;
-
+import java.util.List;
+import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.util.List;
-import java.util.Set;
-
/** Parses groups referenced in the {@code gerrit.config} file. */
-public abstract class GroupSetProvider implements
- Provider<Set<AccountGroup.UUID>> {
+public abstract class GroupSetProvider implements Provider<Set<AccountGroup.UUID>> {
protected Set<AccountGroup.UUID> groupIds;
- protected GroupSetProvider(GroupBackend groupBackend,
+ protected GroupSetProvider(
+ GroupBackend groupBackend,
ThreadLocalRequestContext threadContext,
- ServerRequestContext serverCtx, List<String> groupNames) {
+ ServerRequestContext serverCtx,
+ List<String> groupNames) {
RequestContext ctx = threadContext.setContext(serverCtx);
try {
ImmutableSet.Builder<AccountGroup.UUID> builder = ImmutableSet.builder();
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/ListCaches.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/ListCaches.java
index 15981d0..d78f61d 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/ListCaches.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/ListCaches.java
@@ -28,21 +28,20 @@
import com.google.gerrit.extensions.restapi.RestReadView;
import com.google.gerrit.server.cache.PersistentCache;
import com.google.inject.Inject;
-
-import org.kohsuke.args4j.Option;
-
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
+import org.kohsuke.args4j.Option;
@RequiresAnyCapability({VIEW_CACHES, MAINTAIN_SERVER})
public class ListCaches implements RestReadView<ConfigResource> {
private final DynamicMap<Cache<?, ?>> cacheMap;
public enum OutputFormat {
- LIST, TEXT_LIST
+ LIST,
+ TEXT_LIST
}
@Option(name = "--format", usage = "output format")
@@ -61,8 +60,8 @@
public Map<String, CacheInfo> getCacheInfos() {
Map<String, CacheInfo> cacheInfos = new TreeMap<>();
for (DynamicMap.Entry<Cache<?, ?>> e : cacheMap) {
- cacheInfos.put(cacheNameOf(e.getPluginName(), e.getExportName()),
- new CacheInfo(e.getProvider().get()));
+ cacheInfos.put(
+ cacheNameOf(e.getPluginName(), e.getExportName()), new CacheInfo(e.getProvider().get()));
}
return cacheInfos;
}
@@ -88,7 +87,8 @@
}
public enum CacheType {
- MEM, DISK
+ MEM,
+ DISK
}
public static class CacheInfo {
@@ -98,11 +98,11 @@
public String averageGet;
public HitRatioInfo hitRatio;
- public CacheInfo(Cache<?,?> cache) {
+ public CacheInfo(Cache<?, ?> cache) {
this(null, cache);
}
- public CacheInfo(String name, Cache<?,?> cache) {
+ public CacheInfo(String name, Cache<?, ?> cache) {
this.name = name;
CacheStats stat = cache.stats();
@@ -117,8 +117,7 @@
if (cache instanceof PersistentCache) {
type = CacheType.DISK;
- PersistentCache.DiskStats diskStats =
- ((PersistentCache) cache).diskStats();
+ PersistentCache.DiskStats diskStats = ((PersistentCache) cache).diskStats();
entries.setDisk(diskStats.size());
entries.setSpace(diskStats.space());
hitRatio.setDisk(diskStats.hitCount(), diskStats.requestCount());
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/ListCapabilities.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/ListCapabilities.java
index 3a87239..d21b5fa 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/ListCapabilities.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/ListCapabilities.java
@@ -22,12 +22,10 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.util.Map;
import java.util.TreeMap;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/** List capabilities visible to the calling user. */
@Singleton
@@ -51,8 +49,7 @@
private void collectCoreCapabilities(Map<String, CapabilityInfo> output)
throws IllegalAccessException, NoSuchFieldException {
- Class<? extends CapabilityConstants> bundleClass =
- CapabilityConstants.get().getClass();
+ Class<? extends CapabilityConstants> bundleClass = CapabilityConstants.get().getClass();
CapabilityConstants c = CapabilityConstants.get();
for (String id : GlobalCapability.getAllNames()) {
String name = (String) bundleClass.getField(id).get(c);
@@ -63,26 +60,23 @@
private void collectPluginCapabilities(Map<String, CapabilityInfo> output) {
for (String pluginName : pluginCapabilities.plugins()) {
if (!isPluginNameSane(pluginName)) {
- log.warn(String.format(
- "Plugin name %s must match [A-Za-z0-9-]+ to use capabilities;"
- + " rename the plugin",
- pluginName));
+ log.warn(
+ String.format(
+ "Plugin name %s must match [A-Za-z0-9-]+ to use capabilities;"
+ + " rename the plugin",
+ pluginName));
continue;
}
for (Map.Entry<String, Provider<CapabilityDefinition>> entry :
pluginCapabilities.byPlugin(pluginName).entrySet()) {
String id = String.format("%s-%s", pluginName, entry.getKey());
- output.put(id, new CapabilityInfo(
- id,
- entry.getValue().get().getDescription()));
+ output.put(id, new CapabilityInfo(id, entry.getValue().get().getDescription()));
}
}
}
private static boolean isPluginNameSane(String pluginName) {
- return CharMatcher.javaLetterOrDigit()
- .or(CharMatcher.is('-'))
- .matchesAllOf(pluginName);
+ return CharMatcher.javaLetterOrDigit().or(CharMatcher.is('-')).matchesAllOf(pluginName);
}
public static class CapabilityInfo {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/ListTasks.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/ListTasks.java
index b96d5d9..7e9bd71 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/ListTasks.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/ListTasks.java
@@ -30,7 +30,6 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collections;
@@ -47,8 +46,7 @@
private final Provider<IdentifiedUser> self;
@Inject
- public ListTasks(WorkQueue workQueue, ProjectCache projectCache,
- Provider<IdentifiedUser> self) {
+ public ListTasks(WorkQueue workQueue, ProjectCache projectCache, Provider<IdentifiedUser> self) {
this.workQueue = workQueue;
this.projectCache = projectCache;
this.self = self;
@@ -86,22 +84,25 @@
private List<TaskInfo> getTasks() {
List<TaskInfo> taskInfos =
- workQueue.getTaskInfos(new TaskInfoFactory<TaskInfo>() {
+ workQueue.getTaskInfos(
+ new TaskInfoFactory<TaskInfo>() {
+ @Override
+ public TaskInfo getTaskInfo(Task<?> task) {
+ return new TaskInfo(task);
+ }
+ });
+ Collections.sort(
+ taskInfos,
+ new Comparator<TaskInfo>() {
@Override
- public TaskInfo getTaskInfo(Task<?> task) {
- return new TaskInfo(task);
+ public int compare(TaskInfo a, TaskInfo b) {
+ return ComparisonChain.start()
+ .compare(a.state.ordinal(), b.state.ordinal())
+ .compare(a.delay, b.delay)
+ .compare(a.command, b.command)
+ .result();
}
});
- Collections.sort(taskInfos, new Comparator<TaskInfo>() {
- @Override
- public int compare(TaskInfo a, TaskInfo b) {
- return ComparisonChain.start()
- .compare(a.state.ordinal(), b.state.ordinal())
- .compare(a.delay, b.delay)
- .compare(a.command, b.command)
- .result();
- }
- });
return taskInfos;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/ListTopMenus.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/ListTopMenus.java
index c7d10a3..a7ba938 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/ListTopMenus.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/ListTopMenus.java
@@ -19,7 +19,6 @@
import com.google.gerrit.extensions.webui.TopMenu;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
import java.util.ArrayList;
import java.util.List;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/PluginConfig.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/PluginConfig.java
index d8485fe..1b12495 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/PluginConfig.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/PluginConfig.java
@@ -19,13 +19,11 @@
import com.google.common.collect.Iterables;
import com.google.gerrit.server.git.ProjectConfig;
import com.google.gerrit.server.project.ProjectState;
-
-import org.eclipse.jgit.errors.ConfigInvalidException;
-import org.eclipse.jgit.lib.Config;
-
import java.util.Arrays;
import java.util.List;
import java.util.Set;
+import org.eclipse.jgit.errors.ConfigInvalidException;
+import org.eclipse.jgit.lib.Config;
public class PluginConfig {
private static final String PLUGIN = "plugin";
@@ -53,14 +51,16 @@
ProjectState parent = Iterables.getFirst(state.parents(), null);
if (parent != null) {
PluginConfig parentPluginConfig =
- parent.getConfig().getPluginConfig(pluginName)
- .withInheritance(projectStateFactory);
+ parent.getConfig().getPluginConfig(pluginName).withInheritance(projectStateFactory);
Set<String> allNames = cfg.getNames(PLUGIN, pluginName);
cfg = copyConfig(cfg);
for (String name : parentPluginConfig.cfg.getNames(PLUGIN, pluginName)) {
if (!allNames.contains(name)) {
- cfg.setStringList(PLUGIN, pluginName, name, Arrays
- .asList(parentPluginConfig.cfg.getStringList(PLUGIN, pluginName, name)));
+ cfg.setStringList(
+ PLUGIN,
+ pluginName,
+ name,
+ Arrays.asList(parentPluginConfig.cfg.getStringList(PLUGIN, pluginName, name)));
}
}
}
@@ -86,8 +86,7 @@
if (defaultValue == null) {
return cfg.getString(PLUGIN, pluginName, name);
}
- return MoreObjects.firstNonNull(cfg.getString(PLUGIN, pluginName, name),
- defaultValue);
+ return MoreObjects.firstNonNull(cfg.getString(PLUGIN, pluginName, name), defaultValue);
}
public void setString(String name, String value) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/PluginConfigFactory.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/PluginConfigFactory.java
index e12cc24..ce295bd 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/PluginConfigFactory.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/PluginConfigFactory.java
@@ -25,7 +25,11 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Path;
+import java.util.HashMap;
+import java.util.Map;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.internal.storage.file.FileSnapshot;
import org.eclipse.jgit.lib.Config;
@@ -34,16 +38,9 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.File;
-import java.io.IOException;
-import java.nio.file.Path;
-import java.util.HashMap;
-import java.util.Map;
-
@Singleton
public class PluginConfigFactory implements ReloadPluginListener {
- private static final Logger log =
- LoggerFactory.getLogger(PluginConfigFactory.class);
+ private static final Logger log = LoggerFactory.getLogger(PluginConfigFactory.class);
private static final String EXTENSION = ".config";
private final SitePaths site;
@@ -75,19 +72,14 @@
}
/**
- * Returns the configuration for the specified plugin that is stored in the
- * 'gerrit.config' file.
+ * Returns the configuration for the specified plugin that is stored in the 'gerrit.config' file.
*
- * The returned plugin configuration provides access to all parameters of the
- * 'gerrit.config' file that are set in the 'plugin' subsection of the
- * specified plugin.
+ * <p>The returned plugin configuration provides access to all parameters of the 'gerrit.config'
+ * file that are set in the 'plugin' subsection of the specified plugin.
*
- * E.g.:
- * [plugin "my-plugin"]
- * myKey = myValue
+ * <p>E.g.: [plugin "my-plugin"] myKey = myValue
*
- * @param pluginName the name of the plugin for which the configuration should
- * be returned
+ * @param pluginName the name of the plugin for which the configuration should be returned
* @return the plugin configuration from the 'gerrit.config' file
*/
public PluginConfig getFromGerritConfig(String pluginName) {
@@ -95,20 +87,17 @@
}
/**
- * Returns the configuration for the specified plugin that is stored in the
- * 'gerrit.config' file.
+ * Returns the configuration for the specified plugin that is stored in the 'gerrit.config' file.
*
- * The returned plugin configuration provides access to all parameters of the
- * 'gerrit.config' file that are set in the 'plugin' subsection of the
- * specified plugin.
+ * <p>The returned plugin configuration provides access to all parameters of the 'gerrit.config'
+ * file that are set in the 'plugin' subsection of the specified plugin.
*
- * E.g.: [plugin "my-plugin"] myKey = myValue
+ * <p>E.g.: [plugin "my-plugin"] myKey = myValue
*
- * @param pluginName the name of the plugin for which the configuration should
- * be returned
- * @param refresh if <code>true</code> it is checked if the 'gerrit.config'
- * file was modified and if yes the Gerrit configuration is reloaded,
- * if <code>false</code> the cached Gerrit configuration is used
+ * @param pluginName the name of the plugin for which the configuration should be returned
+ * @param refresh if <code>true</code> it is checked if the 'gerrit.config' file was modified and
+ * if yes the Gerrit configuration is reloaded, if <code>false</code> the cached Gerrit
+ * configuration is used
* @return the plugin configuration from the 'gerrit.config' file
*/
public PluginConfig getFromGerritConfig(String pluginName, boolean refresh) {
@@ -121,28 +110,22 @@
}
/**
- * Returns the configuration for the specified plugin that is stored in the
- * 'project.config' file of the specified project.
+ * Returns the configuration for the specified plugin that is stored in the 'project.config' file
+ * of the specified project.
*
- * The returned plugin configuration provides access to all parameters of the
- * 'project.config' file that are set in the 'plugin' subsection of the
- * specified plugin.
+ * <p>The returned plugin configuration provides access to all parameters of the 'project.config'
+ * file that are set in the 'plugin' subsection of the specified plugin.
*
- * E.g.:
- * [plugin "my-plugin"]
- * myKey = myValue
+ * <p>E.g.: [plugin "my-plugin"] myKey = myValue
*
- * @param projectName the name of the project for which the plugin
- * configuration should be returned
- * @param pluginName the name of the plugin for which the configuration should
- * be returned
- * @return the plugin configuration from the 'project.config' file of the
- * specified project
- * @throws NoSuchProjectException thrown if the specified project does not
- * exist
+ * @param projectName the name of the project for which the plugin configuration should be
+ * returned
+ * @param pluginName the name of the plugin for which the configuration should be returned
+ * @return the plugin configuration from the 'project.config' file of the specified project
+ * @throws NoSuchProjectException thrown if the specified project does not exist
*/
- public PluginConfig getFromProjectConfig(Project.NameKey projectName,
- String pluginName) throws NoSuchProjectException {
+ public PluginConfig getFromProjectConfig(Project.NameKey projectName, String pluginName)
+ throws NoSuchProjectException {
ProjectState projectState = projectCache.get(projectName);
if (projectState == null) {
throw new NoSuchProjectException(projectName);
@@ -151,110 +134,80 @@
}
/**
- * Returns the configuration for the specified plugin that is stored in the
- * 'project.config' file of the specified project.
+ * Returns the configuration for the specified plugin that is stored in the 'project.config' file
+ * of the specified project.
*
- * The returned plugin configuration provides access to all parameters of the
- * 'project.config' file that are set in the 'plugin' subsection of the
- * specified plugin.
+ * <p>The returned plugin configuration provides access to all parameters of the 'project.config'
+ * file that are set in the 'plugin' subsection of the specified plugin.
*
- * E.g.: [plugin "my-plugin"] myKey = myValue
+ * <p>E.g.: [plugin "my-plugin"] myKey = myValue
*
- * @param projectState the project for which the plugin configuration should
- * be returned
- * @param pluginName the name of the plugin for which the configuration should
- * be returned
- * @return the plugin configuration from the 'project.config' file of the
- * specified project
+ * @param projectState the project for which the plugin configuration should be returned
+ * @param pluginName the name of the plugin for which the configuration should be returned
+ * @return the plugin configuration from the 'project.config' file of the specified project
*/
- public PluginConfig getFromProjectConfig(ProjectState projectState,
- String pluginName) {
+ public PluginConfig getFromProjectConfig(ProjectState projectState, String pluginName) {
return projectState.getConfig().getPluginConfig(pluginName);
}
/**
- * Returns the configuration for the specified plugin that is stored in the
- * 'project.config' file of the specified project. Parameters which are not
- * set in the 'project.config' of this project are inherited from the parent
- * project's 'project.config' files.
+ * Returns the configuration for the specified plugin that is stored in the 'project.config' file
+ * of the specified project. Parameters which are not set in the 'project.config' of this project
+ * are inherited from the parent project's 'project.config' files.
*
- * The returned plugin configuration provides access to all parameters of the
- * 'project.config' file that are set in the 'plugin' subsection of the
- * specified plugin.
+ * <p>The returned plugin configuration provides access to all parameters of the 'project.config'
+ * file that are set in the 'plugin' subsection of the specified plugin.
*
- * E.g.:
- * child project:
- * [plugin "my-plugin"]
- * myKey = childValue
+ * <p>E.g.: child project: [plugin "my-plugin"] myKey = childValue
*
- * parent project:
- * [plugin "my-plugin"]
- * myKey = parentValue
- * anotherKey = someValue
+ * <p>parent project: [plugin "my-plugin"] myKey = parentValue anotherKey = someValue
*
- * return:
- * [plugin "my-plugin"]
- * myKey = childValue
- * anotherKey = someValue
+ * <p>return: [plugin "my-plugin"] myKey = childValue anotherKey = someValue
*
- * @param projectName the name of the project for which the plugin
- * configuration should be returned
- * @param pluginName the name of the plugin for which the configuration should
- * be returned
- * @return the plugin configuration from the 'project.config' file of the
- * specified project with inherited non-set parameters from the
- * parent projects
- * @throws NoSuchProjectException thrown if the specified project does not
- * exist
+ * @param projectName the name of the project for which the plugin configuration should be
+ * returned
+ * @param pluginName the name of the plugin for which the configuration should be returned
+ * @return the plugin configuration from the 'project.config' file of the specified project with
+ * inherited non-set parameters from the parent projects
+ * @throws NoSuchProjectException thrown if the specified project does not exist
*/
public PluginConfig getFromProjectConfigWithInheritance(
- Project.NameKey projectName, String pluginName)
- throws NoSuchProjectException {
- return getFromProjectConfig(projectName, pluginName).withInheritance(
- projectStateFactory);
+ Project.NameKey projectName, String pluginName) throws NoSuchProjectException {
+ return getFromProjectConfig(projectName, pluginName).withInheritance(projectStateFactory);
}
/**
- * Returns the configuration for the specified plugin that is stored in the
- * 'project.config' file of the specified project. Parameters which are not
- * set in the 'project.config' of this project are inherited from the parent
- * project's 'project.config' files.
+ * Returns the configuration for the specified plugin that is stored in the 'project.config' file
+ * of the specified project. Parameters which are not set in the 'project.config' of this project
+ * are inherited from the parent project's 'project.config' files.
*
- * The returned plugin configuration provides access to all parameters of the
- * 'project.config' file that are set in the 'plugin' subsection of the
- * specified plugin.
+ * <p>The returned plugin configuration provides access to all parameters of the 'project.config'
+ * file that are set in the 'plugin' subsection of the specified plugin.
*
- * E.g.: child project: [plugin "my-plugin"] myKey = childValue
+ * <p>E.g.: child project: [plugin "my-plugin"] myKey = childValue
*
- * parent project: [plugin "my-plugin"] myKey = parentValue anotherKey =
- * someValue
+ * <p>parent project: [plugin "my-plugin"] myKey = parentValue anotherKey = someValue
*
- * return: [plugin "my-plugin"] myKey = childValue anotherKey = someValue
+ * <p>return: [plugin "my-plugin"] myKey = childValue anotherKey = someValue
*
- * @param projectState the project for which the plugin configuration should
- * be returned
- * @param pluginName the name of the plugin for which the configuration should
- * be returned
- * @return the plugin configuration from the 'project.config' file of the
- * specified project with inherited non-set parameters from the parent
- * projects
+ * @param projectState the project for which the plugin configuration should be returned
+ * @param pluginName the name of the plugin for which the configuration should be returned
+ * @return the plugin configuration from the 'project.config' file of the specified project with
+ * inherited non-set parameters from the parent projects
*/
public PluginConfig getFromProjectConfigWithInheritance(
ProjectState projectState, String pluginName) {
- return getFromProjectConfig(projectState, pluginName).withInheritance(
- projectStateFactory);
+ return getFromProjectConfig(projectState, pluginName).withInheritance(projectStateFactory);
}
/**
- * Returns the configuration for the specified plugin that is stored in the
- * plugin configuration file '{@code etc/<plugin-name>.config}'.
+ * Returns the configuration for the specified plugin that is stored in the plugin configuration
+ * file '{@code etc/<plugin-name>.config}'.
*
- * The plugin configuration is only loaded once and is then cached.
+ * <p>The plugin configuration is only loaded once and is then cached.
*
- * @param pluginName the name of the plugin for which the configuration should
- * be returned
- * @return the plugin configuration from the
- * '{@code etc/<plugin-name>.config}' file
+ * @param pluginName the name of the plugin for which the configuration should be returned
+ * @return the plugin configuration from the '{@code etc/<plugin-name>.config}' file
*/
public synchronized Config getGlobalPluginConfig(String pluginName) {
if (pluginConfigs.containsKey(pluginName)) {
@@ -262,10 +215,8 @@
}
Path pluginConfigFile = site.etc_dir.resolve(pluginName + ".config");
- FileBasedConfig cfg =
- new FileBasedConfig(pluginConfigFile.toFile(), FS.DETECTED);
- GlobalPluginConfig pluginConfig =
- new GlobalPluginConfig(pluginName, cfg, secureStore);
+ FileBasedConfig cfg = new FileBasedConfig(pluginConfigFile.toFile(), FS.DETECTED);
+ GlobalPluginConfig pluginConfig = new GlobalPluginConfig(pluginName, cfg, secureStore);
pluginConfigs.put(pluginName, pluginConfig);
if (!cfg.getFile().exists()) {
log.info("No " + pluginConfigFile.toAbsolutePath() + "; assuming defaults");
@@ -276,8 +227,7 @@
cfg.load();
} catch (ConfigInvalidException e) {
// This is an error in user input, don't spam logs with a stack trace.
- log.warn(
- "Failed to load " + pluginConfigFile.toAbsolutePath() + ": " + e);
+ log.warn("Failed to load " + pluginConfigFile.toAbsolutePath() + ": " + e);
} catch (IOException e) {
log.warn("Failed to load " + pluginConfigFile.toAbsolutePath(), e);
}
@@ -286,101 +236,82 @@
}
/**
- * Returns the configuration for the specified plugin that is stored in the
- * '{@code <plugin-name>.config}' file in the 'refs/meta/config' branch of
- * the specified project.
+ * Returns the configuration for the specified plugin that is stored in the '{@code
+ * <plugin-name>.config}' file in the 'refs/meta/config' branch of the specified project.
*
- * @param projectName the name of the project for which the plugin
- * configuration should be returned
- * @param pluginName the name of the plugin for which the configuration should
- * be returned
- * @return the plugin configuration from the '{@code <plugin-name>.config}'
- * file of the specified project
- * @throws NoSuchProjectException thrown if the specified project does not
- * exist
+ * @param projectName the name of the project for which the plugin configuration should be
+ * returned
+ * @param pluginName the name of the plugin for which the configuration should be returned
+ * @return the plugin configuration from the '{@code <plugin-name>.config}' file of the specified
+ * project
+ * @throws NoSuchProjectException thrown if the specified project does not exist
*/
- public Config getProjectPluginConfig(Project.NameKey projectName,
- String pluginName) throws NoSuchProjectException {
+ public Config getProjectPluginConfig(Project.NameKey projectName, String pluginName)
+ throws NoSuchProjectException {
return getPluginConfig(projectName, pluginName).get();
}
/**
- * Returns the configuration for the specified plugin that is stored in the
- * '{@code <plugin-name>.config}' file in the 'refs/meta/config' branch of
- * the specified project.
+ * Returns the configuration for the specified plugin that is stored in the '{@code
+ * <plugin-name>.config}' file in the 'refs/meta/config' branch of the specified project.
*
- * @param projectState the project for which the plugin configuration should
- * be returned
- * @param pluginName the name of the plugin for which the configuration should
- * be returned
- * @return the plugin configuration from the '{@code <plugin-name>.config}'
- * file of the specified project
+ * @param projectState the project for which the plugin configuration should be returned
+ * @param pluginName the name of the plugin for which the configuration should be returned
+ * @return the plugin configuration from the '{@code <plugin-name>.config}' file of the specified
+ * project
*/
- public Config getProjectPluginConfig(ProjectState projectState,
- String pluginName) {
+ public Config getProjectPluginConfig(ProjectState projectState, String pluginName) {
return projectState.getConfig(pluginName + EXTENSION).get();
}
/**
- * Returns the configuration for the specified plugin that is stored in the
- * '{@code <plugin-name>.config}' file in the 'refs/meta/config' branch of
- * the specified project. Parameters which are not set in the
- * '{@code <plugin-name>.config}' of this project are inherited from the
- * parent project's '{@code <plugin-name>.config}' files.
+ * Returns the configuration for the specified plugin that is stored in the '{@code
+ * <plugin-name>.config}' file in the 'refs/meta/config' branch of the specified project.
+ * Parameters which are not set in the '{@code <plugin-name>.config}' of this project are
+ * inherited from the parent project's '{@code <plugin-name>.config}' files.
*
- * E.g.: child project: [mySection "mySubsection"] myKey = childValue
+ * <p>E.g.: child project: [mySection "mySubsection"] myKey = childValue
*
- * parent project: [mySection "mySubsection"] myKey = parentValue anotherKey =
- * someValue
+ * <p>parent project: [mySection "mySubsection"] myKey = parentValue anotherKey = someValue
*
- * return: [mySection "mySubsection"] myKey = childValue anotherKey =
- * someValue
+ * <p>return: [mySection "mySubsection"] myKey = childValue anotherKey = someValue
*
- * @param projectName the name of the project for which the plugin
- * configuration should be returned
- * @param pluginName the name of the plugin for which the configuration should
- * be returned
- * @return the plugin configuration from the '{@code <plugin-name>.config}'
- * file of the specified project with inheriting non-set parameters
- * from the parent projects
- * @throws NoSuchProjectException thrown if the specified project does not
- * exist
+ * @param projectName the name of the project for which the plugin configuration should be
+ * returned
+ * @param pluginName the name of the plugin for which the configuration should be returned
+ * @return the plugin configuration from the '{@code <plugin-name>.config}' file of the specified
+ * project with inheriting non-set parameters from the parent projects
+ * @throws NoSuchProjectException thrown if the specified project does not exist
*/
- public Config getProjectPluginConfigWithInheritance(Project.NameKey projectName,
- String pluginName) throws NoSuchProjectException {
+ public Config getProjectPluginConfigWithInheritance(
+ Project.NameKey projectName, String pluginName) throws NoSuchProjectException {
return getPluginConfig(projectName, pluginName).getWithInheritance();
}
/**
- * Returns the configuration for the specified plugin that is stored in the
- * '{@code <plugin-name>.config}' file in the 'refs/meta/config' branch of
- * the specified project. Parameters which are not set in the
- * '{@code <plugin-name>.config}' of this project are inherited from the
- * parent project's '{@code <plugin-name>.config}' files.
+ * Returns the configuration for the specified plugin that is stored in the '{@code
+ * <plugin-name>.config}' file in the 'refs/meta/config' branch of the specified project.
+ * Parameters which are not set in the '{@code <plugin-name>.config}' of this project are
+ * inherited from the parent project's '{@code <plugin-name>.config}' files.
*
- * E.g.: child project: [mySection "mySubsection"] myKey = childValue
+ * <p>E.g.: child project: [mySection "mySubsection"] myKey = childValue
*
- * parent project: [mySection "mySubsection"] myKey = parentValue anotherKey =
- * someValue
+ * <p>parent project: [mySection "mySubsection"] myKey = parentValue anotherKey = someValue
*
- * return: [mySection "mySubsection"] myKey = childValue anotherKey =
- * someValue
+ * <p>return: [mySection "mySubsection"] myKey = childValue anotherKey = someValue
*
- * @param projectState the project for which the plugin configuration should
- * be returned
- * @param pluginName the name of the plugin for which the configuration should
- * be returned
- * @return the plugin configuration from the '{@code <plugin-name>.config}'
- * file of the specified project with inheriting non-set parameters
- * from the parent projects
+ * @param projectState the project for which the plugin configuration should be returned
+ * @param pluginName the name of the plugin for which the configuration should be returned
+ * @return the plugin configuration from the '{@code <plugin-name>.config}' file of the specified
+ * project with inheriting non-set parameters from the parent projects
*/
- public Config getProjectPluginConfigWithInheritance(ProjectState projectState,
- String pluginName) {
+ public Config getProjectPluginConfigWithInheritance(
+ ProjectState projectState, String pluginName) {
return projectState.getConfig(pluginName + EXTENSION).getWithInheritance();
}
- private ProjectLevelConfig getPluginConfig(Project.NameKey projectName,
- String pluginName) throws NoSuchProjectException {
+ private ProjectLevelConfig getPluginConfig(Project.NameKey projectName, String pluginName)
+ throws NoSuchProjectException {
ProjectState projectState = projectCache.get(projectName);
if (projectState == null) {
throw new NoSuchProjectException(projectName);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/PostCaches.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/PostCaches.java
index f7968c8..3cfa2b9 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/PostCaches.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/PostCaches.java
@@ -28,7 +28,6 @@
import com.google.gerrit.server.config.PostCaches.Input;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
import java.util.ArrayList;
import java.util.List;
@@ -39,8 +38,7 @@
public Operation operation;
public List<String> caches;
- public Input() {
- }
+ public Input() {}
public Input(Operation op) {
this(op, null);
@@ -53,15 +51,15 @@
}
public enum Operation {
- FLUSH_ALL, FLUSH
+ FLUSH_ALL,
+ FLUSH
}
private final DynamicMap<Cache<?, ?>> cacheMap;
private final FlushCache flushCache;
@Inject
- public PostCaches(DynamicMap<Cache<?, ?>> cacheMap,
- FlushCache flushCache) {
+ public PostCaches(DynamicMap<Cache<?, ?>> cacheMap, FlushCache flushCache) {
this.cacheMap = cacheMap;
this.flushCache = flushCache;
}
@@ -83,8 +81,7 @@
return Response.ok("");
case FLUSH:
if (input.caches == null || input.caches.isEmpty()) {
- throw new BadRequestException(
- "caches must be specified for operation 'FLUSH'");
+ throw new BadRequestException("caches must be specified for operation 'FLUSH'");
}
flush(input.caches);
return Response.ok("");
@@ -96,8 +93,7 @@
private void flushAll() throws AuthException {
for (DynamicMap.Entry<Cache<?, ?>> e : cacheMap) {
CacheResource cacheResource =
- new CacheResource(e.getPluginName(), e.getExportName(),
- e.getProvider());
+ new CacheResource(e.getPluginName(), e.getExportName(), e.getProvider());
if (FlushCache.WEB_SESSIONS.equals(cacheResource.getName())) {
continue;
}
@@ -105,8 +101,7 @@
}
}
- private void flush(List<String> cacheNames)
- throws UnprocessableEntityException, AuthException {
+ private void flush(List<String> cacheNames) throws UnprocessableEntityException, AuthException {
List<CacheResource> cacheResources = new ArrayList<>(cacheNames.size());
for (String n : cacheNames) {
@@ -122,8 +117,7 @@
if (cache != null) {
cacheResources.add(new CacheResource(pluginName, cacheName, cache));
} else {
- throw new UnprocessableEntityException(String.format(
- "cache %s not found", n));
+ throw new UnprocessableEntityException(String.format("cache %s not found", n));
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/ProjectConfigEntry.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/ProjectConfigEntry.java
index 7d11ff4..65d880e 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/ProjectConfigEntry.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/ProjectConfigEntry.java
@@ -29,7 +29,9 @@
import com.google.gerrit.server.project.ProjectState;
import com.google.inject.Inject;
import com.google.inject.ProvisionException;
-
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.List;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
import org.eclipse.jgit.lib.ObjectId;
@@ -37,10 +39,6 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.util.Arrays;
-import java.util.List;
-
@ExtensionPoint
public class ProjectConfigEntry {
private final String displayName;
@@ -54,45 +52,51 @@
this(displayName, defaultValue, false);
}
- public ProjectConfigEntry(String displayName, String defaultValue,
- boolean inheritable) {
+ public ProjectConfigEntry(String displayName, String defaultValue, boolean inheritable) {
this(displayName, defaultValue, inheritable, null);
}
- public ProjectConfigEntry(String displayName, String defaultValue,
- boolean inheritable, String description) {
- this(displayName, defaultValue, ProjectConfigEntryType.STRING, null,
- inheritable, description);
+ public ProjectConfigEntry(
+ String displayName, String defaultValue, boolean inheritable, String description) {
+ this(displayName, defaultValue, ProjectConfigEntryType.STRING, null, inheritable, description);
}
public ProjectConfigEntry(String displayName, int defaultValue) {
this(displayName, defaultValue, false);
}
- public ProjectConfigEntry(String displayName, int defaultValue,
- boolean inheritable) {
+ public ProjectConfigEntry(String displayName, int defaultValue, boolean inheritable) {
this(displayName, defaultValue, inheritable, null);
}
- public ProjectConfigEntry(String displayName, int defaultValue,
- boolean inheritable, String description) {
- this(displayName, Integer.toString(defaultValue),
- ProjectConfigEntryType.INT, null, inheritable, description);
+ public ProjectConfigEntry(
+ String displayName, int defaultValue, boolean inheritable, String description) {
+ this(
+ displayName,
+ Integer.toString(defaultValue),
+ ProjectConfigEntryType.INT,
+ null,
+ inheritable,
+ description);
}
public ProjectConfigEntry(String displayName, long defaultValue) {
this(displayName, defaultValue, false);
}
- public ProjectConfigEntry(String displayName, long defaultValue,
- boolean inheritable) {
+ public ProjectConfigEntry(String displayName, long defaultValue, boolean inheritable) {
this(displayName, defaultValue, inheritable, null);
}
- public ProjectConfigEntry(String displayName, long defaultValue,
- boolean inheritable, String description) {
- this(displayName, Long.toString(defaultValue),
- ProjectConfigEntryType.LONG, null, inheritable, description);
+ public ProjectConfigEntry(
+ String displayName, long defaultValue, boolean inheritable, String description) {
+ this(
+ displayName,
+ Long.toString(defaultValue),
+ ProjectConfigEntryType.LONG,
+ null,
+ inheritable,
+ description);
}
// For inheritable boolean use 'LIST' type with InheritableBoolean
@@ -101,50 +105,72 @@
}
//For inheritable boolean use 'LIST' type with InheritableBoolean
- public ProjectConfigEntry(String displayName, boolean defaultValue,
- String description) {
- this(displayName, Boolean.toString(defaultValue),
- ProjectConfigEntryType.BOOLEAN, null, false, description);
+ public ProjectConfigEntry(String displayName, boolean defaultValue, String description) {
+ this(
+ displayName,
+ Boolean.toString(defaultValue),
+ ProjectConfigEntryType.BOOLEAN,
+ null,
+ false,
+ description);
}
- public ProjectConfigEntry(String displayName, String defaultValue,
- List<String> permittedValues) {
+ public ProjectConfigEntry(String displayName, String defaultValue, List<String> permittedValues) {
this(displayName, defaultValue, permittedValues, false);
}
- public ProjectConfigEntry(String displayName, String defaultValue,
- List<String> permittedValues, boolean inheritable) {
+ public ProjectConfigEntry(
+ String displayName, String defaultValue, List<String> permittedValues, boolean inheritable) {
this(displayName, defaultValue, permittedValues, inheritable, null);
}
- public ProjectConfigEntry(String displayName, String defaultValue,
- List<String> permittedValues, boolean inheritable, String description) {
- this(displayName, defaultValue, ProjectConfigEntryType.LIST,
- permittedValues, inheritable, description);
+ public ProjectConfigEntry(
+ String displayName,
+ String defaultValue,
+ List<String> permittedValues,
+ boolean inheritable,
+ String description) {
+ this(
+ displayName,
+ defaultValue,
+ ProjectConfigEntryType.LIST,
+ permittedValues,
+ inheritable,
+ description);
}
- public <T extends Enum<?>> ProjectConfigEntry(String displayName,
- T defaultValue, Class<T> permittedValues) {
+ public <T extends Enum<?>> ProjectConfigEntry(
+ String displayName, T defaultValue, Class<T> permittedValues) {
this(displayName, defaultValue, permittedValues, false);
}
- public <T extends Enum<?>> ProjectConfigEntry(String displayName,
- T defaultValue, Class<T> permittedValues, boolean inheritable) {
+ public <T extends Enum<?>> ProjectConfigEntry(
+ String displayName, T defaultValue, Class<T> permittedValues, boolean inheritable) {
this(displayName, defaultValue, permittedValues, inheritable, null);
}
- public <T extends Enum<?>> ProjectConfigEntry(String displayName,
- T defaultValue, Class<T> permittedValues, boolean inheritable,
+ public <T extends Enum<?>> ProjectConfigEntry(
+ String displayName,
+ T defaultValue,
+ Class<T> permittedValues,
+ boolean inheritable,
String description) {
- this(displayName, defaultValue.name(), ProjectConfigEntryType.LIST,
- Arrays.stream(permittedValues.getEnumConstants())
- .map(Enum::name).collect(toList()),
- inheritable, description);
+ this(
+ displayName,
+ defaultValue.name(),
+ ProjectConfigEntryType.LIST,
+ Arrays.stream(permittedValues.getEnumConstants()).map(Enum::name).collect(toList()),
+ inheritable,
+ description);
}
- public ProjectConfigEntry(String displayName, String defaultValue,
- ProjectConfigEntryType type, List<String> permittedValues,
- boolean inheritable, String description) {
+ public ProjectConfigEntry(
+ String displayName,
+ String defaultValue,
+ ProjectConfigEntryType type,
+ List<String> permittedValues,
+ boolean inheritable,
+ String description) {
this.displayName = displayName;
this.defaultValue = defaultValue;
this.type = type;
@@ -152,8 +178,7 @@
this.inheritable = inheritable;
this.description = description;
if (type == ProjectConfigEntryType.ARRAY && inheritable) {
- throw new ProvisionException(
- "ARRAY doesn't support inheritable values");
+ throw new ProvisionException("ARRAY doesn't support inheritable values");
}
}
@@ -198,9 +223,9 @@
}
/**
- * Called before the project config is updated. To modify the value before the
- * project config is updated, override this method and return the modified
- * value. Default implementation returns the same value.
+ * Called before the project config is updated. To modify the value before the project config is
+ * updated, override this method and return the modified value. Default implementation returns the
+ * same value.
*
* @param configValue the original configValue that was entered.
* @return the modified configValue.
@@ -210,13 +235,13 @@
}
/**
- * Called after reading the project config value. To modify the value before
- * returning it to the client, override this method and return the modified
- * value. Default implementation returns the same value.
+ * Called after reading the project config value. To modify the value before returning it to the
+ * client, override this method and return the modified value. Default implementation returns the
+ * same value.
*
* @param project the project.
- * @param value the actual value of the config entry (computed out of the
- * configured value, the inherited value and the default value).
+ * @param value the actual value of the config entry (computed out of the configured value, the
+ * inherited value and the default value).
* @return the modified value.
*/
public String onRead(ProjectState project, String value) {
@@ -224,13 +249,13 @@
}
/**
- * Called after reading the project config value of type ARRAY. To modify the
- * values before returning it to the client, override this method and return
- * the modified values. Default implementation returns the same values.
+ * Called after reading the project config value of type ARRAY. To modify the values before
+ * returning it to the client, override this method and return the modified values. Default
+ * implementation returns the same values.
*
* @param project the project.
- * @param values the actual values of the config entry (computed out of the
- * configured value, the inherited value and the default value).
+ * @param values the actual values of the config entry (computed out of the configured value, the
+ * inherited value and the default value).
* @return the modified values.
*/
public List<String> onRead(ProjectState project, List<String> values) {
@@ -244,8 +269,7 @@
* @param oldValue old entry value.
* @param newValue new entry value.
*/
- public void onUpdate(Project.NameKey project, String oldValue, String newValue) {
- }
+ public void onUpdate(Project.NameKey project, String oldValue, String newValue) {}
/**
* Called after a project config is updated.
@@ -254,8 +278,7 @@
* @param oldValue old entry value.
* @param newValue new entry value.
*/
- public void onUpdate(Project.NameKey project, Boolean oldValue, Boolean newValue) {
- }
+ public void onUpdate(Project.NameKey project, Boolean oldValue, Boolean newValue) {}
/**
* Called after a project config is updated.
@@ -264,8 +287,7 @@
* @param oldValue old entry value.
* @param newValue new entry value.
*/
- public void onUpdate(Project.NameKey project, Integer oldValue, Integer newValue) {
- }
+ public void onUpdate(Project.NameKey project, Integer oldValue, Integer newValue) {}
/**
* Called after a project config is updated.
@@ -274,8 +296,7 @@
* @param oldValue old entry value.
* @param newValue new entry value.
*/
- public void onUpdate(Project.NameKey project, Long oldValue, Long newValue) {
- }
+ public void onUpdate(Project.NameKey project, Long oldValue, Long newValue) {}
public static class UpdateChecker implements GitReferenceUpdatedListener {
private static final Logger log = LoggerFactory.getLogger(UpdateChecker.class);
@@ -284,8 +305,8 @@
private final DynamicMap<ProjectConfigEntry> pluginConfigEntries;
@Inject
- UpdateChecker(GitRepositoryManager repoManager,
- DynamicMap<ProjectConfigEntry> pluginConfigEntries) {
+ UpdateChecker(
+ GitRepositoryManager repoManager, DynamicMap<ProjectConfigEntry> pluginConfigEntries) {
this.repoManager = repoManager;
this.pluginConfigEntries = pluginConfigEntries;
}
@@ -329,9 +350,9 @@
}
}
} catch (IOException | ConfigInvalidException e) {
- log.error(String.format(
- "Failed to check if plugin config of project %s was updated.",
- p.get()), e);
+ log.error(
+ String.format("Failed to check if plugin config of project %s was updated.", p.get()),
+ e);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/ProjectOwnerGroupsProvider.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/ProjectOwnerGroupsProvider.java
index 34946ec..33e68d3 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/ProjectOwnerGroupsProvider.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/ProjectOwnerGroupsProvider.java
@@ -22,9 +22,9 @@
import com.google.inject.assistedinject.AssistedInject;
/**
- * Provider of the group(s) which should become owners of a newly created
- * project. The only matching patterns supported are exact match or wildcard
- * matching which can be specified by ending the name with a {@code *}.
+ * Provider of the group(s) which should become owners of a newly created project. The only matching
+ * patterns supported are exact match or wildcard matching which can be specified by ending the name
+ * with a {@code *}.
*
* <pre>
* [repository "*"]
@@ -41,8 +41,10 @@
}
@AssistedInject
- public ProjectOwnerGroupsProvider(GroupBackend gb,
- ThreadLocalRequestContext context, ServerRequestContext serverCtx,
+ public ProjectOwnerGroupsProvider(
+ GroupBackend gb,
+ ThreadLocalRequestContext context,
+ ServerRequestContext serverCtx,
RepositoryConfig repositoryCfg,
@Assisted Project.NameKey project) {
super(gb, context, serverCtx, repositoryCfg.getOwnerGroups(project));
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/RepositoryConfig.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/RepositoryConfig.java
index e250395..4f35fc7 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/RepositoryConfig.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/RepositoryConfig.java
@@ -19,13 +19,11 @@
import com.google.gerrit.reviewdb.client.Project;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.lib.Config;
-
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
+import org.eclipse.jgit.lib.Config;
@Singleton
public class RepositoryConfig {
@@ -43,18 +41,20 @@
}
public SubmitType getDefaultSubmitType(Project.NameKey project) {
- return cfg.getEnum(SECTION_NAME, findSubSection(project.get()),
- DEFAULT_SUBMIT_TYPE_NAME, SubmitType.MERGE_IF_NECESSARY);
+ return cfg.getEnum(
+ SECTION_NAME,
+ findSubSection(project.get()),
+ DEFAULT_SUBMIT_TYPE_NAME,
+ SubmitType.MERGE_IF_NECESSARY);
}
public List<String> getOwnerGroups(Project.NameKey project) {
- return ImmutableList.copyOf(cfg.getStringList(SECTION_NAME,
- findSubSection(project.get()), OWNER_GROUP_NAME));
+ return ImmutableList.copyOf(
+ cfg.getStringList(SECTION_NAME, findSubSection(project.get()), OWNER_GROUP_NAME));
}
public Path getBasePath(Project.NameKey project) {
- String basePath = cfg.getString(SECTION_NAME, findSubSection(project.get()),
- BASE_PATH_NAME);
+ String basePath = cfg.getString(SECTION_NAME, findSubSection(project.get()), BASE_PATH_NAME);
return basePath != null ? Paths.get(basePath) : null;
}
@@ -71,10 +71,9 @@
/**
* Find the subSection to get repository configuration from.
- * <p>
- * SubSection can use the * pattern so if project name matches more than one
- * section, return the more precise one. E.g if the following subSections are
- * defined:
+ *
+ * <p>SubSection can use the * pattern so if project name matches more than one section, return
+ * the more precise one. E.g if the following subSections are defined:
*
* <pre>
* [repository "somePath/*"]
@@ -83,8 +82,8 @@
* name = value
* </pre>
*
- * and this method is called with "somePath/somePath/someProject" as project
- * name, it will return the subSection "somePath/somePath/*"
+ * and this method is called with "somePath/somePath/someProject" as project name, it will return
+ * the subSection "somePath/somePath/*"
*
* @param project Name of the project
* @return the name of the subSection, null if none is found
@@ -93,8 +92,7 @@
String subSectionFound = null;
for (String subSection : cfg.getSubsections(SECTION_NAME)) {
if (isMatch(subSection, project)
- && (subSectionFound == null || subSectionFound.length() < subSection
- .length())) {
+ && (subSectionFound == null || subSectionFound.length() < subSection.length())) {
subSectionFound = subSection;
}
}
@@ -103,7 +101,7 @@
private boolean isMatch(String subSection, String project) {
return project.equals(subSection)
- || (subSection.endsWith("*") && project.startsWith(subSection
- .substring(0, subSection.length() - 1)));
+ || (subSection.endsWith("*")
+ && project.startsWith(subSection.substring(0, subSection.length() - 1)));
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/RequestScopedReviewDbProvider.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/RequestScopedReviewDbProvider.java
index c2c002e..3987aed 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/RequestScopedReviewDbProvider.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/RequestScopedReviewDbProvider.java
@@ -31,8 +31,8 @@
private ReviewDb db;
@Inject
- public RequestScopedReviewDbProvider(final SchemaFactory<ReviewDb> schema,
- final Provider<RequestCleanup> cleanup) {
+ public RequestScopedReviewDbProvider(
+ final SchemaFactory<ReviewDb> schema, final Provider<RequestCleanup> cleanup) {
this.schema = schema;
this.cleanup = cleanup;
}
@@ -48,13 +48,16 @@
throw new ProvisionException("Cannot open ReviewDb", e);
}
try {
- cleanup.get().add(new Runnable() {
- @Override
- public void run() {
- c.close();
- db = null;
- }
- });
+ cleanup
+ .get()
+ .add(
+ new Runnable() {
+ @Override
+ public void run() {
+ c.close();
+ db = null;
+ }
+ });
} catch (Throwable e) {
c.close();
throw new ProvisionException("Cannot defer cleanup of ReviewDb", e);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/ScheduleConfig.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/ScheduleConfig.java
index a2835a6..4a87474 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/ScheduleConfig.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/ScheduleConfig.java
@@ -15,7 +15,9 @@
package com.google.gerrit.server.config;
import com.google.common.annotations.VisibleForTesting;
-
+import java.text.MessageFormat;
+import java.util.Locale;
+import java.util.concurrent.TimeUnit;
import org.eclipse.jgit.lib.Config;
import org.joda.time.DateTime;
import org.joda.time.LocalDateTime;
@@ -27,13 +29,8 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.text.MessageFormat;
-import java.util.Locale;
-import java.util.concurrent.TimeUnit;
-
public class ScheduleConfig {
- private static final Logger log = LoggerFactory
- .getLogger(ScheduleConfig.class);
+ private static final Logger log = LoggerFactory.getLogger(ScheduleConfig.class);
public static final long MISSING_CONFIG = -1L;
public static final long INVALID_CONFIG = -2L;
private static final String KEY_INTERVAL = "interval";
@@ -55,8 +52,8 @@
this(rc, section, subsection, DateTime.now());
}
- public ScheduleConfig(Config rc, String section, String subsection,
- String keyInterval, String keyStartTime) {
+ public ScheduleConfig(
+ Config rc, String section, String subsection, String keyInterval, String keyStartTime) {
this(rc, section, subsection, keyInterval, keyStartTime, DateTime.now());
}
@@ -66,8 +63,13 @@
}
@VisibleForTesting
- ScheduleConfig(Config rc, String section, String subsection,
- String keyInterval, String keyStartTime, DateTime now) {
+ ScheduleConfig(
+ Config rc,
+ String section,
+ String subsection,
+ String keyInterval,
+ String keyStartTime,
+ DateTime now) {
this.rc = rc;
this.section = section;
this.subsection = subsection;
@@ -75,8 +77,7 @@
this.keyStartTime = keyStartTime;
this.interval = interval(rc, section, subsection, keyInterval);
if (interval > 0) {
- this.initialDelay = initialDelay(rc, section, subsection, keyStartTime, now,
- interval);
+ this.initialDelay = initialDelay(rc, section, subsection, keyStartTime, now, interval);
} else {
this.initialDelay = interval;
}
@@ -84,10 +85,9 @@
/**
* Milliseconds between constructor invocation and first event time.
- * <p>
- * If there is any lag between the constructor invocation and queuing the
- * object into an executor the event will run later, as there is no method
- * to adjust for the scheduling delay.
+ *
+ * <p>If there is any lag between the constructor invocation and queuing the object into an
+ * executor the event will run later, as there is no method to adjust for the scheduling delay.
*/
public long getInitialDelay() {
return initialDelay;
@@ -98,29 +98,32 @@
return interval;
}
- private static long interval(Config rc, String section, String subsection,
- String keyInterval) {
+ private static long interval(Config rc, String section, String subsection, String keyInterval) {
long interval = MISSING_CONFIG;
try {
interval =
- ConfigUtil.getTimeUnit(rc, section, subsection, keyInterval, -1,
- TimeUnit.MILLISECONDS);
+ ConfigUtil.getTimeUnit(rc, section, subsection, keyInterval, -1, TimeUnit.MILLISECONDS);
if (interval == MISSING_CONFIG) {
- log.info(MessageFormat.format(
- "{0} schedule parameter \"{0}.{1}\" is not configured", section,
- keyInterval));
+ log.info(
+ MessageFormat.format(
+ "{0} schedule parameter \"{0}.{1}\" is not configured", section, keyInterval));
}
} catch (IllegalArgumentException e) {
- log.error(MessageFormat.format(
- "Invalid {0} schedule parameter \"{0}.{1}\"", section, keyInterval),
+ log.error(
+ MessageFormat.format("Invalid {0} schedule parameter \"{0}.{1}\"", section, keyInterval),
e);
interval = INVALID_CONFIG;
}
return interval;
}
- private static long initialDelay(Config rc, String section,
- String subsection, String keyStartTime, DateTime now, long interval) {
+ private static long initialDelay(
+ Config rc,
+ String section,
+ String subsection,
+ String keyStartTime,
+ DateTime now,
+ long interval) {
long delay = MISSING_CONFIG;
String start = rc.getString(section, subsection, keyStartTime);
try {
@@ -133,8 +136,7 @@
startTime.hourOfDay().set(firstStartTime.getHourOfDay());
startTime.minuteOfHour().set(firstStartTime.getMinuteOfHour());
} catch (IllegalArgumentException e1) {
- formatter = DateTimeFormat.forPattern("E HH:mm")
- .withLocale(Locale.US);
+ formatter = DateTimeFormat.forPattern("E HH:mm").withLocale(Locale.US);
LocalDateTime firstStartDateTime = formatter.parseLocalDateTime(start);
startTime.dayOfWeek().set(firstStartDateTime.getDayOfWeek());
startTime.hourOfDay().set(firstStartDateTime.getHourOfDay());
@@ -149,14 +151,14 @@
delay += interval;
}
} else {
- log.info(MessageFormat.format(
- "{0} schedule parameter \"{0}.{1}\" is not configured", section,
- keyStartTime));
+ log.info(
+ MessageFormat.format(
+ "{0} schedule parameter \"{0}.{1}\" is not configured", section, keyStartTime));
}
} catch (IllegalArgumentException e2) {
log.error(
- MessageFormat.format("Invalid {0} schedule parameter \"{0}.{1}\"",
- section, keyStartTime), e2);
+ MessageFormat.format("Invalid {0} schedule parameter \"{0}.{1}\"", section, keyStartTime),
+ e2);
delay = INVALID_CONFIG;
}
return delay;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/SetDiffPreferences.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/SetDiffPreferences.java
index 8ca072a..80c4625 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/SetDiffPreferences.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/SetDiffPreferences.java
@@ -30,28 +30,25 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
+import java.io.IOException;
+import java.lang.reflect.Field;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.lang.reflect.Field;
-
@RequiresCapability(GlobalCapability.ADMINISTRATE_SERVER)
@Singleton
-public class SetDiffPreferences implements
- RestModifyView<ConfigResource, DiffPreferencesInfo> {
- private static final Logger log =
- LoggerFactory.getLogger(SetDiffPreferences.class);
+public class SetDiffPreferences implements RestModifyView<ConfigResource, DiffPreferencesInfo> {
+ private static final Logger log = LoggerFactory.getLogger(SetDiffPreferences.class);
private final Provider<MetaDataUpdate.User> metaDataUpdateFactory;
private final AllUsersName allUsersName;
private final GitRepositoryManager gitManager;
@Inject
- SetDiffPreferences(GitRepositoryManager gitManager,
+ SetDiffPreferences(
+ GitRepositoryManager gitManager,
Provider<MetaDataUpdate.User> metaDataUpdateFactory,
AllUsersName allUsersName) {
this.gitManager = gitManager;
@@ -60,9 +57,8 @@
}
@Override
- public DiffPreferencesInfo apply(ConfigResource configResource,
- DiffPreferencesInfo in)
- throws BadRequestException, IOException, ConfigInvalidException {
+ public DiffPreferencesInfo apply(ConfigResource configResource, DiffPreferencesInfo in)
+ throws BadRequestException, IOException, ConfigInvalidException {
if (in == null) {
throw new BadRequestException("input must be provided");
}
@@ -76,15 +72,18 @@
throws RepositoryNotFoundException, IOException, ConfigInvalidException {
DiffPreferencesInfo out = new DiffPreferencesInfo();
try (MetaDataUpdate md = metaDataUpdateFactory.get().create(allUsersName)) {
- VersionedAccountPreferences prefs =
- VersionedAccountPreferences.forDefault();
+ VersionedAccountPreferences prefs = VersionedAccountPreferences.forDefault();
prefs.load(md);
DiffPreferencesInfo defaults = DiffPreferencesInfo.defaults();
- storeSection(prefs.getConfig(), UserConfigSections.DIFF, null, in,
- defaults);
+ storeSection(prefs.getConfig(), UserConfigSections.DIFF, null, in, defaults);
prefs.commit(md);
- loadSection(prefs.getConfig(), UserConfigSections.DIFF, null, out,
- DiffPreferencesInfo.defaults(), null);
+ loadSection(
+ prefs.getConfig(),
+ UserConfigSections.DIFF,
+ null,
+ out,
+ DiffPreferencesInfo.defaults(),
+ null);
}
return out;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/SetPreferences.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/SetPreferences.java
index c5c75ee..4792131 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/SetPreferences.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/SetPreferences.java
@@ -33,21 +33,17 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
+import java.io.IOException;
+import java.lang.reflect.Field;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.lang.reflect.Field;
-
@RequiresCapability(GlobalCapability.ADMINISTRATE_SERVER)
@Singleton
-public class SetPreferences implements
- RestModifyView<ConfigResource, GeneralPreferencesInfo> {
- private static final Logger log =
- LoggerFactory.getLogger(SetPreferences.class);
+public class SetPreferences implements RestModifyView<ConfigResource, GeneralPreferencesInfo> {
+ private static final Logger log = LoggerFactory.getLogger(SetPreferences.class);
private final GeneralPreferencesLoader loader;
private final GitRepositoryManager gitManager;
@@ -56,7 +52,8 @@
private final AccountCache accountCache;
@Inject
- SetPreferences(GeneralPreferencesLoader loader,
+ SetPreferences(
+ GeneralPreferencesLoader loader,
GitRepositoryManager gitManager,
Provider<MetaDataUpdate.User> metaDataUpdateFactory,
AllUsersName allUsersName,
@@ -69,9 +66,8 @@
}
@Override
- public GeneralPreferencesInfo apply(ConfigResource rsrc,
- GeneralPreferencesInfo i)
- throws BadRequestException, IOException, ConfigInvalidException {
+ public GeneralPreferencesInfo apply(ConfigResource rsrc, GeneralPreferencesInfo i)
+ throws BadRequestException, IOException, ConfigInvalidException {
if (!hasSetFields(i)) {
throw new BadRequestException("unsupported option");
}
@@ -83,22 +79,26 @@
try (MetaDataUpdate md = metaDataUpdateFactory.get().create(allUsersName)) {
VersionedAccountPreferences p = VersionedAccountPreferences.forDefault();
p.load(md);
- storeSection(p.getConfig(), UserConfigSections.GENERAL, null, i,
- GeneralPreferencesInfo.defaults());
+ storeSection(
+ p.getConfig(), UserConfigSections.GENERAL, null, i, GeneralPreferencesInfo.defaults());
com.google.gerrit.server.account.SetPreferences.storeMyMenus(p, i.my);
com.google.gerrit.server.account.SetPreferences.storeUrlAliases(p, i.urlAliases);
p.commit(md);
accountCache.evictAll();
- GeneralPreferencesInfo r = loadSection(p.getConfig(),
- UserConfigSections.GENERAL, null, new GeneralPreferencesInfo(),
- GeneralPreferencesInfo.defaults(), null);
+ GeneralPreferencesInfo r =
+ loadSection(
+ p.getConfig(),
+ UserConfigSections.GENERAL,
+ null,
+ new GeneralPreferencesInfo(),
+ GeneralPreferencesInfo.defaults(),
+ null);
return loader.loadMyMenusAndUrlAliases(r, p, null);
}
}
-
private static boolean hasSetFields(GeneralPreferencesInfo in) {
try {
for (Field field : in.getClass().getDeclaredFields()) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/SitePath.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/SitePath.java
index d0b3905..a1e66fc 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/SitePath.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/SitePath.java
@@ -17,15 +17,13 @@
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import com.google.inject.BindingAnnotation;
-
import java.lang.annotation.Retention;
/**
* Marker on a {@link java.io.File} pointing to the site path.
- * <p>
- * The site path is where Gerrit Code Review stores most of its configuration.
+ *
+ * <p>The site path is where Gerrit Code Review stores most of its configuration.
*/
@Retention(RUNTIME)
@BindingAnnotation
-public @interface SitePath {
-}
+public @interface SitePath {}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/SitePaths.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/SitePaths.java
index 192ca49..a810077 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/SitePaths.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/SitePaths.java
@@ -17,7 +17,6 @@
import com.google.common.collect.Iterables;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
@@ -113,8 +112,8 @@
/**
* Resolve an absolute or relative path.
- * <p>
- * Relative paths are resolved relative to the {@link #site_path}.
+ *
+ * <p>Relative paths are resolved relative to the {@link #site_path}.
*
* @param path the path string to resolve. May be null.
* @return the resolved path; null if {@code path} was null or empty.
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/TasksCollection.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/TasksCollection.java
index b92cfc2..b239856 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/TasksCollection.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/TasksCollection.java
@@ -32,8 +32,7 @@
import com.google.inject.Singleton;
@Singleton
-public class TasksCollection implements
- ChildCollection<ConfigResource, TaskResource> {
+public class TasksCollection implements ChildCollection<ConfigResource, TaskResource> {
private final DynamicMap<RestView<TaskResource>> views;
private final ListTasks list;
private final WorkQueue workQueue;
@@ -41,8 +40,11 @@
private final ProjectCache projectCache;
@Inject
- TasksCollection(DynamicMap<RestView<TaskResource>> views, ListTasks list,
- WorkQueue workQueue, Provider<IdentifiedUser> self,
+ TasksCollection(
+ DynamicMap<RestView<TaskResource>> views,
+ ListTasks list,
+ WorkQueue workQueue,
+ Provider<IdentifiedUser> self,
ProjectCache projectCache) {
this.views = views;
this.list = list;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/ThreadSettingsConfig.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/ThreadSettingsConfig.java
index c62583e..6cb32cc 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/ThreadSettingsConfig.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/ThreadSettingsConfig.java
@@ -16,7 +16,6 @@
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
import org.eclipse.jgit.lib.Config;
@Singleton
@@ -32,8 +31,7 @@
sshdThreads = cfg.getInt("sshd", "threads", 2 * cores);
httpdMaxThreads = cfg.getInt("httpd", "maxThreads", 25);
int defaultDatabasePoolLimit = sshdThreads + httpdMaxThreads + 2;
- databasePoolLimit =
- cfg.getInt("database", "poolLimit", defaultDatabasePoolLimit);
+ databasePoolLimit = cfg.getInt("database", "poolLimit", defaultDatabasePoolLimit);
sshdBatchThreads = cores == 1 ? 1 : 2;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/TopMenuCollection.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/TopMenuCollection.java
index 32416c52..2fc2dc1 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/TopMenuCollection.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/TopMenuCollection.java
@@ -23,14 +23,12 @@
import com.google.inject.Singleton;
@Singleton
-class TopMenuCollection implements
- ChildCollection<ConfigResource, TopMenuResource> {
+class TopMenuCollection implements ChildCollection<ConfigResource, TopMenuResource> {
private final DynamicMap<RestView<TopMenuResource>> views;
private final ListTopMenus list;
@Inject
- TopMenuCollection(DynamicMap<RestView<TopMenuResource>> views,
- ListTopMenus list) {
+ TopMenuCollection(DynamicMap<RestView<TopMenuResource>> views, ListTopMenus list) {
this.views = views;
this.list = list;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/TrackingFooter.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/TrackingFooter.java
index aeedecd..ac2f0c6 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/TrackingFooter.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/TrackingFooter.java
@@ -14,11 +14,10 @@
package com.google.gerrit.server.config;
-import org.eclipse.jgit.revwalk.FooterKey;
-import org.eclipse.jgit.revwalk.FooterLine;
-
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
+import org.eclipse.jgit.revwalk.FooterKey;
+import org.eclipse.jgit.revwalk.FooterLine;
/** Tracking entry in the configuration file */
public class TrackingFooter {
@@ -26,8 +25,7 @@
private final Pattern match;
private final String system;
- public TrackingFooter(String f, final String m, final String s)
- throws PatternSyntaxException {
+ public TrackingFooter(String f, final String m, final String s) throws PatternSyntaxException {
f = f.trim();
if (f.endsWith(":")) {
f = f.substring(0, f.length() - 1);
@@ -54,7 +52,6 @@
@Override
public String toString() {
- return "footer = " + key.getName() + ", match = " + match.pattern()
- + ", system = " + system;
+ return "footer = " + key.getName() + ", match = " + match.pattern() + ", system = " + system;
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/TrackingFooters.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/TrackingFooters.java
index ee01308..a897bdc 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/TrackingFooters.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/TrackingFooters.java
@@ -16,16 +16,14 @@
import com.google.common.collect.ListMultimap;
import com.google.common.collect.MultimapBuilder;
-
-import org.eclipse.jgit.revwalk.FooterLine;
-
import java.util.List;
import java.util.regex.Matcher;
+import org.eclipse.jgit.revwalk.FooterLine;
public class TrackingFooters {
protected List<TrackingFooter> trackingFooters;
- public TrackingFooters (final List<TrackingFooter> trFooters) {
+ public TrackingFooters(final List<TrackingFooter> trFooters) {
trackingFooters = trFooters;
}
@@ -38,8 +36,7 @@
}
public ListMultimap<String, String> extract(List<FooterLine> lines) {
- ListMultimap<String, String> r =
- MultimapBuilder.hashKeys().arrayListValues().build();
+ ListMultimap<String, String> r = MultimapBuilder.hashKeys().arrayListValues().build();
if (lines == null) {
return r;
}
@@ -49,9 +46,7 @@
if (footer.matches(config.footerKey())) {
Matcher m = config.match().matcher(footer.getValue());
while (m.find()) {
- String id = m.groupCount() > 0
- ? m.group(1)
- : m.group();
+ String id = m.groupCount() > 0 ? m.group(1) : m.group();
if (!id.isEmpty()) {
r.put(config.system(), id);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/TrackingFootersProvider.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/TrackingFootersProvider.java
index 4c1bde9..5389b1f 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/TrackingFootersProvider.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/TrackingFootersProvider.java
@@ -18,11 +18,6 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.lib.Config;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
@@ -30,6 +25,9 @@
import java.util.List;
import java.util.Set;
import java.util.regex.PatternSyntaxException;
+import org.eclipse.jgit.lib.Config;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/** Provides a list of all configured {@link TrackingFooter}s. */
@Singleton
@@ -39,41 +37,49 @@
private static String SYSTEM_TAG = "system";
private static String REGEX_TAG = "match";
private final List<TrackingFooter> trackingFooters = new ArrayList<>();
- private static final Logger log =
- LoggerFactory.getLogger(TrackingFootersProvider.class);
+ private static final Logger log = LoggerFactory.getLogger(TrackingFootersProvider.class);
@Inject
TrackingFootersProvider(@GerritServerConfig final Config cfg) {
for (String name : cfg.getSubsections(TRACKING_ID_TAG)) {
boolean configValid = true;
- Set<String> footers = new HashSet<>(
- Arrays.asList(cfg.getStringList(TRACKING_ID_TAG, name, FOOTER_TAG)));
+ Set<String> footers =
+ new HashSet<>(Arrays.asList(cfg.getStringList(TRACKING_ID_TAG, name, FOOTER_TAG)));
footers.removeAll(Collections.singleton(null));
if (footers.isEmpty()) {
configValid = false;
- log.error("Missing " + TRACKING_ID_TAG + "." + name + "." + FOOTER_TAG
- + " in gerrit.config");
+ log.error(
+ "Missing " + TRACKING_ID_TAG + "." + name + "." + FOOTER_TAG + " in gerrit.config");
}
String system = cfg.getString(TRACKING_ID_TAG, name, SYSTEM_TAG);
if (system == null || system.isEmpty()) {
configValid = false;
- log.error("Missing " + TRACKING_ID_TAG + "." + name + "." + SYSTEM_TAG
- + " in gerrit.config");
+ log.error(
+ "Missing " + TRACKING_ID_TAG + "." + name + "." + SYSTEM_TAG + " in gerrit.config");
} else if (system.length() > TrackingId.TRACKING_SYSTEM_MAX_CHAR) {
configValid = false;
- log.error("String to long \"" + system + "\" in gerrit.config "
- + TRACKING_ID_TAG + "." + name + "." + SYSTEM_TAG + " (max "
- + TrackingId.TRACKING_SYSTEM_MAX_CHAR + " char)");
+ log.error(
+ "String to long \""
+ + system
+ + "\" in gerrit.config "
+ + TRACKING_ID_TAG
+ + "."
+ + name
+ + "."
+ + SYSTEM_TAG
+ + " (max "
+ + TrackingId.TRACKING_SYSTEM_MAX_CHAR
+ + " char)");
}
String match = cfg.getString(TRACKING_ID_TAG, name, REGEX_TAG);
if (match == null || match.isEmpty()) {
configValid = false;
- log.error("Missing " + TRACKING_ID_TAG + "." + name + "." + REGEX_TAG
- + " in gerrit.config");
+ log.error(
+ "Missing " + TRACKING_ID_TAG + "." + name + "." + REGEX_TAG + " in gerrit.config");
}
if (configValid) {
@@ -82,9 +88,17 @@
trackingFooters.add(new TrackingFooter(footer, match, system));
}
} catch (PatternSyntaxException e) {
- log.error("Invalid pattern \"" + match + "\" in gerrit.config "
- + TRACKING_ID_TAG + "." + name + "." + REGEX_TAG + ": "
- + e.getMessage());
+ log.error(
+ "Invalid pattern \""
+ + match
+ + "\" in gerrit.config "
+ + TRACKING_ID_TAG
+ + "."
+ + name
+ + "."
+ + REGEX_TAG
+ + ": "
+ + e.getMessage());
}
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/config/VerboseSuperprojectUpdate.java b/gerrit-server/src/main/java/com/google/gerrit/server/config/VerboseSuperprojectUpdate.java
index f328b1ff..96467a8 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/config/VerboseSuperprojectUpdate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/config/VerboseSuperprojectUpdate.java
@@ -14,9 +14,7 @@
package com.google.gerrit.server.config;
-/**
- * Verbosity level of the commit message for submodule subscriptions.
- */
+/** Verbosity level of the commit message for submodule subscriptions. */
public enum VerboseSuperprojectUpdate {
/** Do not include any commit messages for the gitlink update. */
FALSE,
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/data/AccountAttribute.java b/gerrit-server/src/main/java/com/google/gerrit/server/data/AccountAttribute.java
index e5627c2..19605a2 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/data/AccountAttribute.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/data/AccountAttribute.java
@@ -15,7 +15,7 @@
package com.google.gerrit.server.data;
public class AccountAttribute {
- public String name;
- public String email;
- public String username;
+ public String name;
+ public String email;
+ public String username;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/data/ApprovalAttribute.java b/gerrit-server/src/main/java/com/google/gerrit/server/data/ApprovalAttribute.java
index 90b6fc4..8928a5d 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/data/ApprovalAttribute.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/data/ApprovalAttribute.java
@@ -15,10 +15,10 @@
package com.google.gerrit.server.data;
public class ApprovalAttribute {
- public String type;
- public String description;
- public String value;
- public String oldValue;
- public Long grantedOn;
- public AccountAttribute by;
+ public String type;
+ public String description;
+ public String value;
+ public String oldValue;
+ public Long grantedOn;
+ public AccountAttribute by;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/data/ChangeAttribute.java b/gerrit-server/src/main/java/com/google/gerrit/server/data/ChangeAttribute.java
index 48a1744..1a8a788 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/data/ChangeAttribute.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/data/ChangeAttribute.java
@@ -15,33 +15,32 @@
package com.google.gerrit.server.data;
import com.google.gerrit.reviewdb.client.Change;
-
import java.util.List;
public class ChangeAttribute {
- public String project;
- public String branch;
- public String topic;
- public String id;
- public int number;
- public String subject;
- public AccountAttribute owner;
- public AccountAttribute assignee;
- public String url;
- public String commitMessage;
+ public String project;
+ public String branch;
+ public String topic;
+ public String id;
+ public int number;
+ public String subject;
+ public AccountAttribute owner;
+ public AccountAttribute assignee;
+ public String url;
+ public String commitMessage;
- public Long createdOn;
- public Long lastUpdated;
- public Boolean open;
- public Change.Status status;
- public List<MessageAttribute> comments;
+ public Long createdOn;
+ public Long lastUpdated;
+ public Boolean open;
+ public Change.Status status;
+ public List<MessageAttribute> comments;
- public List<TrackingIdAttribute> trackingIds;
- public PatchSetAttribute currentPatchSet;
- public List<PatchSetAttribute> patchSets;
+ public List<TrackingIdAttribute> trackingIds;
+ public PatchSetAttribute currentPatchSet;
+ public List<PatchSetAttribute> patchSets;
- public List<DependencyAttribute> dependsOn;
- public List<DependencyAttribute> neededBy;
- public List<SubmitRecordAttribute> submitRecords;
- public List<AccountAttribute> allReviewers;
+ public List<DependencyAttribute> dependsOn;
+ public List<DependencyAttribute> neededBy;
+ public List<SubmitRecordAttribute> submitRecords;
+ public List<AccountAttribute> allReviewers;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/data/MessageAttribute.java b/gerrit-server/src/main/java/com/google/gerrit/server/data/MessageAttribute.java
index f18beba..6837d44 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/data/MessageAttribute.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/data/MessageAttribute.java
@@ -15,7 +15,7 @@
package com.google.gerrit.server.data;
public class MessageAttribute {
- public Long timestamp;
- public AccountAttribute reviewer;
- public String message;
+ public Long timestamp;
+ public AccountAttribute reviewer;
+ public String message;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/data/PatchAttribute.java b/gerrit-server/src/main/java/com/google/gerrit/server/data/PatchAttribute.java
index 12ac30a..22f18af 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/data/PatchAttribute.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/data/PatchAttribute.java
@@ -17,9 +17,9 @@
import com.google.gerrit.reviewdb.client.Patch.ChangeType;
public class PatchAttribute {
- public String file;
- public String fileOld;
- public ChangeType type;
- public int insertions;
- public int deletions;
+ public String file;
+ public String fileOld;
+ public ChangeType type;
+ public int insertions;
+ public int deletions;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/data/PatchSetAttribute.java b/gerrit-server/src/main/java/com/google/gerrit/server/data/PatchSetAttribute.java
index 8e43657..d3b3786 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/data/PatchSetAttribute.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/data/PatchSetAttribute.java
@@ -15,7 +15,6 @@
package com.google.gerrit.server.data;
import com.google.gerrit.extensions.client.ChangeKind;
-
import java.util.List;
public class PatchSetAttribute {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/data/PatchSetCommentAttribute.java b/gerrit-server/src/main/java/com/google/gerrit/server/data/PatchSetCommentAttribute.java
index 7610068..d004e6c 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/data/PatchSetCommentAttribute.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/data/PatchSetCommentAttribute.java
@@ -15,8 +15,8 @@
package com.google.gerrit.server.data;
public class PatchSetCommentAttribute {
- public String file;
- public Integer line;
- public AccountAttribute reviewer;
- public String message;
+ public String file;
+ public Integer line;
+ public AccountAttribute reviewer;
+ public String message;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/data/SubmitLabelAttribute.java b/gerrit-server/src/main/java/com/google/gerrit/server/data/SubmitLabelAttribute.java
index 4c774c2..1b3c6a48 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/data/SubmitLabelAttribute.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/data/SubmitLabelAttribute.java
@@ -15,7 +15,7 @@
package com.google.gerrit.server.data;
public class SubmitLabelAttribute {
- public String label;
- public String status;
- public AccountAttribute by;
+ public String label;
+ public String status;
+ public AccountAttribute by;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/data/SubmitRecordAttribute.java b/gerrit-server/src/main/java/com/google/gerrit/server/data/SubmitRecordAttribute.java
index 1ce2ce6..fec870f 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/data/SubmitRecordAttribute.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/data/SubmitRecordAttribute.java
@@ -17,6 +17,6 @@
import java.util.List;
public class SubmitRecordAttribute {
- public String status;
- public List<SubmitLabelAttribute> labels;
+ public String status;
+ public List<SubmitLabelAttribute> labels;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/documentation/MarkdownFormatter.java b/gerrit-server/src/main/java/com/google/gerrit/server/documentation/MarkdownFormatter.java
index 1d9c795..68d2a34 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/documentation/MarkdownFormatter.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/documentation/MarkdownFormatter.java
@@ -20,7 +20,13 @@
import static org.pegdown.Extensions.SUPPRESS_ALL_HTML;
import com.google.common.base.Strings;
-
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UnsupportedEncodingException;
+import java.net.URL;
+import java.nio.charset.Charset;
+import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.commons.lang.StringEscapeUtils;
import org.eclipse.jgit.util.RawParseUtils;
import org.eclipse.jgit.util.TemporaryBuffer;
@@ -34,17 +40,8 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.UnsupportedEncodingException;
-import java.net.URL;
-import java.nio.charset.Charset;
-import java.util.concurrent.atomic.AtomicBoolean;
-
public class MarkdownFormatter {
- private static final Logger log =
- LoggerFactory.getLogger(MarkdownFormatter.class);
+ private static final Logger log = LoggerFactory.getLogger(MarkdownFormatter.class);
private static final String defaultCss;
@@ -85,8 +82,7 @@
return this;
}
- public byte[] markdownToDocHtml(String md, String charEnc)
- throws UnsupportedEncodingException {
+ public byte[] markdownToDocHtml(String md, String charEnc) throws UnsupportedEncodingException {
RootNode root = parseMarkdown(md);
String title = findTitle(root);
@@ -118,9 +114,7 @@
private String findTitle(Node root) {
if (root instanceof HeaderNode) {
HeaderNode h = (HeaderNode) root;
- if (h.getLevel() == 1
- && h.getChildren() != null
- && !h.getChildren().isEmpty()) {
+ if (h.getLevel() == 1 && h.getChildren() != null && !h.getChildren().isEmpty()) {
StringBuilder b = new StringBuilder();
for (Node n : root.getChildren()) {
if (n instanceof TextNode) {
@@ -145,12 +139,10 @@
if (suppressHtml) {
options |= SUPPRESS_ALL_HTML;
}
- return new PegDownProcessor(options)
- .parseMarkdown(md.toCharArray());
+ return new PegDownProcessor(options).parseMarkdown(md.toCharArray());
}
- private static String readPegdownCss(AtomicBoolean file)
- throws IOException {
+ private static String readPegdownCss(AtomicBoolean file) throws IOException {
String name = "pegdown.css";
URL url = MarkdownFormatter.class.getResource(name);
if (url == null) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/documentation/QueryDocumentationExecutor.java b/gerrit-server/src/main/java/com/google/gerrit/server/documentation/QueryDocumentationExecutor.java
index 9b15a42..eef6d35 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/documentation/QueryDocumentationExecutor.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/documentation/QueryDocumentationExecutor.java
@@ -18,7 +18,12 @@
import com.google.common.collect.Lists;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.List;
+import java.util.Map;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
@@ -34,21 +39,14 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.List;
-import java.util.Map;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipInputStream;
-
@Singleton
public class QueryDocumentationExecutor {
- private static final Logger log =
- LoggerFactory.getLogger(QueryDocumentationExecutor.class);
+ private static final Logger log = LoggerFactory.getLogger(QueryDocumentationExecutor.class);
- private static Map<String, Float> WEIGHTS = ImmutableMap.of(
- Constants.TITLE_FIELD, 2.0f,
- Constants.DOC_FIELD, 1.0f);
+ private static Map<String, Float> WEIGHTS =
+ ImmutableMap.of(
+ Constants.TITLE_FIELD, 2.0f,
+ Constants.DOC_FIELD, 1.0f);
private IndexSearcher searcher;
private SimpleQueryParser parser;
@@ -134,8 +132,7 @@
@SuppressWarnings("serial")
public static class DocQueryException extends Exception {
- DocQueryException() {
- }
+ DocQueryException() {}
DocQueryException(String msg) {
super(msg);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/edit/ChangeEdit.java b/gerrit-server/src/main/java/com/google/gerrit/server/edit/ChangeEdit.java
index b7bb360..a6464a7 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/edit/ChangeEdit.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/edit/ChangeEdit.java
@@ -21,18 +21,16 @@
import com.google.gerrit.reviewdb.client.RefNames;
import com.google.gerrit.reviewdb.client.RevId;
import com.google.gerrit.server.IdentifiedUser;
-
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.revwalk.RevCommit;
/**
* A single user's edit for a change.
- * <p>
- * There is max. one edit per user per change. Edits are stored on refs:
- * refs/users/UU/UUUU/edit-CCCC/P where UU/UUUU is sharded representation
- * of user account, CCCC is change number and P is the patch set number it
- * is based on.
+ *
+ * <p>There is max. one edit per user per change. Edits are stored on refs:
+ * refs/users/UU/UUUU/edit-CCCC/P where UU/UUUU is sharded representation of user account, CCCC is
+ * change number and P is the patch set number it is based on.
*/
public class ChangeEdit {
private final IdentifiedUser user;
@@ -41,8 +39,8 @@
private final RevCommit editCommit;
private final PatchSet basePatchSet;
- public ChangeEdit(IdentifiedUser user, Change change, Ref ref,
- RevCommit editCommit, PatchSet basePatchSet) {
+ public ChangeEdit(
+ IdentifiedUser user, Change change, Ref ref, RevCommit editCommit, PatchSet basePatchSet) {
checkNotNull(user);
checkNotNull(change);
checkNotNull(ref);
@@ -72,8 +70,7 @@
}
public String getRefName() {
- return RefNames.refsEdit(user.getAccountId(), change.getId(),
- basePatchSet.getId());
+ return RefNames.refsEdit(user.getAccountId(), change.getId(), basePatchSet.getId());
}
public RevCommit getEditCommit() {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/edit/ChangeEditJson.java b/gerrit-server/src/main/java/com/google/gerrit/server/edit/ChangeEditJson.java
index be9e1b5..41af77d 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/edit/ChangeEditJson.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/edit/ChangeEditJson.java
@@ -26,12 +26,10 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.revwalk.RevCommit;
-
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
+import org.eclipse.jgit.revwalk.RevCommit;
@Singleton
public class ChangeEditJson {
@@ -40,7 +38,8 @@
private final Provider<CurrentUser> userProvider;
@Inject
- ChangeEditJson(DynamicMap<DownloadCommand> downloadCommand,
+ ChangeEditJson(
+ DynamicMap<DownloadCommand> downloadCommand,
DynamicMap<DownloadScheme> downloadSchemes,
Provider<CurrentUser> userProvider) {
this.downloadCommands = downloadCommand;
@@ -62,8 +61,7 @@
CommitInfo commit = new CommitInfo();
commit.commit = editCommit.toObjectId().getName();
commit.author = CommonConverters.toGitPerson(editCommit.getAuthorIdent());
- commit.committer = CommonConverters.toGitPerson(
- editCommit.getCommitterIdent());
+ commit.committer = CommonConverters.toGitPerson(editCommit.getCommitterIdent());
commit.subject = editCommit.getShortMessage();
commit.message = editCommit.getFullMessage();
@@ -83,8 +81,7 @@
String schemeName = e.getExportName();
DownloadScheme scheme = e.getProvider().get();
if (!scheme.isEnabled()
- || (scheme.isAuthRequired()
- && !userProvider.get().isIdentifiedUser())) {
+ || (scheme.isAuthRequired() && !userProvider.get().isIdentifiedUser())) {
continue;
}
@@ -98,8 +95,7 @@
FetchInfo fetchInfo = new FetchInfo(scheme.getUrl(projectName), refName);
r.put(schemeName, fetchInfo);
- ChangeJson.populateFetchMap(scheme, downloadCommands, projectName,
- refName, fetchInfo);
+ ChangeJson.populateFetchMap(scheme, downloadCommands, projectName, refName, fetchInfo);
}
return r;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/edit/ChangeEditModifier.java b/gerrit-server/src/main/java/com/google/gerrit/server/edit/ChangeEditModifier.java
index e7e093a..4a7f7da 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/edit/ChangeEditModifier.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/edit/ChangeEditModifier.java
@@ -42,7 +42,10 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
+import java.io.IOException;
+import java.sql.Timestamp;
+import java.util.Optional;
+import java.util.TimeZone;
import org.eclipse.jgit.lib.BatchRefUpdate;
import org.eclipse.jgit.lib.CommitBuilder;
import org.eclipse.jgit.lib.NullProgressMonitor;
@@ -58,17 +61,12 @@
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.transport.ReceiveCommand;
-import java.io.IOException;
-import java.sql.Timestamp;
-import java.util.Optional;
-import java.util.TimeZone;
-
/**
* Utility functions to manipulate change edits.
- * <p>
- * This class contains methods to modify edit's content.
- * For retrieving, publishing and deleting edit see
- * {@link ChangeEditUtil}.
+ *
+ * <p>This class contains methods to modify edit's content. For retrieving, publishing and deleting
+ * edit see {@link ChangeEditUtil}.
+ *
* <p>
*/
@Singleton
@@ -82,7 +80,8 @@
private final PatchSetUtil patchSetUtil;
@Inject
- ChangeEditModifier(@GerritPersonIdent PersonIdent gerritIdent,
+ ChangeEditModifier(
+ @GerritPersonIdent PersonIdent gerritIdent,
ChangeIndexer indexer,
Provider<ReviewDb> reviewDb,
Provider<CurrentUser> currentUser,
@@ -100,68 +99,64 @@
* Creates a new change edit.
*
* @param repository the affected Git repository
- * @param changeControl the {@code ChangeControl} of the change for which
- * the change edit should be created
- * @throws AuthException if the user isn't authenticated or not allowed to
- * use change edits
- * @throws InvalidChangeOperationException if a change edit already existed
- * for the change
+ * @param changeControl the {@code ChangeControl} of the change for which the change edit should
+ * be created
+ * @throws AuthException if the user isn't authenticated or not allowed to use change edits
+ * @throws InvalidChangeOperationException if a change edit already existed for the change
*/
public void createEdit(Repository repository, ChangeControl changeControl)
- throws AuthException, IOException, InvalidChangeOperationException,
- OrmException {
+ throws AuthException, IOException, InvalidChangeOperationException, OrmException {
ensureAuthenticatedAndPermitted(changeControl);
Optional<ChangeEdit> changeEdit = lookupChangeEdit(changeControl);
if (changeEdit.isPresent()) {
- throw new InvalidChangeOperationException(String.format("A change edit "
- + "already exists for change %s", changeControl.getId()));
+ throw new InvalidChangeOperationException(
+ String.format("A change edit " + "already exists for change %s", changeControl.getId()));
}
PatchSet currentPatchSet = lookupCurrentPatchSet(changeControl);
ObjectId patchSetCommitId = getPatchSetCommitId(currentPatchSet);
- createEditReference(repository, changeControl, currentPatchSet,
- patchSetCommitId, TimeUtil.nowTs());
+ createEditReference(
+ repository, changeControl, currentPatchSet, patchSetCommitId, TimeUtil.nowTs());
}
/**
* Rebase change edit on latest patch set
*
* @param repository the affected Git repository
- * @param changeControl the {@code ChangeControl} of the change whose change
- * edit should be rebased
- * @throws AuthException if the user isn't authenticated or not allowed to
- * use change edits
- * @throws InvalidChangeOperationException if a change edit doesn't exist
- * for the specified change, the change edit is already based on the latest
- * patch set, or the change represents the root commit
+ * @param changeControl the {@code ChangeControl} of the change whose change edit should be
+ * rebased
+ * @throws AuthException if the user isn't authenticated or not allowed to use change edits
+ * @throws InvalidChangeOperationException if a change edit doesn't exist for the specified
+ * change, the change edit is already based on the latest patch set, or the change represents
+ * the root commit
* @throws MergeConflictException if rebase fails due to merge conflicts
*/
public void rebaseEdit(Repository repository, ChangeControl changeControl)
- throws AuthException, InvalidChangeOperationException, IOException,
- OrmException, MergeConflictException {
+ throws AuthException, InvalidChangeOperationException, IOException, OrmException,
+ MergeConflictException {
ensureAuthenticatedAndPermitted(changeControl);
Optional<ChangeEdit> optionalChangeEdit = lookupChangeEdit(changeControl);
if (!optionalChangeEdit.isPresent()) {
- throw new InvalidChangeOperationException(String.format(
- "No change edit exists for change %s", changeControl.getId()));
+ throw new InvalidChangeOperationException(
+ String.format("No change edit exists for change %s", changeControl.getId()));
}
ChangeEdit changeEdit = optionalChangeEdit.get();
PatchSet currentPatchSet = lookupCurrentPatchSet(changeControl);
if (isBasedOn(changeEdit, currentPatchSet)) {
- throw new InvalidChangeOperationException(String.format(
- "Change edit for change %s is already based on latest patch set %s",
- changeControl.getId(), currentPatchSet.getId()));
+ throw new InvalidChangeOperationException(
+ String.format(
+ "Change edit for change %s is already based on latest patch set %s",
+ changeControl.getId(), currentPatchSet.getId()));
}
rebase(repository, changeEdit, currentPatchSet);
}
- private void rebase(Repository repository, ChangeEdit changeEdit,
- PatchSet currentPatchSet) throws IOException, MergeConflictException,
- InvalidChangeOperationException, OrmException {
+ private void rebase(Repository repository, ChangeEdit changeEdit, PatchSet currentPatchSet)
+ throws IOException, MergeConflictException, InvalidChangeOperationException, OrmException {
RevCommit currentEditCommit = changeEdit.getEditCommit();
if (currentEditCommit.getParentCount() == 0) {
throw new InvalidChangeOperationException(
@@ -175,39 +170,42 @@
ObjectId newTreeId = merge(repository, changeEdit, basePatchSetTree);
Timestamp nowTimestamp = TimeUtil.nowTs();
String commitMessage = currentEditCommit.getFullMessage();
- ObjectId newEditCommitId = createCommit(repository, basePatchSetCommit,
- newTreeId, commitMessage, nowTimestamp);
+ ObjectId newEditCommitId =
+ createCommit(repository, basePatchSetCommit, newTreeId, commitMessage, nowTimestamp);
String newEditRefName = getEditRefName(change, currentPatchSet);
- updateReferenceWithNameChange(repository, changeEdit.getRefName(),
- currentEditCommit, newEditRefName, newEditCommitId, nowTimestamp);
+ updateReferenceWithNameChange(
+ repository,
+ changeEdit.getRefName(),
+ currentEditCommit,
+ newEditRefName,
+ newEditCommitId,
+ nowTimestamp);
reindex(change);
}
/**
- * Modifies the commit message of a change edit. If the change edit doesn't
- * exist, a new one will be created based on the current patch set.
+ * Modifies the commit message of a change edit. If the change edit doesn't exist, a new one will
+ * be created based on the current patch set.
*
* @param repository the affected Git repository
- * @param changeControl the {@code ChangeControl} of the change whose change
- * edit's message should be modified
+ * @param changeControl the {@code ChangeControl} of the change whose change edit's message should
+ * be modified
* @param newCommitMessage the new commit message
- * @throws AuthException if the user isn't authenticated or not allowed to
- * use change edits
- * @throws UnchangedCommitMessageException if the commit message is the same
- * as before
+ * @throws AuthException if the user isn't authenticated or not allowed to use change edits
+ * @throws UnchangedCommitMessageException if the commit message is the same as before
*/
- public void modifyMessage(Repository repository, ChangeControl changeControl,
- String newCommitMessage) throws AuthException, IOException,
- UnchangedCommitMessageException, OrmException {
+ public void modifyMessage(
+ Repository repository, ChangeControl changeControl, String newCommitMessage)
+ throws AuthException, IOException, UnchangedCommitMessageException, OrmException {
ensureAuthenticatedAndPermitted(changeControl);
newCommitMessage = getWellFormedCommitMessage(newCommitMessage);
Optional<ChangeEdit> optionalChangeEdit = lookupChangeEdit(changeControl);
PatchSet basePatchSet = getBasePatchSet(optionalChangeEdit, changeControl);
RevCommit basePatchSetCommit = lookupCommit(repository, basePatchSet);
- RevCommit baseCommit = optionalChangeEdit.map(ChangeEdit::getEditCommit)
- .orElse(basePatchSetCommit);
+ RevCommit baseCommit =
+ optionalChangeEdit.map(ChangeEdit::getEditCommit).orElse(basePatchSetCommit);
String currentCommitMessage = baseCommit.getFullMessage();
if (newCommitMessage.equals(currentCommitMessage)) {
@@ -216,123 +214,111 @@
RevTree baseTree = baseCommit.getTree();
Timestamp nowTimestamp = TimeUtil.nowTs();
- ObjectId newEditCommit = createCommit(repository, basePatchSetCommit,
- baseTree, newCommitMessage, nowTimestamp);
+ ObjectId newEditCommit =
+ createCommit(repository, basePatchSetCommit, baseTree, newCommitMessage, nowTimestamp);
if (optionalChangeEdit.isPresent()) {
- updateEditReference(repository, optionalChangeEdit.get(), newEditCommit,
- nowTimestamp);
+ updateEditReference(repository, optionalChangeEdit.get(), newEditCommit, nowTimestamp);
} else {
- createEditReference(repository, changeControl, basePatchSet,
- newEditCommit, nowTimestamp);
+ createEditReference(repository, changeControl, basePatchSet, newEditCommit, nowTimestamp);
}
}
/**
- * Modifies the contents of a file of a change edit. If the change edit
- * doesn't exist, a new one will be created based on the current patch set.
+ * Modifies the contents of a file of a change edit. If the change edit doesn't exist, a new one
+ * will be created based on the current patch set.
*
* @param repository the affected Git repository
- * @param changeControl the {@code ChangeControl} of the change whose change
- * edit should be modified
+ * @param changeControl the {@code ChangeControl} of the change whose change edit should be
+ * modified
* @param filePath the path of the file whose contents should be modified
* @param newContent the new file content
- * @throws AuthException if the user isn't authenticated or not allowed to
- * use change edits
- * @throws InvalidChangeOperationException if the file already had the
- * specified content
+ * @throws AuthException if the user isn't authenticated or not allowed to use change edits
+ * @throws InvalidChangeOperationException if the file already had the specified content
*/
- public void modifyFile(Repository repository, ChangeControl changeControl,
- String filePath, RawInput newContent) throws AuthException,
- InvalidChangeOperationException, IOException, OrmException {
- modifyTree(repository, changeControl,
- new ChangeFileContentModification(filePath, newContent));
+ public void modifyFile(
+ Repository repository, ChangeControl changeControl, String filePath, RawInput newContent)
+ throws AuthException, InvalidChangeOperationException, IOException, OrmException {
+ modifyTree(repository, changeControl, new ChangeFileContentModification(filePath, newContent));
}
/**
- * Deletes a file from the Git tree of a change edit. If the change edit
- * doesn't exist, a new one will be created based on the current patch set.
+ * Deletes a file from the Git tree of a change edit. If the change edit doesn't exist, a new one
+ * will be created based on the current patch set.
*
* @param repository the affected Git repository
- * @param changeControl the {@code ChangeControl} of the change whose change
- * edit should be modified
+ * @param changeControl the {@code ChangeControl} of the change whose change edit should be
+ * modified
* @param file path of the file which should be deleted
- * @throws AuthException if the user isn't authenticated or not allowed to
- * use change edits
+ * @throws AuthException if the user isn't authenticated or not allowed to use change edits
* @throws InvalidChangeOperationException if the file does not exist
*/
- public void deleteFile(Repository repository, ChangeControl changeControl,
- String file) throws AuthException, InvalidChangeOperationException,
- IOException, OrmException {
+ public void deleteFile(Repository repository, ChangeControl changeControl, String file)
+ throws AuthException, InvalidChangeOperationException, IOException, OrmException {
modifyTree(repository, changeControl, new DeleteFileModification(file));
}
/**
- * Renames a file of a change edit or moves it to another directory. If the
- * change edit doesn't exist, a new one will be created based on the current
- * patch set.
+ * Renames a file of a change edit or moves it to another directory. If the change edit doesn't
+ * exist, a new one will be created based on the current patch set.
*
* @param repository the affected Git repository
- * @param changeControl the {@code ChangeControl} of the change whose change
- * edit should be modified
+ * @param changeControl the {@code ChangeControl} of the change whose change edit should be
+ * modified
* @param currentFilePath the current path/name of the file
* @param newFilePath the desired path/name of the file
- * @throws AuthException if the user isn't authenticated or not allowed to
- * use change edits
- * @throws InvalidChangeOperationException if the file was already renamed
- * to the specified new name
+ * @throws AuthException if the user isn't authenticated or not allowed to use change edits
+ * @throws InvalidChangeOperationException if the file was already renamed to the specified new
+ * name
*/
- public void renameFile(Repository repository, ChangeControl changeControl,
- String currentFilePath, String newFilePath) throws AuthException,
- InvalidChangeOperationException, IOException, OrmException {
- modifyTree(repository, changeControl,
- new RenameFileModification(currentFilePath, newFilePath));
+ public void renameFile(
+ Repository repository,
+ ChangeControl changeControl,
+ String currentFilePath,
+ String newFilePath)
+ throws AuthException, InvalidChangeOperationException, IOException, OrmException {
+ modifyTree(repository, changeControl, new RenameFileModification(currentFilePath, newFilePath));
}
/**
- * Restores a file of a change edit to the state it was in before the patch
- * set on which the change edit is based. If the change edit doesn't exist, a
- * new one will be created based on the current patch set.
+ * Restores a file of a change edit to the state it was in before the patch set on which the
+ * change edit is based. If the change edit doesn't exist, a new one will be created based on the
+ * current patch set.
*
* @param repository the affected Git repository
- * @param changeControl the {@code ChangeControl} of the change whose change
- * edit should be modified
+ * @param changeControl the {@code ChangeControl} of the change whose change edit should be
+ * modified
* @param file the path of the file which should be restored
- * @throws AuthException if the user isn't authenticated or not allowed to
- * use change edits
+ * @throws AuthException if the user isn't authenticated or not allowed to use change edits
* @throws InvalidChangeOperationException if the file was already restored
*/
- public void restoreFile(Repository repository, ChangeControl changeControl,
- String file) throws AuthException, InvalidChangeOperationException,
- IOException, OrmException {
+ public void restoreFile(Repository repository, ChangeControl changeControl, String file)
+ throws AuthException, InvalidChangeOperationException, IOException, OrmException {
modifyTree(repository, changeControl, new RestoreFileModification(file));
}
- private void modifyTree(Repository repository, ChangeControl changeControl,
- TreeModification treeModification) throws AuthException, IOException,
- OrmException, InvalidChangeOperationException {
+ private void modifyTree(
+ Repository repository, ChangeControl changeControl, TreeModification treeModification)
+ throws AuthException, IOException, OrmException, InvalidChangeOperationException {
ensureAuthenticatedAndPermitted(changeControl);
Optional<ChangeEdit> optionalChangeEdit = lookupChangeEdit(changeControl);
PatchSet basePatchSet = getBasePatchSet(optionalChangeEdit, changeControl);
RevCommit basePatchSetCommit = lookupCommit(repository, basePatchSet);
- RevCommit baseCommit = optionalChangeEdit.map(ChangeEdit::getEditCommit)
- .orElse(basePatchSetCommit);
+ RevCommit baseCommit =
+ optionalChangeEdit.map(ChangeEdit::getEditCommit).orElse(basePatchSetCommit);
- ObjectId newTreeId = createNewTree(repository, baseCommit,
- treeModification);
+ ObjectId newTreeId = createNewTree(repository, baseCommit, treeModification);
String commitMessage = baseCommit.getFullMessage();
Timestamp nowTimestamp = TimeUtil.nowTs();
- ObjectId newEditCommit = createCommit(repository, basePatchSetCommit,
- newTreeId, commitMessage, nowTimestamp);
+ ObjectId newEditCommit =
+ createCommit(repository, basePatchSetCommit, newTreeId, commitMessage, nowTimestamp);
if (optionalChangeEdit.isPresent()) {
- updateEditReference(repository, optionalChangeEdit.get(), newEditCommit,
- nowTimestamp);
+ updateEditReference(repository, optionalChangeEdit.get(), newEditCommit, nowTimestamp);
} else {
- createEditReference(repository, changeControl, basePatchSet,
- newEditCommit, nowTimestamp);
+ createEditReference(repository, changeControl, basePatchSet, newEditCommit, nowTimestamp);
}
}
@@ -348,8 +334,7 @@
}
}
- private void ensurePermitted(ChangeControl changeControl)
- throws OrmException, AuthException {
+ private void ensurePermitted(ChangeControl changeControl) throws OrmException, AuthException {
if (!changeControl.canAddPatchSet(reviewDb.get())) {
throw new AuthException("Not allowed to edit a change.");
}
@@ -357,8 +342,7 @@
private String getWellFormedCommitMessage(String commitMessage) {
String wellFormedMessage = Strings.nullToEmpty(commitMessage).trim();
- checkState(!wellFormedMessage.isEmpty(),
- "Commit message cannot be null or empty");
+ checkState(!wellFormedMessage.isEmpty(), "Commit message cannot be null or empty");
wellFormedMessage = wellFormedMessage + "\n";
return wellFormedMessage;
}
@@ -368,17 +352,15 @@
return changeEditUtil.byChange(changeControl);
}
- private PatchSet getBasePatchSet(Optional<ChangeEdit> optionalChangeEdit,
- ChangeControl changeControl) throws OrmException {
- Optional<PatchSet> editBasePatchSet =
- optionalChangeEdit.map(ChangeEdit::getBasePatchSet);
+ private PatchSet getBasePatchSet(
+ Optional<ChangeEdit> optionalChangeEdit, ChangeControl changeControl) throws OrmException {
+ Optional<PatchSet> editBasePatchSet = optionalChangeEdit.map(ChangeEdit::getBasePatchSet);
return editBasePatchSet.isPresent()
? editBasePatchSet.get()
: lookupCurrentPatchSet(changeControl);
}
- private PatchSet lookupCurrentPatchSet(ChangeControl changeControl)
- throws OrmException {
+ private PatchSet lookupCurrentPatchSet(ChangeControl changeControl) throws OrmException {
return patchSetUtil.current(reviewDb.get(), changeControl.getNotes());
}
@@ -387,16 +369,16 @@
return editBasePatchSet.getId().equals(patchSet.getId());
}
- private static RevCommit lookupCommit(Repository repository,
- PatchSet patchSet) throws IOException {
+ private static RevCommit lookupCommit(Repository repository, PatchSet patchSet)
+ throws IOException {
ObjectId patchSetCommitId = getPatchSetCommitId(patchSet);
try (RevWalk revWalk = new RevWalk(repository)) {
return revWalk.parseCommit(patchSetCommitId);
}
}
- private static ObjectId createNewTree(Repository repository,
- RevCommit baseCommit, TreeModification treeModification)
+ private static ObjectId createNewTree(
+ Repository repository, RevCommit baseCommit, TreeModification treeModification)
throws IOException, InvalidChangeOperationException {
TreeCreator treeCreator = new TreeCreator(baseCommit);
treeCreator.addTreeModification(treeModification);
@@ -408,14 +390,13 @@
return newTreeId;
}
- private ObjectId merge(Repository repository, ChangeEdit changeEdit,
- ObjectId newTreeId) throws IOException, MergeConflictException {
+ private ObjectId merge(Repository repository, ChangeEdit changeEdit, ObjectId newTreeId)
+ throws IOException, MergeConflictException {
PatchSet basePatchSet = changeEdit.getBasePatchSet();
ObjectId basePatchSetCommitId = getPatchSetCommitId(basePatchSet);
ObjectId editCommitId = changeEdit.getEditCommit();
- ThreeWayMerger threeWayMerger =
- MergeStrategy.RESOLVE.newMerger(repository, true);
+ ThreeWayMerger threeWayMerger = MergeStrategy.RESOLVE.newMerger(repository, true);
threeWayMerger.setBase(basePatchSetCommitId);
boolean successful = threeWayMerger.merge(newTreeId, editCommitId);
@@ -426,9 +407,13 @@
return threeWayMerger.getResultTreeId();
}
- private ObjectId createCommit(Repository repository,
- RevCommit basePatchSetCommit, ObjectId tree, String commitMessage,
- Timestamp timestamp) throws IOException {
+ private ObjectId createCommit(
+ Repository repository,
+ RevCommit basePatchSetCommit,
+ ObjectId tree,
+ String commitMessage,
+ Timestamp timestamp)
+ throws IOException {
try (ObjectInserter objectInserter = repository.newObjectInserter()) {
CommitBuilder builder = new CommitBuilder();
builder.setTreeId(tree);
@@ -451,35 +436,39 @@
return ObjectId.fromString(patchSet.getRevision().get());
}
- private void createEditReference(Repository repository,
- ChangeControl changeControl, PatchSet basePatchSet,
- ObjectId newEditCommit, Timestamp timestamp)
+ private void createEditReference(
+ Repository repository,
+ ChangeControl changeControl,
+ PatchSet basePatchSet,
+ ObjectId newEditCommit,
+ Timestamp timestamp)
throws IOException, OrmException {
Change change = changeControl.getChange();
String editRefName = getEditRefName(change, basePatchSet);
- updateReference(repository, editRefName, ObjectId.zeroId(), newEditCommit,
- timestamp);
+ updateReference(repository, editRefName, ObjectId.zeroId(), newEditCommit, timestamp);
reindex(change);
}
private String getEditRefName(Change change, PatchSet basePatchSet) {
IdentifiedUser me = currentUser.get().asIdentifiedUser();
- return RefNames.refsEdit(me.getAccountId(), change.getId(),
- basePatchSet.getId());
+ return RefNames.refsEdit(me.getAccountId(), change.getId(), basePatchSet.getId());
}
- private void updateEditReference(Repository repository, ChangeEdit changeEdit,
- ObjectId newEditCommit, Timestamp timestamp)
+ private void updateEditReference(
+ Repository repository, ChangeEdit changeEdit, ObjectId newEditCommit, Timestamp timestamp)
throws IOException, OrmException {
String editRefName = changeEdit.getRefName();
RevCommit currentEditCommit = changeEdit.getEditCommit();
- updateReference(repository, editRefName, currentEditCommit, newEditCommit,
- timestamp);
+ updateReference(repository, editRefName, currentEditCommit, newEditCommit, timestamp);
reindex(changeEdit.getChange());
}
- private void updateReference(Repository repository, String refName,
- ObjectId currentObjectId, ObjectId targetObjectId, Timestamp timestamp)
+ private void updateReference(
+ Repository repository,
+ String refName,
+ ObjectId currentObjectId,
+ ObjectId targetObjectId,
+ Timestamp timestamp)
throws IOException {
RefUpdate ru = repository.updateRef(refName);
ru.setExpectedOldObjectId(currentObjectId);
@@ -495,16 +484,18 @@
}
}
- private void updateReferenceWithNameChange(Repository repository,
- String currentRefName, ObjectId currentObjectId, String newRefName,
- ObjectId targetObjectId, Timestamp timestamp)
+ private void updateReferenceWithNameChange(
+ Repository repository,
+ String currentRefName,
+ ObjectId currentObjectId,
+ String newRefName,
+ ObjectId targetObjectId,
+ Timestamp timestamp)
throws IOException {
- BatchRefUpdate batchRefUpdate =
- repository.getRefDatabase().newBatchUpdate();
- batchRefUpdate.addCommand(new ReceiveCommand(ObjectId.zeroId(),
- targetObjectId, newRefName));
- batchRefUpdate.addCommand(new ReceiveCommand(currentObjectId,
- ObjectId.zeroId(), currentRefName));
+ BatchRefUpdate batchRefUpdate = repository.getRefDatabase().newBatchUpdate();
+ batchRefUpdate.addCommand(new ReceiveCommand(ObjectId.zeroId(), targetObjectId, newRefName));
+ batchRefUpdate.addCommand(
+ new ReceiveCommand(currentObjectId, ObjectId.zeroId(), currentRefName));
batchRefUpdate.setRefLogMessage("rebase edit", false);
batchRefUpdate.setRefLogIdent(getRefLogIdent(timestamp));
try (RevWalk revWalk = new RevWalk(repository)) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/edit/ChangeEditUtil.java b/gerrit-server/src/main/java/com/google/gerrit/server/edit/ChangeEditUtil.java
index 784d4d6..31712f3 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/edit/ChangeEditUtil.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/edit/ChangeEditUtil.java
@@ -47,7 +47,8 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
+import java.io.IOException;
+import java.util.Optional;
import org.eclipse.jgit.lib.CommitBuilder;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.ObjectInserter;
@@ -57,14 +58,11 @@
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;
-import java.io.IOException;
-import java.util.Optional;
-
/**
* Utility functions to manipulate change edits.
- * <p>
- * This class contains methods to retrieve, publish and delete edits.
- * For changing edits see {@link ChangeEditModifier}.
+ *
+ * <p>This class contains methods to retrieve, publish and delete edits. For changing edits see
+ * {@link ChangeEditModifier}.
*/
@Singleton
public class ChangeEditUtil {
@@ -79,7 +77,8 @@
private final PatchSetUtil psUtil;
@Inject
- ChangeEditUtil(GitRepositoryManager gitManager,
+ ChangeEditUtil(
+ GitRepositoryManager gitManager,
PatchSetInserter.Factory patchSetInserterFactory,
ChangeControl.GenericFactory changeControlFactory,
ChangeIndexer indexer,
@@ -101,8 +100,8 @@
/**
* Retrieve edit for a change and the user from the request scope.
- * <p>
- * At most one change edit can exist per user and change.
+ *
+ * <p>At most one change edit can exist per user and change.
*
* @param change
* @return edit for this change for this user, if present.
@@ -113,8 +112,7 @@
public Optional<ChangeEdit> byChange(Change change)
throws AuthException, IOException, OrmException {
try {
- return byChange(
- changeControlFactory.controlFor(db.get(), change, user.get()));
+ return byChange(changeControlFactory.controlFor(db.get(), change, user.get()));
} catch (NoSuchChangeException e) {
throw new IOException(e);
}
@@ -122,16 +120,15 @@
/**
* Retrieve edit for a change and the given user.
- * <p>
- * At most one change edit can exist per user and change.
+ *
+ * <p>At most one change edit can exist per user and change.
*
* @param ctl control with user to retrieve change edits for.
* @return edit for this change for this user, if present.
* @throws AuthException if this is not a logged-in user.
* @throws IOException if an error occurs.
*/
- public Optional<ChangeEdit> byChange(ChangeControl ctl)
- throws AuthException, IOException {
+ public Optional<ChangeEdit> byChange(ChangeControl ctl) throws AuthException, IOException {
if (!ctl.getUser().isIdentifiedUser()) {
throw new AuthException("Authentication required");
}
@@ -141,9 +138,8 @@
int n = change.currentPatchSetId().get();
String[] refNames = new String[n];
for (int i = n; i > 0; i--) {
- refNames[i - 1] = RefNames.refsEdit(
- u.getAccountId(), change.getId(),
- new PatchSet.Id(change.getId(), i));
+ refNames[i - 1] =
+ RefNames.refsEdit(u.getAccountId(), change.getId(), new PatchSet.Id(change.getId(), i));
}
Ref ref = repo.getRefDatabase().firstExactRef(refNames);
if (ref == null) {
@@ -161,16 +157,17 @@
* Promote change edit to patch set, by squashing the edit into its parent.
*
* @param edit change edit to publish
- * @param notify Notify handling that defines to whom email notifications
- * should be sent after the change edit is published.
- * @param accountsToNotify Accounts that should be notified after the change
- * edit is published.
+ * @param notify Notify handling that defines to whom email notifications should be sent after the
+ * change edit is published.
+ * @param accountsToNotify Accounts that should be notified after the change edit is published.
* @throws IOException
* @throws OrmException
* @throws UpdateException
* @throws RestApiException
*/
- public void publish(final ChangeEdit edit, NotifyHandling notify,
+ public void publish(
+ final ChangeEdit edit,
+ NotifyHandling notify,
ListMultimap<RecipientType, Account.Id> accountsToNotify)
throws IOException, OrmException, RestApiException, UpdateException {
Change change = edit.getChange();
@@ -179,57 +176,60 @@
ObjectInserter oi = repo.newObjectInserter()) {
PatchSet basePatchSet = edit.getBasePatchSet();
if (!basePatchSet.getId().equals(change.currentPatchSetId())) {
- throw new ResourceConflictException(
- "only edit for current patch set can be published");
+ throw new ResourceConflictException("only edit for current patch set can be published");
}
RevCommit squashed = squashEdit(rw, oi, edit.getEditCommit(), basePatchSet);
- ChangeControl ctl =
- changeControlFactory.controlFor(db.get(), change, edit.getUser());
- PatchSet.Id psId =
- ChangeUtil.nextPatchSetId(repo, change.currentPatchSetId());
- PatchSetInserter inserter = patchSetInserterFactory
- .create(ctl, psId, squashed)
- .setNotify(notify)
- .setAccountsToNotify(accountsToNotify);
+ ChangeControl ctl = changeControlFactory.controlFor(db.get(), change, edit.getUser());
+ PatchSet.Id psId = ChangeUtil.nextPatchSetId(repo, change.currentPatchSetId());
+ PatchSetInserter inserter =
+ patchSetInserterFactory
+ .create(ctl, psId, squashed)
+ .setNotify(notify)
+ .setAccountsToNotify(accountsToNotify);
- StringBuilder message = new StringBuilder("Patch Set ")
- .append(inserter.getPatchSetId().get())
- .append(": ");
+ StringBuilder message =
+ new StringBuilder("Patch Set ").append(inserter.getPatchSetId().get()).append(": ");
// Previously checked that the base patch set is the current patch set.
ObjectId prior = ObjectId.fromString(basePatchSet.getRevision().get());
- ChangeKind kind = changeKindCache.getChangeKind(
- change.getProject(), repo, prior, squashed);
+ ChangeKind kind = changeKindCache.getChangeKind(change.getProject(), repo, prior, squashed);
if (kind == ChangeKind.NO_CODE_CHANGE) {
message.append("Commit message was updated.");
inserter.setDescription("Edit commit message");
} else {
- message.append("Published edit on patch set ")
- .append(basePatchSet.getPatchSetId())
- .append(".");
+ message
+ .append("Published edit on patch set ")
+ .append(basePatchSet.getPatchSetId())
+ .append(".");
}
- try (BatchUpdate bu = updateFactory.create(
- db.get(), change.getProject(), ctl.getUser(),
- TimeUtil.nowTs())) {
+ try (BatchUpdate bu =
+ updateFactory.create(db.get(), change.getProject(), ctl.getUser(), TimeUtil.nowTs())) {
bu.setRepository(repo, rw, oi);
- bu.addOp(change.getId(), inserter
- .setDraft(change.getStatus() == Status.DRAFT ||
- basePatchSet.isDraft())
- .setMessage(message.toString()));
- bu.addOp(change.getId(), new BatchUpdate.Op() {
- @Override
- public void updateRepo(RepoContext ctx) throws Exception {
- deleteRef(ctx.getRepository(), edit);
- }
- });
+ bu.addOp(
+ change.getId(),
+ inserter
+ .setDraft(change.getStatus() == Status.DRAFT || basePatchSet.isDraft())
+ .setMessage(message.toString()));
+ bu.addOp(
+ change.getId(),
+ new BatchUpdate.Op() {
+ @Override
+ public void updateRepo(RepoContext ctx) throws Exception {
+ deleteRef(ctx.getRepository(), edit);
+ }
+ });
bu.execute();
} catch (UpdateException e) {
- if (e.getCause() instanceof IOException && e.getMessage()
- .equals(String.format("%s: Failed to delete ref %s: %s",
- IOException.class.getName(), edit.getRefName(),
- RefUpdate.Result.LOCK_FAILURE.name()))) {
+ if (e.getCause() instanceof IOException
+ && e.getMessage()
+ .equals(
+ String.format(
+ "%s: Failed to delete ref %s: %s",
+ IOException.class.getName(),
+ edit.getRefName(),
+ RefUpdate.Result.LOCK_FAILURE.name()))) {
throw new ResourceConflictException("edit ref was updated");
}
}
@@ -245,8 +245,7 @@
* @throws IOException
* @throws OrmException
*/
- public void delete(ChangeEdit edit)
- throws IOException, OrmException {
+ public void delete(ChangeEdit edit) throws IOException, OrmException {
Change change = edit.getChange();
try (Repository repo = gitManager.openRepository(change.getProject())) {
deleteRef(repo, edit);
@@ -254,24 +253,22 @@
indexer.index(db.get(), change);
}
- private PatchSet getBasePatchSet(ChangeControl ctl, Ref ref)
- throws IOException {
+ private PatchSet getBasePatchSet(ChangeControl ctl, Ref ref) throws IOException {
try {
int pos = ref.getName().lastIndexOf("/");
checkArgument(pos > 0, "invalid edit ref: %s", ref.getName());
String psId = ref.getName().substring(pos + 1);
- return psUtil.get(db.get(), ctl.getNotes(),
- new PatchSet.Id(ctl.getId(), Integer.parseInt(psId)));
+ return psUtil.get(
+ db.get(), ctl.getNotes(), new PatchSet.Id(ctl.getId(), Integer.parseInt(psId)));
} catch (OrmException | NumberFormatException e) {
throw new IOException(e);
}
}
- private RevCommit squashEdit(RevWalk rw, ObjectInserter inserter,
- RevCommit edit, PatchSet basePatchSet)
+ private RevCommit squashEdit(
+ RevWalk rw, ObjectInserter inserter, RevCommit edit, PatchSet basePatchSet)
throws IOException, ResourceConflictException {
- RevCommit parent = rw.parseCommit(ObjectId.fromString(
- basePatchSet.getRevision().get()));
+ RevCommit parent = rw.parseCommit(ObjectId.fromString(basePatchSet.getRevision().get()));
if (parent.getTree().equals(edit.getTree())
&& edit.getFullMessage().equals(parent.getFullMessage())) {
throw new ResourceConflictException("identical tree and message");
@@ -279,8 +276,7 @@
return writeSquashedCommit(rw, inserter, parent, edit);
}
- private static void deleteRef(Repository repo, ChangeEdit edit)
- throws IOException {
+ private static void deleteRef(Repository repo, ChangeEdit edit) throws IOException {
String refName = edit.getRefName();
RefUpdate ru = repo.updateRef(refName, true);
ru.setExpectedOldObjectId(edit.getRef().getObjectId());
@@ -299,14 +295,12 @@
case REJECTED_CURRENT_BRANCH:
case RENAMED:
default:
- throw new IOException(String.format("Failed to delete ref %s: %s",
- refName, result));
+ throw new IOException(String.format("Failed to delete ref %s: %s", refName, result));
}
}
- private static RevCommit writeSquashedCommit(RevWalk rw,
- ObjectInserter inserter, RevCommit parent, RevCommit edit)
- throws IOException {
+ private static RevCommit writeSquashedCommit(
+ RevWalk rw, ObjectInserter inserter, RevCommit parent, RevCommit edit) throws IOException {
CommitBuilder mergeCommit = new CommitBuilder();
for (int i = 0; i < parent.getParentCount(); i++) {
mergeCommit.addParentId(parent.getParent(i));
@@ -319,8 +313,8 @@
return rw.parseCommit(commit(inserter, mergeCommit));
}
- private static ObjectId commit(ObjectInserter inserter,
- CommitBuilder mergeCommit) throws IOException {
+ private static ObjectId commit(ObjectInserter inserter, CommitBuilder mergeCommit)
+ throws IOException {
ObjectId id = inserter.insert(mergeCommit);
inserter.flush();
return id;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/edit/tree/AddPath.java b/gerrit-server/src/main/java/com/google/gerrit/server/edit/tree/AddPath.java
index 9bf8e2c..d7cf29d 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/edit/tree/AddPath.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/edit/tree/AddPath.java
@@ -20,8 +20,8 @@
import org.eclipse.jgit.lib.ObjectId;
/**
- * A {@code PathEdit} which adds a file path to the index. This operation is the
- * counterpart to {@link org.eclipse.jgit.dircache.DirCacheEditor.DeletePath}.
+ * A {@code PathEdit} which adds a file path to the index. This operation is the counterpart to
+ * {@link org.eclipse.jgit.dircache.DirCacheEditor.DeletePath}.
*/
class AddPath extends DirCacheEditor.PathEdit {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/edit/tree/ChangeFileContentModification.java b/gerrit-server/src/main/java/com/google/gerrit/server/edit/tree/ChangeFileContentModification.java
index e83155d..dc35309 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/edit/tree/ChangeFileContentModification.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/edit/tree/ChangeFileContentModification.java
@@ -19,7 +19,10 @@
import com.google.common.io.ByteStreams;
import com.google.gerrit.extensions.restapi.RawInput;
-
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Collections;
+import java.util.List;
import org.eclipse.jgit.dircache.DirCacheEditor;
import org.eclipse.jgit.dircache.DirCacheEntry;
import org.eclipse.jgit.errors.InvalidObjectIdException;
@@ -31,18 +34,10 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Collections;
-import java.util.List;
-
-/**
- * A {@code TreeModification} which changes the content of a file.
- */
+/** A {@code TreeModification} which changes the content of a file. */
public class ChangeFileContentModification implements TreeModification {
- private static final Logger log =
- LoggerFactory.getLogger(ChangeFileContentModification.class);
+ private static final Logger log = LoggerFactory.getLogger(ChangeFileContentModification.class);
private final String filePath;
private final RawInput newContent;
@@ -53,16 +48,12 @@
}
@Override
- public List<DirCacheEditor.PathEdit> getPathEdits(Repository repository,
- RevCommit baseCommit) {
- DirCacheEditor.PathEdit changeContentEdit = new ChangeContent(filePath,
- newContent, repository);
+ public List<DirCacheEditor.PathEdit> getPathEdits(Repository repository, RevCommit baseCommit) {
+ DirCacheEditor.PathEdit changeContentEdit = new ChangeContent(filePath, newContent, repository);
return Collections.singletonList(changeContentEdit);
}
- /**
- * A {@code PathEdit} which changes the contents of a file.
- */
+ /** A {@code PathEdit} which changes the contents of a file. */
private static class ChangeContent extends DirCacheEditor.PathEdit {
private final RawInput newContent;
@@ -93,8 +84,8 @@
// situation, we log them now. However, we should think of a better
// approach.
} catch (IOException e) {
- String message = String.format("Could not change the content of %s",
- dirCacheEntry.getPathString());
+ String message =
+ String.format("Could not change the content of %s", dirCacheEntry.getPathString());
log.error(message, e);
} catch (InvalidObjectIdException e) {
log.error("Invalid object id in submodule link", e);
@@ -109,8 +100,7 @@
}
}
- private ObjectId createNewBlobAndGetItsId(ObjectInserter objectInserter)
- throws IOException {
+ private ObjectId createNewBlobAndGetItsId(ObjectInserter objectInserter) throws IOException {
long contentLength = newContent.getContentLength();
if (contentLength < 0) {
return objectInserter.insert(OBJ_BLOB, getNewContentBytes());
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/edit/tree/DeleteFileModification.java b/gerrit-server/src/main/java/com/google/gerrit/server/edit/tree/DeleteFileModification.java
index 64fe63b..62da19a 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/edit/tree/DeleteFileModification.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/edit/tree/DeleteFileModification.java
@@ -14,16 +14,13 @@
package com.google.gerrit.server.edit.tree;
+import java.util.Collections;
+import java.util.List;
import org.eclipse.jgit.dircache.DirCacheEditor;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
-import java.util.Collections;
-import java.util.List;
-
-/**
- * A {@code TreeModification} which deletes a file.
- */
+/** A {@code TreeModification} which deletes a file. */
public class DeleteFileModification implements TreeModification {
private final String filePath;
@@ -33,10 +30,8 @@
}
@Override
- public List<DirCacheEditor.PathEdit> getPathEdits(Repository repository,
- RevCommit baseCommit) {
- DirCacheEditor.DeletePath deletePathEdit =
- new DirCacheEditor.DeletePath(filePath);
+ public List<DirCacheEditor.PathEdit> getPathEdits(Repository repository, RevCommit baseCommit) {
+ DirCacheEditor.DeletePath deletePathEdit = new DirCacheEditor.DeletePath(filePath);
return Collections.singletonList(deletePathEdit);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/edit/tree/RenameFileModification.java b/gerrit-server/src/main/java/com/google/gerrit/server/edit/tree/RenameFileModification.java
index 32c1e0d..aeacd23 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/edit/tree/RenameFileModification.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/edit/tree/RenameFileModification.java
@@ -14,21 +14,17 @@
package com.google.gerrit.server.edit.tree;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
import org.eclipse.jgit.dircache.DirCacheEditor;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.treewalk.TreeWalk;
-import java.io.IOException;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-
-/**
- * A {@code TreeModification} which renames a file or moves it to a different
- * path.
- */
+/** A {@code TreeModification} which renames a file or moves it to a different path. */
public class RenameFileModification implements TreeModification {
private final String currentFilePath;
@@ -40,20 +36,18 @@
}
@Override
- public List<DirCacheEditor.PathEdit> getPathEdits(Repository repository,
- RevCommit baseCommit)
+ public List<DirCacheEditor.PathEdit> getPathEdits(Repository repository, RevCommit baseCommit)
throws IOException {
try (RevWalk revWalk = new RevWalk(repository)) {
revWalk.parseHeaders(baseCommit);
- try (TreeWalk treeWalk = TreeWalk.forPath(revWalk.getObjectReader(),
- currentFilePath, baseCommit.getTree())) {
+ try (TreeWalk treeWalk =
+ TreeWalk.forPath(revWalk.getObjectReader(), currentFilePath, baseCommit.getTree())) {
if (treeWalk == null) {
return Collections.emptyList();
}
- DirCacheEditor.DeletePath deletePathEdit =
- new DirCacheEditor.DeletePath(currentFilePath);
- AddPath addPathEdit = new AddPath(newFilePath, treeWalk.getFileMode(0),
- treeWalk.getObjectId(0));
+ DirCacheEditor.DeletePath deletePathEdit = new DirCacheEditor.DeletePath(currentFilePath);
+ AddPath addPathEdit =
+ new AddPath(newFilePath, treeWalk.getFileMode(0), treeWalk.getObjectId(0));
return Arrays.asList(deletePathEdit, addPathEdit);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/edit/tree/RestoreFileModification.java b/gerrit-server/src/main/java/com/google/gerrit/server/edit/tree/RestoreFileModification.java
index b5cc9e6..1bd55f6 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/edit/tree/RestoreFileModification.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/edit/tree/RestoreFileModification.java
@@ -14,19 +14,18 @@
package com.google.gerrit.server.edit.tree;
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
import org.eclipse.jgit.dircache.DirCacheEditor;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.treewalk.TreeWalk;
-import java.io.IOException;
-import java.util.Collections;
-import java.util.List;
-
/**
- * A {@code TreeModification} which restores a file. The file is added again if
- * it was present before the specified commit or deleted if it was absent.
+ * A {@code TreeModification} which restores a file. The file is added again if it was present
+ * before the specified commit or deleted if it was absent.
*/
public class RestoreFileModification implements TreeModification {
@@ -37,28 +36,24 @@
}
@Override
- public List<DirCacheEditor.PathEdit> getPathEdits(Repository repository,
- RevCommit baseCommit)
+ public List<DirCacheEditor.PathEdit> getPathEdits(Repository repository, RevCommit baseCommit)
throws IOException {
if (baseCommit.getParentCount() == 0) {
- DirCacheEditor.DeletePath deletePath =
- new DirCacheEditor.DeletePath(filePath);
+ DirCacheEditor.DeletePath deletePath = new DirCacheEditor.DeletePath(filePath);
return Collections.singletonList(deletePath);
}
RevCommit base = baseCommit.getParent(0);
try (RevWalk revWalk = new RevWalk(repository)) {
revWalk.parseHeaders(base);
- try (TreeWalk treeWalk = TreeWalk.forPath(revWalk.getObjectReader(),
- filePath, base.getTree())) {
+ try (TreeWalk treeWalk =
+ TreeWalk.forPath(revWalk.getObjectReader(), filePath, base.getTree())) {
if (treeWalk == null) {
- DirCacheEditor.DeletePath deletePath =
- new DirCacheEditor.DeletePath(filePath);
+ DirCacheEditor.DeletePath deletePath = new DirCacheEditor.DeletePath(filePath);
return Collections.singletonList(deletePath);
}
- AddPath addPath = new AddPath(filePath, treeWalk.getFileMode(0),
- treeWalk.getObjectId(0));
+ AddPath addPath = new AddPath(filePath, treeWalk.getFileMode(0), treeWalk.getObjectId(0));
return Collections.singletonList(addPath);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/edit/tree/TreeCreator.java b/gerrit-server/src/main/java/com/google/gerrit/server/edit/tree/TreeCreator.java
index 39e6ac4..7e9a96a 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/edit/tree/TreeCreator.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/edit/tree/TreeCreator.java
@@ -16,6 +16,9 @@
import static com.google.common.base.Preconditions.checkNotNull;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
import org.eclipse.jgit.dircache.DirCache;
import org.eclipse.jgit.dircache.DirCacheBuilder;
import org.eclipse.jgit.dircache.DirCacheEditor;
@@ -26,13 +29,9 @@
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-
/**
- * A creator for a new Git tree. To create the new tree, the tree of another
- * commit is taken as a basis and modified.
+ * A creator for a new Git tree. To create the new tree, the tree of another commit is taken as a
+ * basis and modified.
*/
public class TreeCreator {
@@ -46,12 +45,10 @@
}
/**
- * Apply a modification to the tree which is taken as a basis. If this
- * method is called multiple times, the modifications are applied
- * subsequently in exactly the order they were provided.
+ * Apply a modification to the tree which is taken as a basis. If this method is called multiple
+ * times, the modifications are applied subsequently in exactly the order they were provided.
*
- * @param treeModification a modification which should be applied to the
- * base tree
+ * @param treeModification a modification which should be applied to the base tree
*/
public void addTreeModification(TreeModification treeModification) {
checkNotNull(treeModification, "treeModification must not be null");
@@ -59,16 +56,15 @@
}
/**
- * Creates the new tree. When this method is called, the specified base tree
- * is read from the repository, the specified modifications are applied, and
- * the resulting tree is written to the object store of the repository.
+ * Creates the new tree. When this method is called, the specified base tree is read from the
+ * repository, the specified modifications are applied, and the resulting tree is written to the
+ * object store of the repository.
*
* @param repository the affected Git repository
* @return the {@code ObjectId} of the created tree
* @throws IOException if problems arise when accessing the repository
*/
- public ObjectId createNewTreeAndGetId(Repository repository)
- throws IOException {
+ public ObjectId createNewTreeAndGetId(Repository repository) throws IOException {
DirCache newTree = createNewTree(repository);
return writeAndGetId(repository, newTree);
}
@@ -84,15 +80,14 @@
try (ObjectReader objectReader = repository.newObjectReader()) {
DirCache dirCache = DirCache.newInCore();
DirCacheBuilder dirCacheBuilder = dirCache.builder();
- dirCacheBuilder.addTree(new byte[0], DirCacheEntry.STAGE_0, objectReader,
- baseCommit.getTree());
+ dirCacheBuilder.addTree(
+ new byte[0], DirCacheEntry.STAGE_0, objectReader, baseCommit.getTree());
dirCacheBuilder.finish();
return dirCache;
}
}
- private List<DirCacheEditor.PathEdit> getPathEdits(Repository repository)
- throws IOException {
+ private List<DirCacheEditor.PathEdit> getPathEdits(Repository repository) throws IOException {
List<DirCacheEditor.PathEdit> pathEdits = new ArrayList<>();
for (TreeModification treeModification : treeModifications) {
pathEdits.addAll(treeModification.getPathEdits(repository, baseCommit));
@@ -100,15 +95,13 @@
return pathEdits;
}
- private static void applyPathEdits(DirCache tree,
- List<DirCacheEditor.PathEdit> pathEdits) {
+ private static void applyPathEdits(DirCache tree, List<DirCacheEditor.PathEdit> pathEdits) {
DirCacheEditor dirCacheEditor = tree.editor();
pathEdits.forEach(dirCacheEditor::add);
dirCacheEditor.finish();
}
- private static ObjectId writeAndGetId(Repository repository, DirCache tree)
- throws IOException {
+ private static ObjectId writeAndGetId(Repository repository, DirCache tree) throws IOException {
try (ObjectInserter objectInserter = repository.newObjectInserter()) {
ObjectId treeId = tree.writeTree(objectInserter);
objectInserter.flush();
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/edit/tree/TreeModification.java b/gerrit-server/src/main/java/com/google/gerrit/server/edit/tree/TreeModification.java
index 4b66cd4..217a309 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/edit/tree/TreeModification.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/edit/tree/TreeModification.java
@@ -14,29 +14,25 @@
package com.google.gerrit.server.edit.tree;
+import java.io.IOException;
+import java.util.List;
import org.eclipse.jgit.dircache.DirCacheEditor;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
-import java.io.IOException;
-import java.util.List;
-
-/**
- * A specific modification of a Git tree.
- */
+/** A specific modification of a Git tree. */
public interface TreeModification {
/**
- * Returns a list of {@code PathEdit}s which are necessary in order to
- * achieve the desired modification of the Git tree. The order of the
- * {@code PathEdit}s can be crucial and hence shouldn't be changed.
+ * Returns a list of {@code PathEdit}s which are necessary in order to achieve the desired
+ * modification of the Git tree. The order of the {@code PathEdit}s can be crucial and hence
+ * shouldn't be changed.
*
* @param repository the affected Git repository
* @param baseCommit the commit to whose tree this modification is applied
* @return an ordered list of necessary {@code PathEdit}s
* @throws IOException if problems arise when accessing the repository
*/
- List<DirCacheEditor.PathEdit> getPathEdits(Repository repository,
- RevCommit baseCommit) throws IOException;
-
+ List<DirCacheEditor.PathEdit> getPathEdits(Repository repository, RevCommit baseCommit)
+ throws IOException;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/events/ChangeRestoredEvent.java b/gerrit-server/src/main/java/com/google/gerrit/server/events/ChangeRestoredEvent.java
index 639ca55..7c86d70 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/events/ChangeRestoredEvent.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/events/ChangeRestoredEvent.java
@@ -23,7 +23,7 @@
public Supplier<AccountAttribute> restorer;
public String reason;
- public ChangeRestoredEvent (Change change) {
+ public ChangeRestoredEvent(Change change) {
super(TYPE, change);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/events/CommitReceivedEvent.java b/gerrit-server/src/main/java/com/google/gerrit/server/events/CommitReceivedEvent.java
index 085abe3..17fc52b 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/events/CommitReceivedEvent.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/events/CommitReceivedEvent.java
@@ -16,7 +16,6 @@
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.server.IdentifiedUser;
-
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.transport.ReceiveCommand;
@@ -32,8 +31,12 @@
super(TYPE);
}
- public CommitReceivedEvent(ReceiveCommand command, Project project,
- String refName, RevCommit commit, IdentifiedUser user) {
+ public CommitReceivedEvent(
+ ReceiveCommand command,
+ Project project,
+ String refName,
+ RevCommit commit,
+ IdentifiedUser user) {
this();
this.command = command;
this.project = project;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/events/EventDeserializer.java b/gerrit-server/src/main/java/com/google/gerrit/server/events/EventDeserializer.java
index 3508acf..2a7eada 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/events/EventDeserializer.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/events/EventDeserializer.java
@@ -18,24 +18,24 @@
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
-
import java.lang.reflect.Type;
/**
* JSON deserializer for {@link Event}s.
- * <p>
- * Deserialized objects are of an appropriate subclass based on the value of the
- * top-level "type" element.
+ *
+ * <p>Deserialized objects are of an appropriate subclass based on the value of the top-level "type"
+ * element.
*/
public class EventDeserializer implements JsonDeserializer<Event> {
@Override
- public Event deserialize(JsonElement json, Type typeOfT,
- JsonDeserializationContext context) throws JsonParseException {
+ public Event deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
+ throws JsonParseException {
if (!json.isJsonObject()) {
throw new JsonParseException("Not an object");
}
JsonElement typeJson = json.getAsJsonObject().get("type");
- if (typeJson == null || !typeJson.isJsonPrimitive()
+ if (typeJson == null
+ || !typeJson.isJsonPrimitive()
|| !typeJson.getAsJsonPrimitive().isString()) {
throw new JsonParseException("Type is not a string: " + typeJson);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/events/EventFactory.java b/gerrit-server/src/main/java/com/google/gerrit/server/events/EventFactory.java
index 88df57d..3de1243 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/events/EventFactory.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/events/EventFactory.java
@@ -63,14 +63,6 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.lib.PersonIdent;
-import org.eclipse.jgit.revwalk.RevCommit;
-import org.eclipse.jgit.revwalk.RevWalk;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
@@ -79,6 +71,12 @@
import java.util.List;
import java.util.Map;
import java.util.Set;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.lib.PersonIdent;
+import org.eclipse.jgit.revwalk.RevCommit;
+import org.eclipse.jgit.revwalk.RevWalk;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
@Singleton
public class EventFactory {
@@ -96,7 +94,8 @@
private final SchemaFactory<ReviewDb> schema;
@Inject
- EventFactory(AccountCache accountCache,
+ EventFactory(
+ AccountCache accountCache,
@CanonicalWebUrl @Nullable Provider<String> urlProvider,
AccountByEmailCache byEmailCache,
PatchListCache patchListCache,
@@ -119,8 +118,7 @@
}
/**
- * Create a ChangeAttribute for the given change suitable for serialization to
- * JSON.
+ * Create a ChangeAttribute for the given change suitable for serialization to JSON.
*
* @param change
* @return object suitable for serialization to JSON
@@ -135,8 +133,7 @@
}
/**
- * Create a ChangeAttribute for the given change suitable for serialization to
- * JSON.
+ * Create a ChangeAttribute for the given change suitable for serialization to JSON.
*
* @param db Review database
* @param change
@@ -153,8 +150,7 @@
try {
a.commitMessage = changeDataFactory.create(db, change).commitMessage();
} catch (Exception e) {
- log.error("Error while getting full commit message for"
- + " change " + a.number);
+ log.error("Error while getting full commit message for" + " change " + a.number);
}
a.url = getChangeUrl(change);
a.owner = asAccountAttribute(change.getOwner());
@@ -164,16 +160,16 @@
}
/**
- * Create a RefUpdateAttribute for the given old ObjectId, new ObjectId, and
- * branch that is suitable for serialization to JSON.
+ * Create a RefUpdateAttribute for the given old ObjectId, new ObjectId, and branch that is
+ * suitable for serialization to JSON.
*
* @param oldId
* @param newId
* @param refName
* @return object suitable for serialization to JSON
*/
- public RefUpdateAttribute asRefUpdateAttribute(ObjectId oldId, ObjectId newId,
- Branch.NameKey refName) {
+ public RefUpdateAttribute asRefUpdateAttribute(
+ ObjectId oldId, ObjectId newId, Branch.NameKey refName) {
RefUpdateAttribute ru = new RefUpdateAttribute();
ru.newRev = newId != null ? newId.getName() : ObjectId.zeroId().getName();
ru.oldRev = oldId != null ? oldId.getName() : ObjectId.zeroId().getName();
@@ -202,8 +198,7 @@
*/
public void addAllReviewers(ReviewDb db, ChangeAttribute a, ChangeNotes notes)
throws OrmException {
- Collection<Account.Id> reviewers =
- approvalsUtil.getReviewers(db, notes).all();
+ Collection<Account.Id> reviewers = approvalsUtil.getReviewers(db, notes).all();
if (!reviewers.isEmpty()) {
a.allReviewers = Lists.newArrayListWithCapacity(reviewers.size());
for (Account.Id id : reviewers) {
@@ -218,8 +213,7 @@
* @param ca
* @param submitRecords
*/
- public void addSubmitRecords(ChangeAttribute ca,
- List<SubmitRecord> submitRecords) {
+ public void addSubmitRecords(ChangeAttribute ca, List<SubmitRecord> submitRecords) {
ca.submitRecords = new ArrayList<>();
for (SubmitRecord submitRecord : submitRecords) {
@@ -236,8 +230,7 @@
}
}
- private void addSubmitRecordLabels(SubmitRecord submitRecord,
- SubmitRecordAttribute sa) {
+ private void addSubmitRecordLabels(SubmitRecord submitRecord, SubmitRecordAttribute sa) {
if (submitRecord.labels != null && !submitRecord.labels.isEmpty()) {
sa.labels = new ArrayList<>();
for (SubmitRecord.Label lbl : submitRecord.labels) {
@@ -253,8 +246,7 @@
}
}
- public void addDependencies(RevWalk rw, ChangeAttribute ca, Change change,
- PatchSet currentPs) {
+ public void addDependencies(RevWalk rw, ChangeAttribute ca, Change change, PatchSet currentPs) {
if (change == null || currentPs == null) {
return;
}
@@ -275,10 +267,9 @@
}
}
- private void addDependsOn(RevWalk rw, ChangeAttribute ca, Change change,
- PatchSet currentPs) throws OrmException, IOException {
- RevCommit commit =
- rw.parseCommit(ObjectId.fromString(currentPs.getRevision().get()));
+ private void addDependsOn(RevWalk rw, ChangeAttribute ca, Change change, PatchSet currentPs)
+ throws OrmException, IOException {
+ RevCommit commit = rw.parseCommit(ObjectId.fromString(currentPs.getRevision().get()));
final List<String> parentNames = new ArrayList<>(commit.getParentCount());
for (RevCommit p : commit.getParents()) {
parentNames.add(p.name());
@@ -286,8 +277,7 @@
// Find changes in this project having a patch set matching any parent of
// this patch set's revision.
- for (ChangeData cd : queryProvider.get().byProjectCommits(
- change.getProject(), parentNames)) {
+ for (ChangeData cd : queryProvider.get().byProjectCommits(change.getProject(), parentNames)) {
for (PatchSet ps : cd.patchSets()) {
for (String p : parentNames) {
if (!ps.getRevision().get().equals(p)) {
@@ -319,11 +309,11 @@
String rev = currentPs.getRevision().get();
// Find changes in the same related group as this patch set, having a patch
// set whose parent matches this patch set's revision.
- for (ChangeData cd : queryProvider.get().byProjectGroups(
- change.getProject(), currentPs.getGroups())) {
- patchSets: for (PatchSet ps : cd.patchSets()) {
- RevCommit commit =
- rw.parseCommit(ObjectId.fromString(ps.getRevision().get()));
+ for (ChangeData cd :
+ queryProvider.get().byProjectGroups(change.getProject(), currentPs.getGroups())) {
+ patchSets:
+ for (PatchSet ps : cd.patchSets()) {
+ RevCommit commit = rw.parseCommit(ObjectId.fromString(ps.getRevision().get()));
for (RevCommit p : commit.getParents()) {
if (!p.name().equals(rev)) {
continue;
@@ -354,8 +344,7 @@
return d;
}
- public void addTrackingIds(ChangeAttribute a,
- ListMultimap<String, String> set) {
+ public void addTrackingIds(ChangeAttribute a, ListMultimap<String, String> set) {
if (!set.isEmpty()) {
a.trackingIds = new ArrayList<>(set.size());
for (Map.Entry<String, Collection<String>> e : set.asMap().entrySet()) {
@@ -373,17 +362,25 @@
a.commitMessage = commitMessage;
}
- public void addPatchSets(ReviewDb db, RevWalk revWalk, ChangeAttribute ca,
+ public void addPatchSets(
+ ReviewDb db,
+ RevWalk revWalk,
+ ChangeAttribute ca,
Collection<PatchSet> ps,
Map<PatchSet.Id, Collection<PatchSetApproval>> approvals,
LabelTypes labelTypes) {
addPatchSets(db, revWalk, ca, ps, approvals, false, null, labelTypes);
}
- public void addPatchSets(ReviewDb db, RevWalk revWalk, ChangeAttribute ca,
+ public void addPatchSets(
+ ReviewDb db,
+ RevWalk revWalk,
+ ChangeAttribute ca,
Collection<PatchSet> ps,
Map<PatchSet.Id, Collection<PatchSetApproval>> approvals,
- boolean includeFiles, Change change, LabelTypes labelTypes) {
+ boolean includeFiles,
+ Change change,
+ LabelTypes labelTypes) {
if (!ps.isEmpty()) {
ca.patchSets = new ArrayList<>(ps.size());
for (PatchSet p : ps) {
@@ -399,8 +396,8 @@
}
}
- public void addPatchSetComments(PatchSetAttribute patchSetAttribute,
- Collection<Comment> comments) {
+ public void addPatchSetComments(
+ PatchSetAttribute patchSetAttribute, Collection<Comment> comments) {
for (Comment comment : comments) {
if (comment.key.patchSetId == patchSetAttribute.number) {
if (patchSetAttribute.comments == null) {
@@ -411,8 +408,8 @@
}
}
- public void addPatchSetFileNames(PatchSetAttribute patchSetAttribute,
- Change change, PatchSet patchSet) {
+ public void addPatchSetFileNames(
+ PatchSetAttribute patchSetAttribute, Change change, PatchSet patchSet) {
try {
PatchList patchList = patchListCache.get(change, patchSet);
for (PatchListEntry patch : patchList.getPatches()) {
@@ -433,8 +430,7 @@
}
}
- public void addComments(ChangeAttribute ca,
- Collection<ChangeMessage> messages) {
+ public void addComments(ChangeAttribute ca, Collection<ChangeMessage> messages) {
if (!messages.isEmpty()) {
ca.comments = new ArrayList<>();
for (ChangeMessage message : messages) {
@@ -444,15 +440,13 @@
}
/**
- * Create a PatchSetAttribute for the given patchset suitable for
- * serialization to JSON.
+ * Create a PatchSetAttribute for the given patchset suitable for serialization to JSON.
*
* @param revWalk
* @param patchSet
* @return object suitable for serialization to JSON
*/
- public PatchSetAttribute asPatchSetAttribute(RevWalk revWalk,
- Change change, PatchSet patchSet) {
+ public PatchSetAttribute asPatchSetAttribute(RevWalk revWalk, Change change, PatchSet patchSet) {
try (ReviewDb db = schema.open()) {
return asPatchSetAttribute(db, revWalk, change, patchSet);
} catch (OrmException e) {
@@ -462,15 +456,14 @@
}
/**
- * Create a PatchSetAttribute for the given patchset suitable for
- * serialization to JSON.
+ * Create a PatchSetAttribute for the given patchset suitable for serialization to JSON.
*
* @param db Review database
* @param patchSet
* @return object suitable for serialization to JSON
*/
- public PatchSetAttribute asPatchSetAttribute(ReviewDb db, RevWalk revWalk,
- Change change, PatchSet patchSet) {
+ public PatchSetAttribute asPatchSetAttribute(
+ ReviewDb db, RevWalk revWalk, Change change, PatchSet patchSet) {
PatchSetAttribute p = new PatchSetAttribute();
p.revision = patchSet.getRevision().get();
p.number = patchSet.getPatchSetId();
@@ -496,8 +489,7 @@
p.author = asAccountAttribute(author.getAccount());
}
- List<Patch> list =
- patchListCache.get(change, patchSet).toPatchList(pId);
+ List<Patch> list = patchListCache.get(change, patchSet).toPatchList(pId);
for (Patch pe : list) {
if (!Patch.isMagic(pe.getFileName())) {
p.sizeDeletions -= pe.getDeletions();
@@ -533,7 +525,9 @@
return u;
}
- public void addApprovals(PatchSetAttribute p, PatchSet.Id id,
+ public void addApprovals(
+ PatchSetAttribute p,
+ PatchSet.Id id,
Map<PatchSet.Id, Collection<PatchSetApproval>> all,
LabelTypes labelTypes) {
Collection<PatchSetApproval> list = all.get(id);
@@ -542,8 +536,8 @@
}
}
- public void addApprovals(PatchSetAttribute p,
- Collection<PatchSetApproval> list, LabelTypes labelTypes) {
+ public void addApprovals(
+ PatchSetAttribute p, Collection<PatchSetApproval> list, LabelTypes labelTypes) {
if (!list.isEmpty()) {
p.approvals = new ArrayList<>(list.size());
for (PatchSetApproval a : list) {
@@ -558,8 +552,7 @@
}
/**
- * Create an AuthorAttribute for the given account suitable for serialization
- * to JSON.
+ * Create an AuthorAttribute for the given account suitable for serialization to JSON.
*
* @param id
* @return object suitable for serialization to JSON
@@ -572,8 +565,7 @@
}
/**
- * Create an AuthorAttribute for the given account suitable for serialization
- * to JSON.
+ * Create an AuthorAttribute for the given account suitable for serialization to JSON.
*
* @param account
* @return object suitable for serialization to JSON
@@ -591,8 +583,7 @@
}
/**
- * Create an AuthorAttribute for the given person ident suitable for
- * serialization to JSON.
+ * Create an AuthorAttribute for the given person ident suitable for serialization to JSON.
*
* @param ident
* @return object suitable for serialization to JSON
@@ -605,15 +596,13 @@
}
/**
- * Create an ApprovalAttribute for the given approval suitable for
- * serialization to JSON.
+ * Create an ApprovalAttribute for the given approval suitable for serialization to JSON.
*
* @param approval
* @param labelTypes label types for the containing project
* @return object suitable for serialization to JSON
*/
- public ApprovalAttribute asApprovalAttribute(PatchSetApproval approval,
- LabelTypes labelTypes) {
+ public ApprovalAttribute asApprovalAttribute(PatchSetApproval approval, LabelTypes labelTypes) {
ApprovalAttribute a = new ApprovalAttribute();
a.type = approval.getLabelId().get();
a.value = Short.toString(approval.getValue());
@@ -632,7 +621,8 @@
MessageAttribute a = new MessageAttribute();
a.timestamp = message.getWrittenOn().getTime() / 1000L;
a.reviewer =
- message.getAuthor() != null ? asAccountAttribute(message.getAuthor())
+ message.getAuthor() != null
+ ? asAccountAttribute(message.getAuthor())
: asAccountAttribute(myIdent);
a.message = message.getMessage();
return a;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/events/EventTypes.java b/gerrit-server/src/main/java/com/google/gerrit/server/events/EventTypes.java
index cd6e2f9..74453f3 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/events/EventTypes.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/events/EventTypes.java
@@ -44,18 +44,17 @@
*
* @param eventType The event type to register.
* @param eventClass The event class to register.
- **/
- public static void register(String eventType,
- Class<? extends Event> eventClass) {
+ */
+ public static void register(String eventType, Class<? extends Event> eventClass) {
typesByString.put(eventType, eventClass);
}
- /** Get the class for an event type.
+ /**
+ * Get the class for an event type.
*
* @param type The type.
- * @return The event class, or null if no class is registered with the
- * given type
- **/
+ * @return The event class, or null if no class is registered with the given type
+ */
public static Class<?> getClass(String type) {
return typesByString.get(type);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/events/EventsMetrics.java b/gerrit-server/src/main/java/com/google/gerrit/server/events/EventsMetrics.java
index eaaf1a83..fcf4a08 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/events/EventsMetrics.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/events/EventsMetrics.java
@@ -28,12 +28,11 @@
@Inject
public EventsMetrics(MetricMaker metricMaker) {
- events = metricMaker.newCounter(
- "events",
- new Description("Triggered events")
- .setRate()
- .setUnit("triggered events"),
- Field.ofString("type"));
+ events =
+ metricMaker.newCounter(
+ "events",
+ new Description("Triggered events").setRate().setUnit("triggered events"),
+ Field.ofString("type"));
}
@Override
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/events/HashtagsChangedEvent.java b/gerrit-server/src/main/java/com/google/gerrit/server/events/HashtagsChangedEvent.java
index 4365c74..1de0fc3 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/events/HashtagsChangedEvent.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/events/HashtagsChangedEvent.java
@@ -25,7 +25,7 @@
public String[] removed;
public String[] hashtags;
- public HashtagsChangedEvent (Change change) {
+ public HashtagsChangedEvent(Change change) {
super(TYPE, change);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/events/ProjectNameKeySerializer.java b/gerrit-server/src/main/java/com/google/gerrit/server/events/ProjectNameKeySerializer.java
index e2f51ac..743b314 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/events/ProjectNameKeySerializer.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/events/ProjectNameKeySerializer.java
@@ -19,14 +19,12 @@
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
-
import java.lang.reflect.Type;
-public class ProjectNameKeySerializer
- implements JsonSerializer<Project.NameKey> {
+public class ProjectNameKeySerializer implements JsonSerializer<Project.NameKey> {
@Override
- public JsonElement serialize(Project.NameKey project, Type typeOfSrc,
- JsonSerializationContext context) {
+ public JsonElement serialize(
+ Project.NameKey project, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(project.get());
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/events/RefReceivedEvent.java b/gerrit-server/src/main/java/com/google/gerrit/server/events/RefReceivedEvent.java
index 6cc1ae5..aa02d11 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/events/RefReceivedEvent.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/events/RefReceivedEvent.java
@@ -15,7 +15,6 @@
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.server.IdentifiedUser;
-
import org.eclipse.jgit.transport.ReceiveCommand;
public class RefReceivedEvent extends RefEvent {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/events/StreamEventsApiListener.java b/gerrit-server/src/main/java/com/google/gerrit/server/events/StreamEventsApiListener.java
index c867d26..15c1ae9 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/events/StreamEventsApiListener.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/events/StreamEventsApiListener.java
@@ -59,66 +59,51 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
+import java.io.IOException;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Map.Entry;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevWalk;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Map.Entry;
-
@Singleton
-public class StreamEventsApiListener implements
- AssigneeChangedListener,
- ChangeAbandonedListener,
- ChangeMergedListener,
- ChangeRestoredListener,
- CommentAddedListener,
- DraftPublishedListener,
- GitReferenceUpdatedListener,
- HashtagsEditedListener,
- NewProjectCreatedListener,
- ReviewerAddedListener,
- ReviewerDeletedListener,
- RevisionCreatedListener,
- TopicEditedListener {
- private static final Logger log =
- LoggerFactory.getLogger(StreamEventsApiListener.class);
+public class StreamEventsApiListener
+ implements AssigneeChangedListener,
+ ChangeAbandonedListener,
+ ChangeMergedListener,
+ ChangeRestoredListener,
+ CommentAddedListener,
+ DraftPublishedListener,
+ GitReferenceUpdatedListener,
+ HashtagsEditedListener,
+ NewProjectCreatedListener,
+ ReviewerAddedListener,
+ ReviewerDeletedListener,
+ RevisionCreatedListener,
+ TopicEditedListener {
+ private static final Logger log = LoggerFactory.getLogger(StreamEventsApiListener.class);
public static class Module extends AbstractModule {
@Override
protected void configure() {
- DynamicSet.bind(binder(), AssigneeChangedListener.class)
- .to(StreamEventsApiListener.class);
- DynamicSet.bind(binder(), ChangeAbandonedListener.class)
- .to(StreamEventsApiListener.class);
- DynamicSet.bind(binder(), ChangeMergedListener.class)
- .to(StreamEventsApiListener.class);
- DynamicSet.bind(binder(), ChangeRestoredListener.class)
- .to(StreamEventsApiListener.class);
- DynamicSet.bind(binder(), CommentAddedListener.class)
- .to(StreamEventsApiListener.class);
- DynamicSet.bind(binder(), DraftPublishedListener.class)
- .to(StreamEventsApiListener.class);
+ DynamicSet.bind(binder(), AssigneeChangedListener.class).to(StreamEventsApiListener.class);
+ DynamicSet.bind(binder(), ChangeAbandonedListener.class).to(StreamEventsApiListener.class);
+ DynamicSet.bind(binder(), ChangeMergedListener.class).to(StreamEventsApiListener.class);
+ DynamicSet.bind(binder(), ChangeRestoredListener.class).to(StreamEventsApiListener.class);
+ DynamicSet.bind(binder(), CommentAddedListener.class).to(StreamEventsApiListener.class);
+ DynamicSet.bind(binder(), DraftPublishedListener.class).to(StreamEventsApiListener.class);
DynamicSet.bind(binder(), GitReferenceUpdatedListener.class)
- .to(StreamEventsApiListener.class);
- DynamicSet.bind(binder(), HashtagsEditedListener.class)
- .to(StreamEventsApiListener.class);
- DynamicSet.bind(binder(), NewProjectCreatedListener.class)
- .to(StreamEventsApiListener.class);
- DynamicSet.bind(binder(), ReviewerAddedListener.class)
- .to(StreamEventsApiListener.class);
- DynamicSet.bind(binder(), ReviewerDeletedListener.class)
- .to(StreamEventsApiListener.class);
- DynamicSet.bind(binder(), RevisionCreatedListener.class)
- .to(StreamEventsApiListener.class);
- DynamicSet.bind(binder(), TopicEditedListener.class)
- .to(StreamEventsApiListener.class);
+ .to(StreamEventsApiListener.class);
+ DynamicSet.bind(binder(), HashtagsEditedListener.class).to(StreamEventsApiListener.class);
+ DynamicSet.bind(binder(), NewProjectCreatedListener.class).to(StreamEventsApiListener.class);
+ DynamicSet.bind(binder(), ReviewerAddedListener.class).to(StreamEventsApiListener.class);
+ DynamicSet.bind(binder(), ReviewerDeletedListener.class).to(StreamEventsApiListener.class);
+ DynamicSet.bind(binder(), RevisionCreatedListener.class).to(StreamEventsApiListener.class);
+ DynamicSet.bind(binder(), TopicEditedListener.class).to(StreamEventsApiListener.class);
}
}
@@ -131,7 +116,8 @@
private final ChangeNotes.Factory changeNotesFactory;
@Inject
- StreamEventsApiListener(DynamicItem<EventDispatcher> dispatcher,
+ StreamEventsApiListener(
+ DynamicItem<EventDispatcher> dispatcher,
Provider<ReviewDb> db,
EventFactory eventFactory,
ProjectCache projectCache,
@@ -159,13 +145,11 @@
return getNotes(info).getChange();
}
- private PatchSet getPatchSet(ChangeNotes notes, RevisionInfo info)
- throws OrmException {
+ private PatchSet getPatchSet(ChangeNotes notes, RevisionInfo info) throws OrmException {
return psUtil.get(db.get(), notes, PatchSet.Id.fromRef(info.ref));
}
- private Supplier<ChangeAttribute> changeAttributeSupplier(
- final Change change) {
+ private Supplier<ChangeAttribute> changeAttributeSupplier(final Change change) {
return Suppliers.memoize(
new Supplier<ChangeAttribute>() {
@Override
@@ -175,14 +159,14 @@
});
}
- private Supplier<AccountAttribute> accountAttributeSupplier(
- final AccountInfo account) {
+ private Supplier<AccountAttribute> accountAttributeSupplier(final AccountInfo account) {
return Suppliers.memoize(
new Supplier<AccountAttribute>() {
@Override
public AccountAttribute get() {
- return account != null ? eventFactory.asAccountAttribute(
- new Account.Id(account._accountId)) : null;
+ return account != null
+ ? eventFactory.asAccountAttribute(new Account.Id(account._accountId))
+ : null;
}
});
}
@@ -193,11 +177,9 @@
new Supplier<PatchSetAttribute>() {
@Override
public PatchSetAttribute get() {
- try (Repository repo =
- repoManager.openRepository(change.getProject());
+ try (Repository repo = repoManager.openRepository(change.getProject());
RevWalk revWalk = new RevWalk(repo)) {
- return eventFactory.asPatchSetAttribute(
- revWalk, change, patchSet);
+ return eventFactory.asPatchSetAttribute(revWalk, change, patchSet);
} catch (IOException e) {
throw new RuntimeException(e);
}
@@ -205,21 +187,18 @@
});
}
- private static Map<String, Short> convertApprovalsMap(
- Map<String, ApprovalInfo> approvals) {
+ private static Map<String, Short> convertApprovalsMap(Map<String, ApprovalInfo> approvals) {
Map<String, Short> result = new HashMap<>();
for (Entry<String, ApprovalInfo> e : approvals.entrySet()) {
- Short value =
- e.getValue().value == null ? null : e.getValue().value.shortValue();
+ Short value = e.getValue().value == null ? null : e.getValue().value.shortValue();
result.put(e.getKey(), value);
}
return result;
}
- private ApprovalAttribute getApprovalAttribute(LabelTypes labelTypes,
- Entry<String, Short> approval,
- Map<String, Short> oldApprovals) {
- ApprovalAttribute a = new ApprovalAttribute();
+ private ApprovalAttribute getApprovalAttribute(
+ LabelTypes labelTypes, Entry<String, Short> approval, Map<String, Short> oldApprovals) {
+ ApprovalAttribute a = new ApprovalAttribute();
a.type = approval.getKey();
if (oldApprovals != null && !oldApprovals.isEmpty()) {
@@ -238,21 +217,21 @@
}
private Supplier<ApprovalAttribute[]> approvalsAttributeSupplier(
- final Change change, Map<String, ApprovalInfo> newApprovals,
+ final Change change,
+ Map<String, ApprovalInfo> newApprovals,
final Map<String, ApprovalInfo> oldApprovals) {
final Map<String, Short> approvals = convertApprovalsMap(newApprovals);
return Suppliers.memoize(
new Supplier<ApprovalAttribute[]>() {
@Override
public ApprovalAttribute[] get() {
- LabelTypes labelTypes = projectCache.get(
- change.getProject()).getLabelTypes();
+ LabelTypes labelTypes = projectCache.get(change.getProject()).getLabelTypes();
if (approvals.size() > 0) {
ApprovalAttribute[] r = new ApprovalAttribute[approvals.size()];
int i = 0;
for (Map.Entry<String, Short> approval : approvals.entrySet()) {
- r[i++] = getApprovalAttribute(labelTypes, approval,
- convertApprovalsMap(oldApprovals));
+ r[i++] =
+ getApprovalAttribute(labelTypes, approval, convertApprovalsMap(oldApprovals));
}
return r;
}
@@ -263,8 +242,7 @@
String[] hashtagArray(Collection<String> hashtags) {
if (hashtags != null && hashtags.size() > 0) {
- return Sets.newHashSet(hashtags).toArray(
- new String[hashtags.size()]);
+ return Sets.newHashSet(hashtags).toArray(new String[hashtags.size()]);
}
return null;
}
@@ -326,18 +304,16 @@
Change change = notes.getChange();
ReviewerDeletedEvent event = new ReviewerDeletedEvent(change);
event.change = changeAttributeSupplier(change);
- event.patchSet = patchSetAttributeSupplier(change,
- psUtil.current(db.get(), notes));
+ event.patchSet = patchSetAttributeSupplier(change, psUtil.current(db.get(), notes));
event.reviewer = accountAttributeSupplier(ev.getReviewer());
event.comment = ev.getComment();
- event.approvals = approvalsAttributeSupplier(change,
- ev.getNewApprovals(), ev.getOldApprovals());
+ event.approvals =
+ approvalsAttributeSupplier(change, ev.getNewApprovals(), ev.getOldApprovals());
dispatcher.get().postEvent(change, event);
} catch (OrmException e) {
log.error("Failed to dispatch event", e);
}
-
}
@Override
@@ -348,8 +324,7 @@
ReviewerAddedEvent event = new ReviewerAddedEvent(change);
event.change = changeAttributeSupplier(change);
- event.patchSet = patchSetAttributeSupplier(change,
- psUtil.current(db.get(), notes));
+ event.patchSet = patchSetAttributeSupplier(change, psUtil.current(db.get(), notes));
for (AccountInfo reviewer : ev.getReviewers()) {
event.reviewer = accountAttributeSupplier(reviewer);
dispatcher.get().postEvent(change, event);
@@ -392,18 +367,18 @@
if (ev.getUpdater() != null) {
event.submitter = accountAttributeSupplier(ev.getUpdater());
}
- final Branch.NameKey refName =
- new Branch.NameKey(ev.getProjectName(), ev.getRefName());
- event.refUpdate = Suppliers.memoize(
- new Supplier<RefUpdateAttribute>() {
- @Override
- public RefUpdateAttribute get() {
- return eventFactory.asRefUpdateAttribute(
- ObjectId.fromString(ev.getOldObjectId()),
- ObjectId.fromString(ev.getNewObjectId()),
- refName);
- }
- });
+ final Branch.NameKey refName = new Branch.NameKey(ev.getProjectName(), ev.getRefName());
+ event.refUpdate =
+ Suppliers.memoize(
+ new Supplier<RefUpdateAttribute>() {
+ @Override
+ public RefUpdateAttribute get() {
+ return eventFactory.asRefUpdateAttribute(
+ ObjectId.fromString(ev.getOldObjectId()),
+ ObjectId.fromString(ev.getNewObjectId()),
+ refName);
+ }
+ });
dispatcher.get().postEvent(refName, event);
}
@@ -434,11 +409,10 @@
CommentAddedEvent event = new CommentAddedEvent(change);
event.change = changeAttributeSupplier(change);
- event.author = accountAttributeSupplier(ev.getWho());
+ event.author = accountAttributeSupplier(ev.getWho());
event.patchSet = patchSetAttributeSupplier(change, ps);
event.comment = ev.getComment();
- event.approvals = approvalsAttributeSupplier(
- change, ev.getApprovals(), ev.getOldApprovals());
+ event.approvals = approvalsAttributeSupplier(change, ev.getApprovals(), ev.getOldApprovals());
dispatcher.get().postEvent(change, event);
} catch (OrmException e) {
@@ -455,8 +429,7 @@
event.change = changeAttributeSupplier(change);
event.restorer = accountAttributeSupplier(ev.getWho());
- event.patchSet = patchSetAttributeSupplier(change,
- psUtil.current(db.get(), notes));
+ event.patchSet = patchSetAttributeSupplier(change, psUtil.current(db.get(), notes));
event.reason = ev.getReason();
dispatcher.get().postEvent(change, event);
@@ -474,8 +447,7 @@
event.change = changeAttributeSupplier(change);
event.submitter = accountAttributeSupplier(ev.getWho());
- event.patchSet = patchSetAttributeSupplier(change,
- psUtil.current(db.get(), notes));
+ event.patchSet = patchSetAttributeSupplier(change, psUtil.current(db.get(), notes));
event.newRev = ev.getNewRevisionId();
dispatcher.get().postEvent(change, event);
@@ -493,8 +465,7 @@
event.change = changeAttributeSupplier(change);
event.abandoner = accountAttributeSupplier(ev.getWho());
- event.patchSet = patchSetAttributeSupplier(change,
- psUtil.current(db.get(), notes));
+ event.patchSet = patchSetAttributeSupplier(change, psUtil.current(db.get(), notes));
event.reason = ev.getReason();
dispatcher.get().postEvent(change, event);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/events/SupplierDeserializer.java b/gerrit-server/src/main/java/com/google/gerrit/server/events/SupplierDeserializer.java
index fd7b350..a6e27b8 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/events/SupplierDeserializer.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/events/SupplierDeserializer.java
@@ -21,20 +21,18 @@
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
-
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
public class SupplierDeserializer implements JsonDeserializer<Supplier<?>> {
@Override
- public Supplier<?> deserialize(JsonElement json, Type typeOfT,
- JsonDeserializationContext context) throws JsonParseException {
+ public Supplier<?> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
+ throws JsonParseException {
checkArgument(typeOfT instanceof ParameterizedType);
ParameterizedType parameterizedType = (ParameterizedType) typeOfT;
if (parameterizedType.getActualTypeArguments().length != 1) {
- throw new JsonParseException(
- "Expected one parameter type in Supplier interface.");
+ throw new JsonParseException("Expected one parameter type in Supplier interface.");
}
Type supplierOf = parameterizedType.getActualTypeArguments()[0];
return Suppliers.ofInstance(context.deserialize(json, supplierOf));
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/events/SupplierSerializer.java b/gerrit-server/src/main/java/com/google/gerrit/server/events/SupplierSerializer.java
index 76138b0..5f66c49 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/events/SupplierSerializer.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/events/SupplierSerializer.java
@@ -18,14 +18,12 @@
import com.google.gson.JsonElement;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
-
import java.lang.reflect.Type;
public class SupplierSerializer implements JsonSerializer<Supplier<?>> {
@Override
- public JsonElement serialize(Supplier<?> src, Type typeOfSrc,
- JsonSerializationContext context) {
+ public JsonElement serialize(Supplier<?> src, Type typeOfSrc, JsonSerializationContext context) {
return context.serialize(src.get());
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/AbstractChangeEvent.java b/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/AbstractChangeEvent.java
index be6f692..a5800fb2 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/AbstractChangeEvent.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/AbstractChangeEvent.java
@@ -18,7 +18,6 @@
import com.google.gerrit.extensions.common.AccountInfo;
import com.google.gerrit.extensions.common.ChangeInfo;
import com.google.gerrit.extensions.events.ChangeEvent;
-
import java.sql.Timestamp;
public abstract class AbstractChangeEvent implements ChangeEvent {
@@ -27,8 +26,8 @@
private final Timestamp when;
private final NotifyHandling notify;
- protected AbstractChangeEvent(ChangeInfo change, AccountInfo who,
- Timestamp when, NotifyHandling notify) {
+ protected AbstractChangeEvent(
+ ChangeInfo change, AccountInfo who, Timestamp when, NotifyHandling notify) {
this.changeInfo = change;
this.who = who;
this.when = when;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/AbstractRevisionEvent.java b/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/AbstractRevisionEvent.java
index d3d7e09..6b72b5e 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/AbstractRevisionEvent.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/AbstractRevisionEvent.java
@@ -19,16 +19,18 @@
import com.google.gerrit.extensions.common.ChangeInfo;
import com.google.gerrit.extensions.common.RevisionInfo;
import com.google.gerrit.extensions.events.RevisionEvent;
-
import java.sql.Timestamp;
-public abstract class AbstractRevisionEvent extends AbstractChangeEvent
- implements RevisionEvent {
+public abstract class AbstractRevisionEvent extends AbstractChangeEvent implements RevisionEvent {
private final RevisionInfo revisionInfo;
- protected AbstractRevisionEvent(ChangeInfo change, RevisionInfo revision,
- AccountInfo who, Timestamp when, NotifyHandling notify) {
+ protected AbstractRevisionEvent(
+ ChangeInfo change,
+ RevisionInfo revision,
+ AccountInfo who,
+ Timestamp when,
+ NotifyHandling notify) {
super(change, who, when, notify);
revisionInfo = revision;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/AgreementSignup.java b/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/AgreementSignup.java
index c910a7a..669690a 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/AgreementSignup.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/AgreementSignup.java
@@ -25,8 +25,7 @@
private final EventUtil util;
@Inject
- AgreementSignup(DynamicSet<AgreementSignupListener> listeners,
- EventUtil util) {
+ AgreementSignup(DynamicSet<AgreementSignupListener> listeners, EventUtil util) {
this.listeners = listeners;
this.util = util;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/AssigneeChanged.java b/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/AssigneeChanged.java
index 53d837f..2583744 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/AssigneeChanged.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/AssigneeChanged.java
@@ -23,37 +23,33 @@
import com.google.gerrit.reviewdb.client.Change;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
-
+import java.sql.Timestamp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.sql.Timestamp;
-
public class AssigneeChanged {
- private static final Logger log =
- LoggerFactory.getLogger(AssigneeChanged.class);
+ private static final Logger log = LoggerFactory.getLogger(AssigneeChanged.class);
private final DynamicSet<AssigneeChangedListener> listeners;
private final EventUtil util;
@Inject
- AssigneeChanged(DynamicSet<AssigneeChangedListener> listeners,
- EventUtil util) {
+ AssigneeChanged(DynamicSet<AssigneeChangedListener> listeners, EventUtil util) {
this.listeners = listeners;
this.util = util;
}
- public void fire(Change change, Account account, Account oldAssignee,
- Timestamp when) {
+ public void fire(Change change, Account account, Account oldAssignee, Timestamp when) {
if (!listeners.iterator().hasNext()) {
return;
}
try {
- Event event = new Event(
- util.changeInfo(change),
- util.accountInfo(account),
- util.accountInfo(oldAssignee),
- when);
+ Event event =
+ new Event(
+ util.changeInfo(change),
+ util.accountInfo(account),
+ util.accountInfo(oldAssignee),
+ when);
for (AssigneeChangedListener l : listeners) {
try {
l.onAssigneeChanged(event);
@@ -66,12 +62,10 @@
}
}
- private static class Event extends AbstractChangeEvent
- implements AssigneeChangedListener.Event {
+ private static class Event extends AbstractChangeEvent implements AssigneeChangedListener.Event {
private final AccountInfo oldAssignee;
- Event(ChangeInfo change, AccountInfo editor, AccountInfo oldAssignee,
- Timestamp when) {
+ Event(ChangeInfo change, AccountInfo editor, AccountInfo oldAssignee, Timestamp when) {
super(change, editor, when, NotifyHandling.ALL);
this.oldAssignee = oldAssignee;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/ChangeAbandoned.java b/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/ChangeAbandoned.java
index 5a7aec2..f9fc60a 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/ChangeAbandoned.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/ChangeAbandoned.java
@@ -27,38 +27,42 @@
import com.google.gerrit.server.patch.PatchListNotAvailableException;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
-
+import java.io.IOException;
+import java.sql.Timestamp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.sql.Timestamp;
-
public class ChangeAbandoned {
- private static final Logger log =
- LoggerFactory.getLogger(ChangeAbandoned.class);
+ private static final Logger log = LoggerFactory.getLogger(ChangeAbandoned.class);
private final DynamicSet<ChangeAbandonedListener> listeners;
private final EventUtil util;
@Inject
- ChangeAbandoned(DynamicSet<ChangeAbandonedListener> listeners,
- EventUtil util) {
+ ChangeAbandoned(DynamicSet<ChangeAbandonedListener> listeners, EventUtil util) {
this.listeners = listeners;
this.util = util;
}
- public void fire(Change change, PatchSet ps, Account abandoner, String reason,
- Timestamp when, NotifyHandling notifyHandling) {
+ public void fire(
+ Change change,
+ PatchSet ps,
+ Account abandoner,
+ String reason,
+ Timestamp when,
+ NotifyHandling notifyHandling) {
if (!listeners.iterator().hasNext()) {
return;
}
try {
- Event event = new Event(
- util.changeInfo(change),
- util.revisionInfo(change.getProject(), ps),
- util.accountInfo(abandoner),
- reason, when, notifyHandling);
+ Event event =
+ new Event(
+ util.changeInfo(change),
+ util.revisionInfo(change.getProject(), ps),
+ util.accountInfo(abandoner),
+ reason,
+ when,
+ notifyHandling);
for (ChangeAbandonedListener l : listeners) {
try {
l.onChangeAbandoned(event);
@@ -66,8 +70,7 @@
util.logEventListenerError(this, l, e);
}
}
- } catch (PatchListNotAvailableException | GpgException | IOException
- | OrmException e) {
+ } catch (PatchListNotAvailableException | GpgException | IOException | OrmException e) {
log.error("Couldn't fire event", e);
}
}
@@ -76,8 +79,13 @@
implements ChangeAbandonedListener.Event {
private final String reason;
- Event(ChangeInfo change, RevisionInfo revision, AccountInfo abandoner,
- String reason, Timestamp when, NotifyHandling notifyHandling) {
+ Event(
+ ChangeInfo change,
+ RevisionInfo revision,
+ AccountInfo abandoner,
+ String reason,
+ Timestamp when,
+ NotifyHandling notifyHandling) {
super(change, revision, abandoner, when, notifyHandling);
this.reason = reason;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/ChangeMerged.java b/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/ChangeMerged.java
index 8b4a6a0..feaa54a 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/ChangeMerged.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/ChangeMerged.java
@@ -27,38 +27,36 @@
import com.google.gerrit.server.patch.PatchListNotAvailableException;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
-
+import java.io.IOException;
+import java.sql.Timestamp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.sql.Timestamp;
-
public class ChangeMerged {
- private static final Logger log =
- LoggerFactory.getLogger(ChangeMerged.class);
+ private static final Logger log = LoggerFactory.getLogger(ChangeMerged.class);
private final DynamicSet<ChangeMergedListener> listeners;
private final EventUtil util;
@Inject
- ChangeMerged(DynamicSet<ChangeMergedListener> listeners,
- EventUtil util) {
+ ChangeMerged(DynamicSet<ChangeMergedListener> listeners, EventUtil util) {
this.listeners = listeners;
this.util = util;
}
- public void fire(Change change, PatchSet ps, Account merger,
- String newRevisionId, Timestamp when) {
+ public void fire(
+ Change change, PatchSet ps, Account merger, String newRevisionId, Timestamp when) {
if (!listeners.iterator().hasNext()) {
return;
}
try {
- Event event = new Event(
- util.changeInfo(change),
- util.revisionInfo(change.getProject(), ps),
- util.accountInfo(merger),
- newRevisionId, when);
+ Event event =
+ new Event(
+ util.changeInfo(change),
+ util.revisionInfo(change.getProject(), ps),
+ util.accountInfo(merger),
+ newRevisionId,
+ when);
for (ChangeMergedListener l : listeners) {
try {
l.onChangeMerged(event);
@@ -66,18 +64,20 @@
util.logEventListenerError(this, l, e);
}
}
- } catch (PatchListNotAvailableException | GpgException | IOException
- | OrmException e) {
+ } catch (PatchListNotAvailableException | GpgException | IOException | OrmException e) {
log.error("Couldn't fire event", e);
}
}
- private static class Event extends AbstractRevisionEvent
- implements ChangeMergedListener.Event {
+ private static class Event extends AbstractRevisionEvent implements ChangeMergedListener.Event {
private final String newRevisionId;
- Event(ChangeInfo change, RevisionInfo revision, AccountInfo merger,
- String newRevisionId, Timestamp when) {
+ Event(
+ ChangeInfo change,
+ RevisionInfo revision,
+ AccountInfo merger,
+ String newRevisionId,
+ Timestamp when) {
super(change, revision, merger, when, NotifyHandling.ALL);
this.newRevisionId = newRevisionId;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/ChangeRestored.java b/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/ChangeRestored.java
index 1d2682a..03a6f1f 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/ChangeRestored.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/ChangeRestored.java
@@ -27,38 +27,35 @@
import com.google.gerrit.server.patch.PatchListNotAvailableException;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
-
+import java.io.IOException;
+import java.sql.Timestamp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.sql.Timestamp;
-
public class ChangeRestored {
- private static final Logger log =
- LoggerFactory.getLogger(ChangeRestored.class);
+ private static final Logger log = LoggerFactory.getLogger(ChangeRestored.class);
private final DynamicSet<ChangeRestoredListener> listeners;
private final EventUtil util;
@Inject
- ChangeRestored(DynamicSet<ChangeRestoredListener> listeners,
- EventUtil util) {
+ ChangeRestored(DynamicSet<ChangeRestoredListener> listeners, EventUtil util) {
this.listeners = listeners;
this.util = util;
}
- public void fire(Change change, PatchSet ps, Account restorer, String reason,
- Timestamp when) {
+ public void fire(Change change, PatchSet ps, Account restorer, String reason, Timestamp when) {
if (!listeners.iterator().hasNext()) {
return;
}
try {
- Event event = new Event(
- util.changeInfo(change),
- util.revisionInfo(change.getProject(), ps),
- util.accountInfo(restorer),
- reason, when);
+ Event event =
+ new Event(
+ util.changeInfo(change),
+ util.revisionInfo(change.getProject(), ps),
+ util.accountInfo(restorer),
+ reason,
+ when);
for (ChangeRestoredListener l : listeners) {
try {
l.onChangeRestored(event);
@@ -66,19 +63,21 @@
util.logEventListenerError(this, l, e);
}
}
- } catch (PatchListNotAvailableException | GpgException | IOException
- | OrmException e) {
+ } catch (PatchListNotAvailableException | GpgException | IOException | OrmException e) {
log.error("Couldn't fire event", e);
}
}
- private static class Event extends AbstractRevisionEvent
- implements ChangeRestoredListener.Event {
+ private static class Event extends AbstractRevisionEvent implements ChangeRestoredListener.Event {
private String reason;
- Event(ChangeInfo change, RevisionInfo revision, AccountInfo restorer,
- String reason, Timestamp when) {
+ Event(
+ ChangeInfo change,
+ RevisionInfo revision,
+ AccountInfo restorer,
+ String reason,
+ Timestamp when) {
super(change, revision, restorer, when, NotifyHandling.ALL);
this.reason = reason;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/ChangeReverted.java b/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/ChangeReverted.java
index d963a47..e57cbdd 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/ChangeReverted.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/ChangeReverted.java
@@ -21,22 +21,18 @@
import com.google.gerrit.reviewdb.client.Change;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
-
+import java.sql.Timestamp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.sql.Timestamp;
-
public class ChangeReverted {
- private static final Logger log =
- LoggerFactory.getLogger(ChangeReverted.class);
+ private static final Logger log = LoggerFactory.getLogger(ChangeReverted.class);
private final DynamicSet<ChangeRevertedListener> listeners;
private final EventUtil util;
@Inject
- ChangeReverted(DynamicSet<ChangeRevertedListener> listeners,
- EventUtil util) {
+ ChangeReverted(DynamicSet<ChangeRevertedListener> listeners, EventUtil util) {
this.listeners = listeners;
this.util = util;
}
@@ -46,8 +42,7 @@
return;
}
try {
- Event event = new Event(
- util.changeInfo(change), util.changeInfo(revertChange), when);
+ Event event = new Event(util.changeInfo(change), util.changeInfo(revertChange), when);
for (ChangeRevertedListener l : listeners) {
try {
l.onChangeReverted(event);
@@ -60,8 +55,7 @@
}
}
- private static class Event extends AbstractChangeEvent
- implements ChangeRevertedListener.Event {
+ private static class Event extends AbstractChangeEvent implements ChangeRevertedListener.Event {
private final ChangeInfo revertChange;
Event(ChangeInfo change, ChangeInfo revertChange, Timestamp when) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/CommentAdded.java b/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/CommentAdded.java
index f1bb50a..e76a032 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/CommentAdded.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/CommentAdded.java
@@ -28,42 +28,45 @@
import com.google.gerrit.server.patch.PatchListNotAvailableException;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Map;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class CommentAdded {
- private static final Logger log =
- LoggerFactory.getLogger(CommentAdded.class);
+ private static final Logger log = LoggerFactory.getLogger(CommentAdded.class);
private final DynamicSet<CommentAddedListener> listeners;
private final EventUtil util;
@Inject
- CommentAdded(DynamicSet<CommentAddedListener> listeners,
- EventUtil util) {
+ CommentAdded(DynamicSet<CommentAddedListener> listeners, EventUtil util) {
this.listeners = listeners;
this.util = util;
}
- public void fire(Change change, PatchSet ps, Account author,
- String comment, Map<String, Short> approvals,
- Map<String, Short> oldApprovals, Timestamp when) {
+ public void fire(
+ Change change,
+ PatchSet ps,
+ Account author,
+ String comment,
+ Map<String, Short> approvals,
+ Map<String, Short> oldApprovals,
+ Timestamp when) {
if (!listeners.iterator().hasNext()) {
return;
}
try {
- Event event = new Event(util.changeInfo(change),
- util.revisionInfo(change.getProject(), ps),
- util.accountInfo(author),
- comment,
- util.approvals(author, approvals, when),
- util.approvals(author, oldApprovals, when),
- when);
+ Event event =
+ new Event(
+ util.changeInfo(change),
+ util.revisionInfo(change.getProject(), ps),
+ util.accountInfo(author),
+ comment,
+ util.approvals(author, approvals, when),
+ util.approvals(author, oldApprovals, when),
+ when);
for (CommentAddedListener l : listeners) {
try {
l.onCommentAdded(event);
@@ -71,22 +74,25 @@
util.logEventListenerError(this, l, e);
}
}
- } catch (PatchListNotAvailableException | GpgException | IOException
- | OrmException e) {
+ } catch (PatchListNotAvailableException | GpgException | IOException | OrmException e) {
log.error("Couldn't fire event", e);
}
}
- private static class Event extends AbstractRevisionEvent
- implements CommentAddedListener.Event {
+ private static class Event extends AbstractRevisionEvent implements CommentAddedListener.Event {
private final String comment;
private final Map<String, ApprovalInfo> approvals;
private final Map<String, ApprovalInfo> oldApprovals;
- Event(ChangeInfo change, RevisionInfo revision, AccountInfo author,
- String comment, Map<String, ApprovalInfo> approvals,
- Map<String, ApprovalInfo> oldApprovals, Timestamp when) {
+ Event(
+ ChangeInfo change,
+ RevisionInfo revision,
+ AccountInfo author,
+ String comment,
+ Map<String, ApprovalInfo> approvals,
+ Map<String, ApprovalInfo> oldApprovals,
+ Timestamp when) {
super(change, revision, author, when, NotifyHandling.ALL);
this.comment = comment;
this.approvals = approvals;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/DraftPublished.java b/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/DraftPublished.java
index 4f6d298..b5db0da 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/DraftPublished.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/DraftPublished.java
@@ -27,35 +27,31 @@
import com.google.gerrit.server.patch.PatchListNotAvailableException;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
-
+import java.io.IOException;
+import java.sql.Timestamp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.sql.Timestamp;
-
public class DraftPublished {
- private static final Logger log =
- LoggerFactory.getLogger(DraftPublished.class);
+ private static final Logger log = LoggerFactory.getLogger(DraftPublished.class);
private final DynamicSet<DraftPublishedListener> listeners;
private final EventUtil util;
@Inject
- public DraftPublished(DynamicSet<DraftPublishedListener> listeners,
- EventUtil util) {
+ public DraftPublished(DynamicSet<DraftPublishedListener> listeners, EventUtil util) {
this.listeners = listeners;
this.util = util;
}
- public void fire(Change change, PatchSet patchSet, Account accountId,
- Timestamp when) {
+ public void fire(Change change, PatchSet patchSet, Account accountId, Timestamp when) {
try {
- Event event = new Event(
- util.changeInfo(change),
- util.revisionInfo(change.getProject(), patchSet),
- util.accountInfo(accountId),
- when);
+ Event event =
+ new Event(
+ util.changeInfo(change),
+ util.revisionInfo(change.getProject(), patchSet),
+ util.accountInfo(accountId),
+ when);
for (DraftPublishedListener l : listeners) {
try {
l.onDraftPublished(event);
@@ -63,17 +59,14 @@
util.logEventListenerError(this, l, e);
}
}
- } catch (PatchListNotAvailableException | GpgException | IOException
- | OrmException e) {
+ } catch (PatchListNotAvailableException | GpgException | IOException | OrmException e) {
log.error("Couldn't fire event", e);
}
}
- private static class Event extends AbstractRevisionEvent
- implements DraftPublishedListener.Event {
+ private static class Event extends AbstractRevisionEvent implements DraftPublishedListener.Event {
- Event(ChangeInfo change, RevisionInfo revision, AccountInfo publisher,
- Timestamp when) {
+ Event(ChangeInfo change, RevisionInfo revision, AccountInfo publisher, Timestamp when) {
super(change, revision, publisher, when, NotifyHandling.ALL);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/EventUtil.java b/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/EventUtil.java
index a267802..887ce57 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/EventUtil.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/EventUtil.java
@@ -32,15 +32,13 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.io.IOException;
import java.sql.Timestamp;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class EventUtil {
private static final Logger log = LoggerFactory.getLogger(EventUtil.class);
@@ -50,7 +48,8 @@
private final ChangeJson changeJson;
@Inject
- EventUtil(ChangeJson.Factory changeJsonFactory,
+ EventUtil(
+ ChangeJson.Factory changeJsonFactory,
ChangeData.Factory changeDataFactory,
Provider<ReviewDb> db) {
this.changeDataFactory = changeDataFactory;
@@ -65,16 +64,13 @@
}
public RevisionInfo revisionInfo(Project project, PatchSet ps)
- throws OrmException, PatchListNotAvailableException, GpgException,
- IOException {
+ throws OrmException, PatchListNotAvailableException, GpgException, IOException {
return revisionInfo(project.getNameKey(), ps);
}
public RevisionInfo revisionInfo(Project.NameKey project, PatchSet ps)
- throws OrmException, PatchListNotAvailableException, GpgException,
- IOException {
- ChangeData cd = changeDataFactory.create(db.get(),
- project, ps.getId().getParentKey());
+ throws OrmException, PatchListNotAvailableException, GpgException, IOException {
+ ChangeData cd = changeDataFactory.create(db.get(), project, ps.getId().getParentKey());
ChangeControl ctl = cd.changeControl();
return changeJson.getRevisionInfo(ctl, ps);
}
@@ -90,25 +86,22 @@
return accountInfo;
}
- public Map<String, ApprovalInfo> approvals(Account a,
- Map<String, Short> approvals, Timestamp ts) {
+ public Map<String, ApprovalInfo> approvals(
+ Account a, Map<String, Short> approvals, Timestamp ts) {
Map<String, ApprovalInfo> result = new HashMap<>();
for (Map.Entry<String, Short> e : approvals.entrySet()) {
Integer value = e.getValue() != null ? Integer.valueOf(e.getValue()) : null;
- result.put(e.getKey(),
- ChangeJson.getApprovalInfo(a.getId(), value, null, null, ts));
+ result.put(e.getKey(), ChangeJson.getApprovalInfo(a.getId(), value, null, null, ts));
}
return result;
}
- public void logEventListenerError(Object event, Object listener,
- Exception error) {
+ public void logEventListenerError(Object event, Object listener, Exception error) {
if (log.isDebugEnabled()) {
log.debug(
String.format(
"Error in event listener %s for event %s",
- listener.getClass().getName(),
- event.getClass().getName()),
+ listener.getClass().getName(), event.getClass().getName()),
error);
} else {
log.warn(
@@ -121,15 +114,9 @@
public static void logEventListenerError(Object listener, Exception error) {
if (log.isDebugEnabled()) {
- log.debug(
- String.format(
- "Error in event listener %s", listener.getClass().getName()),
- error);
+ log.debug(String.format("Error in event listener %s", listener.getClass().getName()), error);
} else {
- log.warn(
- "Error in listener {}: {}",
- listener.getClass().getName(),
- error.getMessage());
+ log.warn("Error in listener {}: {}", listener.getClass().getName(), error.getMessage());
}
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/GitReferenceUpdated.java b/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/GitReferenceUpdated.java
index 381dced..2b65965 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/GitReferenceUpdated.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/GitReferenceUpdated.java
@@ -21,41 +21,44 @@
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.reviewdb.client.Project;
import com.google.inject.Inject;
-
import org.eclipse.jgit.lib.BatchRefUpdate;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.RefUpdate;
import org.eclipse.jgit.transport.ReceiveCommand;
public class GitReferenceUpdated {
- public static final GitReferenceUpdated DISABLED = new GitReferenceUpdated() {
- @Override
- public void fire(Project.NameKey project, RefUpdate refUpdate,
- ReceiveCommand.Type type, Account updater) {}
+ public static final GitReferenceUpdated DISABLED =
+ new GitReferenceUpdated() {
+ @Override
+ public void fire(
+ Project.NameKey project,
+ RefUpdate refUpdate,
+ ReceiveCommand.Type type,
+ Account updater) {}
- @Override
- public void fire(Project.NameKey project, RefUpdate refUpdate,
- Account updater) {}
+ @Override
+ public void fire(Project.NameKey project, RefUpdate refUpdate, Account updater) {}
- @Override
- public void fire(Project.NameKey project, String ref, ObjectId oldObjectId,
- ObjectId newObjectId, Account updater) {}
+ @Override
+ public void fire(
+ Project.NameKey project,
+ String ref,
+ ObjectId oldObjectId,
+ ObjectId newObjectId,
+ Account updater) {}
- @Override
- public void fire(Project.NameKey project, ReceiveCommand cmd,
- Account updater) {}
+ @Override
+ public void fire(Project.NameKey project, ReceiveCommand cmd, Account updater) {}
- @Override
- public void fire(Project.NameKey project, BatchRefUpdate batchRefUpdate,
- Account updater) {}
- };
+ @Override
+ public void fire(Project.NameKey project, BatchRefUpdate batchRefUpdate, Account updater) {}
+ };
private final DynamicSet<GitReferenceUpdatedListener> listeners;
private final EventUtil util;
@Inject
- GitReferenceUpdated(DynamicSet<GitReferenceUpdatedListener> listeners,
- EventUtil util) {
+ GitReferenceUpdated(DynamicSet<GitReferenceUpdatedListener> listeners, EventUtil util) {
this.listeners = listeners;
this.util = util;
}
@@ -65,38 +68,60 @@
this.util = null;
}
- public void fire(Project.NameKey project, RefUpdate refUpdate,
- ReceiveCommand.Type type, Account updater) {
- fire(project, refUpdate.getName(), refUpdate.getOldObjectId(),
- refUpdate.getNewObjectId(), type, util.accountInfo(updater));
- }
-
- public void fire(Project.NameKey project, RefUpdate refUpdate,
- Account updater) {
- fire(project, refUpdate.getName(), refUpdate.getOldObjectId(),
- refUpdate.getNewObjectId(), ReceiveCommand.Type.UPDATE,
+ public void fire(
+ Project.NameKey project, RefUpdate refUpdate, ReceiveCommand.Type type, Account updater) {
+ fire(
+ project,
+ refUpdate.getName(),
+ refUpdate.getOldObjectId(),
+ refUpdate.getNewObjectId(),
+ type,
util.accountInfo(updater));
}
- public void fire(Project.NameKey project, String ref, ObjectId oldObjectId,
- ObjectId newObjectId, Account updater) {
- fire(project, ref, oldObjectId, newObjectId, ReceiveCommand.Type.UPDATE,
+ public void fire(Project.NameKey project, RefUpdate refUpdate, Account updater) {
+ fire(
+ project,
+ refUpdate.getName(),
+ refUpdate.getOldObjectId(),
+ refUpdate.getNewObjectId(),
+ ReceiveCommand.Type.UPDATE,
+ util.accountInfo(updater));
+ }
+
+ public void fire(
+ Project.NameKey project,
+ String ref,
+ ObjectId oldObjectId,
+ ObjectId newObjectId,
+ Account updater) {
+ fire(
+ project,
+ ref,
+ oldObjectId,
+ newObjectId,
+ ReceiveCommand.Type.UPDATE,
util.accountInfo(updater));
}
public void fire(Project.NameKey project, ReceiveCommand cmd, Account updater) {
- fire(project, cmd.getRefName(), cmd.getOldId(), cmd.getNewId(), cmd.getType(),
+ fire(
+ project,
+ cmd.getRefName(),
+ cmd.getOldId(),
+ cmd.getNewId(),
+ cmd.getType(),
util.accountInfo(updater));
}
- public void fire(Project.NameKey project, BatchRefUpdate batchRefUpdate,
- Account updater) {
+ public void fire(Project.NameKey project, BatchRefUpdate batchRefUpdate, Account updater) {
if (!listeners.iterator().hasNext()) {
return;
}
for (ReceiveCommand cmd : batchRefUpdate.getCommands()) {
if (cmd.getResult() == ReceiveCommand.Result.OK) {
- fire(project,
+ fire(
+ project,
cmd.getRefName(),
cmd.getOldId(),
cmd.getNewId(),
@@ -106,8 +131,13 @@
}
}
- private void fire(Project.NameKey project, String ref, ObjectId oldObjectId,
- ObjectId newObjectId, ReceiveCommand.Type type, AccountInfo updater) {
+ private void fire(
+ Project.NameKey project,
+ String ref,
+ ObjectId oldObjectId,
+ ObjectId newObjectId,
+ ReceiveCommand.Type type,
+ AccountInfo updater) {
if (!listeners.iterator().hasNext()) {
return;
}
@@ -131,8 +161,11 @@
private final ReceiveCommand.Type type;
private final AccountInfo updater;
- Event(Project.NameKey project, String ref,
- String oldObjectId, String newObjectId,
+ Event(
+ Project.NameKey project,
+ String ref,
+ String oldObjectId,
+ String newObjectId,
ReceiveCommand.Type type,
AccountInfo updater) {
this.projectName = project.get();
@@ -185,8 +218,9 @@
@Override
public String toString() {
- return String.format("%s[%s,%s: %s -> %s]", getClass().getSimpleName(),
- projectName, ref, oldObjectId, newObjectId);
+ return String.format(
+ "%s[%s,%s: %s -> %s]",
+ getClass().getSimpleName(), projectName, ref, oldObjectId, newObjectId);
}
@Override
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/HashtagsEdited.java b/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/HashtagsEdited.java
index 233a89e..b086beb 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/HashtagsEdited.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/HashtagsEdited.java
@@ -24,40 +24,38 @@
import com.google.gerrit.reviewdb.client.Change;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.sql.Timestamp;
import java.util.Collection;
import java.util.Set;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class HashtagsEdited {
- private static final Logger log =
- LoggerFactory.getLogger(HashtagsEdited.class);
+ private static final Logger log = LoggerFactory.getLogger(HashtagsEdited.class);
private final DynamicSet<HashtagsEditedListener> listeners;
private final EventUtil util;
@Inject
- public HashtagsEdited(DynamicSet<HashtagsEditedListener> listeners,
- EventUtil util) {
+ public HashtagsEdited(DynamicSet<HashtagsEditedListener> listeners, EventUtil util) {
this.listeners = listeners;
this.util = util;
}
- public void fire(Change change, Account editor,
- ImmutableSortedSet<String> hashtags, Set<String> added,
- Set<String> removed, Timestamp when) {
+ public void fire(
+ Change change,
+ Account editor,
+ ImmutableSortedSet<String> hashtags,
+ Set<String> added,
+ Set<String> removed,
+ Timestamp when) {
if (!listeners.iterator().hasNext()) {
return;
}
try {
- Event event = new Event(
- util.changeInfo(change),
- util.accountInfo(editor),
- hashtags, added, removed,
- when);
+ Event event =
+ new Event(
+ util.changeInfo(change), util.accountInfo(editor), hashtags, added, removed, when);
for (HashtagsEditedListener l : listeners) {
try {
l.onHashtagsEdited(event);
@@ -70,15 +68,19 @@
}
}
- private static class Event extends AbstractChangeEvent
- implements HashtagsEditedListener.Event {
+ private static class Event extends AbstractChangeEvent implements HashtagsEditedListener.Event {
private Collection<String> updatedHashtags;
private Collection<String> addedHashtags;
private Collection<String> removedHashtags;
- Event(ChangeInfo change, AccountInfo editor, Collection<String> updated,
- Collection<String> added, Collection<String> removed, Timestamp when) {
+ Event(
+ ChangeInfo change,
+ AccountInfo editor,
+ Collection<String> updated,
+ Collection<String> added,
+ Collection<String> removed,
+ Timestamp when) {
super(change, editor, when, NotifyHandling.ALL);
this.updatedHashtags = updated;
this.addedHashtags = added;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/PluginEvent.java b/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/PluginEvent.java
index fbca02e..bd643e2 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/PluginEvent.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/PluginEvent.java
@@ -36,8 +36,7 @@
}
}
- private static class Event extends AbstractNoNotifyEvent
- implements PluginEventListener.Event {
+ private static class Event extends AbstractNoNotifyEvent implements PluginEventListener.Event {
private final String pluginName;
private final String type;
private final String data;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/ReviewerAdded.java b/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/ReviewerAdded.java
index 8860a42..e4f8572 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/ReviewerAdded.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/ReviewerAdded.java
@@ -28,41 +28,38 @@
import com.google.gerrit.server.patch.PatchListNotAvailableException;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.io.IOException;
import java.sql.Timestamp;
import java.util.List;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class ReviewerAdded {
- private static final Logger log =
- LoggerFactory.getLogger(ReviewerAdded.class);
+ private static final Logger log = LoggerFactory.getLogger(ReviewerAdded.class);
private final DynamicSet<ReviewerAddedListener> listeners;
private final EventUtil util;
@Inject
- ReviewerAdded(DynamicSet<ReviewerAddedListener> listeners,
- EventUtil util) {
+ ReviewerAdded(DynamicSet<ReviewerAddedListener> listeners, EventUtil util) {
this.listeners = listeners;
this.util = util;
}
- public void fire(Change change, PatchSet patchSet, List<Account> reviewers,
- Account adder, Timestamp when) {
+ public void fire(
+ Change change, PatchSet patchSet, List<Account> reviewers, Account adder, Timestamp when) {
if (!listeners.iterator().hasNext() || reviewers.isEmpty()) {
return;
}
try {
- Event event = new Event(
- util.changeInfo(change),
- util.revisionInfo(change.getProject(), patchSet),
- Lists.transform(reviewers, util::accountInfo),
- util.accountInfo(adder),
- when);
+ Event event =
+ new Event(
+ util.changeInfo(change),
+ util.revisionInfo(change.getProject(), patchSet),
+ Lists.transform(reviewers, util::accountInfo),
+ util.accountInfo(adder),
+ when);
for (ReviewerAddedListener l : listeners) {
try {
l.onReviewersAdded(event);
@@ -70,18 +67,20 @@
util.logEventListenerError(this, l, e);
}
}
- } catch (PatchListNotAvailableException | GpgException | IOException
- | OrmException e) {
+ } catch (PatchListNotAvailableException | GpgException | IOException | OrmException e) {
log.error("Couldn't fire event", e);
}
}
- private static class Event extends AbstractRevisionEvent
- implements ReviewerAddedListener.Event {
+ private static class Event extends AbstractRevisionEvent implements ReviewerAddedListener.Event {
private final List<AccountInfo> reviewers;
- Event(ChangeInfo change, RevisionInfo revision, List<AccountInfo> reviewers,
- AccountInfo adder, Timestamp when) {
+ Event(
+ ChangeInfo change,
+ RevisionInfo revision,
+ List<AccountInfo> reviewers,
+ AccountInfo adder,
+ Timestamp when) {
super(change, revision, adder, when, NotifyHandling.ALL);
this.reviewers = reviewers;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/ReviewerDeleted.java b/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/ReviewerDeleted.java
index 4bc4764..033efe2 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/ReviewerDeleted.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/ReviewerDeleted.java
@@ -28,45 +28,49 @@
import com.google.gerrit.server.patch.PatchListNotAvailableException;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Map;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class ReviewerDeleted {
- private static final Logger log =
- LoggerFactory.getLogger(ReviewerDeleted.class);
+ private static final Logger log = LoggerFactory.getLogger(ReviewerDeleted.class);
private final DynamicSet<ReviewerDeletedListener> listeners;
private final EventUtil util;
@Inject
- ReviewerDeleted(DynamicSet<ReviewerDeletedListener> listeners,
- EventUtil util) {
+ ReviewerDeleted(DynamicSet<ReviewerDeletedListener> listeners, EventUtil util) {
this.listeners = listeners;
this.util = util;
}
- public void fire(Change change, PatchSet patchSet, Account reviewer,
- Account remover, String message, Map<String, Short> newApprovals,
- Map<String, Short> oldApprovals, NotifyHandling notify, Timestamp when) {
+ public void fire(
+ Change change,
+ PatchSet patchSet,
+ Account reviewer,
+ Account remover,
+ String message,
+ Map<String, Short> newApprovals,
+ Map<String, Short> oldApprovals,
+ NotifyHandling notify,
+ Timestamp when) {
if (!listeners.iterator().hasNext()) {
return;
}
try {
- Event event = new Event(
- util.changeInfo(change),
- util.revisionInfo(change.getProject(), patchSet),
- util.accountInfo(reviewer),
- util.accountInfo(remover),
- message,
- util.approvals(reviewer, newApprovals, when),
- util.approvals(reviewer, oldApprovals, when),
- notify,
- when);
+ Event event =
+ new Event(
+ util.changeInfo(change),
+ util.revisionInfo(change.getProject(), patchSet),
+ util.accountInfo(reviewer),
+ util.accountInfo(remover),
+ message,
+ util.approvals(reviewer, newApprovals, when),
+ util.approvals(reviewer, oldApprovals, when),
+ notify,
+ when);
for (ReviewerDeletedListener listener : listeners) {
try {
listener.onReviewerDeleted(event);
@@ -74,11 +78,9 @@
util.logEventListenerError(this, listener, e);
}
}
- } catch (PatchListNotAvailableException | GpgException | IOException
- | OrmException e) {
+ } catch (PatchListNotAvailableException | GpgException | IOException | OrmException e) {
log.error("Couldn't fire event", e);
}
-
}
private static class Event extends AbstractRevisionEvent
@@ -88,10 +90,15 @@
private final Map<String, ApprovalInfo> newApprovals;
private final Map<String, ApprovalInfo> oldApprovals;
- Event(ChangeInfo change, RevisionInfo revision, AccountInfo reviewer,
- AccountInfo remover, String comment,
+ Event(
+ ChangeInfo change,
+ RevisionInfo revision,
+ AccountInfo reviewer,
+ AccountInfo remover,
+ String comment,
Map<String, ApprovalInfo> newApprovals,
- Map<String, ApprovalInfo> oldApprovals, NotifyHandling notify,
+ Map<String, ApprovalInfo> oldApprovals,
+ NotifyHandling notify,
Timestamp when) {
super(change, revision, remover, when, notify);
this.reviewer = reviewer;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/RevisionCreated.java b/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/RevisionCreated.java
index 7f03c63..8a781d0 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/RevisionCreated.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/RevisionCreated.java
@@ -27,38 +27,36 @@
import com.google.gerrit.server.patch.PatchListNotAvailableException;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
-
+import java.io.IOException;
+import java.sql.Timestamp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.sql.Timestamp;
-
public class RevisionCreated {
- private static final Logger log =
- LoggerFactory.getLogger(RevisionCreated.class);
+ private static final Logger log = LoggerFactory.getLogger(RevisionCreated.class);
private final DynamicSet<RevisionCreatedListener> listeners;
private final EventUtil util;
@Inject
- RevisionCreated(DynamicSet<RevisionCreatedListener> listeners,
- EventUtil util) {
+ RevisionCreated(DynamicSet<RevisionCreatedListener> listeners, EventUtil util) {
this.listeners = listeners;
this.util = util;
}
- public void fire(Change change, PatchSet patchSet, Account uploader,
- Timestamp when, NotifyHandling notify) {
+ public void fire(
+ Change change, PatchSet patchSet, Account uploader, Timestamp when, NotifyHandling notify) {
if (!listeners.iterator().hasNext()) {
return;
}
try {
- Event event = new Event(
- util.changeInfo(change),
- util.revisionInfo(change.getProject(), patchSet),
- util.accountInfo(uploader),
- when, notify);
+ Event event =
+ new Event(
+ util.changeInfo(change),
+ util.revisionInfo(change.getProject(), patchSet),
+ util.accountInfo(uploader),
+ when,
+ notify);
for (RevisionCreatedListener l : listeners) {
try {
l.onRevisionCreated(event);
@@ -66,8 +64,7 @@
util.logEventListenerError(this, l, e);
}
}
- } catch ( PatchListNotAvailableException | GpgException | IOException
- | OrmException e) {
+ } catch (PatchListNotAvailableException | GpgException | IOException | OrmException e) {
log.error("Couldn't fire event", e);
}
}
@@ -75,8 +72,12 @@
private static class Event extends AbstractRevisionEvent
implements RevisionCreatedListener.Event {
- Event(ChangeInfo change, RevisionInfo revision, AccountInfo uploader,
- Timestamp when, NotifyHandling notify) {
+ Event(
+ ChangeInfo change,
+ RevisionInfo revision,
+ AccountInfo uploader,
+ Timestamp when,
+ NotifyHandling notify) {
super(change, revision, uploader, when, notify);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/TopicEdited.java b/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/TopicEdited.java
index 2e583a8..d7e7245 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/TopicEdited.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/TopicEdited.java
@@ -23,37 +23,29 @@
import com.google.gerrit.reviewdb.client.Change;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
-
+import java.sql.Timestamp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.sql.Timestamp;
-
public class TopicEdited {
- private static final Logger log =
- LoggerFactory.getLogger(TopicEdited.class);
+ private static final Logger log = LoggerFactory.getLogger(TopicEdited.class);
private final DynamicSet<TopicEditedListener> listeners;
private final EventUtil util;
@Inject
- TopicEdited(DynamicSet<TopicEditedListener> listeners,
- EventUtil util) {
+ TopicEdited(DynamicSet<TopicEditedListener> listeners, EventUtil util) {
this.listeners = listeners;
this.util = util;
}
- public void fire(Change change, Account account, String oldTopicName,
- Timestamp when) {
+ public void fire(Change change, Account account, String oldTopicName, Timestamp when) {
if (!listeners.iterator().hasNext()) {
return;
}
try {
- Event event = new Event(
- util.changeInfo(change),
- util.accountInfo(account),
- oldTopicName,
- when);
+ Event event =
+ new Event(util.changeInfo(change), util.accountInfo(account), oldTopicName, when);
for (TopicEditedListener l : listeners) {
try {
l.onTopicEdited(event);
@@ -66,12 +58,10 @@
}
}
- private static class Event extends AbstractChangeEvent
- implements TopicEditedListener.Event {
+ private static class Event extends AbstractChangeEvent implements TopicEditedListener.Event {
private final String oldTopic;
- Event(ChangeInfo change, AccountInfo editor, String oldTopic,
- Timestamp when) {
+ Event(ChangeInfo change, AccountInfo editor, String oldTopic, Timestamp when) {
super(change, editor, when, NotifyHandling.ALL);
this.oldTopic = oldTopic;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/VoteDeleted.java b/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/VoteDeleted.java
index e421ea6..acb332d 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/VoteDeleted.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/extensions/events/VoteDeleted.java
@@ -29,44 +29,47 @@
import com.google.gerrit.server.patch.PatchListNotAvailableException;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Map;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class VoteDeleted {
- private static final Logger log =
- LoggerFactory.getLogger(VoteDeleted.class);
+ private static final Logger log = LoggerFactory.getLogger(VoteDeleted.class);
private final DynamicSet<VoteDeletedListener> listeners;
private final EventUtil util;
@Inject
- VoteDeleted(DynamicSet<VoteDeletedListener> listeners,
- EventUtil util) {
+ VoteDeleted(DynamicSet<VoteDeletedListener> listeners, EventUtil util) {
this.listeners = listeners;
this.util = util;
}
- public void fire(Change change, PatchSet ps,
+ public void fire(
+ Change change,
+ PatchSet ps,
Map<String, Short> approvals,
Map<String, Short> oldApprovals,
- NotifyHandling notify, String message,
- Account remover, Timestamp when) {
+ NotifyHandling notify,
+ String message,
+ Account remover,
+ Timestamp when) {
if (!listeners.iterator().hasNext()) {
return;
}
try {
- Event event = new Event(
- util.changeInfo(change),
- util.revisionInfo(change.getProject(), ps),
- util.approvals(remover, approvals, when),
- util.approvals(remover, oldApprovals, when),
- notify, message,
- util.accountInfo(remover), when);
+ Event event =
+ new Event(
+ util.changeInfo(change),
+ util.revisionInfo(change.getProject(), ps),
+ util.approvals(remover, approvals, when),
+ util.approvals(remover, oldApprovals, when),
+ notify,
+ message,
+ util.accountInfo(remover),
+ when);
for (VoteDeletedListener l : listeners) {
try {
l.onVoteDeleted(event);
@@ -74,24 +77,26 @@
util.logEventListenerError(this, l, e);
}
}
- } catch (PatchListNotAvailableException | GpgException | IOException
- | OrmException e) {
+ } catch (PatchListNotAvailableException | GpgException | IOException | OrmException e) {
log.error("Couldn't fire event", e);
}
}
- private static class Event extends AbstractRevisionEvent
- implements VoteDeletedListener.Event {
+ private static class Event extends AbstractRevisionEvent implements VoteDeletedListener.Event {
private final Map<String, ApprovalInfo> approvals;
private final Map<String, ApprovalInfo> oldApprovals;
private final String message;
- Event(ChangeInfo change, RevisionInfo revision,
+ Event(
+ ChangeInfo change,
+ RevisionInfo revision,
Map<String, ApprovalInfo> approvals,
Map<String, ApprovalInfo> oldApprovals,
- NotifyHandling notify, String message,
- AccountInfo remover, Timestamp when) {
+ NotifyHandling notify,
+ String message,
+ AccountInfo remover,
+ Timestamp when) {
super(change, revision, remover, when, notify);
this.approvals = approvals;
this.oldApprovals = oldApprovals;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/extensions/webui/UiActions.java b/gerrit-server/src/main/java/com/google/gerrit/server/extensions/webui/UiActions.java
index fe261e9..85ee4f9 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/extensions/webui/UiActions.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/extensions/webui/UiActions.java
@@ -26,12 +26,10 @@
import com.google.gerrit.server.CurrentUser;
import com.google.gerrit.server.account.CapabilityUtils;
import com.google.inject.Provider;
-
+import java.util.Objects;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.util.Objects;
-
public class UiActions {
private static final Logger log = LoggerFactory.getLogger(UiActions.class);
@@ -39,21 +37,16 @@
return UiAction.Description::isEnabled;
}
- public static <R extends RestResource> FluentIterable<UiAction.Description>
- from(
- RestCollection<?, R> collection,
- R resource,
- Provider<CurrentUser> userProvider) {
+ public static <R extends RestResource> FluentIterable<UiAction.Description> from(
+ RestCollection<?, R> collection, R resource, Provider<CurrentUser> userProvider) {
return from(collection.views(), resource, userProvider);
}
- public static <R extends RestResource> FluentIterable<UiAction.Description>
- from(
- DynamicMap<RestView<R>> views,
- R resource,
- Provider<CurrentUser> userProvider) {
+ public static <R extends RestResource> FluentIterable<UiAction.Description> from(
+ DynamicMap<RestView<R>> views, R resource, Provider<CurrentUser> userProvider) {
return FluentIterable.from(views)
- .transform((DynamicMap.Entry<RestView<R>> e) -> {
+ .transform(
+ (DynamicMap.Entry<RestView<R>> e) -> {
int d = e.getExportName().indexOf('.');
if (d < 0) {
return null;
@@ -63,9 +56,10 @@
try {
view = e.getProvider().get();
} catch (RuntimeException err) {
- log.error(String.format(
- "error creating view %s.%s",
- e.getPluginName(), e.getExportName()), err);
+ log.error(
+ String.format(
+ "error creating view %s.%s", e.getPluginName(), e.getExportName()),
+ err);
return null;
}
@@ -74,32 +68,26 @@
}
try {
- CapabilityUtils.checkRequiresCapability(userProvider,
- e.getPluginName(), view.getClass());
+ CapabilityUtils.checkRequiresCapability(
+ userProvider, e.getPluginName(), view.getClass());
} catch (AuthException exc) {
return null;
}
- UiAction.Description dsc =
- ((UiAction<R>) view).getDescription(resource);
+ UiAction.Description dsc = ((UiAction<R>) view).getDescription(resource);
if (dsc == null || !dsc.isVisible()) {
return null;
}
String name = e.getExportName().substring(d + 1);
PrivateInternals_UiActionDescription.setMethod(
- dsc,
- e.getExportName().substring(0, d));
+ dsc, e.getExportName().substring(0, d));
PrivateInternals_UiActionDescription.setId(
- dsc,
- "gerrit".equals(e.getPluginName())
- ? name
- : e.getPluginName() + '~' + name);
+ dsc, "gerrit".equals(e.getPluginName()) ? name : e.getPluginName() + '~' + name);
return dsc;
})
.filter(Objects::nonNull);
}
- private UiActions() {
- }
+ private UiActions() {}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/AbandonOp.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/AbandonOp.java
index f4e84b2e..bebff61 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/AbandonOp.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/AbandonOp.java
@@ -35,7 +35,6 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -91,8 +90,7 @@
}
@Override
- public boolean updateChange(ChangeContext ctx)
- throws OrmException, ResourceConflictException {
+ public boolean updateChange(ChangeContext ctx) throws OrmException, ResourceConflictException {
change = ctx.getChange();
PatchSet.Id psId = change.currentPatchSetId();
ChangeUpdate update = ctx.getUpdate(psId);
@@ -119,15 +117,13 @@
msg.append(msgTxt.trim());
}
- return ChangeMessagesUtil.newMessage(
- ctx, msg.toString(), ChangeMessagesUtil.TAG_ABANDON);
+ return ChangeMessagesUtil.newMessage(ctx, msg.toString(), ChangeMessagesUtil.TAG_ABANDON);
}
@Override
public void postUpdate(Context ctx) throws OrmException {
try {
- ReplyToChangeSender cm =
- abandonedSenderFactory.create(ctx.getProject(), change.getId());
+ ReplyToChangeSender cm = abandonedSenderFactory.create(ctx.getProject(), change.getId());
if (account != null) {
cm.setFrom(account.getId());
}
@@ -138,8 +134,7 @@
} catch (Exception e) {
log.error("Cannot email update for change " + change.getId(), e);
}
- changeAbandoned.fire(
- change, patchSet, account, msgTxt, ctx.getWhen(), notifyHandling);
+ changeAbandoned.fire(change, patchSet, account, msgTxt, ctx.getWhen(), notifyHandling);
}
private static String status(Change change) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/AccountsSection.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/AccountsSection.java
index 4ea24ef..ffecc36 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/AccountsSection.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/AccountsSection.java
@@ -15,7 +15,6 @@
package com.google.gerrit.server.git;
import com.google.gerrit.common.data.PermissionRule;
-
import java.util.ArrayList;
import java.util.List;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/AsyncReceiveCommits.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/AsyncReceiveCommits.java
index 899b06a..a3ea7f8 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/AsyncReceiveCommits.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/AsyncReceiveCommits.java
@@ -27,7 +27,10 @@
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.FactoryModuleBuilder;
import com.google.inject.name.Named;
-
+import java.io.OutputStream;
+import java.util.Collection;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.transport.PreReceiveHook;
@@ -37,33 +40,24 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.OutputStream;
-import java.util.Collection;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.TimeUnit;
-
/** Hook that delegates to {@link ReceiveCommits} in a worker thread. */
public class AsyncReceiveCommits implements PreReceiveHook {
- private static final Logger log =
- LoggerFactory.getLogger(AsyncReceiveCommits.class);
+ private static final Logger log = LoggerFactory.getLogger(AsyncReceiveCommits.class);
private static final String TIMEOUT_NAME = "ReceiveCommitsOverallTimeout";
public interface Factory {
- AsyncReceiveCommits create(ProjectControl projectControl,
- Repository repository);
+ AsyncReceiveCommits create(ProjectControl projectControl, Repository repository);
}
public static class Module extends PrivateModule {
@Override
public void configure() {
- install(new FactoryModuleBuilder()
- .build(AsyncReceiveCommits.Factory.class));
+ install(new FactoryModuleBuilder().build(AsyncReceiveCommits.Factory.class));
expose(AsyncReceiveCommits.Factory.class);
// Don't expose the binding for ReceiveCommits.Factory. All callers should
// be using AsyncReceiveCommits.Factory instead.
- install(new FactoryModuleBuilder()
- .build(ReceiveCommits.Factory.class));
+ install(new FactoryModuleBuilder().build(ReceiveCommits.Factory.class));
}
@Provides
@@ -71,9 +65,7 @@
@Named(TIMEOUT_NAME)
long getTimeoutMillis(@GerritServerConfig final Config cfg) {
return ConfigUtil.getTimeUnit(
- cfg, "receive", null, "timeout",
- TimeUnit.MINUTES.toMillis(4),
- TimeUnit.MILLISECONDS);
+ cfg, "receive", null, "timeout", TimeUnit.MINUTES.toMillis(4), TimeUnit.MILLISECONDS);
}
}
@@ -113,7 +105,7 @@
private class MessageSenderOutputStream extends OutputStream {
@Override
public void write(int b) {
- rc.getMessageSender().sendBytes(new byte[]{(byte)b});
+ rc.getMessageSender().sendBytes(new byte[] {(byte) b});
}
@Override
@@ -139,7 +131,8 @@
private final long timeoutMillis;
@Inject
- AsyncReceiveCommits(final ReceiveCommits.Factory factory,
+ AsyncReceiveCommits(
+ final ReceiveCommits.Factory factory,
@ReceiveCommitsExecutor final Executor executor,
final RequestScopePropagator scopePropagator,
@Named(TIMEOUT_NAME) final long timeoutMillis,
@@ -150,22 +143,23 @@
rc = factory.create(projectControl, repo);
rc.getReceivePack().setPreReceiveHook(this);
- progress = new MultiProgressMonitor(
- new MessageSenderOutputStream(), "Processing changes");
+ progress = new MultiProgressMonitor(new MessageSenderOutputStream(), "Processing changes");
this.timeoutMillis = timeoutMillis;
}
@Override
- public void onPreReceive(final ReceivePack rp,
- final Collection<ReceiveCommand> commands) {
+ public void onPreReceive(final ReceivePack rp, final Collection<ReceiveCommand> commands) {
try {
progress.waitFor(
executor.submit(scopePropagator.wrap(new Worker(commands))),
- timeoutMillis, TimeUnit.MILLISECONDS);
+ timeoutMillis,
+ TimeUnit.MILLISECONDS);
} catch (ExecutionException e) {
- log.warn(String.format(
- "Error in ReceiveCommits while processing changes for project %s",
- rc.getProject().getName()), e);
+ log.warn(
+ String.format(
+ "Error in ReceiveCommits while processing changes for project %s",
+ rc.getProject().getName()),
+ e);
rc.addError("internal error while processing changes");
// ReceiveCommits has tried its best to catch errors, so anything at this
// point is very bad.
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/BanCommit.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/BanCommit.java
index be17776..d09e857 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/BanCommit.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/BanCommit.java
@@ -26,7 +26,10 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
+import java.io.IOException;
+import java.util.Date;
+import java.util.List;
+import java.util.TimeZone;
import org.eclipse.jgit.api.errors.ConcurrentRefUpdateException;
import org.eclipse.jgit.errors.IncorrectObjectTypeException;
import org.eclipse.jgit.errors.MissingObjectException;
@@ -41,11 +44,6 @@
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;
-import java.io.IOException;
-import java.util.Date;
-import java.util.List;
-import java.util.TimeZone;
-
@Singleton
public class BanCommit {
/**
@@ -56,8 +54,7 @@
* @return NoteMap of commits to be rejected, null if there are none.
* @throws IOException the map cannot be loaded.
*/
- public static NoteMap loadRejectCommitsMap(Repository repo, RevWalk walk)
- throws IOException {
+ public static NoteMap loadRejectCommitsMap(Repository repo, RevWalk walk) throws IOException {
try {
Ref ref = repo.getRefDatabase().exactRef(RefNames.REFS_REJECT_COMMITS);
if (ref == null) {
@@ -67,8 +64,7 @@
RevCommit map = walk.parseCommit(ref.getObjectId());
return NoteMap.read(walk.getObjectReader(), map);
} catch (IOException badMap) {
- throw new IOException("Cannot load " + RefNames.REFS_REJECT_COMMITS,
- badMap);
+ throw new IOException("Cannot load " + RefNames.REFS_REJECT_COMMITS, badMap);
}
}
@@ -78,7 +74,8 @@
private NotesBranchUtil.Factory notesBranchUtilFactory;
@Inject
- BanCommit(final Provider<IdentifiedUser> currentUser,
+ BanCommit(
+ final Provider<IdentifiedUser> currentUser,
final GitRepositoryManager repoManager,
@GerritPersonIdent final PersonIdent gerritIdent,
final NotesBranchUtil.Factory notesBranchUtilFactory) {
@@ -88,13 +85,11 @@
this.tz = gerritIdent.getTimeZone();
}
- public BanCommitResult ban(final ProjectControl projectControl,
- final List<ObjectId> commitsToBan, final String reason)
- throws PermissionDeniedException, IOException,
- ConcurrentRefUpdateException {
+ public BanCommitResult ban(
+ final ProjectControl projectControl, final List<ObjectId> commitsToBan, final String reason)
+ throws PermissionDeniedException, IOException, ConcurrentRefUpdateException {
if (!projectControl.isOwner()) {
- throw new PermissionDeniedException(
- "Not project owner: not permitted to ban commits");
+ throw new PermissionDeniedException("Not project owner: not permitted to ban commits");
}
final BanCommitResult result = new BanCommitResult();
@@ -119,11 +114,13 @@
}
banCommitNotes.set(commitToBan, noteId);
}
- NotesBranchUtil notesBranchUtil =
- notesBranchUtilFactory.create(project, repo, inserter);
+ NotesBranchUtil notesBranchUtil = notesBranchUtilFactory.create(project, repo, inserter);
NoteMap newlyCreated =
- notesBranchUtil.commitNewNotes(banCommitNotes, REFS_REJECT_COMMITS,
- createPersonIdent(), buildCommitMessage(commitsToBan, reason));
+ notesBranchUtil.commitNewNotes(
+ banCommitNotes,
+ REFS_REJECT_COMMITS,
+ createPersonIdent(),
+ buildCommitMessage(commitsToBan, reason));
for (Note n : banCommitNotes) {
if (newlyCreated.contains(n)) {
@@ -136,8 +133,7 @@
}
}
- private ObjectId createNoteContent(String reason, ObjectInserter inserter)
- throws IOException {
+ private ObjectId createNoteContent(String reason, ObjectInserter inserter) throws IOException {
String noteContent = reason != null ? reason : "";
if (noteContent.length() > 0 && !noteContent.endsWith("\n")) {
noteContent = noteContent + "\n";
@@ -150,8 +146,8 @@
return currentUser.get().newCommitterIdent(now, tz);
}
- private static String buildCommitMessage(final List<ObjectId> bannedCommits,
- final String reason) {
+ private static String buildCommitMessage(
+ final List<ObjectId> bannedCommits, final String reason) {
final StringBuilder commitMsg = new StringBuilder();
commitMsg.append("Banning ");
commitMsg.append(bannedCommits.size());
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/BanCommitResult.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/BanCommitResult.java
index 92c3b6c..baa6013 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/BanCommitResult.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/BanCommitResult.java
@@ -14,10 +14,9 @@
package com.google.gerrit.server.git;
-import org.eclipse.jgit.lib.ObjectId;
-
import java.util.ArrayList;
import java.util.List;
+import org.eclipse.jgit.lib.ObjectId;
public class BanCommitResult {
private final List<ObjectId> newlyBannedCommits = new ArrayList<>(4);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/BatchUpdate.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/BatchUpdate.java
index 93571d6..38a8199 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/BatchUpdate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/BatchUpdate.java
@@ -72,19 +72,6 @@
import com.google.inject.Singleton;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
-
-import org.eclipse.jgit.lib.BatchRefUpdate;
-import org.eclipse.jgit.lib.Config;
-import org.eclipse.jgit.lib.NullProgressMonitor;
-import org.eclipse.jgit.lib.ObjectInserter;
-import org.eclipse.jgit.lib.ObjectReader;
-import org.eclipse.jgit.lib.PersonIdent;
-import org.eclipse.jgit.lib.Repository;
-import org.eclipse.jgit.revwalk.RevWalk;
-import org.eclipse.jgit.transport.ReceiveCommand;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
@@ -97,53 +84,62 @@
import java.util.TreeMap;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
+import org.eclipse.jgit.lib.BatchRefUpdate;
+import org.eclipse.jgit.lib.Config;
+import org.eclipse.jgit.lib.NullProgressMonitor;
+import org.eclipse.jgit.lib.ObjectInserter;
+import org.eclipse.jgit.lib.ObjectReader;
+import org.eclipse.jgit.lib.PersonIdent;
+import org.eclipse.jgit.lib.Repository;
+import org.eclipse.jgit.revwalk.RevWalk;
+import org.eclipse.jgit.transport.ReceiveCommand;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* Context for a set of updates that should be applied for a site.
- * <p>
- * An update operation can be divided into three phases:
+ *
+ * <p>An update operation can be divided into three phases:
+ *
* <ol>
- * <li>Git reference updates</li>
- * <li>Database updates</li>
- * <li>Post-update steps<li>
+ * <li>Git reference updates
+ * <li>Database updates
+ * <li>Post-update steps
+ * <li>
* </ol>
- * A single conceptual operation, such as a REST API call or a merge operation,
- * may make multiple changes at each step, which all need to be serialized
- * relative to each other. Moreover, for consistency, <em>all</em> git ref
- * updates must be performed before <em>any</em> database updates, since
- * database updates might refer to newly-created patch set refs. And all
- * post-update steps, such as hooks, should run only after all storage
- * mutations have completed.
- * <p>
- * Depending on the backend used, each step might support batching, for example
- * in a {@code BatchRefUpdate} or one or more database transactions. All
- * operations in one phase must complete successfully before proceeding to the
- * next phase.
+ *
+ * A single conceptual operation, such as a REST API call or a merge operation, may make multiple
+ * changes at each step, which all need to be serialized relative to each other. Moreover, for
+ * consistency, <em>all</em> git ref updates must be performed before <em>any</em> database updates,
+ * since database updates might refer to newly-created patch set refs. And all post-update steps,
+ * such as hooks, should run only after all storage mutations have completed.
+ *
+ * <p>Depending on the backend used, each step might support batching, for example in a {@code
+ * BatchRefUpdate} or one or more database transactions. All operations in one phase must complete
+ * successfully before proceeding to the next phase.
*/
public class BatchUpdate implements AutoCloseable {
private static final Logger log = LoggerFactory.getLogger(BatchUpdate.class);
public interface Factory {
- BatchUpdate create(ReviewDb db, Project.NameKey project,
- CurrentUser user, Timestamp when);
+ BatchUpdate create(ReviewDb db, Project.NameKey project, CurrentUser user, Timestamp when);
}
/** Order of execution of the various phases. */
public enum Order {
/**
- * Update the repository and execute all ref updates before touching the
- * database.
- * <p>
- * The default and most common, as Gerrit does not behave well when a patch
- * set has no corresponding ref in the repo.
+ * Update the repository and execute all ref updates before touching the database.
+ *
+ * <p>The default and most common, as Gerrit does not behave well when a patch set has no
+ * corresponding ref in the repo.
*/
REPO_BEFORE_DB,
/**
* Update the database before touching the repository.
- * <p>
- * Generally only used when deleting patch sets, which should be deleted
- * first from the database (for the same reason as above.)
+ *
+ * <p>Generally only used when deleting patch sets, which should be deleted first from the
+ * database (for the same reason as above.)
*/
DB_BEFORE_REPO;
}
@@ -228,8 +224,8 @@
private boolean deleted;
private boolean bumpLastUpdatedOn = true;
- protected ChangeContext(ChangeControl ctl, ReviewDbWrapper dbWrapper,
- Repository repo, RevWalk rw) {
+ protected ChangeContext(
+ ChangeControl ctl, ReviewDbWrapper dbWrapper, Repository repo, RevWalk rw) {
this.ctl = ctl;
this.dbWrapper = dbWrapper;
this.threadLocalRepo = repo;
@@ -298,18 +294,15 @@
*
* @param ctx context
*/
- public void updateRepo(RepoContext ctx) throws Exception {
- }
+ public void updateRepo(RepoContext ctx) throws Exception {}
/**
- * Override this method to do something after the update
- * e.g. send email or run hooks
+ * Override this method to do something after the update e.g. send email or run hooks
*
* @param ctx context
*/
//TODO(dborowitz): Support async operations?
- public void postUpdate(Context ctx) throws Exception {
- }
+ public void postUpdate(Context ctx) throws Exception {}
}
public static class Op extends RepoOnlyOp {
@@ -317,8 +310,7 @@
* Override this method to modify a change.
*
* @param ctx context
- * @return whether anything was changed that might require a write to
- * the metadata storage.
+ * @return whether anything was changed that might require a write to the metadata storage.
*/
public boolean updateChange(ChangeContext ctx) throws Exception {
return false;
@@ -331,27 +323,21 @@
/**
* Interface for listening during batch update execution.
- * <p>
- * When used during execution of multiple batch updates, the {@code after*}
- * methods are called after that phase has been completed for <em>all</em> updates.
+ *
+ * <p>When used during execution of multiple batch updates, the {@code after*} methods are called
+ * after that phase has been completed for <em>all</em> updates.
*/
public static class Listener {
public static final Listener NONE = new Listener();
- /**
- * Called after updating all repositories and flushing objects but before
- * updating any refs.
- */
- public void afterUpdateRepos() throws Exception {
- }
+ /** Called after updating all repositories and flushing objects but before updating any refs. */
+ public void afterUpdateRepos() throws Exception {}
/** Called after updating all refs. */
- public void afterRefUpdates() throws Exception {
- }
+ public void afterRefUpdates() throws Exception {}
/** Called after updating all changes. */
- public void afterUpdateChanges() throws Exception {
- }
+ public void afterUpdateChanges() throws Exception {}
}
@Singleton
@@ -360,13 +346,13 @@
@Inject
Metrics(MetricMaker metricMaker) {
- executeChangeOpsLatency = metricMaker.newTimer(
- "batch_update/execute_change_ops",
- new Description(
- "BatchUpdate change update latency, excluding reindexing")
- .setCumulative()
- .setUnit(Units.MILLISECONDS),
- Field.ofBoolean("success"));
+ executeChangeOpsLatency =
+ metricMaker.newTimer(
+ "batch_update/execute_change_ops",
+ new Description("BatchUpdate change update latency, excluding reindexing")
+ .setCumulative()
+ .setUnit(Units.MILLISECONDS),
+ Field.ofBoolean("success"));
}
}
@@ -382,37 +368,41 @@
return o;
}
- private static boolean getUpdateChangesInParallel(
- Collection<BatchUpdate> updates) {
+ private static boolean getUpdateChangesInParallel(Collection<BatchUpdate> updates) {
checkArgument(!updates.isEmpty());
Boolean p = null;
for (BatchUpdate u : updates) {
if (p == null) {
p = u.updateChangesInParallel;
} else if (u.updateChangesInParallel != p) {
- throw new IllegalArgumentException(
- "cannot mix parallel and non-parallel operations");
+ throw new IllegalArgumentException("cannot mix parallel and non-parallel operations");
}
}
// Properly implementing this would involve hoisting the parallel loop up
// even further. As of this writing, the only user is ReceiveCommits,
// which only executes a single BatchUpdate at a time. So bail for now.
- checkArgument(!p || updates.size() <= 1,
+ checkArgument(
+ !p || updates.size() <= 1,
"cannot execute ChangeOps in parallel with more than 1 BatchUpdate");
return p;
}
- static void execute(Collection<BatchUpdate> updates, Listener listener,
- @Nullable RequestId requestId, boolean dryrun)
- throws UpdateException, RestApiException {
+ static void execute(
+ Collection<BatchUpdate> updates,
+ Listener listener,
+ @Nullable RequestId requestId,
+ boolean dryrun)
+ throws UpdateException, RestApiException {
if (updates.isEmpty()) {
return;
}
if (requestId != null) {
for (BatchUpdate u : updates) {
- checkArgument(u.requestId == null || u.requestId == requestId,
+ checkArgument(
+ u.requestId == null || u.requestId == requestId,
"refusing to overwrite RequestId %s in update with %s",
- u.requestId, requestId);
+ u.requestId,
+ requestId);
u.setRequestId(requestId);
}
}
@@ -430,15 +420,13 @@
}
listener.afterRefUpdates();
for (BatchUpdate u : updates) {
- u.reindexChanges(
- u.executeChangeOps(updateChangesInParallel, dryrun));
+ u.reindexChanges(u.executeChangeOps(updateChangesInParallel, dryrun));
}
listener.afterUpdateChanges();
break;
case DB_BEFORE_REPO:
for (BatchUpdate u : updates) {
- u.reindexChanges(
- u.executeChangeOps(updateChangesInParallel, dryrun));
+ u.reindexChanges(u.executeChangeOps(updateChangesInParallel, dryrun));
}
listener.afterUpdateChanges();
for (BatchUpdate u : updates) {
@@ -469,9 +457,7 @@
u.gitRefUpdated.fire(
u.project,
u.batchRefUpdate,
- u.getUser().isIdentifiedUser()
- ? u.getUser().asIdentifiedUser().getAccount()
- : null);
+ u.getUser().isIdentifiedUser() ? u.getUser().asIdentifiedUser().getAccount() : null);
}
}
if (!dryrun) {
@@ -485,12 +471,11 @@
// failure.
throw e;
- // Convert other common non-REST exception types with user-visible
- // messages to corresponding REST exception types
+ // Convert other common non-REST exception types with user-visible
+ // messages to corresponding REST exception types
} catch (InvalidChangeOperationException e) {
throw new ResourceConflictException(e.getMessage(), e);
- } catch (NoSuchChangeException | NoSuchRefException
- | NoSuchProjectException e) {
+ } catch (NoSuchChangeException | NoSuchRefException | NoSuchProjectException e) {
throw new ResourceNotFoundException(e.getMessage(), e);
} catch (Exception e) {
@@ -522,8 +507,7 @@
private final ListMultimap<Change.Id, Op> ops =
MultimapBuilder.linkedHashKeys().arrayListValues().build();
private final Map<Change.Id, Change> newChanges = new HashMap<>();
- private final List<CheckedFuture<?, IOException>> indexFutures =
- new ArrayList<>();
+ private final List<CheckedFuture<?, IOException>> indexFutures = new ArrayList<>();
private final List<RepoOnlyOp> repoOnlyOps = new ArrayList<>();
private Repository repo;
@@ -592,8 +576,7 @@
return this;
}
- public BatchUpdate setRepository(Repository repo, RevWalk revWalk,
- ObjectInserter inserter) {
+ public BatchUpdate setRepository(Repository repo, RevWalk revWalk, ObjectInserter inserter) {
checkState(this.repo == null, "repo already set");
closeRepo = false;
this.repo = checkNotNull(repo, "repo");
@@ -609,17 +592,15 @@
}
/**
- * Add a validation step for intended ref operations, which will be performed
- * at the end of {@link RepoOnlyOp#updateRepo(RepoContext)} step.
+ * Add a validation step for intended ref operations, which will be performed at the end of {@link
+ * RepoOnlyOp#updateRepo(RepoContext)} step.
*/
BatchUpdate setOnSubmitValidators(OnSubmitValidators onSubmitValidators) {
this.onSubmitValidators = onSubmitValidators;
return this;
}
- /**
- * Execute {@link Op#updateChange(ChangeContext)} in parallel for each change.
- */
+ /** Execute {@link Op#updateChange(ChangeContext)} in parallel for each change. */
public BatchUpdate updateChangesInParallel() {
this.updateChangesInParallel = true;
return this;
@@ -670,8 +651,8 @@
public BatchUpdate insertChange(InsertChangeOp op) {
Context ctx = new Context();
Change c = op.createChange(ctx);
- checkArgument(!newChanges.containsKey(c.getId()),
- "only one op allowed to create change %s", c.getId());
+ checkArgument(
+ !newChanges.containsKey(c.getId()), "only one op allowed to create change %s", c.getId());
newChanges.put(c.getId(), c);
ops.get(c.getId()).add(0, op);
return this;
@@ -685,8 +666,7 @@
execute(Listener.NONE);
}
- public void execute(Listener listener)
- throws UpdateException, RestApiException {
+ public void execute(Listener listener) throws UpdateException, RestApiException {
execute(ImmutableList.of(this), listener, requestId, false);
}
@@ -703,16 +683,17 @@
op.updateRepo(ctx);
}
- if (onSubmitValidators != null && commands != null
- && !commands.isEmpty()) {
+ if (onSubmitValidators != null && commands != null && !commands.isEmpty()) {
// Validation of refs has to take place here and not at the beginning
// executeRefUpdates. Otherwise failing validation in a second
// BatchUpdate object will happen *after* first object's
// executeRefUpdates has finished, hence after first repo's refs have
// been updated, which is too late.
- onSubmitValidators.validate(project,
+ onSubmitValidators.validate(
+ project,
new ReadOnlyRepository(getRepository()),
- ctx.getInserter().newReader(), commands.getCommands());
+ ctx.getInserter().newReader(),
+ commands.getCommands());
}
if (inserter != null) {
@@ -727,8 +708,7 @@
}
}
- private void executeRefUpdates(boolean dryrun)
- throws IOException, RestApiException {
+ private void executeRefUpdates(boolean dryrun) throws IOException, RestApiException {
if (commands == null || commands.isEmpty()) {
logDebug("No ref updates to execute");
return;
@@ -737,8 +717,7 @@
initRepository();
batchRefUpdate = repo.getRefDatabase().newBatchUpdate();
commands.addTo(batchRefUpdate);
- logDebug("Executing batch of {} ref updates",
- batchRefUpdate.getCommands().size());
+ logDebug("Executing batch of {} ref updates", batchRefUpdate.getCommands().size());
if (dryrun) {
return;
}
@@ -756,17 +735,15 @@
}
}
- private List<ChangeTask> executeChangeOps(boolean parallel,
- boolean dryrun) throws UpdateException,
- RestApiException {
+ private List<ChangeTask> executeChangeOps(boolean parallel, boolean dryrun)
+ throws UpdateException, RestApiException {
List<ChangeTask> tasks;
boolean success = false;
Stopwatch sw = Stopwatch.createStarted();
try {
logDebug("Executing change ops (parallel? {})", parallel);
- ListeningExecutorService executor = parallel
- ? changeUpdateExector
- : MoreExecutors.newDirectExecutorService();
+ ListeningExecutorService executor =
+ parallel ? changeUpdateExector : MoreExecutors.newDirectExecutorService();
tasks = new ArrayList<>(ops.keySet().size());
try {
@@ -782,12 +759,10 @@
logDebug("Failing early due to read-only Changes table");
throw new OrmException(NoteDbUpdateManager.CHANGES_READ_ONLY);
}
- List<ListenableFuture<?>> futures =
- new ArrayList<>(ops.keySet().size());
+ List<ListenableFuture<?>> futures = new ArrayList<>(ops.keySet().size());
for (Map.Entry<Change.Id, Collection<Op>> e : ops.asMap().entrySet()) {
ChangeTask task =
- new ChangeTask(e.getKey(), e.getValue(), Thread.currentThread(),
- dryrun);
+ new ChangeTask(e.getKey(), e.getValue(), Thread.currentThread(), dryrun);
tasks.add(task);
if (!parallel) {
logDebug("Direct execution of task for ops: {}", ops);
@@ -795,8 +770,8 @@
futures.add(executor.submit(task));
}
if (parallel) {
- logDebug("Waiting on futures for {} ops spanning {} changes",
- ops.size(), ops.keySet().size());
+ logDebug(
+ "Waiting on futures for {} ops spanning {} changes", ops.size(), ops.keySet().size());
}
Futures.allAsList(futures).get();
@@ -814,8 +789,7 @@
throw new UpdateException(e);
}
} finally {
- metrics.executeChangeOpsLatency.record(
- success, sw.elapsed(NANOSECONDS), NANOSECONDS);
+ metrics.executeChangeOpsLatency.record(success, sw.elapsed(NANOSECONDS), NANOSECONDS);
}
return tasks;
}
@@ -844,8 +818,7 @@
// updates on the change repo first.
logDebug("Executing NoteDb updates for {} changes", tasks.size());
try {
- BatchRefUpdate changeRefUpdate =
- getRepository().getRefDatabase().newBatchUpdate();
+ BatchRefUpdate changeRefUpdate = getRepository().getRefDatabase().newBatchUpdate();
boolean hasAllUsersCommands = false;
try (ObjectInserter ins = getRepository().newObjectInserter()) {
int objs = 0;
@@ -861,11 +834,12 @@
objs++;
ins.insert(obj.type(), obj.data().toByteArray());
}
- hasAllUsersCommands |=
- !task.noteDbResult.allUsersCommands().isEmpty();
+ hasAllUsersCommands |= !task.noteDbResult.allUsersCommands().isEmpty();
}
- logDebug("Collected {} objects and {} ref updates to change repo",
- objs, changeRefUpdate.getCommands().size());
+ logDebug(
+ "Collected {} objects and {} ref updates to change repo",
+ objs,
+ changeRefUpdate.getCommands().size());
executeNoteDbUpdate(getRevWalk(), ins, changeRefUpdate);
}
@@ -874,8 +848,7 @@
RevWalk allUsersRw = new RevWalk(allUsersRepo);
ObjectInserter allUsersIns = allUsersRepo.newObjectInserter()) {
int objs = 0;
- BatchRefUpdate allUsersRefUpdate =
- allUsersRepo.getRefDatabase().newBatchUpdate();
+ BatchRefUpdate allUsersRefUpdate = allUsersRepo.getRefDatabase().newBatchUpdate();
for (ChangeTask task : tasks) {
for (ReceiveCommand cmd : task.noteDbResult.allUsersCommands()) {
allUsersRefUpdate.addCommand(cmd);
@@ -884,8 +857,10 @@
allUsersIns.insert(obj.type(), obj.data().toByteArray());
}
}
- logDebug("Collected {} objects and {} ref updates to All-Users",
- objs, allUsersRefUpdate.getCommands().size());
+ logDebug(
+ "Collected {} objects and {} ref updates to All-Users",
+ objs,
+ allUsersRefUpdate.getCommands().size());
executeNoteDbUpdate(allUsersRw, allUsersIns, allUsersRefUpdate);
}
} else {
@@ -898,20 +873,18 @@
// if any state is out of date it will be rebuilt the next time it
// is needed.
// Always log even without RequestId.
- log.debug(
- "Ignoring NoteDb update error after ReviewDb write", e);
+ log.debug("Ignoring NoteDb update error after ReviewDb write", e);
} else {
// We can't prove it's safe to ignore the error, either because some
// change had NOTE_DB primary, or a task failed before determining the
// primary storage.
throw e;
}
-
}
}
- private void executeNoteDbUpdate(RevWalk rw, ObjectInserter ins,
- BatchRefUpdate bru) throws IOException {
+ private void executeNoteDbUpdate(RevWalk rw, ObjectInserter ins, BatchRefUpdate bru)
+ throws IOException {
if (bru.getCommands().isEmpty()) {
logDebug("No commands, skipping flush and ref update");
return;
@@ -939,8 +912,7 @@
boolean deleted;
private String taskId;
- private ChangeTask(Change.Id id, Collection<Op> changeOps,
- Thread mainThread, boolean dryrun) {
+ private ChangeTask(Change.Id id, Collection<Op> changeOps, Thread mainThread, boolean dryrun) {
this.id = id;
this.changeOps = changeOps;
this.mainThread = mainThread;
@@ -972,8 +944,7 @@
return null;
}
- private void call(ReviewDb db, Repository repo, RevWalk rw)
- throws Exception {
+ private void call(ReviewDb db, Repository repo, RevWalk rw) throws Exception {
@SuppressWarnings("resource") // Not always opened.
NoteDbUpdateManager updateManager = null;
try {
@@ -984,10 +955,8 @@
NoteDbChangeState.checkNotReadOnly(oldState, skewMs);
storage = PrimaryStorage.of(oldState);
- if (storage == PrimaryStorage.NOTE_DB
- && !notesMigration.readChanges()) {
- throw new OrmException(
- "must have NoteDb enabled to update change " + id);
+ if (storage == PrimaryStorage.NOTE_DB && !notesMigration.readChanges()) {
+ throw new OrmException("must have NoteDb enabled to update change " + id);
}
// Call updateChange on each op.
@@ -1029,8 +998,7 @@
db.commit();
}
} else {
- logDebug(
- "Skipping ReviewDb write since primary storage is {}", storage);
+ logDebug("Skipping ReviewDb write since primary storage is {}", storage);
}
} finally {
db.rollback();
@@ -1054,8 +1022,7 @@
// already written the NoteDbChangeState to ReviewDb, which means
// if the state is out of date it will be rebuilt the next time it
// is needed.
- log.debug(
- "Ignoring NoteDb update error after ReviewDb write", ex);
+ log.debug("Ignoring NoteDb update error after ReviewDb write", ex);
}
}
} catch (Exception e) {
@@ -1069,14 +1036,13 @@
}
}
- private ChangeContext newChangeContext(ReviewDb db, Repository repo,
- RevWalk rw, Change.Id id) throws OrmException {
+ private ChangeContext newChangeContext(ReviewDb db, Repository repo, RevWalk rw, Change.Id id)
+ throws OrmException {
Change c = newChanges.get(id);
boolean isNew = c != null;
if (isNew) {
// New change: populate noteDbState.
- checkState(c.getNoteDbState() == null,
- "noteDbState should not be filled in by callers");
+ checkState(c.getNoteDbState() == null, "noteDbState should not be filled in by callers");
if (notesMigration.changePrimaryStorage() == PrimaryStorage.NOTE_DB) {
c.setNoteDbState(NoteDbChangeState.NOTE_DB_PRIMARY_STATE);
}
@@ -1110,13 +1076,14 @@
return new ChangeContext(ctl, new BatchUpdateReviewDb(db), repo, rw);
}
- private NoteDbUpdateManager stageNoteDbUpdate(ChangeContext ctx,
- boolean deleted) throws OrmException, IOException {
+ private NoteDbUpdateManager stageNoteDbUpdate(ChangeContext ctx, boolean deleted)
+ throws OrmException, IOException {
logDebug("Staging NoteDb update");
- NoteDbUpdateManager updateManager = updateManagerFactory
- .create(ctx.getProject())
- .setChangeRepo(ctx.getRepository(), ctx.getRevWalk(), null,
- new ChainedReceiveCommands(repo));
+ NoteDbUpdateManager updateManager =
+ updateManagerFactory
+ .create(ctx.getProject())
+ .setChangeRepo(
+ ctx.getRepository(), ctx.getRevWalk(), null, new ChainedReceiveCommands(repo));
if (ctx.getUser().isIdentifiedUser()) {
updateManager.setRefLogIdent(
ctx.getUser().asIdentifiedUser().newRefLogIdent(ctx.getWhen(), tz));
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/BatchUpdateReviewDb.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/BatchUpdateReviewDb.java
index 1de98d3..1f476fa 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/BatchUpdateReviewDb.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/BatchUpdateReviewDb.java
@@ -64,7 +64,7 @@
public void upsert(Iterable<Change> instances) {
throw new UnsupportedOperationException(
"do not call upsert; existing changes are updated automatically,"
- + " or use InsertChangeOp for insertion");
+ + " or use InsertChangeOp for insertion");
}
@Override
@@ -75,8 +75,7 @@
@Override
public void beginTransaction(Change.Id key) {
- throw new UnsupportedOperationException(
- "updateChange is always called within a transaction");
+ throw new UnsupportedOperationException("updateChange is always called within a transaction");
}
@Override
@@ -92,11 +91,9 @@
}
@Override
- public Change atomicUpdate(Change.Id key,
- AtomicUpdate<Change> update) {
+ public Change atomicUpdate(Change.Id key, AtomicUpdate<Change> update) {
throw new UnsupportedOperationException(
- "do not call atomicUpdate; updateChange is always called within a"
- + " transaction");
+ "do not call atomicUpdate; updateChange is always called within a" + " transaction");
}
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/BranchOrderSection.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/BranchOrderSection.java
index 0ef9e0c..d4b537e 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/BranchOrderSection.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/BranchOrderSection.java
@@ -16,7 +16,6 @@
import com.google.common.collect.ImmutableList;
import com.google.gerrit.reviewdb.client.RefNames;
-
import java.util.List;
public class BranchOrderSection {
@@ -24,7 +23,7 @@
/**
* Branch names ordered from least to the most stable.
*
- * Typically the order will be like: master, stable-M.N, stable-M.N-1, ...
+ * <p>Typically the order will be like: master, stable-M.N, stable-M.N-1, ...
*/
private final ImmutableList<String> order;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/ChainedReceiveCommands.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/ChainedReceiveCommands.java
index a3b30d1..424f9ed 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/ChainedReceiveCommands.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/ChainedReceiveCommands.java
@@ -17,24 +17,22 @@
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
-import org.eclipse.jgit.lib.BatchRefUpdate;
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.lib.Repository;
-import org.eclipse.jgit.transport.ReceiveCommand;
-
import java.io.IOException;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
+import org.eclipse.jgit.lib.BatchRefUpdate;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.lib.Repository;
+import org.eclipse.jgit.transport.ReceiveCommand;
/**
* Collection of {@link ReceiveCommand}s that supports multiple updates per ref.
- * <p>
- * The underlying behavior of {@link BatchRefUpdate} is undefined (an
- * implementations vary) when more than one command per ref is added. This class
- * works around that limitation by allowing multiple updates per ref, as long as
- * the previous new SHA-1 matches the next old SHA-1.
+ *
+ * <p>The underlying behavior of {@link BatchRefUpdate} is undefined (an implementations vary) when
+ * more than one command per ref is added. This class works around that limitation by allowing
+ * multiple updates per ref, as long as the previous new SHA-1 matches the next old SHA-1.
*/
public class ChainedReceiveCommands implements RefCache {
private final Map<String, ReceiveCommand> commands = new LinkedHashMap<>();
@@ -59,33 +57,36 @@
/**
* Add a command.
*
- * @param cmd command to add. If a command has been previously added for the
- * same ref, the new SHA-1 of the most recent previous command must match
- * the old SHA-1 of this command.
+ * @param cmd command to add. If a command has been previously added for the same ref, the new
+ * SHA-1 of the most recent previous command must match the old SHA-1 of this command.
*/
public void add(ReceiveCommand cmd) {
- checkArgument(!cmd.getOldId().equals(cmd.getNewId()),
- "ref update is a no-op: %s", cmd);
+ checkArgument(!cmd.getOldId().equals(cmd.getNewId()), "ref update is a no-op: %s", cmd);
ReceiveCommand old = commands.get(cmd.getRefName());
if (old == null) {
commands.put(cmd.getRefName(), cmd);
return;
}
- checkArgument(old.getResult() == ReceiveCommand.Result.NOT_ATTEMPTED,
+ checkArgument(
+ old.getResult() == ReceiveCommand.Result.NOT_ATTEMPTED,
"cannot chain ref update %s after update %s with result %s",
- cmd, old, old.getResult());
- checkArgument(cmd.getOldId().equals(old.getNewId()),
+ cmd,
+ old,
+ old.getResult());
+ checkArgument(
+ cmd.getOldId().equals(old.getNewId()),
"cannot chain ref update %s after update %s with different new ID",
- cmd, old);
- commands.put(cmd.getRefName(), new ReceiveCommand(
- old.getOldId(), cmd.getNewId(), cmd.getRefName()));
+ cmd,
+ old);
+ commands.put(
+ cmd.getRefName(), new ReceiveCommand(old.getOldId(), cmd.getNewId(), cmd.getRefName()));
}
/**
* Get the latest value of a ref according to this sequence of commands.
- * <p>
- * After the value for a ref is read from the repo once, it is cached as in
- * {@link RepoRefCache}.
+ *
+ * <p>After the value for a ref is read from the repo once, it is cached as in {@link
+ * RepoRefCache}.
*
* @see RefCache#get(String)
*/
@@ -102,10 +103,10 @@
/**
* Add commands from this instance to a native JGit batch update.
- * <p>
- * Exactly one command per ref will be added to the update. The old SHA-1 will
- * be the old SHA-1 of the first command added to this instance for that ref;
- * the new SHA-1 will be the new SHA-1 of the last command.
+ *
+ * <p>Exactly one command per ref will be added to the update. The old SHA-1 will be the old SHA-1
+ * of the first command added to this instance for that ref; the new SHA-1 will be the new SHA-1
+ * of the last command.
*
* @param bru batch update
*/
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/ChangeAlreadyMergedException.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/ChangeAlreadyMergedException.java
index f2e7f78..0af4b72 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/ChangeAlreadyMergedException.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/ChangeAlreadyMergedException.java
@@ -14,9 +14,7 @@
package com.google.gerrit.server.git;
-/**
- * Indicates that the change or commit is already in the source tree.
- */
+/** Indicates that the change or commit is already in the source tree. */
public class ChangeAlreadyMergedException extends MergeIdenticalTreeException {
private static final long serialVersionUID = 1L;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/ChangeMessageModifier.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/ChangeMessageModifier.java
index 75911f3f..7d4edcf 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/ChangeMessageModifier.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/ChangeMessageModifier.java
@@ -16,15 +16,13 @@
import com.google.gerrit.extensions.annotations.ExtensionPoint;
import com.google.gerrit.reviewdb.client.Branch;
-
import org.eclipse.jgit.revwalk.RevCommit;
/**
- * Allows to modify the commit message for new commits generated by Rebase
- * Always submit strategy.
+ * Allows to modify the commit message for new commits generated by Rebase Always submit strategy.
*
- * Invoked by Gerrit when all information about new commit is already known such
- * as parent(s), tree hash, etc, but commit's message can still be modified.
+ * <p>Invoked by Gerrit when all information about new commit is already known such as parent(s),
+ * tree hash, etc, but commit's message can still be modified.
*/
@ExtensionPoint
public interface ChangeMessageModifier {
@@ -32,22 +30,22 @@
/**
* Implementation must return non-Null commit message.
*
- * mergeTip and original commit are guaranteed to have their body parsed,
- * meaning that their commit messages and footers can be accessed.
+ * <p>mergeTip and original commit are guaranteed to have their body parsed, meaning that their
+ * commit messages and footers can be accessed.
*
* @param newCommitMessage the new commit message that was result of either
- * <ul>
- * <li>{@link MergeUtil#createDetailedCommitMessage} called before</li>
- * <li>other extensions or plugins implementing the same point and
- * called before.</li>
- * </ul>
- * @param original the commit of the change being submitted. <b>Note that its
- * commit message may be different than newCommitMessage argument.</b>
- * @param mergeTip the current HEAD of the destination branch, which will be a
- * parent of a new commit being generated
+ * <ul>
+ * <li>{@link MergeUtil#createDetailedCommitMessage} called before
+ * <li>other extensions or plugins implementing the same point and called before.
+ * </ul>
+ *
+ * @param original the commit of the change being submitted. <b>Note that its commit message may
+ * be different than newCommitMessage argument.</b>
+ * @param mergeTip the current HEAD of the destination branch, which will be a parent of a new
+ * commit being generated
* @param destination the branch onto which the change is being submitted
* @return a new not null commit message.
*/
- String onSubmit(String newCommitMessage, RevCommit original,
- RevCommit mergeTip, Branch.NameKey destination);
+ String onSubmit(
+ String newCommitMessage, RevCommit original, RevCommit mergeTip, Branch.NameKey destination);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/ChangeProgressOp.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/ChangeProgressOp.java
index 370bc2d..9612873 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/ChangeProgressOp.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/ChangeProgressOp.java
@@ -15,7 +15,6 @@
package com.google.gerrit.server.git;
import com.google.gerrit.server.git.BatchUpdate.ChangeContext;
-
import org.eclipse.jgit.lib.ProgressMonitor;
/** Trivial op to update a counter during {@code updateChange} */
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/ChangeSet.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/ChangeSet.java
index 400532d..03d44ca 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/ChangeSet.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/ChangeSet.java
@@ -24,29 +24,26 @@
import com.google.gerrit.reviewdb.client.Change;
import com.google.gerrit.server.query.change.ChangeData;
import com.google.gwtorm.server.OrmException;
-
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* A set of changes grouped together to be submitted atomically.
- * <p>
- * MergeSuperSet constructs ChangeSets to accumulate intermediate
- * results toward the ChangeSet it returns when done.
- * <p>
- * This class is not thread safe.
+ *
+ * <p>MergeSuperSet constructs ChangeSets to accumulate intermediate results toward the ChangeSet it
+ * returns when done.
+ *
+ * <p>This class is not thread safe.
*/
public class ChangeSet {
private final ImmutableMap<Change.Id, ChangeData> changeData;
/**
- * Additional changes not included in changeData because their
- * connection to the original change is not visible to the
- * current user. That is, this map includes both
- * - changes that are not visible to the current user, and
- * - changes whose only relationship to the set is via a change
- * that is not visible to the current user
+ * Additional changes not included in changeData because their connection to the original change
+ * is not visible to the current user. That is, this map includes both - changes that are not
+ * visible to the current user, and - changes whose only relationship to the set is via a change
+ * that is not visible to the current user
*/
private final ImmutableMap<Change.Id, ChangeData> nonVisibleChanges;
@@ -62,14 +59,14 @@
return ImmutableMap.copyOf(ret);
}
- public ChangeSet(
- Iterable<ChangeData> changes, Iterable<ChangeData> hiddenChanges) {
+ public ChangeSet(Iterable<ChangeData> changes, Iterable<ChangeData> hiddenChanges) {
changeData = index(changes, ImmutableList.<Change.Id>of());
nonVisibleChanges = index(hiddenChanges, changeData.keySet());
}
public ChangeSet(ChangeData change, boolean visible) {
- this(visible ? ImmutableList.of(change) : ImmutableList.<ChangeData>of(),
+ this(
+ visible ? ImmutableList.of(change) : ImmutableList.<ChangeData>of(),
ImmutableList.of(change));
}
@@ -81,8 +78,7 @@
return changeData;
}
- public ListMultimap<Branch.NameKey, ChangeData> changesByBranch()
- throws OrmException {
+ public ListMultimap<Branch.NameKey, ChangeData> changesByBranch() throws OrmException {
ListMultimap<Branch.NameKey, ChangeData> ret =
MultimapBuilder.hashKeys().arrayListValues().build();
for (ChangeData cd : changeData.values()) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/ChangeUpdateExecutor.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/ChangeUpdateExecutor.java
index 3452bb0..ace8a38 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/ChangeUpdateExecutor.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/ChangeUpdateExecutor.java
@@ -18,14 +18,12 @@
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.inject.BindingAnnotation;
-
import java.lang.annotation.Retention;
/**
- * Marker on the global {@link ListeningExecutorService} used by
- * {@link ReceiveCommits} to create or replace changes.
+ * Marker on the global {@link ListeningExecutorService} used by {@link ReceiveCommits} to create or
+ * replace changes.
*/
@Retention(RUNTIME)
@BindingAnnotation
-public @interface ChangeUpdateExecutor {
-}
+public @interface ChangeUpdateExecutor {}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/CodeReviewCommit.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/CodeReviewCommit.java
index 6fa3c2a..80c705e 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/CodeReviewCommit.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/CodeReviewCommit.java
@@ -22,7 +22,7 @@
import com.google.gerrit.server.git.strategy.CommitMergeStatus;
import com.google.gerrit.server.notedb.ChangeNotes;
import com.google.gerrit.server.project.ChangeControl;
-
+import java.io.IOException;
import org.eclipse.jgit.errors.IncorrectObjectTypeException;
import org.eclipse.jgit.errors.MissingObjectException;
import org.eclipse.jgit.lib.AnyObjectId;
@@ -31,24 +31,22 @@
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;
-import java.io.IOException;
-
/** Extended commit entity with code review specific metadata. */
public class CodeReviewCommit extends RevCommit {
/**
* Default ordering when merging multiple topologically-equivalent commits.
- * <p>
- * Operates only on these commits and does not take ancestry into account.
- * <p>
- * Use this in preference to the default order, which comes from {@link
- * AnyObjectId} and only orders on SHA-1.
+ *
+ * <p>Operates only on these commits and does not take ancestry into account.
+ *
+ * <p>Use this in preference to the default order, which comes from {@link AnyObjectId} and only
+ * orders on SHA-1.
*/
- public static final Ordering<CodeReviewCommit> ORDER = Ordering.natural()
- .onResultOf((CodeReviewCommit c) ->
- c.getPatchsetId() != null
- ? c.getPatchsetId().getParentKey().get()
- : null)
- .nullsFirst();
+ public static final Ordering<CodeReviewCommit> ORDER =
+ Ordering.natural()
+ .onResultOf(
+ (CodeReviewCommit c) ->
+ c.getPatchsetId() != null ? c.getPatchsetId().getParentKey().get() : null)
+ .nullsFirst();
public static CodeReviewRevWalk newRevWalk(Repository repo) {
return new CodeReviewRevWalk(repo);
@@ -73,22 +71,21 @@
}
@Override
- public CodeReviewCommit next() throws MissingObjectException,
- IncorrectObjectTypeException, IOException {
+ public CodeReviewCommit next()
+ throws MissingObjectException, IncorrectObjectTypeException, IOException {
return (CodeReviewCommit) super.next();
}
@Override
- public void markStart(RevCommit c) throws MissingObjectException,
- IncorrectObjectTypeException, IOException {
+ public void markStart(RevCommit c)
+ throws MissingObjectException, IncorrectObjectTypeException, IOException {
checkArgument(c instanceof CodeReviewCommit);
super.markStart(c);
}
@Override
public void markUninteresting(final RevCommit c)
- throws MissingObjectException, IncorrectObjectTypeException,
- IOException {
+ throws MissingObjectException, IncorrectObjectTypeException, IOException {
checkArgument(c instanceof CodeReviewCommit);
super.markUninteresting(c);
}
@@ -100,17 +97,16 @@
@Override
public CodeReviewCommit parseCommit(AnyObjectId id)
- throws MissingObjectException, IncorrectObjectTypeException,
- IOException {
+ throws MissingObjectException, IncorrectObjectTypeException, IOException {
return (CodeReviewCommit) super.parseCommit(id);
}
}
/**
* Unique key of the PatchSet entity from the code review system.
- * <p>
- * This value is only available on commits that have a PatchSet represented in
- * the code review system.
+ *
+ * <p>This value is only available on commits that have a PatchSet represented in the code review
+ * system.
*/
private PatchSet.Id patchsetId;
@@ -119,8 +115,8 @@
/**
* The result status for this commit.
- * <p>
- * Only valid if {@link #patchsetId} is not null.
+ *
+ * <p>Only valid if {@link #patchsetId} is not null.
*/
private CommitMergeStatus statusCode;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/ConfiguredMimeTypes.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/ConfiguredMimeTypes.java
index 082e1a2..9f77fde 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/ConfiguredMimeTypes.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/ConfiguredMimeTypes.java
@@ -14,22 +14,20 @@
package com.google.gerrit.server.git;
-import org.eclipse.jgit.errors.InvalidPatternException;
-import org.eclipse.jgit.fnmatch.FileNameMatcher;
-import org.eclipse.jgit.lib.Config;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
+import org.eclipse.jgit.errors.InvalidPatternException;
+import org.eclipse.jgit.fnmatch.FileNameMatcher;
+import org.eclipse.jgit.lib.Config;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class ConfiguredMimeTypes {
- private static final Logger log = LoggerFactory
- .getLogger(ConfiguredMimeTypes.class);
+ private static final Logger log = LoggerFactory.getLogger(ConfiguredMimeTypes.class);
private static final String MIMETYPE = "mimetype";
private static final String KEY_PATH = "path";
@@ -47,10 +45,10 @@
try {
add(typeName, path);
} catch (PatternSyntaxException | InvalidPatternException e) {
- log.warn(String.format(
- "Ignoring invalid %s.%s.%s = %s in project %s: %s",
- MIMETYPE, typeName, KEY_PATH,
- path, projectName, e.getMessage()));
+ log.warn(
+ String.format(
+ "Ignoring invalid %s.%s.%s = %s in project %s: %s",
+ MIMETYPE, typeName, KEY_PATH, path, projectName, e.getMessage()));
}
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/DefaultQueueOp.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/DefaultQueueOp.java
index cff69c6..a9c21ff 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/DefaultQueueOp.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/DefaultQueueOp.java
@@ -28,9 +28,7 @@
return workQueue.getDefaultQueue().schedule(this, delay, unit);
}
- public ScheduledFuture<?> startWithFixedDelay(long initialDelay, long delay,
- TimeUnit unit) {
- return workQueue.getDefaultQueue()
- .scheduleWithFixedDelay(this, initialDelay, delay, unit);
+ public ScheduledFuture<?> startWithFixedDelay(long initialDelay, long delay, TimeUnit unit) {
+ return workQueue.getDefaultQueue().scheduleWithFixedDelay(this, initialDelay, delay, unit);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/DestinationList.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/DestinationList.java
index c4d4d61..eacf66e 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/DestinationList.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/DestinationList.java
@@ -20,7 +20,6 @@
import com.google.common.collect.Sets;
import com.google.gerrit.reviewdb.client.Branch;
import com.google.gerrit.reviewdb.client.Project;
-
import java.io.IOException;
import java.util.List;
import java.util.Set;
@@ -34,10 +33,9 @@
return destinations.get(label);
}
- public void parseLabel(String label, String text,
- ValidationError.Sink errors) throws IOException {
- destinations.replaceValues(label,
- toSet(parse(text, DIR_NAME + label, TRIM, null, errors)));
+ public void parseLabel(String label, String text, ValidationError.Sink errors)
+ throws IOException {
+ destinations.replaceValues(label, toSet(parse(text, DIR_NAME + label, TRIM, null, errors)));
}
public String asText(String label) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/EmailMerge.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/EmailMerge.java
index 1da5257..e80bbd8 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/EmailMerge.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/EmailMerge.java
@@ -34,18 +34,19 @@
import com.google.inject.Provider;
import com.google.inject.ProvisionException;
import com.google.inject.assistedinject.Assisted;
-
+import java.util.concurrent.ExecutorService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.util.concurrent.ExecutorService;
-
public class EmailMerge implements Runnable, RequestContext {
private static final Logger log = LoggerFactory.getLogger(EmailMerge.class);
public interface Factory {
- EmailMerge create(Project.NameKey project, Change.Id changeId,
- Account.Id submitter, NotifyHandling notifyHandling,
+ EmailMerge create(
+ Project.NameKey project,
+ Change.Id changeId,
+ Account.Id submitter,
+ NotifyHandling notifyHandling,
ListMultimap<RecipientType, Account.Id> accountsToNotify);
}
@@ -64,7 +65,8 @@
private ReviewDb db;
@Inject
- EmailMerge(@SendEmailExecutor ExecutorService executor,
+ EmailMerge(
+ @SendEmailExecutor ExecutorService executor,
MergedSender.Factory mergedSenderFactory,
SchemaFactory<ReviewDb> schemaFactory,
ThreadLocalRequestContext requestContext,
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/GarbageCollection.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/GarbageCollection.java
index 5bb4dfd..33c31fd 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/GarbageCollection.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/GarbageCollection.java
@@ -22,7 +22,10 @@
import com.google.gerrit.server.config.GcConfig;
import com.google.gerrit.server.extensions.events.AbstractNoNotifyEvent;
import com.google.inject.Inject;
-
+import java.io.PrintWriter;
+import java.util.List;
+import java.util.Properties;
+import java.util.Set;
import org.eclipse.jgit.api.GarbageCollectCommand;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
@@ -35,19 +38,12 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.PrintWriter;
-import java.util.List;
-import java.util.Properties;
-import java.util.Set;
-
public class GarbageCollection {
- private static final Logger log = LoggerFactory
- .getLogger(GarbageCollection.class);
+ private static final Logger log = LoggerFactory.getLogger(GarbageCollection.class);
public static final String LOG_NAME = "gc_log";
private static final Logger gcLog = LoggerFactory.getLogger(LOG_NAME);
-
private final GitRepositoryManager repoManager;
private final GarbageCollectionQueue gcQueue;
private final GcConfig gcConfig;
@@ -58,8 +54,10 @@
}
@Inject
- GarbageCollection(GitRepositoryManager repoManager,
- GarbageCollectionQueue gcQueue, GcConfig config,
+ GarbageCollection(
+ GitRepositoryManager repoManager,
+ GarbageCollectionQueue gcQueue,
+ GcConfig config,
DynamicSet<GarbageCollectorListener> listeners) {
this.repoManager = repoManager;
this.gcQueue = gcQueue;
@@ -71,19 +69,19 @@
return run(projectNames, null);
}
- public GarbageCollectionResult run(List<Project.NameKey> projectNames,
- PrintWriter writer) {
+ public GarbageCollectionResult run(List<Project.NameKey> projectNames, PrintWriter writer) {
return run(projectNames, gcConfig.isAggressive(), writer);
}
- public GarbageCollectionResult run(List<Project.NameKey> projectNames,
- boolean aggressive, PrintWriter writer) {
+ public GarbageCollectionResult run(
+ List<Project.NameKey> projectNames, boolean aggressive, PrintWriter writer) {
GarbageCollectionResult result = new GarbageCollectionResult();
Set<Project.NameKey> projectsToGc = gcQueue.addAll(projectNames);
- for (Project.NameKey projectName : Sets.difference(
- Sets.newHashSet(projectNames), projectsToGc)) {
- result.addError(new GarbageCollectionResult.Error(
- GarbageCollectionResult.Error.Type.GC_ALREADY_SCHEDULED, projectName));
+ for (Project.NameKey projectName :
+ Sets.difference(Sets.newHashSet(projectNames), projectsToGc)) {
+ result.addError(
+ new GarbageCollectionResult.Error(
+ GarbageCollectionResult.Error.Type.GC_ALREADY_SCHEDULED, projectName));
}
for (Project.NameKey p : projectsToGc) {
try (Repository repo = repoManager.openRepository(p)) {
@@ -92,21 +90,21 @@
GarbageCollectCommand gc = Git.wrap(repo).gc();
gc.setAggressive(aggressive);
logGcInfo(p, "before:", gc.getStatistics());
- gc.setProgressMonitor(writer != null ? new TextProgressMonitor(writer)
- : NullProgressMonitor.INSTANCE);
+ gc.setProgressMonitor(
+ writer != null ? new TextProgressMonitor(writer) : NullProgressMonitor.INSTANCE);
Properties statistics = gc.call();
logGcInfo(p, "after: ", statistics);
print(writer, "done.\n\n");
fire(p, statistics);
} catch (RepositoryNotFoundException e) {
logGcError(writer, p, e);
- result.addError(new GarbageCollectionResult.Error(
- GarbageCollectionResult.Error.Type.REPOSITORY_NOT_FOUND,
- p));
+ result.addError(
+ new GarbageCollectionResult.Error(
+ GarbageCollectionResult.Error.Type.REPOSITORY_NOT_FOUND, p));
} catch (Exception e) {
logGcError(writer, p, e);
- result.addError(new GarbageCollectionResult.Error(
- GarbageCollectionResult.Error.Type.GC_FAILED, p));
+ result.addError(
+ new GarbageCollectionResult.Error(GarbageCollectionResult.Error.Type.GC_FAILED, p));
} finally {
gcQueue.gcFinished(p);
}
@@ -132,8 +130,7 @@
logGcInfo(projectName, msg, null);
}
- private static void logGcInfo(Project.NameKey projectName, String msg,
- Properties statistics) {
+ private static void logGcInfo(Project.NameKey projectName, String msg, Properties statistics) {
StringBuilder b = new StringBuilder();
b.append("[").append(projectName.get()).append("] ");
b.append(msg);
@@ -148,15 +145,14 @@
gcLog.info(b.toString());
}
- private static void logGcConfiguration(Project.NameKey projectName,
- Repository repo, boolean aggressive) {
+ private static void logGcConfiguration(
+ Project.NameKey projectName, Repository repo, boolean aggressive) {
StringBuilder b = new StringBuilder();
Config cfg = repo.getConfig();
b.append("gc.aggressive=").append(aggressive).append("; ");
b.append(formatConfigValues(cfg, ConfigConstants.CONFIG_GC_SECTION, null));
for (String subsection : cfg.getSubsections(ConfigConstants.CONFIG_GC_SECTION)) {
- b.append(formatConfigValues(cfg, ConfigConstants.CONFIG_GC_SECTION,
- subsection));
+ b.append(formatConfigValues(cfg, ConfigConstants.CONFIG_GC_SECTION, subsection));
}
if (b.length() == 0) {
b.append("no set");
@@ -166,8 +162,7 @@
logGcInfo(projectName, "pack config: " + (new PackConfig(repo)).toString());
}
- private static String formatConfigValues(Config config, String section,
- String subsection) {
+ private static String formatConfigValues(Config config, String section, String subsection) {
StringBuilder b = new StringBuilder();
Set<String> names = config.getNames(section, subsection);
for (String name : names) {
@@ -183,8 +178,7 @@
return b.toString();
}
- private static void logGcError(PrintWriter writer,
- Project.NameKey projectName, Exception e) {
+ private static void logGcError(PrintWriter writer, Project.NameKey projectName, Exception e) {
print(writer, "failed.\n\n");
StringBuilder b = new StringBuilder();
b.append("[").append(projectName.get()).append("]");
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/GarbageCollectionLogFile.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/GarbageCollectionLogFile.java
index b2a4311..e1f0594 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/GarbageCollectionLogFile.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/GarbageCollectionLogFile.java
@@ -18,13 +18,11 @@
import com.google.gerrit.server.config.SitePaths;
import com.google.gerrit.server.util.SystemLog;
import com.google.inject.Inject;
-
+import java.nio.file.Path;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
-import java.nio.file.Path;
-
public class GarbageCollectionLogFile implements LifecycleListener {
@Inject
@@ -35,8 +33,7 @@
}
@Override
- public void start() {
- }
+ public void start() {}
@Override
public void stop() {
@@ -46,8 +43,9 @@
private static void initLogSystem(Path logdir) {
Logger gcLogger = LogManager.getLogger(GarbageCollection.LOG_NAME);
gcLogger.removeAllAppenders();
- gcLogger.addAppender(SystemLog.createAppender(logdir,
- GarbageCollection.LOG_NAME, new PatternLayout("[%d] %-5p %x: %m%n")));
+ gcLogger.addAppender(
+ SystemLog.createAppender(
+ logdir, GarbageCollection.LOG_NAME, new PatternLayout("[%d] %-5p %x: %m%n")));
gcLogger.setAdditivity(false);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/GarbageCollectionQueue.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/GarbageCollectionQueue.java
index 90e2aac..31cd880 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/GarbageCollectionQueue.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/GarbageCollectionQueue.java
@@ -17,7 +17,6 @@
import com.google.common.collect.Sets;
import com.google.gerrit.reviewdb.client.Project;
import com.google.inject.Singleton;
-
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
@@ -27,8 +26,7 @@
private final Set<Project.NameKey> projectsScheduledForGc = new HashSet<>();
public synchronized Set<Project.NameKey> addAll(Collection<Project.NameKey> projects) {
- Set<Project.NameKey> added =
- Sets.newLinkedHashSetWithExpectedSize(projects.size());
+ Set<Project.NameKey> added = Sets.newLinkedHashSetWithExpectedSize(projects.size());
for (Project.NameKey p : projects) {
if (projectsScheduledForGc.add(p)) {
added.add(p);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/GarbageCollectionRunner.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/GarbageCollectionRunner.java
index e01924e..eba5177 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/GarbageCollectionRunner.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/GarbageCollectionRunner.java
@@ -22,16 +22,13 @@
import com.google.gerrit.server.config.ScheduleConfig;
import com.google.gerrit.server.project.ProjectCache;
import com.google.inject.Inject;
-
+import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.util.concurrent.TimeUnit;
-
/** Runnable to enable scheduling gc to run periodically */
public class GarbageCollectionRunner implements Runnable {
- private static final Logger gcLog = LoggerFactory
- .getLogger(GarbageCollection.LOG_NAME);
+ private static final Logger gcLog = LoggerFactory.getLogger(GarbageCollection.LOG_NAME);
static class Lifecycle implements LifecycleListener {
private final WorkQueue queue;
@@ -39,8 +36,7 @@
private final GcConfig gcConfig;
@Inject
- Lifecycle(WorkQueue queue, GarbageCollectionRunner gcRunner,
- GcConfig config) {
+ Lifecycle(WorkQueue queue, GarbageCollectionRunner gcRunner, GcConfig config) {
this.queue = queue;
this.gcRunner = gcRunner;
this.gcConfig = config;
@@ -54,11 +50,11 @@
if (delay == MISSING_CONFIG && interval == MISSING_CONFIG) {
gcLog.info("Ignoring missing gc schedule configuration");
} else if (delay < 0 || interval <= 0) {
- gcLog.warn(String.format(
- "Ignoring invalid gc schedule configuration: %s", scheduleConfig));
+ gcLog.warn(String.format("Ignoring invalid gc schedule configuration: %s", scheduleConfig));
} else {
- queue.getDefaultQueue().scheduleAtFixedRate(gcRunner, delay,
- interval, TimeUnit.MILLISECONDS);
+ queue
+ .getDefaultQueue()
+ .scheduleAtFixedRate(gcRunner, delay, interval, TimeUnit.MILLISECONDS);
}
}
@@ -72,8 +68,8 @@
private final ProjectCache projectCache;
@Inject
- GarbageCollectionRunner(GarbageCollection.Factory garbageCollectionFactory,
- ProjectCache projectCache) {
+ GarbageCollectionRunner(
+ GarbageCollection.Factory garbageCollectionFactory, ProjectCache projectCache) {
this.garbageCollectionFactory = garbageCollectionFactory;
this.projectCache = projectCache;
}
@@ -81,8 +77,7 @@
@Override
public void run() {
gcLog.info("Triggering gc on all repositories");
- garbageCollectionFactory.create().run(
- Lists.newArrayList(projectCache.all()));
+ garbageCollectionFactory.create().run(Lists.newArrayList(projectCache.all()));
}
@Override
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/GitModule.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/GitModule.java
index e609d68..36805d6 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/GitModule.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/GitModule.java
@@ -16,7 +16,6 @@
import com.google.gerrit.extensions.config.FactoryModule;
import com.google.gerrit.extensions.registration.DynamicSet;
-
import org.eclipse.jgit.transport.PostUploadHook;
/** Configures the Git support. */
@@ -27,7 +26,6 @@
factory(MetaDataUpdate.InternalFactory.class);
bind(MetaDataUpdate.Server.class);
bind(ReceiveConfig.class);
- DynamicSet.bind(binder(), PostUploadHook.class)
- .to(UploadPackMetricsHook.class);
+ DynamicSet.bind(binder(), PostUploadHook.class).to(UploadPackMetricsHook.class);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/GitModules.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/GitModules.java
index 192691d..1c74984 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/GitModules.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/GitModules.java
@@ -25,7 +25,11 @@
import com.google.gerrit.server.util.SubmoduleSectionParser;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
-
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Set;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.lib.BlobBasedConfig;
import org.eclipse.jgit.lib.FileMode;
@@ -35,15 +39,9 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Set;
-
/**
- * Loads the .gitmodules file of the specified project/branch.
- * It can be queried which submodules this branch is subscribed to.
+ * Loads the .gitmodules file of the specified project/branch. It can be queried which submodules
+ * this branch is subscribed to.
*/
public class GitModules {
private static final Logger log = LoggerFactory.getLogger(GitModules.class);
@@ -61,7 +59,8 @@
GitModules(
@CanonicalWebUrl @Nullable String canonicalWebUrl,
@Assisted Branch.NameKey branch,
- @Assisted MergeOpRepoManager orm) throws IOException {
+ @Assisted MergeOpRepoManager orm)
+ throws IOException {
this.submissionId = orm.getSubmissionId();
Project.NameKey project = branch.getParentKey();
logDebug("Loading .gitmodules of {} for project {}", branch, project);
@@ -74,10 +73,8 @@
}
RevCommit commit = or.rw.parseCommit(id);
- try (TreeWalk tw =
- TreeWalk.forPath(or.repo, GIT_MODULES, commit.getTree())) {
- if (tw == null
- || (tw.getRawMode(0) & FileMode.TYPE_MASK) != FileMode.TYPE_FILE) {
+ try (TreeWalk tw = TreeWalk.forPath(or.repo, GIT_MODULES, commit.getTree())) {
+ if (tw == null || (tw.getRawMode(0) & FileMode.TYPE_MASK) != FileMode.TYPE_FILE) {
subscriptions = Collections.emptySet();
logDebug("The .gitmodules file doesn't exist in " + branch);
return;
@@ -87,11 +84,10 @@
try {
bbc = new BlobBasedConfig(null, or.repo, commit, GIT_MODULES);
} catch (ConfigInvalidException e) {
- throw new IOException("Could not read .gitmodules of super project: " +
- branch.getParentKey(), e);
+ throw new IOException(
+ "Could not read .gitmodules of super project: " + branch.getParentKey(), e);
}
- subscriptions = new SubmoduleSectionParser(bbc, canonicalWebUrl,
- branch).parseAllSections();
+ subscriptions = new SubmoduleSectionParser(bbc, canonicalWebUrl, branch).parseAllSections();
} catch (NoSuchProjectException e) {
throw new IOException(e);
} finally {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/GitRepositoryManager.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/GitRepositoryManager.java
index 1724808..f8d8a49 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/GitRepositoryManager.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/GitRepositoryManager.java
@@ -17,19 +17,16 @@
import com.google.gerrit.reviewdb.client.Project;
import com.google.inject.ImplementedBy;
import com.google.inject.Singleton;
-
+import java.io.IOException;
+import java.util.SortedSet;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
import org.eclipse.jgit.lib.Repository;
-import java.io.IOException;
-import java.util.SortedSet;
-
/**
* Manages Git repositories for the Gerrit server process.
- * <p>
- * Implementations of this interface should be a {@link Singleton} and
- * registered in Guice so they are globally available within the server
- * environment.
+ *
+ * <p>Implementations of this interface should be a {@link Singleton} and registered in Guice so
+ * they are globally available within the server environment.
*/
@ImplementedBy(value = LocalDiskRepositoryManager.class)
public interface GitRepositoryManager {
@@ -37,29 +34,26 @@
* Get (or open) a repository by name.
*
* @param name the repository name, relative to the base directory.
- * @return the cached Repository instance. Caller must call {@code close()}
- * when done to decrement the resource handle.
- * @throws RepositoryNotFoundException the name does not denote an existing
- * repository.
+ * @return the cached Repository instance. Caller must call {@code close()} when done to decrement
+ * the resource handle.
+ * @throws RepositoryNotFoundException the name does not denote an existing repository.
* @throws IOException the name cannot be read as a repository.
*/
- Repository openRepository(Project.NameKey name)
- throws RepositoryNotFoundException, IOException;
+ Repository openRepository(Project.NameKey name) throws RepositoryNotFoundException, IOException;
/**
* Create (and open) a repository by name.
*
* @param name the repository name, relative to the base directory.
- * @return the cached Repository instance. Caller must call {@code close()}
- * when done to decrement the resource handle.
- * @throws RepositoryCaseMismatchException the name collides with an existing
- * repository name, but only in case of a character within the name.
+ * @return the cached Repository instance. Caller must call {@code close()} when done to decrement
+ * the resource handle.
+ * @throws RepositoryCaseMismatchException the name collides with an existing repository name, but
+ * only in case of a character within the name.
* @throws RepositoryNotFoundException the name is invalid.
* @throws IOException the repository cannot be created.
*/
Repository createRepository(Project.NameKey name)
- throws RepositoryCaseMismatchException, RepositoryNotFoundException,
- IOException;
+ throws RepositoryCaseMismatchException, RepositoryNotFoundException, IOException;
/** @return set of all known projects, sorted by natural NameKey order. */
SortedSet<Project.NameKey> list();
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/GroupCollector.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/GroupCollector.java
index 0ac39ad..960c72a 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/GroupCollector.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/GroupCollector.java
@@ -34,13 +34,6 @@
import com.google.gerrit.server.change.RevisionResource;
import com.google.gerrit.server.notedb.ChangeNotes;
import com.google.gwtorm.server.OrmException;
-
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.lib.Ref;
-import org.eclipse.jgit.revwalk.RevCommit;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.util.ArrayDeque;
import java.util.Collection;
import java.util.Deque;
@@ -48,38 +41,41 @@
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.lib.Ref;
+import org.eclipse.jgit.revwalk.RevCommit;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* Helper for assigning groups to commits during {@link ReceiveCommits}.
- * <p>
- * For each commit encountered along a walk between the branch tip and the tip
- * of the push, the group of a commit is defined as follows:
+ *
+ * <p>For each commit encountered along a walk between the branch tip and the tip of the push, the
+ * group of a commit is defined as follows:
+ *
* <ul>
- * <li>If the commit is an existing patch set of a change, the group is read
- * from the group field in the corresponding {@link PatchSet} record.</li>
- * <li>If all of a commit's parents are merged into the branch, then its group
- * is its own SHA-1.</li>
- * <li>If the commit has a single parent that is not yet merged into the
- * branch, then its group is the same as the parent's group.<li>
- * <li>For a merge commit, choose a parent and use that parent's group. If one
- * of the parents has a group from a patch set, use that group, otherwise, use
- * the group from the first parent. In addition to setting this merge commit's
- * group, use the chosen group for all commits that would otherwise use a
- * group from the parents that were not chosen.</li>
- * <li>If a merge commit has multiple parents whose group comes from separate
- * patch sets, concatenate the groups from those parents together. This
- * indicates two side branches were pushed separately, followed by the merge.
+ * <li>If the commit is an existing patch set of a change, the group is read from the group field
+ * in the corresponding {@link PatchSet} record.
+ * <li>If all of a commit's parents are merged into the branch, then its group is its own SHA-1.
+ * <li>If the commit has a single parent that is not yet merged into the branch, then its group is
+ * the same as the parent's group.
+ * <li>
+ * <li>For a merge commit, choose a parent and use that parent's group. If one of the parents has
+ * a group from a patch set, use that group, otherwise, use the group from the first parent.
+ * In addition to setting this merge commit's group, use the chosen group for all commits that
+ * would otherwise use a group from the parents that were not chosen.
+ * <li>If a merge commit has multiple parents whose group comes from separate patch sets,
+ * concatenate the groups from those parents together. This indicates two side branches were
+ * pushed separately, followed by the merge.
* <li>
* </ul>
- * <p>
- * Callers must call {@link #visit(RevCommit)} on all commits between the
- * current branch tip and the tip of a push, in reverse topo order (parents
- * before children). Once all commits have been visited, call {@link
- * #getGroups()} for the result.
+ *
+ * <p>Callers must call {@link #visit(RevCommit)} on all commits between the current branch tip and
+ * the tip of a push, in reverse topo order (parents before children). Once all commits have been
+ * visited, call {@link #getGroups()} for the result.
*/
public class GroupCollector {
- private static final Logger log =
- LoggerFactory.getLogger(GroupCollector.class);
+ private static final Logger log = LoggerFactory.getLogger(GroupCollector.class);
public static List<String> getDefaultGroups(PatchSet ps) {
return ImmutableList.of(ps.getRevision().get());
@@ -109,8 +105,11 @@
private boolean done;
- public static GroupCollector create(ListMultimap<ObjectId, Ref> changeRefsById,
- ReviewDb db, PatchSetUtil psUtil, ChangeNotes.Factory notesFactory,
+ public static GroupCollector create(
+ ListMultimap<ObjectId, Ref> changeRefsById,
+ ReviewDb db,
+ PatchSetUtil psUtil,
+ ChangeNotes.Factory notesFactory,
Project.NameKey project) {
return new GroupCollector(
transformRefs(changeRefsById),
@@ -118,8 +117,7 @@
@Override
public List<String> lookup(PatchSet.Id psId) throws OrmException {
// TODO(dborowitz): Reuse open repository from caller.
- ChangeNotes notes =
- notesFactory.createChecked(db, project, psId.getParentKey());
+ ChangeNotes notes = notesFactory.createChecked(db, project, psId.getParentKey());
PatchSet ps = psUtil.get(db, notes, psId);
return ps != null ? ps.getGroups() : null;
}
@@ -139,9 +137,7 @@
});
}
- private GroupCollector(
- ListMultimap<ObjectId, PatchSet.Id> patchSetsBySha,
- Lookup groupLookup) {
+ private GroupCollector(ListMultimap<ObjectId, PatchSet.Id> patchSetsBySha, Lookup groupLookup) {
this.patchSetsBySha = patchSetsBySha;
this.groupLookup = groupLookup;
groups = MultimapBuilder.hashKeys().arrayListValues().build();
@@ -150,8 +146,7 @@
private static ListMultimap<ObjectId, PatchSet.Id> transformRefs(
ListMultimap<ObjectId, Ref> refs) {
- return Multimaps.transformValues(
- refs, r -> PatchSet.Id.fromRef(r.getName()));
+ return Multimaps.transformValues(refs, r -> PatchSet.Id.fromRef(r.getName()));
}
@VisibleForTesting
@@ -195,8 +190,8 @@
for (RevCommit p : interestingParents) {
Collection<String> parentGroups = groups.get(p);
if (parentGroups.isEmpty()) {
- throw new IllegalStateException(String.format(
- "no group assigned to parent %s of commit %s", p.name(), c.name()));
+ throw new IllegalStateException(
+ String.format("no group assigned to parent %s of commit %s", p.name(), c.name()));
}
for (String parentGroup : parentGroups) {
@@ -231,12 +226,9 @@
public SortedSetMultimap<ObjectId, String> getGroups() throws OrmException {
done = true;
- SortedSetMultimap<ObjectId, String> result = MultimapBuilder
- .hashKeys(groups.keySet().size())
- .treeSetValues()
- .build();
- for (Map.Entry<ObjectId, Collection<String>> e
- : groups.asMap().entrySet()) {
+ SortedSetMultimap<ObjectId, String> result =
+ MultimapBuilder.hashKeys(groups.keySet().size()).treeSetValues().build();
+ for (Map.Entry<ObjectId, Collection<String>> e : groups.asMap().entrySet()) {
ObjectId id = e.getKey();
result.putAll(id.copy(), resolveGroups(id, e.getValue()));
}
@@ -244,8 +236,7 @@
}
private Set<RevCommit> getInterestingParents(RevCommit commit) {
- Set<RevCommit> result =
- Sets.newLinkedHashSetWithExpectedSize(commit.getParentCount());
+ Set<RevCommit> result = Sets.newLinkedHashSetWithExpectedSize(commit.getParentCount());
for (RevCommit p : commit.getParents()) {
if (!p.has(UNINTERESTING)) {
result.add(p);
@@ -259,8 +250,8 @@
return id != null && patchSetsBySha.containsKey(id);
}
- private Set<String> resolveGroups(ObjectId forCommit,
- Collection<String> candidates) throws OrmException {
+ private Set<String> resolveGroups(ObjectId forCommit, Collection<String> candidates)
+ throws OrmException {
Set<String> actual = Sets.newTreeSet();
Set<String> done = Sets.newHashSetWithExpectedSize(candidates.size());
Set<String> seen = Sets.newHashSetWithExpectedSize(candidates.size());
@@ -290,14 +281,12 @@
return ObjectId.fromString(group);
} catch (IllegalArgumentException e) {
// Shouldn't happen; some sort of corruption or manual tinkering?
- log.warn("group for commit {} is not a SHA-1: {}",
- forCommit.name(), group);
+ log.warn("group for commit {} is not a SHA-1: {}", forCommit.name(), group);
return null;
}
}
- private Iterable<String> resolveGroup(ObjectId forCommit, String group)
- throws OrmException {
+ private Iterable<String> resolveGroup(ObjectId forCommit, String group) throws OrmException {
ObjectId id = parseGroup(forCommit, group);
if (id != null) {
PatchSet.Id psId = Iterables.getFirst(patchSetsBySha.get(id), null);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/GroupList.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/GroupList.java
index 880fc0b..5791843 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/GroupList.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/GroupList.java
@@ -17,10 +17,6 @@
import com.google.gerrit.common.data.GroupReference;
import com.google.gerrit.reviewdb.client.AccountGroup;
import com.google.gerrit.reviewdb.client.Project;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
@@ -28,6 +24,8 @@
import java.util.List;
import java.util.Map;
import java.util.Set;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class GroupList extends TabFile {
private static final Logger log = LoggerFactory.getLogger(GroupList.class);
@@ -40,11 +38,10 @@
this.byUUID = byUUID;
}
- public static GroupList parse(Project.NameKey project, String text,
- ValidationError.Sink errors) throws IOException {
+ public static GroupList parse(Project.NameKey project, String text, ValidationError.Sink errors)
+ throws IOException {
List<Row> rows = parse(text, FILE_NAME, TRIM, TRIM, errors);
- Map<AccountGroup.UUID, GroupReference> groupsByUUID =
- new HashMap<>(rows.size());
+ Map<AccountGroup.UUID, GroupReference> groupsByUUID = new HashMap<>(rows.size());
for (Row row : rows) {
if (row.left == null) {
log.warn("null field in group list for {}:\n{}", project, text);
@@ -115,5 +112,4 @@
public void retainUUIDs(Collection<AccountGroup.UUID> toBeRetained) {
byUUID.keySet().retainAll(toBeRetained);
}
-
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/HackPushNegotiateHook.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/HackPushNegotiateHook.java
index 8080419..0011994 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/HackPushNegotiateHook.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/HackPushNegotiateHook.java
@@ -17,7 +17,11 @@
import static org.eclipse.jgit.lib.RefDatabase.ALL;
import com.google.common.collect.Sets;
-
+import java.io.IOException;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Map;
+import java.util.Set;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Ref;
@@ -30,43 +34,32 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Map;
-import java.util.Set;
-
/**
* Advertises part of history to git push clients.
- * <p>
- * This is a hack to work around the lack of negotiation in the
- * send-pack/receive-pack wire protocol.
- * <p>
- * When the server is frequently advancing master by creating merge commits, the
- * client may not be able to discover a common ancestor during push. Attempting
- * to push will re-upload a very large amount of history. This hook hacks in a
- * fake negotiation replacement by walking history and sending recent commits as
- * {@code ".have"} lines in the wire protocol, allowing the client to find a
- * common ancestor.
+ *
+ * <p>This is a hack to work around the lack of negotiation in the send-pack/receive-pack wire
+ * protocol.
+ *
+ * <p>When the server is frequently advancing master by creating merge commits, the client may not
+ * be able to discover a common ancestor during push. Attempting to push will re-upload a very large
+ * amount of history. This hook hacks in a fake negotiation replacement by walking history and
+ * sending recent commits as {@code ".have"} lines in the wire protocol, allowing the client to find
+ * a common ancestor.
*/
public class HackPushNegotiateHook implements AdvertiseRefsHook {
- private static final Logger log = LoggerFactory
- .getLogger(HackPushNegotiateHook.class);
+ private static final Logger log = LoggerFactory.getLogger(HackPushNegotiateHook.class);
/** Size of an additional ".have" line. */
- private static final int HAVE_LINE_LEN = 4
- + Constants.OBJECT_ID_STRING_LENGTH
- + 1 + 5 + 1;
+ private static final int HAVE_LINE_LEN = 4 + Constants.OBJECT_ID_STRING_LENGTH + 1 + 5 + 1;
/**
- * Maximum number of bytes to "waste" in the advertisement with a peek at this
- * repository's current reachable history.
+ * Maximum number of bytes to "waste" in the advertisement with a peek at this repository's
+ * current reachable history.
*/
private static final int MAX_EXTRA_BYTES = 8192;
/**
- * Number of recent commits to advertise immediately, hoping to show a client
- * a nearby merge base.
+ * Number of recent commits to advertise immediately, hoping to show a client a nearby merge base.
*/
private static final int BASE_COMMITS = 64;
@@ -78,13 +71,11 @@
@Override
public void advertiseRefs(UploadPack us) {
- throw new UnsupportedOperationException(
- "HackPushNegotiateHook cannot be used for UploadPack");
+ throw new UnsupportedOperationException("HackPushNegotiateHook cannot be used for UploadPack");
}
@Override
- public void advertiseRefs(BaseReceivePack rp)
- throws ServiceMayNotContinueException {
+ public void advertiseRefs(BaseReceivePack rp) throws ServiceMayNotContinueException {
Map<String, Ref> r = rp.getAdvertisedRefs();
if (r == null) {
try {
@@ -128,7 +119,7 @@
Set<ObjectId> history = Sets.newHashSetWithExpectedSize(max);
try {
int stepCnt = 0;
- for (RevCommit c; history.size() < max && (c = rw.next()) != null;) {
+ for (RevCommit c; history.size() < max && (c = rw.next()) != null; ) {
if (c.getParentCount() <= 1
&& !alreadySending.contains(c)
&& (history.size() < BASE_COMMITS || (++stepCnt % STEP_COMMITS) == 0)) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/InMemoryInserter.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/InMemoryInserter.java
index a70c235..9c43bdb 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/InMemoryInserter.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/InMemoryInserter.java
@@ -17,7 +17,13 @@
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.collect.ImmutableList;
-
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Set;
import org.eclipse.jgit.errors.IncorrectObjectTypeException;
import org.eclipse.jgit.lib.AbbreviatedObjectId;
import org.eclipse.jgit.lib.AnyObjectId;
@@ -28,14 +34,6 @@
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.transport.PackParser;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.LinkedHashMap;
-import java.util.Map;
-import java.util.Set;
-
public class InMemoryInserter extends ObjectInserter {
private final ObjectReader reader;
private final Map<ObjectId, InsertedObject> inserted = new LinkedHashMap<>();
@@ -52,8 +50,7 @@
}
@Override
- public ObjectId insert(int type, long length, InputStream in)
- throws IOException {
+ public ObjectId insert(int type, long length, InputStream in) throws IOException {
return insert(InsertedObject.create(type, in));
}
@@ -109,8 +106,7 @@
}
@Override
- public Collection<ObjectId> resolve(AbbreviatedObjectId id)
- throws IOException {
+ public Collection<ObjectId> resolve(AbbreviatedObjectId id) throws IOException {
Set<ObjectId> result = new HashSet<>();
for (ObjectId insId : inserted.keySet()) {
if (id.prefixCompare(insId) == 0) {
@@ -122,8 +118,7 @@
}
@Override
- public ObjectLoader open(AnyObjectId objectId, int typeHint)
- throws IOException {
+ public ObjectLoader open(AnyObjectId objectId, int typeHint) throws IOException {
InsertedObject obj = inserted.get(objectId);
if (obj == null) {
return reader.open(objectId, typeHint);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/InsertedObject.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/InsertedObject.java
index 1aee14f..8a766af 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/InsertedObject.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/InsertedObject.java
@@ -16,14 +16,12 @@
import com.google.auto.value.AutoValue;
import com.google.protobuf.ByteString;
-
+import java.io.IOException;
+import java.io.InputStream;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.ObjectInserter;
import org.eclipse.jgit.lib.ObjectLoader;
-import java.io.IOException;
-import java.io.InputStream;
-
@AutoValue
public abstract class InsertedObject {
static InsertedObject create(int type, InputStream in) throws IOException {
@@ -45,7 +43,9 @@
}
public abstract ObjectId id();
+
public abstract int type();
+
public abstract ByteString data();
ObjectLoader newLoader() {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/LabelNormalizer.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/LabelNormalizer.java
index 7832e0b..6a05d22 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/LabelNormalizer.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/LabelNormalizer.java
@@ -36,18 +36,16 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.util.Collection;
import java.util.List;
/**
* Normalizes votes on labels according to project config and permissions.
- * <p>
- * Votes are recorded in the database for a user based on the state of the
- * project at that time: what labels are defined for the project, and what the
- * user is allowed to vote on. Both of those can change between the time a vote
- * is originally made and a later point, for example when a change is submitted.
- * This class normalizes old votes against current project configuration.
+ *
+ * <p>Votes are recorded in the database for a user based on the state of the project at that time:
+ * what labels are defined for the project, and what the user is allowed to vote on. Both of those
+ * can change between the time a vote is originally made and a later point, for example when a
+ * change is submitted. This class normalizes old votes against current project configuration.
*/
@Singleton
public class LabelNormalizer {
@@ -65,7 +63,9 @@
}
public abstract ImmutableList<PatchSetApproval> unchanged();
+
public abstract ImmutableList<PatchSetApproval> updated();
+
public abstract ImmutableList<PatchSetApproval> deleted();
public Iterable<PatchSetApproval> getNormalized() {
@@ -90,41 +90,36 @@
/**
* @param change change containing the given approvals.
* @param approvals list of approvals.
- * @return copies of approvals normalized to the defined ranges for the label
- * type and permissions for the user. Approvals for unknown labels are not
- * included in the output, nor are approvals where the user has no
- * permissions for that label.
+ * @return copies of approvals normalized to the defined ranges for the label type and permissions
+ * for the user. Approvals for unknown labels are not included in the output, nor are
+ * approvals where the user has no permissions for that label.
* @throws OrmException
*/
public Result normalize(Change change, Collection<PatchSetApproval> approvals)
throws OrmException {
IdentifiedUser user = userFactory.create(change.getOwner());
- return normalize(
- changeFactory.controlFor(db.get(), change, user), approvals);
+ return normalize(changeFactory.controlFor(db.get(), change, user), approvals);
}
/**
* @param ctl change control containing the given approvals.
* @param approvals list of approvals.
- * @return copies of approvals normalized to the defined ranges for the label
- * type and permissions for the user. Approvals for unknown labels are not
- * included in the output, nor are approvals where the user has no
- * permissions for that label.
+ * @return copies of approvals normalized to the defined ranges for the label type and permissions
+ * for the user. Approvals for unknown labels are not included in the output, nor are
+ * approvals where the user has no permissions for that label.
*/
- public Result normalize(ChangeControl ctl,
- Collection<PatchSetApproval> approvals) {
- List<PatchSetApproval> unchanged =
- Lists.newArrayListWithCapacity(approvals.size());
- List<PatchSetApproval> updated =
- Lists.newArrayListWithCapacity(approvals.size());
- List<PatchSetApproval> deleted =
- Lists.newArrayListWithCapacity(approvals.size());
+ public Result normalize(ChangeControl ctl, Collection<PatchSetApproval> approvals) {
+ List<PatchSetApproval> unchanged = Lists.newArrayListWithCapacity(approvals.size());
+ List<PatchSetApproval> updated = Lists.newArrayListWithCapacity(approvals.size());
+ List<PatchSetApproval> deleted = Lists.newArrayListWithCapacity(approvals.size());
LabelTypes labelTypes = ctl.getLabelTypes();
for (PatchSetApproval psa : approvals) {
Change.Id changeId = psa.getKey().getParentKey().getParentKey();
- checkArgument(changeId.equals(ctl.getId()),
+ checkArgument(
+ changeId.equals(ctl.getId()),
"Approval %s does not match change %s",
- psa.getKey(), ctl.getChange().getKey());
+ psa.getKey(),
+ ctl.getChange().getKey());
if (psa.isLegacySubmit()) {
unchanged.add(psa);
continue;
@@ -151,8 +146,7 @@
* @param ctl change control (for any user).
* @param lt label type.
* @param id account ID.
- * @return whether the given account ID has any permissions to vote on this
- * label for this change.
+ * @return whether the given account ID has any permissions to vote on this label for this change.
*/
public boolean canVote(ChangeControl ctl, LabelType lt, Account.Id id) {
return !getRange(ctl, lt, id).isEmpty();
@@ -162,15 +156,13 @@
return new PatchSetApproval(src.getPatchSetId(), src);
}
- private PermissionRange getRange(ChangeControl ctl, LabelType lt,
- Account.Id id) {
+ private PermissionRange getRange(ChangeControl ctl, LabelType lt, Account.Id id) {
String permission = Permission.forLabel(lt.getName());
IdentifiedUser user = userFactory.create(id);
return ctl.forUser(user).getRange(permission);
}
- private boolean applyRightFloor(ChangeControl ctl, LabelType lt,
- PatchSetApproval a) {
+ private boolean applyRightFloor(ChangeControl ctl, LabelType lt, PatchSetApproval a) {
PermissionRange range = getRange(ctl, lt, a.getAccountId());
if (range.isEmpty()) {
return false;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/LargeObjectException.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/LargeObjectException.java
index d08b8768..bcde7f8 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/LargeObjectException.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/LargeObjectException.java
@@ -16,18 +16,17 @@
/**
* Wrapper for {@link org.eclipse.jgit.errors.LargeObjectException}. Since
- * org.eclipse.jgit.errors.LargeObjectException is a {@link RuntimeException}
- * the GerritJsonServlet would treat it as internal failure and as result the
- * web ui would just show 'Internal Server Error'. Wrapping
- * org.eclipse.jgit.errors.LargeObjectException into a normal {@link Exception}
+ * org.eclipse.jgit.errors.LargeObjectException is a {@link RuntimeException} the GerritJsonServlet
+ * would treat it as internal failure and as result the web ui would just show 'Internal Server
+ * Error'. Wrapping org.eclipse.jgit.errors.LargeObjectException into a normal {@link Exception}
* allows to display a proper error message.
*/
public class LargeObjectException extends Exception {
private static final long serialVersionUID = 1L;
- public LargeObjectException(final String message,
- final org.eclipse.jgit.errors.LargeObjectException cause) {
+ public LargeObjectException(
+ final String message, final org.eclipse.jgit.errors.LargeObjectException cause) {
super(message, cause);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/LazyPostReceiveHookChain.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/LazyPostReceiveHookChain.java
index ebfaae7..bc12e02 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/LazyPostReceiveHookChain.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/LazyPostReceiveHookChain.java
@@ -16,13 +16,11 @@
import com.google.gerrit.extensions.registration.DynamicSet;
import com.google.inject.Inject;
-
+import java.util.Collection;
import org.eclipse.jgit.transport.PostReceiveHook;
import org.eclipse.jgit.transport.ReceiveCommand;
import org.eclipse.jgit.transport.ReceivePack;
-import java.util.Collection;
-
class LazyPostReceiveHookChain implements PostReceiveHook {
private final DynamicSet<PostReceiveHook> hooks;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/LocalDiskRepositoryManager.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/LocalDiskRepositoryManager.java
index dc15a8b..592f4a5 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/LocalDiskRepositoryManager.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/LocalDiskRepositoryManager.java
@@ -22,21 +22,6 @@
import com.google.gerrit.server.config.SitePaths;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.errors.RepositoryNotFoundException;
-import org.eclipse.jgit.lib.Config;
-import org.eclipse.jgit.lib.ConfigConstants;
-import org.eclipse.jgit.lib.Constants;
-import org.eclipse.jgit.lib.Repository;
-import org.eclipse.jgit.lib.RepositoryCache;
-import org.eclipse.jgit.lib.RepositoryCache.FileKey;
-import org.eclipse.jgit.lib.RepositoryCacheConfig;
-import org.eclipse.jgit.lib.StoredConfig;
-import org.eclipse.jgit.storage.file.WindowCacheConfig;
-import org.eclipse.jgit.util.FS;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitOption;
@@ -51,12 +36,24 @@
import java.util.TreeSet;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
+import org.eclipse.jgit.errors.RepositoryNotFoundException;
+import org.eclipse.jgit.lib.Config;
+import org.eclipse.jgit.lib.ConfigConstants;
+import org.eclipse.jgit.lib.Constants;
+import org.eclipse.jgit.lib.Repository;
+import org.eclipse.jgit.lib.RepositoryCache;
+import org.eclipse.jgit.lib.RepositoryCache.FileKey;
+import org.eclipse.jgit.lib.RepositoryCacheConfig;
+import org.eclipse.jgit.lib.StoredConfig;
+import org.eclipse.jgit.storage.file.WindowCacheConfig;
+import org.eclipse.jgit.util.FS;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/** Manages Git repositories stored on the local filesystem. */
@Singleton
public class LocalDiskRepositoryManager implements GitRepositoryManager {
- private static final Logger log =
- LoggerFactory.getLogger(LocalDiskRepositoryManager.class);
+ private static final Logger log = LoggerFactory.getLogger(LocalDiskRepositoryManager.class);
public static class Module extends LifecycleModule {
@Override
@@ -83,9 +80,11 @@
cfg.fromConfig(serverConfig);
if (serverConfig.getString("core", null, "streamFileThreshold") == null) {
long mx = Runtime.getRuntime().maxMemory();
- int limit = (int) Math.min(
- mx / 4, // don't use more than 1/4 of the heap.
- 2047 << 20); // cannot exceed array length
+ int limit =
+ (int)
+ Math.min(
+ mx / 4, // don't use more than 1/4 of the heap.
+ 2047 << 20); // cannot exceed array length
if ((5 << 20) < limit && limit % (1 << 20) != 0) {
// If the limit is at least 5 MiB but is not a whole multiple
// of MiB round up to the next one full megabyte. This is a very
@@ -101,17 +100,14 @@
} else {
desc = String.format("%d", limit);
}
- log.info(String.format(
- "Defaulting core.streamFileThreshold to %s",
- desc));
+ log.info(String.format("Defaulting core.streamFileThreshold to %s", desc));
cfg.setStreamFileThreshold(limit);
}
cfg.install();
}
@Override
- public void stop() {
- }
+ public void stop() {}
}
private final Path basePath;
@@ -119,8 +115,7 @@
private volatile SortedSet<Project.NameKey> names = new TreeSet<>();
@Inject
- LocalDiskRepositoryManager(SitePaths site,
- @GerritServerConfig Config cfg) {
+ LocalDiskRepositoryManager(SitePaths site, @GerritServerConfig Config cfg) {
basePath = site.resolve(cfg.getString("gerrit", null, "basePath"));
if (basePath == null) {
throw new IllegalStateException("gerrit.basePath must be configured");
@@ -140,8 +135,7 @@
}
@Override
- public Repository openRepository(Project.NameKey name)
- throws RepositoryNotFoundException {
+ public Repository openRepository(Project.NameKey name) throws RepositoryNotFoundException {
return openRepository(getBasePath(name), name);
}
@@ -164,11 +158,11 @@
}
} else {
final File directory = gitDir;
- if (FileKey.isGitRepository(new File(directory, Constants.DOT_GIT),
- FS.DETECTED)) {
+ if (FileKey.isGitRepository(new File(directory, Constants.DOT_GIT), FS.DETECTED)) {
onCreateProject(name);
- } else if (FileKey.isGitRepository(new File(directory.getParentFile(),
- directory.getName() + Constants.DOT_GIT_EXT), FS.DETECTED)) {
+ } else if (FileKey.isGitRepository(
+ new File(directory.getParentFile(), directory.getName() + Constants.DOT_GIT_EXT),
+ FS.DETECTED)) {
onCreateProject(name);
} else {
throw new RepositoryNotFoundException(gitDir);
@@ -188,8 +182,7 @@
@Override
public Repository createRepository(Project.NameKey name)
- throws RepositoryNotFoundException, RepositoryCaseMismatchException,
- IOException {
+ throws RepositoryNotFoundException, RepositoryCaseMismatchException, IOException {
Path path = getBasePath(name);
if (isUnreasonableName(name)) {
throw new RepositoryNotFoundException("Invalid name: " + name);
@@ -200,8 +193,7 @@
if (dir != null) {
// Already exists on disk, use the repository we found.
//
- Project.NameKey onDiskName = getProjectName(
- path, dir.getCanonicalFile().toPath());
+ Project.NameKey onDiskName = getProjectName(path, dir.getCanonicalFile().toPath());
onCreateProject(onDiskName);
loc = FileKey.exact(dir, FS.DETECTED);
@@ -222,20 +214,21 @@
db.create(true /* bare */);
StoredConfig config = db.getConfig();
- config.setBoolean(ConfigConstants.CONFIG_CORE_SECTION,
- null, ConfigConstants.CONFIG_KEY_LOGALLREFUPDATES, true);
+ config.setBoolean(
+ ConfigConstants.CONFIG_CORE_SECTION,
+ null,
+ ConfigConstants.CONFIG_KEY_LOGALLREFUPDATES,
+ true);
config.save();
// JGit only writes to the reflog for refs/meta/config if the log file
// already exists.
//
- File metaConfigLog =
- new File(db.getDirectory(), "logs/" + RefNames.REFS_CONFIG);
- if (!metaConfigLog.getParentFile().mkdirs()
- || !metaConfigLog.createNewFile()) {
- log.error(String.format(
- "Failed to create ref log for %s in repository %s",
- RefNames.REFS_CONFIG, name));
+ File metaConfigLog = new File(db.getDirectory(), "logs/" + RefNames.REFS_CONFIG);
+ if (!metaConfigLog.getParentFile().mkdirs() || !metaConfigLog.createNewFile()) {
+ log.error(
+ String.format(
+ "Failed to create ref log for %s in repository %s", RefNames.REFS_CONFIG, name));
}
onCreateProject(name);
@@ -263,25 +256,25 @@
private boolean isUnreasonableName(final Project.NameKey nameKey) {
final String name = nameKey.get();
- return name.length() == 0 // no empty paths
- || name.charAt(name.length() - 1) == '/' // no suffix
- || name.indexOf('\\') >= 0 // no windows/dos style paths
- || name.charAt(0) == '/' // no absolute paths
- || new File(name).isAbsolute() // no absolute paths
- || name.startsWith("../") // no "l../etc/passwd"
- || name.contains("/../") // no "foo/../etc/passwd"
- || name.contains("/./") // "foo/./foo" is insane to ask
- || name.contains("//") // windows UNC path can be "//..."
- || name.contains(".git/") // no path segments that end with '.git' as "foo.git/bar"
- || name.contains("?") // common unix wildcard
- || name.contains("%") // wildcard or string parameter
- || name.contains("*") // wildcard
- || name.contains(":") // Could be used for absolute paths in windows?
- || name.contains("<") // redirect input
- || name.contains(">") // redirect output
- || name.contains("|") // pipe
- || name.contains("$") // dollar sign
- || name.contains("\r"); // carriage return
+ return name.length() == 0 // no empty paths
+ || name.charAt(name.length() - 1) == '/' // no suffix
+ || name.indexOf('\\') >= 0 // no windows/dos style paths
+ || name.charAt(0) == '/' // no absolute paths
+ || new File(name).isAbsolute() // no absolute paths
+ || name.startsWith("../") // no "l../etc/passwd"
+ || name.contains("/../") // no "foo/../etc/passwd"
+ || name.contains("/./") // "foo/./foo" is insane to ask
+ || name.contains("//") // windows UNC path can be "//..."
+ || name.contains(".git/") // no path segments that end with '.git' as "foo.git/bar"
+ || name.contains("?") // common unix wildcard
+ || name.contains("%") // wildcard or string parameter
+ || name.contains("*") // wildcard
+ || name.contains(":") // Could be used for absolute paths in windows?
+ || name.contains("<") // redirect input
+ || name.contains(">") // redirect output
+ || name.contains("|") // pipe
+ || name.contains("$") // dollar sign
+ || name.contains("\r"); // carriage return
}
@Override
@@ -305,11 +298,13 @@
protected void scanProjects(ProjectVisitor visitor) {
try {
- Files.walkFileTree(visitor.startFolder,
- EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, visitor);
+ Files.walkFileTree(
+ visitor.startFolder,
+ EnumSet.of(FileVisitOption.FOLLOW_LINKS),
+ Integer.MAX_VALUE,
+ visitor);
} catch (IOException e) {
- log.error("Error walking repository tree "
- + visitor.startFolder.toAbsolutePath(), e);
+ log.error("Error walking repository tree " + visitor.startFolder.toAbsolutePath(), e);
}
}
@@ -338,8 +333,8 @@
}
@Override
- public FileVisitResult preVisitDirectory(Path dir,
- BasicFileAttributes attrs) throws IOException {
+ public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
+ throws IOException {
if (!dir.equals(startFolder) && isRepo(dir)) {
addProject(dir);
return FileVisitResult.SKIP_SUBTREE;
@@ -358,8 +353,7 @@
Project.NameKey nameKey = getProjectName(startFolder, p);
if (getBasePath(nameKey).equals(startFolder)) {
if (isUnreasonableName(nameKey)) {
- log.warn(
- "Ignoring unreasonably named repository " + p.toAbsolutePath());
+ log.warn("Ignoring unreasonably named repository " + p.toAbsolutePath());
} else {
found.add(nameKey);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/MergeIdenticalTreeException.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/MergeIdenticalTreeException.java
index dd6b717..cee08d4 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/MergeIdenticalTreeException.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/MergeIdenticalTreeException.java
@@ -17,8 +17,8 @@
import com.google.gerrit.extensions.restapi.RestApiException;
/**
- * Indicates that the commit is already contained in destination branch.
- * Either the commit itself is in the source tree, or the content is merged
+ * Indicates that the commit is already contained in destination branch. Either the commit itself is
+ * in the source tree, or the content is merged
*/
public class MergeIdenticalTreeException extends RestApiException {
private static final long serialVersionUID = 1L;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/MergeOp.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/MergeOp.java
index 55b236a..3da17a4 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/MergeOp.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/MergeOp.java
@@ -65,15 +65,6 @@
import com.google.gerrit.server.util.RequestId;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
-
-import org.eclipse.jgit.errors.IncorrectObjectTypeException;
-import org.eclipse.jgit.lib.Constants;
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.lib.Ref;
-import org.eclipse.jgit.revwalk.RevCommit;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
@@ -85,26 +76,29 @@
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
+import org.eclipse.jgit.errors.IncorrectObjectTypeException;
+import org.eclipse.jgit.lib.Constants;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.lib.Ref;
+import org.eclipse.jgit.revwalk.RevCommit;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* Merges changes in submission order into a single branch.
- * <p>
- * Branches are reduced to the minimum number of heads needed to merge
- * everything. This allows commits to be entered into the queue in any order
- * (such as ancestors before descendants) and only the most recent commit on any
- * line of development will be merged. All unmerged commits along a line of
- * development must be in the submission queue in order to merge the tip of that
- * line.
- * <p>
- * Conflicts are handled by discarding the entire line of development and
- * marking it as conflicting, even if an earlier commit along that same line can
- * be merged cleanly.
+ *
+ * <p>Branches are reduced to the minimum number of heads needed to merge everything. This allows
+ * commits to be entered into the queue in any order (such as ancestors before descendants) and only
+ * the most recent commit on any line of development will be merged. All unmerged commits along a
+ * line of development must be in the submission queue in order to merge the tip of that line.
+ *
+ * <p>Conflicts are handled by discarding the entire line of development and marking it as
+ * conflicting, even if an earlier commit along that same line can be merged cleanly.
*/
public class MergeOp implements AutoCloseable {
private static final Logger log = LoggerFactory.getLogger(MergeOp.class);
- private static final SubmitRuleOptions SUBMIT_RULE_OPTIONS =
- SubmitRuleOptions.defaults().build();
+ private static final SubmitRuleOptions SUBMIT_RULE_OPTIONS = SubmitRuleOptions.defaults().build();
public static class CommitStatus {
private final ImmutableMap<Change.Id, ChangeData> changes;
@@ -113,20 +107,16 @@
private final ListMultimap<Change.Id, String> problems;
private CommitStatus(ChangeSet cs) throws OrmException {
- checkArgument(!cs.furtherHiddenChanges(),
- "CommitStatus must not be called with hidden changes");
+ checkArgument(
+ !cs.furtherHiddenChanges(), "CommitStatus must not be called with hidden changes");
changes = cs.changesById();
- ImmutableSetMultimap.Builder<Branch.NameKey, Change.Id> bb =
- ImmutableSetMultimap.builder();
+ ImmutableSetMultimap.Builder<Branch.NameKey, Change.Id> bb = ImmutableSetMultimap.builder();
for (ChangeData cd : cs.changes()) {
bb.put(cd.change().getDest(), cd.getId());
}
byBranch = bb.build();
commits = new HashMap<>();
- problems = MultimapBuilder
- .treeKeys(comparing(Change.Id::get))
- .arrayListValues(1)
- .build();
+ problems = MultimapBuilder.treeKeys(comparing(Change.Id::get)).arrayListValues(1).build();
}
public ImmutableSet<Change.Id> getChangeIds() {
@@ -178,7 +168,8 @@
// However, do NOT expose that ChangeData directly, as it is way out of
// date by this point.
ChangeData cd = checkNotNull(changes.get(id), "ChangeData for %s", id);
- return checkNotNull(cd.getSubmitRecords(SUBMIT_RULE_OPTIONS),
+ return checkNotNull(
+ cd.getSubmitRecords(SUBMIT_RULE_OPTIONS),
"getSubmitRecord only valid after submit rules are evalutated");
}
@@ -186,9 +177,12 @@
if (isOk()) {
return;
}
- String msg = "Failed to submit " + changes.size() + " change"
- + (changes.size() > 1 ? "s" : "")
- + " due to the following problems:\n";
+ String msg =
+ "Failed to submit "
+ + changes.size()
+ + " change"
+ + (changes.size() > 1 ? "s" : "")
+ + " due to the following problems:\n";
List<String> ps = new ArrayList<>(problems.keySet().size());
for (Change.Id id : problems.keySet()) {
ps.add("Change " + id + ": " + Joiner.on("; ").join(problems.get(id)));
@@ -234,7 +228,8 @@
private boolean dryrun;
@Inject
- MergeOp(ChangeMessagesUtil cmUtil,
+ MergeOp(
+ ChangeMessagesUtil cmUtil,
BatchUpdate.Factory batchUpdateFactory,
InternalUser.Factory internalUserFactory,
MergeSuperSet mergeSuperSet,
@@ -261,24 +256,20 @@
orm.close();
}
- public static void checkSubmitRule(ChangeData cd)
- throws ResourceConflictException, OrmException {
+ public static void checkSubmitRule(ChangeData cd) throws ResourceConflictException, OrmException {
PatchSet patchSet = cd.currentPatchSet();
if (patchSet == null) {
- throw new ResourceConflictException(
- "missing current patch set for change " + cd.getId());
+ throw new ResourceConflictException("missing current patch set for change " + cd.getId());
}
List<SubmitRecord> results = getSubmitRecords(cd);
if (SubmitRecord.findOkRecord(results).isPresent()) {
// Rules supplied a valid solution.
return;
} else if (results.isEmpty()) {
- throw new IllegalStateException(String.format(
- "SubmitRuleEvaluator.evaluate for change %s " +
- "returned empty list for %s in %s",
- cd.getId(),
- patchSet.getId(),
- cd.change().getProject().get()));
+ throw new IllegalStateException(
+ String.format(
+ "SubmitRuleEvaluator.evaluate for change %s " + "returned empty list for %s in %s",
+ cd.getId(), patchSet.getId(), cd.change().getProject().get()));
}
for (SubmitRecord record : results) {
@@ -287,33 +278,29 @@
throw new ResourceConflictException("change is closed");
case RULE_ERROR:
- throw new ResourceConflictException(
- "submit rule error: " + record.errorMessage);
+ throw new ResourceConflictException("submit rule error: " + record.errorMessage);
case NOT_READY:
- throw new ResourceConflictException(
- describeLabels(cd, record.labels));
+ throw new ResourceConflictException(describeLabels(cd, record.labels));
case FORCED:
case OK:
default:
- throw new IllegalStateException(String.format(
- "Unexpected SubmitRecord status %s for %s in %s",
- record.status,
- patchSet.getId().getId(),
- cd.change().getProject().get()));
+ throw new IllegalStateException(
+ String.format(
+ "Unexpected SubmitRecord status %s for %s in %s",
+ record.status, patchSet.getId().getId(), cd.change().getProject().get()));
}
}
throw new IllegalStateException();
}
- private static List<SubmitRecord> getSubmitRecords(ChangeData cd)
- throws OrmException {
+ private static List<SubmitRecord> getSubmitRecords(ChangeData cd) throws OrmException {
return cd.submitRecords(SUBMIT_RULE_OPTIONS);
}
- private static String describeLabels(ChangeData cd,
- List<SubmitRecord.Label> labels) throws OrmException {
+ private static String describeLabels(ChangeData cd, List<SubmitRecord.Label> labels)
+ throws OrmException {
List<String> labelResults = new ArrayList<>();
for (SubmitRecord.Label lbl : labels) {
switch (lbl.status) {
@@ -330,30 +317,28 @@
break;
case IMPOSSIBLE:
- labelResults.add(
- "needs " + lbl.label + " (check project access)");
+ labelResults.add("needs " + lbl.label + " (check project access)");
break;
default:
- throw new IllegalStateException(String.format(
- "Unsupported SubmitRecord.Label %s for %s in %s",
- lbl,
- cd.change().currentPatchSetId(),
- cd.change().getProject()));
+ throw new IllegalStateException(
+ String.format(
+ "Unsupported SubmitRecord.Label %s for %s in %s",
+ lbl, cd.change().currentPatchSetId(), cd.change().getProject()));
}
}
return Joiner.on("; ").join(labelResults);
}
- private void checkSubmitRulesAndState(ChangeSet cs)
- throws ResourceConflictException {
- checkArgument(!cs.furtherHiddenChanges(),
- "checkSubmitRulesAndState called for topic with hidden change");
+ private void checkSubmitRulesAndState(ChangeSet cs) throws ResourceConflictException {
+ checkArgument(
+ !cs.furtherHiddenChanges(), "checkSubmitRulesAndState called for topic with hidden change");
for (ChangeData cd : cs.changes()) {
try {
if (cd.change().getStatus() != Change.Status.NEW) {
- commitStatus.problem(cd.getId(), "Change " + cd.getId() + " is "
- + cd.change().getStatus().toString().toLowerCase());
+ commitStatus.problem(
+ cd.getId(),
+ "Change " + cd.getId() + " is " + cd.change().getStatus().toString().toLowerCase());
} else {
checkSubmitRule(cd);
}
@@ -369,8 +354,8 @@
}
private void bypassSubmitRules(ChangeSet cs) {
- checkArgument(!cs.furtherHiddenChanges(),
- "cannot bypass submit rules for topic with hidden change");
+ checkArgument(
+ !cs.furtherHiddenChanges(), "cannot bypass submit rules for topic with hidden change");
for (ChangeData cd : cs.changes()) {
List<SubmitRecord> records;
try {
@@ -389,9 +374,9 @@
/**
* Merges the given change.
*
- * Depending on the server configuration, more changes may be affected, e.g.
- * by submission of a topic or via superproject subscriptions. All affected
- * changes are integrated using the projects integration strategy.
+ * <p>Depending on the server configuration, more changes may be affected, e.g. by submission of a
+ * topic or via superproject subscriptions. All affected changes are integrated using the projects
+ * integration strategy.
*
* @param db the review database.
* @param change the change to be merged.
@@ -401,12 +386,16 @@
* @throws OrmException an error occurred reading or writing the database.
* @throws RestApiException if an error occurred.
*/
- public void merge(ReviewDb db, Change change, IdentifiedUser caller,
- boolean checkSubmitRules, SubmitInput submitInput, boolean dryrun)
+ public void merge(
+ ReviewDb db,
+ Change change,
+ IdentifiedUser caller,
+ boolean checkSubmitRules,
+ SubmitInput submitInput,
+ boolean dryrun)
throws OrmException, RestApiException {
this.submitInput = submitInput;
- this.accountsToNotify =
- notifyUtil.resolveAccounts(submitInput.notifyDetails);
+ this.accountsToNotify = notifyUtil.resolveAccounts(submitInput.notifyDetails);
this.dryrun = dryrun;
this.caller = caller;
this.ts = TimeUtil.nowTs();
@@ -416,13 +405,12 @@
logDebug("Beginning integration of {}", change);
try {
- ChangeSet cs = mergeSuperSet.setMergeOpRepoManager(orm)
- .completeChangeSet(db, change, caller);
- checkState(cs.ids().contains(change.getId()),
- "change %s missing from %s", change.getId(), cs);
+ ChangeSet cs = mergeSuperSet.setMergeOpRepoManager(orm).completeChangeSet(db, change, caller);
+ checkState(
+ cs.ids().contains(change.getId()), "change %s missing from %s", change.getId(), cs);
if (cs.furtherHiddenChanges()) {
- throw new AuthException("A change to be submitted with "
- + change.getId() + " is not visible");
+ throw new AuthException(
+ "A change to be submitted with " + change.getId() + " is not visible");
}
this.commitStatus = new CommitStatus(cs);
MergeSuperSet.reloadChanges(cs);
@@ -446,10 +434,8 @@
}
}
- private void integrateIntoHistory(ChangeSet cs)
- throws IntegrationException, RestApiException {
- checkArgument(!cs.furtherHiddenChanges(),
- "cannot integrate hidden changes into history");
+ private void integrateIntoHistory(ChangeSet cs) throws IntegrationException, RestApiException {
+ checkArgument(!cs.furtherHiddenChanges(), "cannot integrate hidden changes into history");
logDebug("Beginning merge attempt on {}", cs);
Map<Branch.NameKey, BranchBatch> toSubmit = new HashMap<>();
@@ -470,12 +456,13 @@
commitStatus.maybeFailVerbose();
SubmoduleOp submoduleOp = subOpFactory.create(branches, orm);
try {
- List<SubmitStrategy> strategies = getSubmitStrategies(toSubmit,
- submoduleOp, dryrun);
+ List<SubmitStrategy> strategies = getSubmitStrategies(toSubmit, submoduleOp, dryrun);
this.allProjects = submoduleOp.getProjectsInOrder();
- BatchUpdate.execute(orm.batchUpdates(allProjects),
+ BatchUpdate.execute(
+ orm.batchUpdates(allProjects),
new SubmitStrategyListener(submitInput, strategies, commitStatus),
- submissionId, dryrun);
+ submissionId,
+ dryrun);
} catch (SubmoduleException e) {
throw new IntegrationException(e);
} catch (UpdateException e) {
@@ -505,32 +492,51 @@
}
private List<SubmitStrategy> getSubmitStrategies(
- Map<Branch.NameKey, BranchBatch> toSubmit, SubmoduleOp submoduleOp,
- boolean dryrun) throws IntegrationException {
+ Map<Branch.NameKey, BranchBatch> toSubmit, SubmoduleOp submoduleOp, boolean dryrun)
+ throws IntegrationException {
List<SubmitStrategy> strategies = new ArrayList<>();
Set<Branch.NameKey> allBranches = submoduleOp.getBranchesInOrder();
Set<CodeReviewCommit> allCommits =
- toSubmit.values().stream().map(BranchBatch::commits)
- .flatMap(Set::stream).collect(Collectors.toSet());
+ toSubmit
+ .values()
+ .stream()
+ .map(BranchBatch::commits)
+ .flatMap(Set::stream)
+ .collect(Collectors.toSet());
for (Branch.NameKey branch : allBranches) {
OpenRepo or = orm.getRepo(branch.getParentKey());
if (toSubmit.containsKey(branch)) {
BranchBatch submitting = toSubmit.get(branch);
OpenBranch ob = or.getBranch(branch);
- checkNotNull(submitting.submitType(),
+ checkNotNull(
+ submitting.submitType(),
"null submit type for %s; expected to previously fail fast",
submitting);
Set<CodeReviewCommit> commitsToSubmit = submitting.commits();
ob.mergeTip = new MergeTip(ob.oldTip, commitsToSubmit);
- SubmitStrategy strategy = submitStrategyFactory
- .create(submitting.submitType(), db, or.repo, or.rw, or.ins,
- or.canMergeFlag, getAlreadyAccepted(or, ob.oldTip), allCommits,
- branch, caller, ob.mergeTip, commitStatus, submissionId,
- submitInput.notify, accountsToNotify, submoduleOp, dryrun);
+ SubmitStrategy strategy =
+ submitStrategyFactory.create(
+ submitting.submitType(),
+ db,
+ or.repo,
+ or.rw,
+ or.ins,
+ or.canMergeFlag,
+ getAlreadyAccepted(or, ob.oldTip),
+ allCommits,
+ branch,
+ caller,
+ ob.mergeTip,
+ commitStatus,
+ submissionId,
+ submitInput.notify,
+ accountsToNotify,
+ submoduleOp,
+ dryrun);
strategies.add(strategy);
strategy.addOps(or.getUpdate(), commitsToSubmit);
- if (submitting.submitType().equals(SubmitType.FAST_FORWARD_ONLY) &&
- submoduleOp.hasSubscription(branch)) {
+ if (submitting.submitType().equals(SubmitType.FAST_FORWARD_ONLY)
+ && submoduleOp.hasSubscription(branch)) {
submoduleOp.addOp(or.getUpdate(), branch);
}
} else {
@@ -542,8 +548,8 @@
return strategies;
}
- private Set<RevCommit> getAlreadyAccepted(OpenRepo or,
- CodeReviewCommit branchTip) throws IntegrationException {
+ private Set<RevCommit> getAlreadyAccepted(OpenRepo or, CodeReviewCommit branchTip)
+ throws IntegrationException {
Set<RevCommit> alreadyAccepted = new HashSet<>();
if (branchTip != null) {
@@ -551,8 +557,7 @@
}
try {
- for (Ref r : or.repo.getRefDatabase().getRefs(Constants.R_HEADS)
- .values()) {
+ for (Ref r : or.repo.getRefDatabase().getRefs(Constants.R_HEADS).values()) {
try {
CodeReviewCommit aac = or.rw.parseCommit(r.getObjectId());
if (!commitStatus.commits.values().contains(aac)) {
@@ -563,8 +568,7 @@
}
}
} catch (IOException e) {
- throw new IntegrationException(
- "Failed to determine already accepted commits.", e);
+ throw new IntegrationException("Failed to determine already accepted commits.", e);
}
logDebug("Found {} existing heads", alreadyAccepted.size());
@@ -573,12 +577,14 @@
@AutoValue
abstract static class BranchBatch {
- @Nullable abstract SubmitType submitType();
+ @Nullable
+ abstract SubmitType submitType();
+
abstract Set<CodeReviewCommit> commits();
}
- private BranchBatch validateChangeList(OpenRepo or,
- Collection<ChangeData> submitted) throws IntegrationException {
+ private BranchBatch validateChangeList(OpenRepo or, Collection<ChangeData> submitted)
+ throws IntegrationException {
logDebug("Validating {} changes", submitted.size());
Set<CodeReviewCommit> toSubmit = new LinkedHashSet<>(submitted.size());
SetMultimap<ObjectId, PatchSet.Id> revisions = getRevisions(or, submitted);
@@ -606,10 +612,12 @@
submitType = st;
choseSubmitTypeFrom = cd;
} else if (st != submitType) {
- commitStatus.problem(changeId, String.format(
- "Change has submit type %s, but previously chose submit type %s "
- + "from change %s in the same batch",
- st, submitType, choseSubmitTypeFrom.getId()));
+ commitStatus.problem(
+ changeId,
+ String.format(
+ "Change has submit type %s, but previously chose submit type %s "
+ + "from change %s in the same batch",
+ st, submitType, choseSubmitTypeFrom.getId()));
continue;
}
if (chg.currentPatchSetId() == null) {
@@ -627,8 +635,7 @@
commitStatus.logProblem(changeId, e);
continue;
}
- if (ps == null || ps.getRevision() == null
- || ps.getRevision().get() == null) {
+ if (ps == null || ps.getRevision() == null || ps.getRevision().get() == null) {
commitStatus.logProblem(changeId, "Missing patch set or revision on change");
continue;
}
@@ -647,9 +654,15 @@
// want to merge the issue. We can't safely do that if the
// tip is not reachable.
//
- commitStatus.logProblem(changeId, "Revision " + idstr + " of patch set "
- + ps.getPatchSetId() + " does not match " + ps.getId().toRefName()
- + " for change");
+ commitStatus.logProblem(
+ changeId,
+ "Revision "
+ + idstr
+ + " of patch set "
+ + ps.getPatchSetId()
+ + " does not match "
+ + ps.getId().toRefName()
+ + " for change");
continue;
}
@@ -681,8 +694,8 @@
return new AutoValue_MergeOp_BranchBatch(submitType, toSubmit);
}
- private SetMultimap<ObjectId, PatchSet.Id> getRevisions(OpenRepo or,
- Collection<ChangeData> cds) throws IntegrationException {
+ private SetMultimap<ObjectId, PatchSet.Id> getRevisions(OpenRepo or, Collection<ChangeData> cds)
+ throws IntegrationException {
try {
List<String> refNames = new ArrayList<>(cds.size());
for (ChangeData cd : cds) {
@@ -693,10 +706,12 @@
}
SetMultimap<ObjectId, PatchSet.Id> revisions =
MultimapBuilder.hashKeys(cds.size()).hashSetValues(1).build();
- for (Map.Entry<String, Ref> e : or.repo.getRefDatabase().exactRef(
- refNames.toArray(new String[refNames.size()])).entrySet()) {
- revisions.put(
- e.getValue().getObjectId(), PatchSet.Id.fromRef(e.getKey()));
+ for (Map.Entry<String, Ref> e :
+ or.repo
+ .getRefDatabase()
+ .exactRef(refNames.toArray(new String[refNames.size()]))
+ .entrySet()) {
+ revisions.put(e.getValue().getObjectId(), PatchSet.Id.fromRef(e.getKey()));
}
return revisions;
} catch (IOException | OrmException e) {
@@ -714,13 +729,11 @@
}
}
- private OpenRepo openRepo(Project.NameKey project)
- throws IntegrationException {
+ private OpenRepo openRepo(Project.NameKey project) throws IntegrationException {
try {
return orm.openRepo(project);
} catch (NoSuchProjectException noProject) {
- logWarn("Project " + noProject.project() + " no longer exists, "
- + "abandoning open changes");
+ logWarn("Project " + noProject.project() + " no longer exists, " + "abandoning open changes");
abandonAllOpenChangeForDeletedProject(noProject.project());
} catch (IOException e) {
throw new IntegrationException("Error opening project " + project, e);
@@ -728,39 +741,41 @@
return null;
}
- private void abandonAllOpenChangeForDeletedProject(
- Project.NameKey destProject) {
+ private void abandonAllOpenChangeForDeletedProject(Project.NameKey destProject) {
try {
for (ChangeData cd : internalChangeQuery.byProjectOpen(destProject)) {
- try (BatchUpdate bu = batchUpdateFactory.create(db, destProject,
- internalUserFactory.create(), ts)) {
+ try (BatchUpdate bu =
+ batchUpdateFactory.create(db, destProject, internalUserFactory.create(), ts)) {
bu.setRequestId(submissionId);
- bu.addOp(cd.getId(), new BatchUpdate.Op() {
- @Override
- public boolean updateChange(ChangeContext ctx) throws OrmException {
- Change change = ctx.getChange();
- if (!change.getStatus().isOpen()) {
- return false;
- }
+ bu.addOp(
+ cd.getId(),
+ new BatchUpdate.Op() {
+ @Override
+ public boolean updateChange(ChangeContext ctx) throws OrmException {
+ Change change = ctx.getChange();
+ if (!change.getStatus().isOpen()) {
+ return false;
+ }
- change.setStatus(Change.Status.ABANDONED);
+ change.setStatus(Change.Status.ABANDONED);
- ChangeMessage msg = ChangeMessagesUtil.newMessage(
- change.currentPatchSetId(),
- internalUserFactory.create(), change.getLastUpdatedOn(),
- ChangeMessagesUtil.TAG_MERGED,
- "Project was deleted.");
- cmUtil.addChangeMessage(ctx.getDb(),
- ctx.getUpdate(change.currentPatchSetId()), msg);
+ ChangeMessage msg =
+ ChangeMessagesUtil.newMessage(
+ change.currentPatchSetId(),
+ internalUserFactory.create(),
+ change.getLastUpdatedOn(),
+ ChangeMessagesUtil.TAG_MERGED,
+ "Project was deleted.");
+ cmUtil.addChangeMessage(
+ ctx.getDb(), ctx.getUpdate(change.currentPatchSetId()), msg);
- return true;
- }
- });
+ return true;
+ }
+ });
try {
bu.execute();
} catch (UpdateException | RestApiException e) {
- logWarn("Cannot abandon changes for deleted project " + destProject,
- e);
+ logWarn("Cannot abandon changes for deleted project " + destProject, e);
}
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/MergeOpRepoManager.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/MergeOpRepoManager.java
index 1244ad3..97ac265 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/MergeOpRepoManager.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/MergeOpRepoManager.java
@@ -28,7 +28,14 @@
import com.google.gerrit.server.project.ProjectState;
import com.google.gerrit.server.util.RequestId;
import com.google.inject.Inject;
-
+import java.io.IOException;
+import java.sql.Timestamp;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.ObjectInserter;
@@ -38,21 +45,11 @@
import org.eclipse.jgit.revwalk.RevFlag;
import org.eclipse.jgit.revwalk.RevSort;
-import java.io.IOException;
-import java.sql.Timestamp;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-
/**
* This is a helper class for MergeOp and not intended for general use.
*
- * Some database backends require to open a repository just once within
- * a transaction of a submission, this caches open repositories to satisfy
- * that requirement.
+ * <p>Some database backends require to open a repository just once within a transaction of a
+ * submission, this caches open repositories to satisfy that requirement.
*/
public class MergeOpRepoManager implements AutoCloseable {
public class OpenRepo {
@@ -106,17 +103,19 @@
public BatchUpdate getUpdate() {
checkState(db != null, "call setContext before getUpdate");
if (update == null) {
- update = batchUpdateFactory.create(db, getProjectName(), caller, ts)
- .setRepository(repo, rw, ins)
- .setRequestId(submissionId)
- .setOnSubmitValidators(onSubmitValidatorsFactory.create());
+ update =
+ batchUpdateFactory
+ .create(db, getProjectName(), caller, ts)
+ .setRepository(repo, rw, ins)
+ .setRequestId(submissionId)
+ .setOnSubmitValidators(onSubmitValidatorsFactory.create());
}
return update;
}
/**
- * Make sure the update has already executed before reset it.
- * TODO:czhen Have a flag in BatchUpdate to mark if it has been executed
+ * Make sure the update has already executed before reset it. TODO:czhen Have a flag in
+ * BatchUpdate to mark if it has been executed
*/
void resetUpdate() {
update = null;
@@ -147,8 +146,8 @@
oldTip = null;
update.setExpectedOldObjectId(ObjectId.zeroId());
} else {
- throw new IntegrationException("The destination branch "
- + name + " does not exist anymore.");
+ throw new IntegrationException(
+ "The destination branch " + name + " does not exist anymore.");
}
} catch (IOException e) {
throw new IntegrationException("Cannot open branch " + name, e);
@@ -156,7 +155,6 @@
}
}
-
private final Map<Project.NameKey, OpenRepo> openRepos;
private final BatchUpdate.Factory batchUpdateFactory;
private final OnSubmitValidators.Factory onSubmitValidatorsFactory;
@@ -182,8 +180,7 @@
openRepos = new HashMap<>();
}
- void setContext(ReviewDb db, Timestamp ts, IdentifiedUser caller,
- RequestId submissionId) {
+ void setContext(ReviewDb db, Timestamp ts, IdentifiedUser caller, RequestId submissionId) {
this.db = db;
this.ts = ts;
this.caller = caller;
@@ -200,8 +197,7 @@
return or;
}
- public OpenRepo openRepo(Project.NameKey project)
- throws NoSuchProjectException, IOException {
+ public OpenRepo openRepo(Project.NameKey project) throws NoSuchProjectException, IOException {
if (openRepos.containsKey(project)) {
return openRepos.get(project);
}
@@ -211,8 +207,7 @@
throw new NoSuchProjectException(project);
}
try {
- OpenRepo or =
- new OpenRepo(repoManager.openRepository(project), projectState);
+ OpenRepo or = new OpenRepo(repoManager.openRepository(project), projectState);
openRepos.put(project, or);
return or;
} catch (RepositoryNotFoundException e) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/MergeSorter.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/MergeSorter.java
index 059a23e..78fc495 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/MergeSorter.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/MergeSorter.java
@@ -16,36 +16,33 @@
import com.google.gerrit.server.git.CodeReviewCommit.CodeReviewRevWalk;
import com.google.gerrit.server.git.strategy.CommitMergeStatus;
-
-import org.eclipse.jgit.revwalk.RevCommit;
-import org.eclipse.jgit.revwalk.RevCommitList;
-import org.eclipse.jgit.revwalk.RevFlag;
-
import java.io.IOException;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
+import org.eclipse.jgit.revwalk.RevCommit;
+import org.eclipse.jgit.revwalk.RevCommitList;
+import org.eclipse.jgit.revwalk.RevFlag;
public class MergeSorter {
private final CodeReviewRevWalk rw;
private final RevFlag canMergeFlag;
private final Set<RevCommit> accepted;
- public MergeSorter(CodeReviewRevWalk rw, Set<RevCommit> alreadyAccepted,
- RevFlag canMergeFlag) {
+ public MergeSorter(CodeReviewRevWalk rw, Set<RevCommit> alreadyAccepted, RevFlag canMergeFlag) {
this.rw = rw;
this.canMergeFlag = canMergeFlag;
this.accepted = alreadyAccepted;
}
- Collection<CodeReviewCommit> sort(final Collection<CodeReviewCommit> toMerge)
- throws IOException {
+ Collection<CodeReviewCommit> sort(final Collection<CodeReviewCommit> toMerge) throws IOException {
return sort(toMerge, toMerge);
}
- Collection<CodeReviewCommit> sort(final Collection<CodeReviewCommit> toMerge,
- final Collection<CodeReviewCommit> incoming) throws IOException {
+ Collection<CodeReviewCommit> sort(
+ final Collection<CodeReviewCommit> toMerge, final Collection<CodeReviewCommit> incoming)
+ throws IOException {
final Set<CodeReviewCommit> heads = new HashSet<>();
final Set<CodeReviewCommit> sort = new HashSet<>(toMerge);
while (!sort.isEmpty()) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/MergeSuperSet.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/MergeSuperSet.java
index 751933c..cdbe9cf 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/MergeSuperSet.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/MergeSuperSet.java
@@ -43,15 +43,6 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
-
-import org.eclipse.jgit.lib.Config;
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.lib.Ref;
-import org.eclipse.jgit.revwalk.RevCommit;
-import org.eclipse.jgit.revwalk.RevSort;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
@@ -62,16 +53,23 @@
import java.util.Map;
import java.util.Optional;
import java.util.Set;
+import org.eclipse.jgit.lib.Config;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.lib.Ref;
+import org.eclipse.jgit.revwalk.RevCommit;
+import org.eclipse.jgit.revwalk.RevSort;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* Calculates the minimal superset of changes required to be merged.
- * <p>
- * This includes all parents between a change and the tip of its target
- * branch for the merging/rebasing submit strategies. For the cherry-pick
- * strategy no additional changes are included.
- * <p>
- * If change.submitWholeTopic is enabled, also all changes of the topic
- * and their parents are included.
+ *
+ * <p>This includes all parents between a change and the tip of its target branch for the
+ * merging/rebasing submit strategies. For the cherry-pick strategy no additional changes are
+ * included.
+ *
+ * <p>If change.submitWholeTopic is enabled, also all changes of the topic and their parents are
+ * included.
*/
public class MergeSuperSet {
private static final Logger log = LoggerFactory.getLogger(MergeOp.class);
@@ -87,13 +85,12 @@
@AutoValue
abstract static class QueryKey {
- private static QueryKey create(
- Branch.NameKey branch, Iterable<String> hashes) {
- return new AutoValue_MergeSuperSet_QueryKey(
- branch, ImmutableSet.copyOf(hashes));
+ private static QueryKey create(Branch.NameKey branch, Iterable<String> hashes) {
+ return new AutoValue_MergeSuperSet_QueryKey(branch, ImmutableSet.copyOf(hashes));
}
abstract Branch.NameKey branch();
+
abstract ImmutableSet<String> hashes();
}
@@ -108,7 +105,8 @@
private boolean closeOrm;
@Inject
- MergeSuperSet(@GerritServerConfig Config cfg,
+ MergeSuperSet(
+ @GerritServerConfig Config cfg,
ChangeData.Factory changeDataFactory,
Provider<InternalChangeQuery> queryProvider,
Provider<MergeOpRepoManager> repoManagerProvider) {
@@ -127,11 +125,10 @@
return this;
}
- public ChangeSet completeChangeSet(ReviewDb db, Change change,
- CurrentUser user) throws IOException, OrmException {
+ public ChangeSet completeChangeSet(ReviewDb db, Change change, CurrentUser user)
+ throws IOException, OrmException {
try {
- ChangeData cd =
- changeDataFactory.create(db, change.getProject(), change.getId());
+ ChangeData cd = changeDataFactory.create(db, change.getProject(), change.getId());
cd.changeControl(user);
ChangeSet cs = new ChangeSet(cd, cd.changeControl().isVisible(db, cd));
if (Submit.wholeTopicEnabled(cfg)) {
@@ -146,8 +143,7 @@
}
}
- private SubmitType submitType(ChangeData cd, PatchSet ps, boolean visible)
- throws OrmException {
+ private SubmitType submitType(ChangeData cd, PatchSet ps, boolean visible) throws OrmException {
// Submit type prolog rules mean that the submit type can depend on the
// submitting user and the content of the change.
//
@@ -167,14 +163,13 @@
? cd.submitTypeRecord()
: new SubmitRuleEvaluator(cd).setPatchSet(ps).getSubmitType();
if (!str.isOk()) {
- logErrorAndThrow("Failed to get submit type for " + cd.getId()
- + ": " + str.errorMessage);
+ logErrorAndThrow("Failed to get submit type for " + cd.getId() + ": " + str.errorMessage);
}
return str.type;
}
- private static ImmutableListMultimap<Branch.NameKey, ChangeData>
- byBranch(Iterable<ChangeData> changes) throws OrmException {
+ private static ImmutableListMultimap<Branch.NameKey, ChangeData> byBranch(
+ Iterable<ChangeData> changes) throws OrmException {
ImmutableListMultimap.Builder<Branch.NameKey, ChangeData> builder =
ImmutableListMultimap.builder();
for (ChangeData cd : changes) {
@@ -183,8 +178,8 @@
return builder.build();
}
- private Set<String> walkChangesByHashes(Collection<RevCommit> sourceCommits,
- Set<String> ignoreHashes, OpenRepo or, Branch.NameKey b)
+ private Set<String> walkChangesByHashes(
+ Collection<RevCommit> sourceCommits, Set<String> ignoreHashes, OpenRepo or, Branch.NameKey b)
throws IOException {
Set<String> destHashes = new HashSet<>();
or.rw.reset();
@@ -208,21 +203,22 @@
return destHashes;
}
- private ChangeSet completeChangeSetWithoutTopic(ReviewDb db,
- ChangeSet changes, CurrentUser user) throws IOException, OrmException {
+ private ChangeSet completeChangeSetWithoutTopic(ReviewDb db, ChangeSet changes, CurrentUser user)
+ throws IOException, OrmException {
Collection<ChangeData> visibleChanges = new ArrayList<>();
Collection<ChangeData> nonVisibleChanges = new ArrayList<>();
// For each target branch we run a separate rev walk to find open changes
// reachable from changes already in the merge super set.
- ImmutableListMultimap<Branch.NameKey, ChangeData> bc = byBranch(
- Iterables.concat(changes.changes(), changes.nonVisibleChanges()));
+ ImmutableListMultimap<Branch.NameKey, ChangeData> bc =
+ byBranch(Iterables.concat(changes.changes(), changes.nonVisibleChanges()));
for (Branch.NameKey b : bc.keySet()) {
OpenRepo or = getRepo(b.getParentKey());
List<RevCommit> visibleCommits = new ArrayList<>();
List<RevCommit> nonVisibleCommits = new ArrayList<>();
for (ChangeData cd : bc.get(b)) {
- checkState(cd.hasChangeControl(),
+ checkState(
+ cd.hasChangeControl(),
"completeChangeSet forgot to set changeControl for current user"
+ " at ChangeData creation time");
@@ -233,8 +229,7 @@
// completeChangeSet computation, for example.
visible = false;
}
- Collection<RevCommit> toWalk = visible ?
- visibleCommits : nonVisibleCommits;
+ Collection<RevCommit> toWalk = visible ? visibleCommits : nonVisibleCommits;
// Pick a revision to use for traversal. If any of the patch sets
// is visible, we use the most recent one. Otherwise, use the current
@@ -271,20 +266,17 @@
}
Set<String> emptySet = Collections.emptySet();
- Set<String> visibleHashes =
- walkChangesByHashes(visibleCommits, emptySet, or, b);
+ Set<String> visibleHashes = walkChangesByHashes(visibleCommits, emptySet, or, b);
- List<ChangeData> cds =
- byCommitsOnBranchNotMerged(or, db, user, b, visibleHashes);
+ List<ChangeData> cds = byCommitsOnBranchNotMerged(or, db, user, b, visibleHashes);
for (ChangeData chd : cds) {
chd.changeControl(user);
visibleChanges.add(chd);
}
- Set<String> nonVisibleHashes =
- walkChangesByHashes(nonVisibleCommits, visibleHashes, or, b);
- Iterables.addAll(nonVisibleChanges,
- byCommitsOnBranchNotMerged(or, db, user, b, nonVisibleHashes));
+ Set<String> nonVisibleHashes = walkChangesByHashes(nonVisibleCommits, visibleHashes, or, b);
+ Iterables.addAll(
+ nonVisibleChanges, byCommitsOnBranchNotMerged(or, db, user, b, nonVisibleHashes));
}
return new ChangeSet(visibleChanges, nonVisibleChanges);
@@ -304,14 +296,11 @@
}
}
- private void markHeadUninteresting(OpenRepo or, Branch.NameKey b)
- throws IOException {
+ private void markHeadUninteresting(OpenRepo or, Branch.NameKey b) throws IOException {
Optional<RevCommit> head = heads.get(b);
if (head == null) {
Ref ref = or.repo.getRefDatabase().exactRef(b.get());
- head = ref != null
- ? Optional.of(or.rw.parseCommit(ref.getObjectId()))
- : Optional.empty();
+ head = ref != null ? Optional.of(or.rw.parseCommit(ref.getObjectId())) : Optional.empty();
heads.put(b, head);
}
if (head.isPresent()) {
@@ -319,8 +308,8 @@
}
}
- private List<ChangeData> byCommitsOnBranchNotMerged(OpenRepo or, ReviewDb db,
- CurrentUser user, Branch.NameKey branch, Set<String> hashes)
+ private List<ChangeData> byCommitsOnBranchNotMerged(
+ OpenRepo or, ReviewDb db, CurrentUser user, Branch.NameKey branch, Set<String> hashes)
throws OrmException, IOException {
if (hashes.isEmpty()) {
return ImmutableList.of();
@@ -332,8 +321,8 @@
}
List<ChangeData> result = new ArrayList<>();
- Iterable<ChangeData> destChanges = query()
- .byCommitsOnBranchNotMerged(or.repo, db, branch, hashes);
+ Iterable<ChangeData> destChanges =
+ query().byCommitsOnBranchNotMerged(or.repo, db, branch, hashes);
for (ChangeData chd : destChanges) {
chd.changeControl(user);
result.add(chd);
@@ -344,20 +333,22 @@
/**
* Completes {@code cs} with any additional changes from its topics
- * <p>
- * {@link #completeChangeSetIncludingTopics} calls this repeatedly,
- * alternating with {@link #completeChangeSetWithoutTopic}, to discover
- * what additional changes should be submitted with a change until the
- * set stops growing.
- * <p>
- * {@code topicsSeen} and {@code visibleTopicsSeen} keep track of topics
- * already explored to avoid wasted work.
+ *
+ * <p>{@link #completeChangeSetIncludingTopics} calls this repeatedly, alternating with {@link
+ * #completeChangeSetWithoutTopic}, to discover what additional changes should be submitted with a
+ * change until the set stops growing.
+ *
+ * <p>{@code topicsSeen} and {@code visibleTopicsSeen} keep track of topics already explored to
+ * avoid wasted work.
*
* @return the resulting larger {@link ChangeSet}
*/
private ChangeSet topicClosure(
- ReviewDb db, ChangeSet cs, CurrentUser user,
- Set<String> topicsSeen, Set<String> visibleTopicsSeen)
+ ReviewDb db,
+ ChangeSet cs,
+ CurrentUser user,
+ Set<String> topicsSeen,
+ Set<String> visibleTopicsSeen)
throws OrmException {
List<ChangeData> visibleChanges = new ArrayList<>();
List<ChangeData> nonVisibleChanges = new ArrayList<>();
@@ -403,8 +394,7 @@
}
private ChangeSet completeChangeSetIncludingTopics(
- ReviewDb db, ChangeSet changes, CurrentUser user)
- throws IOException, OrmException {
+ ReviewDb db, ChangeSet changes, CurrentUser user) throws IOException, OrmException {
Set<String> topicsSeen = new HashSet<>();
Set<String> visibleTopicsSeen = new HashSet<>();
int oldSeen;
@@ -427,10 +417,11 @@
// more than necessary. This provides reasonable performance when loading
// the change screen; callers that care about reading the latest value of
// these fields should clear them explicitly using reloadChanges().
- Set<String> fields = ImmutableSet.of(
- ChangeField.CHANGE.getName(),
- ChangeField.PATCH_SET.getName(),
- ChangeField.MERGEABLE.getName());
+ Set<String> fields =
+ ImmutableSet.of(
+ ChangeField.CHANGE.getName(),
+ ChangeField.PATCH_SET.getName(),
+ ChangeField.MERGEABLE.getName());
return queryProvider.get().setRequestedFields(fields);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/MergeTip.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/MergeTip.java
index 5ea0c02..3bd0f38 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/MergeTip.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/MergeTip.java
@@ -18,20 +18,17 @@
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.gerrit.common.Nullable;
-
-import org.eclipse.jgit.lib.ObjectId;
-
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
+import org.eclipse.jgit.lib.ObjectId;
/**
* Class describing a merge tip during merge operation.
- * <p>
- * The current tip of a {@link MergeTip} may be null if the merge operation is
- * against an unborn branch, and has not yet been attempted. This is distinct
- * from a null {@link MergeTip} instance, which may be used to indicate that a
- * merge failed or another error state.
+ *
+ * <p>The current tip of a {@link MergeTip} may be null if the merge operation is against an unborn
+ * branch, and has not yet been attempted. This is distinct from a null {@link MergeTip} instance,
+ * which may be used to indicate that a merge failed or another error state.
*/
public class MergeTip {
private CodeReviewCommit initialTip;
@@ -39,13 +36,10 @@
private Map<ObjectId, ObjectId> mergeResults;
/**
- * @param initialTip tip before the merge operation; may be null, indicating
- * an unborn branch.
- * @param toMerge list of commits to be merged in merge operation; may not be
- * null or empty.
+ * @param initialTip tip before the merge operation; may be null, indicating an unborn branch.
+ * @param toMerge list of commits to be merged in merge operation; may not be null or empty.
*/
- public MergeTip(@Nullable CodeReviewCommit initialTip,
- Collection<CodeReviewCommit> toMerge) {
+ public MergeTip(@Nullable CodeReviewCommit initialTip, Collection<CodeReviewCommit> toMerge) {
checkNotNull(toMerge, "toMerge may not be null");
checkArgument(!toMerge.isEmpty(), "toMerge may not be empty");
this.initialTip = initialTip;
@@ -58,8 +52,8 @@
}
/**
- * @return the initial tip of the branch before the merge operation started;
- * may be null, indicating a previously unborn branch.
+ * @return the initial tip of the branch before the merge operation started; may be null,
+ * indicating a previously unborn branch.
*/
public CodeReviewCommit getInitialTip() {
return initialTip;
@@ -80,16 +74,16 @@
/**
* The merge results of all the merges of this merge operation.
*
- * @return The merge results of the merge operation as a map of SHA-1 to be
- * merged to SHA-1 of the merge result.
+ * @return The merge results of the merge operation as a map of SHA-1 to be merged to SHA-1 of the
+ * merge result.
*/
public Map<ObjectId, ObjectId> getMergeResults() {
return mergeResults;
}
/**
- * @return The current tip of the current merge operation; may be null,
- * indicating an unborn branch.
+ * @return The current tip of the current merge operation; may be null, indicating an unborn
+ * branch.
*/
@Nullable
public CodeReviewCommit getCurrentTip() {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/MergeUtil.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/MergeUtil.java
index 0c304a2..c7e0222 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/MergeUtil.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/MergeUtil.java
@@ -51,7 +51,15 @@
import com.google.inject.Provider;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
-
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Objects;
+import java.util.Set;
import org.eclipse.jgit.errors.AmbiguousObjectException;
import org.eclipse.jgit.errors.IncorrectObjectTypeException;
import org.eclipse.jgit.errors.LargeObjectException;
@@ -81,24 +89,13 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Objects;
-import java.util.Set;
-
/**
* Utility methods used during the merge process.
- * <p>
- * <strong>Note:</strong> Unless otherwise specified, the methods in this class
- * <strong>do not</strong> flush {@link ObjectInserter}s. Callers that want to
- * read back objects before flushing should use {@link
- * ObjectInserter#newReader()}. This is already the default behavior of {@code
- * BatchUpdate}.
+ *
+ * <p><strong>Note:</strong> Unless otherwise specified, the methods in this class <strong>do
+ * not</strong> flush {@link ObjectInserter}s. Callers that want to read back objects before
+ * flushing should use {@link ObjectInserter#newReader()}. This is already the default behavior of
+ * {@code BatchUpdate}.
*/
public class MergeUtil {
private static final Logger log = LoggerFactory.getLogger(MergeUtil.class);
@@ -107,42 +104,41 @@
private final DynamicSet<ChangeMessageModifier> changeMessageModifiers;
@Inject
- PluggableCommitMessageGenerator(
- DynamicSet<ChangeMessageModifier> changeMessageModifiers) {
+ PluggableCommitMessageGenerator(DynamicSet<ChangeMessageModifier> changeMessageModifiers) {
this.changeMessageModifiers = changeMessageModifiers;
}
- public String generate(RevCommit original, RevCommit mergeTip,
- ChangeControl ctl, String current) {
+ public String generate(
+ RevCommit original, RevCommit mergeTip, ChangeControl ctl, String current) {
checkNotNull(original.getRawBuffer());
if (mergeTip != null) {
checkNotNull(mergeTip.getRawBuffer());
}
for (ChangeMessageModifier changeMessageModifier : changeMessageModifiers) {
- current = changeMessageModifier.onSubmit(current, original,
- mergeTip, ctl.getChange().getDest());
- checkNotNull(current, changeMessageModifier.getClass().getName()
- + ".OnSubmit returned null instead of new commit message");
+ current =
+ changeMessageModifier.onSubmit(current, original, mergeTip, ctl.getChange().getDest());
+ checkNotNull(
+ current,
+ changeMessageModifier.getClass().getName()
+ + ".OnSubmit returned null instead of new commit message");
}
return current;
}
}
- private static final String R_HEADS_MASTER =
- Constants.R_HEADS + Constants.MASTER;
+ private static final String R_HEADS_MASTER = Constants.R_HEADS + Constants.MASTER;
public static boolean useRecursiveMerge(Config cfg) {
return cfg.getBoolean("core", null, "useRecursiveMerge", true);
}
public static ThreeWayMergeStrategy getMergeStrategy(Config cfg) {
- return useRecursiveMerge(cfg)
- ? MergeStrategy.RECURSIVE
- : MergeStrategy.RESOLVE;
+ return useRecursiveMerge(cfg) ? MergeStrategy.RECURSIVE : MergeStrategy.RESOLVE;
}
public interface Factory {
MergeUtil create(ProjectState project);
+
MergeUtil create(ProjectState project, boolean useContentMerge);
}
@@ -156,19 +152,28 @@
private final PluggableCommitMessageGenerator commitMessageGenerator;
@AssistedInject
- MergeUtil(@GerritServerConfig Config serverConfig,
+ MergeUtil(
+ @GerritServerConfig Config serverConfig,
Provider<ReviewDb> db,
IdentifiedUser.GenericFactory identifiedUserFactory,
@CanonicalWebUrl @Nullable Provider<String> urlProvider,
ApprovalsUtil approvalsUtil,
PluggableCommitMessageGenerator commitMessageGenerator,
@Assisted ProjectState project) {
- this(serverConfig, db, identifiedUserFactory, urlProvider, approvalsUtil,
- project, commitMessageGenerator, project.isUseContentMerge());
+ this(
+ serverConfig,
+ db,
+ identifiedUserFactory,
+ urlProvider,
+ approvalsUtil,
+ project,
+ commitMessageGenerator,
+ project.isUseContentMerge());
}
@AssistedInject
- MergeUtil(@GerritServerConfig Config serverConfig,
+ MergeUtil(
+ @GerritServerConfig Config serverConfig,
Provider<ReviewDb> db,
IdentifiedUser.GenericFactory identifiedUserFactory,
@CanonicalWebUrl @Nullable Provider<String> urlProvider,
@@ -187,9 +192,9 @@
}
public CodeReviewCommit getFirstFastForward(
- final CodeReviewCommit mergeTip, final RevWalk rw,
- final List<CodeReviewCommit> toMerge) throws IntegrationException {
- for (final Iterator<CodeReviewCommit> i = toMerge.iterator(); i.hasNext();) {
+ final CodeReviewCommit mergeTip, final RevWalk rw, final List<CodeReviewCommit> toMerge)
+ throws IntegrationException {
+ for (final Iterator<CodeReviewCommit> i = toMerge.iterator(); i.hasNext(); ) {
try {
final CodeReviewCommit n = i.next();
if (mergeTip == null || rw.isMergedInto(mergeTip, n)) {
@@ -197,15 +202,14 @@
return n;
}
} catch (IOException e) {
- throw new IntegrationException(
- "Cannot fast-forward test during merge", e);
+ throw new IntegrationException("Cannot fast-forward test during merge", e);
}
}
return mergeTip;
}
- public List<CodeReviewCommit> reduceToMinimalMerge(MergeSorter mergeSorter,
- Collection<CodeReviewCommit> toSort, Set<CodeReviewCommit> incoming)
+ public List<CodeReviewCommit> reduceToMinimalMerge(
+ MergeSorter mergeSorter, Collection<CodeReviewCommit> toSort, Set<CodeReviewCommit> incoming)
throws IntegrationException {
List<CodeReviewCommit> result = new ArrayList<>();
try {
@@ -217,12 +221,18 @@
return result;
}
- public CodeReviewCommit createCherryPickFromCommit(Repository repo,
- ObjectInserter inserter, RevCommit mergeTip, RevCommit originalCommit,
- PersonIdent cherryPickCommitterIdent, String commitMsg,
- CodeReviewRevWalk rw, int parentIndex, boolean ignoreIdenticalTree)
+ public CodeReviewCommit createCherryPickFromCommit(
+ Repository repo,
+ ObjectInserter inserter,
+ RevCommit mergeTip,
+ RevCommit originalCommit,
+ PersonIdent cherryPickCommitterIdent,
+ String commitMsg,
+ CodeReviewRevWalk rw,
+ int parentIndex,
+ boolean ignoreIdenticalTree)
throws MissingObjectException, IncorrectObjectTypeException, IOException,
- MergeIdenticalTreeException, MergeConflictException {
+ MergeIdenticalTreeException, MergeConflictException {
final ThreeWayMerger m = newThreeWayMerger(repo, inserter);
@@ -244,13 +254,19 @@
throw new MergeConflictException("merge conflict");
}
- public static RevCommit createMergeCommit(Repository repo, ObjectInserter inserter,
- RevCommit mergeTip, RevCommit originalCommit, String mergeStrategy,
- PersonIdent committerIndent, String commitMsg, RevWalk rw)
+ public static RevCommit createMergeCommit(
+ Repository repo,
+ ObjectInserter inserter,
+ RevCommit mergeTip,
+ RevCommit originalCommit,
+ String mergeStrategy,
+ PersonIdent committerIndent,
+ String commitMsg,
+ RevWalk rw)
throws IOException, MergeIdenticalTreeException, MergeConflictException {
- if (!MergeStrategy.THEIRS.getName().equals(mergeStrategy) &&
- rw.isMergedInto(originalCommit, mergeTip)) {
+ if (!MergeStrategy.THEIRS.getName().equals(mergeStrategy)
+ && rw.isMergedInto(originalCommit, mergeTip)) {
throw new ChangeAlreadyMergedException(
"'" + originalCommit.getName() + "' has already been merged");
}
@@ -285,13 +301,12 @@
/**
* Adds footers to existing commit message based on the state of the change.
*
- * This adds the following footers if they are missing:
+ * <p>This adds the following footers if they are missing:
*
* <ul>
- * <li> Reviewed-on: <i>url</i></li>
+ * <li> Reviewed-on: <i>url</i>
* <li> Reviewed-by | Tested-by | <i>Other-Label-Name</i>: <i>reviewer</i>
- * </li>
- * <li> Change-Id </li>
+ * <li> Change-Id
* </ul>
*
* @param n
@@ -299,8 +314,7 @@
* @param psId
* @return new message
*/
- private String createDetailedCommitMessage(RevCommit n, ChangeControl ctl,
- PatchSet.Id psId) {
+ private String createDetailedCommitMessage(RevCommit n, ChangeControl ctl, PatchSet.Id psId) {
Change c = ctl.getChange();
final List<FooterLine> footers = n.getFooterLines();
final StringBuilder msgbuf = new StringBuilder();
@@ -350,15 +364,13 @@
if (a.isLegacySubmit()) {
// Submit is treated specially, below (becomes committer)
//
- if (submitAudit == null
- || a.getGranted().compareTo(submitAudit.getGranted()) > 0) {
+ if (submitAudit == null || a.getGranted().compareTo(submitAudit.getGranted()) > 0) {
submitAudit = a;
}
continue;
}
- final Account acc =
- identifiedUserFactory.create(a.getAccountId()).getAccount();
+ final Account acc = identifiedUserFactory.create(a.getAccountId()).getAccount();
final StringBuilder identbuf = new StringBuilder();
if (acc.getFullName() != null && acc.getFullName().length() > 0) {
if (identbuf.length() > 0) {
@@ -366,8 +378,7 @@
}
identbuf.append(acc.getFullName());
}
- if (acc.getPreferredEmail() != null
- && acc.getPreferredEmail().length() > 0) {
+ if (acc.getPreferredEmail() != null && acc.getPreferredEmail().length() > 0) {
if (isSignedOffBy(footers, acc.getPreferredEmail())) {
continue;
}
@@ -406,18 +417,16 @@
return msgbuf.toString();
}
- public String createCommitMessageOnSubmit(CodeReviewCommit n,
- RevCommit mergeTip) {
- return createCommitMessageOnSubmit(n, mergeTip, n.getControl(),
- n.getPatchsetId());
+ public String createCommitMessageOnSubmit(CodeReviewCommit n, RevCommit mergeTip) {
+ return createCommitMessageOnSubmit(n, mergeTip, n.getControl(), n.getPatchsetId());
}
/**
* Creates a commit message for a change, which can be customized by plugins.
*
- * By default, adds footers to existing commit message based on the state of
- * the change. Plugins implementing {@link ChangeMessageModifier} can modify
- * the resulting commit message arbitrarily.
+ * <p>By default, adds footers to existing commit message based on the state of the change.
+ * Plugins implementing {@link ChangeMessageModifier} can modify the resulting commit message
+ * arbitrarily.
*
* @param n
* @param mergeTip
@@ -425,10 +434,10 @@
* @param id
* @return new message
*/
- public String createCommitMessageOnSubmit(RevCommit n, RevCommit mergeTip,
- ChangeControl ctl, Id id) {
- return commitMessageGenerator.generate(n, mergeTip, ctl,
- createDetailedCommitMessage(n, ctl, id));
+ public String createCommitMessageOnSubmit(
+ RevCommit n, RevCommit mergeTip, ChangeControl ctl, Id id) {
+ return commitMessageGenerator.generate(
+ n, mergeTip, ctl, createDetailedCommitMessage(n, ctl, id));
}
private static boolean isCodeReview(LabelId id) {
@@ -439,8 +448,7 @@
return "Verified".equalsIgnoreCase(id.get());
}
- private Iterable<PatchSetApproval> safeGetApprovals(
- ChangeControl ctl, PatchSet.Id psId) {
+ private Iterable<PatchSetApproval> safeGetApprovals(ChangeControl ctl, PatchSet.Id psId) {
try {
return approvalsUtil.byPatchSet(db.get(), ctl, psId);
} catch (OrmException e) {
@@ -460,16 +468,17 @@
private static boolean isSignedOffBy(List<FooterLine> footers, String email) {
for (final FooterLine line : footers) {
- if (line.matches(FooterKey.SIGNED_OFF_BY)
- && email.equals(line.getEmailAddress())) {
+ if (line.matches(FooterKey.SIGNED_OFF_BY) && email.equals(line.getEmailAddress())) {
return true;
}
}
return false;
}
- public boolean canMerge(final MergeSorter mergeSorter,
- final Repository repo, final CodeReviewCommit mergeTip,
+ public boolean canMerge(
+ final MergeSorter mergeSorter,
+ final Repository repo,
+ final CodeReviewCommit mergeTip,
final CodeReviewCommit toMerge)
throws IntegrationException {
if (hasMissingDependencies(mergeSorter, toMerge)) {
@@ -477,8 +486,7 @@
}
try (ObjectInserter ins = new InMemoryInserter(repo)) {
- return newThreeWayMerger(repo, ins)
- .merge(new AnyObjectId[] {mergeTip, toMerge});
+ return newThreeWayMerger(repo, ins).merge(new AnyObjectId[] {mergeTip, toMerge});
} catch (LargeObjectException e) {
log.warn("Cannot merge due to LargeObjectException: " + toMerge.name());
return false;
@@ -489,23 +497,31 @@
}
}
- public boolean canFastForward(MergeSorter mergeSorter,
- CodeReviewCommit mergeTip, CodeReviewRevWalk rw, CodeReviewCommit toMerge)
+ public boolean canFastForward(
+ MergeSorter mergeSorter,
+ CodeReviewCommit mergeTip,
+ CodeReviewRevWalk rw,
+ CodeReviewCommit toMerge)
throws IntegrationException {
if (hasMissingDependencies(mergeSorter, toMerge)) {
return false;
}
try {
- return mergeTip == null || rw.isMergedInto(mergeTip, toMerge)
+ return mergeTip == null
+ || rw.isMergedInto(mergeTip, toMerge)
|| rw.isMergedInto(toMerge, mergeTip);
} catch (IOException e) {
throw new IntegrationException("Cannot fast-forward test during merge", e);
}
}
- public boolean canCherryPick(MergeSorter mergeSorter, Repository repo,
- CodeReviewCommit mergeTip, CodeReviewRevWalk rw, CodeReviewCommit toMerge)
+ public boolean canCherryPick(
+ MergeSorter mergeSorter,
+ Repository repo,
+ CodeReviewCommit mergeTip,
+ CodeReviewRevWalk rw,
+ CodeReviewCommit toMerge)
throws IntegrationException {
if (mergeTip == null) {
// The branch is unborn. Fast-forward is possible.
@@ -531,8 +547,8 @@
return m.merge(mergeTip, toMerge);
} catch (IOException e) {
throw new IntegrationException(
- String.format("Cannot merge commit %s with mergetip %s",
- toMerge.name(), mergeTip.name()),
+ String.format(
+ "Cannot merge commit %s with mergetip %s", toMerge.name(), mergeTip.name()),
e);
}
}
@@ -547,8 +563,8 @@
|| canMerge(mergeSorter, repo, mergeTip, toMerge);
}
- public boolean hasMissingDependencies(final MergeSorter mergeSorter,
- final CodeReviewCommit toMerge) throws IntegrationException {
+ public boolean hasMissingDependencies(
+ final MergeSorter mergeSorter, final CodeReviewCommit toMerge) throws IntegrationException {
try {
return !mergeSorter.sort(Collections.singleton(toMerge)).contains(toMerge);
} catch (IOException e) {
@@ -556,16 +572,21 @@
}
}
- public CodeReviewCommit mergeOneCommit(PersonIdent author,
- PersonIdent committer, Repository repo, CodeReviewRevWalk rw,
- ObjectInserter inserter, Branch.NameKey destBranch,
- CodeReviewCommit mergeTip, CodeReviewCommit n)
+ public CodeReviewCommit mergeOneCommit(
+ PersonIdent author,
+ PersonIdent committer,
+ Repository repo,
+ CodeReviewRevWalk rw,
+ ObjectInserter inserter,
+ Branch.NameKey destBranch,
+ CodeReviewCommit mergeTip,
+ CodeReviewCommit n)
throws IntegrationException {
final ThreeWayMerger m = newThreeWayMerger(repo, inserter);
try {
if (m.merge(new AnyObjectId[] {mergeTip, n})) {
- return writeMergeCommit(author, committer, rw, inserter, destBranch,
- mergeTip, m.getResultTreeId(), n);
+ return writeMergeCommit(
+ author, committer, rw, inserter, destBranch, mergeTip, m.getResultTreeId(), n);
}
failed(rw, mergeTip, n, CommitMergeStatus.PATH_CONFLICT);
} catch (NoMergeBaseException e) {
@@ -580,8 +601,7 @@
return mergeTip;
}
- private static CommitMergeStatus getCommitMergeStatus(
- MergeBaseFailureReason reason) {
+ private static CommitMergeStatus getCommitMergeStatus(MergeBaseFailureReason reason) {
switch (reason) {
case MULTIPLE_MERGE_BASES_NOT_SUPPORTED:
case TOO_MANY_MERGE_BASES:
@@ -592,8 +612,11 @@
}
}
- private static CodeReviewCommit failed(CodeReviewRevWalk rw,
- CodeReviewCommit mergeTip, CodeReviewCommit n, CommitMergeStatus failure)
+ private static CodeReviewCommit failed(
+ CodeReviewRevWalk rw,
+ CodeReviewCommit mergeTip,
+ CodeReviewCommit n,
+ CommitMergeStatus failure)
throws MissingObjectException, IncorrectObjectTypeException, IOException {
rw.reset();
rw.markStart(n);
@@ -605,11 +628,16 @@
return failed;
}
- public CodeReviewCommit writeMergeCommit(PersonIdent author,
- PersonIdent committer, CodeReviewRevWalk rw, ObjectInserter inserter,
- Branch.NameKey destBranch, CodeReviewCommit mergeTip, ObjectId treeId,
- CodeReviewCommit n) throws IOException, MissingObjectException,
- IncorrectObjectTypeException {
+ public CodeReviewCommit writeMergeCommit(
+ PersonIdent author,
+ PersonIdent committer,
+ CodeReviewRevWalk rw,
+ ObjectInserter inserter,
+ Branch.NameKey destBranch,
+ CodeReviewCommit mergeTip,
+ ObjectId treeId,
+ CodeReviewCommit n)
+ throws IOException, MissingObjectException, IncorrectObjectTypeException {
final List<CodeReviewCommit> merged = new ArrayList<>();
rw.reset();
rw.markStart(n);
@@ -644,14 +672,12 @@
mergeCommit.setCommitter(committer);
mergeCommit.setMessage(msgbuf.toString());
- CodeReviewCommit mergeResult =
- rw.parseCommit(inserter.insert(mergeCommit));
+ CodeReviewCommit mergeResult = rw.parseCommit(inserter.insert(mergeCommit));
mergeResult.setControl(n.getControl());
return mergeResult;
}
- private String summarize(RevWalk rw, List<CodeReviewCommit> merged)
- throws IOException {
+ private String summarize(RevWalk rw, List<CodeReviewCommit> merged) throws IOException {
if (merged.size() == 1) {
CodeReviewCommit c = merged.get(0);
rw.parseBody(c);
@@ -666,13 +692,12 @@
}
if (topics.size() == 1) {
- return String.format("Merge changes from topic '%s'",
- Iterables.getFirst(topics, null));
+ return String.format("Merge changes from topic '%s'", Iterables.getFirst(topics, null));
} else if (topics.size() > 1) {
- return String.format("Merge changes from topics '%s'",
- Joiner.on("', '").join(topics));
+ return String.format("Merge changes from topics '%s'", Joiner.on("', '").join(topics));
} else {
- return String.format("Merge changes %s%s",
+ return String.format(
+ "Merge changes %s%s",
FluentIterable.from(merged)
.limit(5)
.transform(c -> c.change().getKey().abbreviate())
@@ -681,8 +706,7 @@
}
}
- public ThreeWayMerger newThreeWayMerger(final Repository repo,
- final ObjectInserter inserter) {
+ public ThreeWayMerger newThreeWayMerger(final Repository repo, final ObjectInserter inserter) {
return newThreeWayMerger(repo, inserter, mergeStrategyName());
}
@@ -690,8 +714,7 @@
return mergeStrategyName(useContentMerge, useRecursiveMerge);
}
- public static String mergeStrategyName(boolean useContentMerge,
- boolean useRecursiveMerge) {
+ public static String mergeStrategyName(boolean useContentMerge, boolean useRecursiveMerge) {
if (useContentMerge) {
// Settings for this project allow us to try and automatically resolve
// conflicts within files if needed. Use either the old resolve merger or
@@ -706,39 +729,43 @@
return MergeStrategy.SIMPLE_TWO_WAY_IN_CORE.getName();
}
- public static ThreeWayMerger newThreeWayMerger(Repository repo,
- final ObjectInserter inserter, String strategyName) {
+ public static ThreeWayMerger newThreeWayMerger(
+ Repository repo, final ObjectInserter inserter, String strategyName) {
Merger m = newMerger(repo, inserter, strategyName);
- checkArgument(m instanceof ThreeWayMerger,
- "merge strategy %s does not support three-way merging", strategyName);
+ checkArgument(
+ m instanceof ThreeWayMerger,
+ "merge strategy %s does not support three-way merging",
+ strategyName);
return (ThreeWayMerger) m;
}
- public static Merger newMerger(Repository repo,
- final ObjectInserter inserter, String strategyName) {
+ public static Merger newMerger(
+ Repository repo, final ObjectInserter inserter, String strategyName) {
MergeStrategy strategy = MergeStrategy.get(strategyName);
checkArgument(strategy != null, "invalid merge strategy: %s", strategyName);
Merger m = strategy.newMerger(repo, true);
- m.setObjectInserter(new ObjectInserter.Filter() {
- @Override
- protected ObjectInserter delegate() {
- return inserter;
- }
+ m.setObjectInserter(
+ new ObjectInserter.Filter() {
+ @Override
+ protected ObjectInserter delegate() {
+ return inserter;
+ }
- @Override
- public void flush() {
- }
+ @Override
+ public void flush() {}
- @Override
- public void close() {
- }
- });
+ @Override
+ public void close() {}
+ });
return m;
}
- public void markCleanMerges(final RevWalk rw,
- final RevFlag canMergeFlag, final CodeReviewCommit mergeTip,
- final Set<RevCommit> alreadyAccepted) throws IntegrationException {
+ public void markCleanMerges(
+ final RevWalk rw,
+ final RevFlag canMergeFlag,
+ final CodeReviewCommit mergeTip,
+ final Set<RevCommit> alreadyAccepted)
+ throws IntegrationException {
if (mergeTip == null) {
// If mergeTip is null here, branchTip was null, indicating a new branch
// at the start of the merge process. We also elected to merge nothing,
@@ -770,9 +797,13 @@
}
}
- public Set<Change.Id> findUnmergedChanges(Set<Change.Id> expected,
- CodeReviewRevWalk rw, RevFlag canMergeFlag, CodeReviewCommit oldTip,
- CodeReviewCommit mergeTip, Iterable<Change.Id> alreadyMerged)
+ public Set<Change.Id> findUnmergedChanges(
+ Set<Change.Id> expected,
+ CodeReviewRevWalk rw,
+ RevFlag canMergeFlag,
+ CodeReviewCommit oldTip,
+ CodeReviewCommit mergeTip,
+ Iterable<Change.Id> alreadyMerged)
throws IntegrationException {
if (mergeTip == null) {
return expected;
@@ -808,8 +839,9 @@
}
}
- public static CodeReviewCommit findAnyMergedInto(CodeReviewRevWalk rw,
- Iterable<CodeReviewCommit> commits, CodeReviewCommit tip) throws IOException {
+ public static CodeReviewCommit findAnyMergedInto(
+ CodeReviewRevWalk rw, Iterable<CodeReviewCommit> commits, CodeReviewCommit tip)
+ throws IOException {
for (CodeReviewCommit c : commits) {
// TODO(dborowitz): Seems like this could get expensive for many patch
// sets. Is there a more efficient implementation?
@@ -825,12 +857,10 @@
try {
ObjectId commitId = repo.resolve(str);
if (commitId == null) {
- throw new BadRequestException(
- "Cannot resolve '" + str + "' to a commit");
+ throw new BadRequestException("Cannot resolve '" + str + "' to a commit");
}
return rw.parseCommit(commitId);
- } catch (AmbiguousObjectException | IncorrectObjectTypeException |
- RevisionSyntaxException e) {
+ } catch (AmbiguousObjectException | IncorrectObjectTypeException | RevisionSyntaxException e) {
throw new BadRequestException(e.getMessage());
} catch (MissingObjectException e) {
throw new ResourceNotFoundException(e.getMessage());
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/MergedByPushOp.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/MergedByPushOp.java
index 1502c4a..8946042 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/MergedByPushOp.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/MergedByPushOp.java
@@ -36,7 +36,9 @@
import com.google.inject.Provider;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
-
+import java.io.IOException;
+import java.util.Collections;
+import java.util.concurrent.ExecutorService;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Repository;
@@ -45,17 +47,12 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.util.Collections;
-import java.util.concurrent.ExecutorService;
-
public class MergedByPushOp extends BatchUpdate.Op {
- private static final Logger log =
- LoggerFactory.getLogger(MergedByPushOp.class);
+ private static final Logger log = LoggerFactory.getLogger(MergedByPushOp.class);
public interface Factory {
- MergedByPushOp create(RequestScopePropagator requestScopePropagator,
- PatchSet.Id psId, String refName);
+ MergedByPushOp create(
+ RequestScopePropagator requestScopePropagator, PatchSet.Id psId, String refName);
}
private final RequestScopePropagator requestScopePropagator;
@@ -101,15 +98,13 @@
return refName;
}
- public MergedByPushOp setPatchSetProvider(
- Provider<PatchSet> patchSetProvider) {
+ public MergedByPushOp setPatchSetProvider(Provider<PatchSet> patchSetProvider) {
this.patchSetProvider = checkNotNull(patchSetProvider);
return this;
}
@Override
- public boolean updateChange(ChangeContext ctx)
- throws OrmException, IOException {
+ public boolean updateChange(ChangeContext ctx) throws OrmException, IOException {
change = ctx.getChange();
correctBranch = refName.equals(change.getDest().get());
if (!correctBranch) {
@@ -121,9 +116,9 @@
// that is not present in the old notes so we can't use PatchSetUtil.
patchSet = patchSetProvider.get();
} else {
- patchSet = checkNotNull(
- psUtil.get(ctx.getDb(), ctx.getNotes(), psId),
- "patch set %s not found", psId);
+ patchSet =
+ checkNotNull(
+ psUtil.get(ctx.getDb(), ctx.getNotes(), psId), "patch set %s not found", psId);
}
info = getPatchSetInfo(ctx);
@@ -150,17 +145,16 @@
}
}
msgBuf.append(".");
- ChangeMessage msg = ChangeMessagesUtil.newMessage(
- psId, ctx.getUser(), ctx.getWhen(), msgBuf.toString(),
- ChangeMessagesUtil.TAG_MERGED);
+ ChangeMessage msg =
+ ChangeMessagesUtil.newMessage(
+ psId, ctx.getUser(), ctx.getWhen(), msgBuf.toString(), ChangeMessagesUtil.TAG_MERGED);
cmUtil.addChangeMessage(ctx.getDb(), update, msg);
- PatchSetApproval submitter = ApprovalsUtil.newApproval(
- change.currentPatchSetId(), ctx.getUser(), LabelId.legacySubmit(),
- 1, ctx.getWhen());
+ PatchSetApproval submitter =
+ ApprovalsUtil.newApproval(
+ change.currentPatchSetId(), ctx.getUser(), LabelId.legacySubmit(), 1, ctx.getWhen());
update.putApproval(submitter.getLabel(), submitter.getValue());
- ctx.getDb().patchSetApprovals().upsert(
- Collections.singleton(submitter));
+ ctx.getDb().patchSetApprovals().upsert(Collections.singleton(submitter));
return true;
}
@@ -170,36 +164,36 @@
if (!correctBranch) {
return;
}
- sendEmailExecutor.submit(requestScopePropagator.wrap(new Runnable() {
- @Override
- public void run() {
- try {
- MergedSender cm =
- mergedSenderFactory.create(ctx.getProject(), psId.getParentKey());
- cm.setFrom(ctx.getAccountId());
- cm.setPatchSet(patchSet, info);
- cm.send();
- } catch (Exception e) {
- log.error("Cannot send email for submitted patch set " + psId, e);
- }
- }
+ sendEmailExecutor.submit(
+ requestScopePropagator.wrap(
+ new Runnable() {
+ @Override
+ public void run() {
+ try {
+ MergedSender cm =
+ mergedSenderFactory.create(ctx.getProject(), psId.getParentKey());
+ cm.setFrom(ctx.getAccountId());
+ cm.setPatchSet(patchSet, info);
+ cm.send();
+ } catch (Exception e) {
+ log.error("Cannot send email for submitted patch set " + psId, e);
+ }
+ }
- @Override
- public String toString() {
- return "send-email merged";
- }
- }));
+ @Override
+ public String toString() {
+ return "send-email merged";
+ }
+ }));
- changeMerged.fire(change, patchSet,
- ctx.getAccount(),
- patchSet.getRevision().get(),
- ctx.getWhen());
+ changeMerged.fire(
+ change, patchSet, ctx.getAccount(), patchSet.getRevision().get(), ctx.getWhen());
}
private PatchSetInfo getPatchSetInfo(ChangeContext ctx) throws IOException {
RevWalk rw = ctx.getRevWalk();
- RevCommit commit = rw.parseCommit(
- ObjectId.fromString(checkNotNull(patchSet).getRevision().get()));
+ RevCommit commit =
+ rw.parseCommit(ObjectId.fromString(checkNotNull(patchSet).getRevision().get()));
return patchSetInfoFactory.get(rw, commit, psId);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/MetaDataUpdate.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/MetaDataUpdate.java
index 7e47d1e..e3b1ad6 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/MetaDataUpdate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/MetaDataUpdate.java
@@ -23,7 +23,7 @@
import com.google.inject.Provider;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
-
+import java.io.IOException;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
import org.eclipse.jgit.lib.BatchRefUpdate;
import org.eclipse.jgit.lib.CommitBuilder;
@@ -31,8 +31,6 @@
import org.eclipse.jgit.lib.RefUpdate;
import org.eclipse.jgit.lib.Repository;
-import java.io.IOException;
-
/** Helps with the updating of a {@link VersionedMetaData}. */
public class MetaDataUpdate implements AutoCloseable {
public static class User {
@@ -42,7 +40,9 @@
private final Provider<IdentifiedUser> identifiedUser;
@Inject
- User(InternalFactory factory, GitRepositoryManager mgr,
+ User(
+ InternalFactory factory,
+ GitRepositoryManager mgr,
@GerritPersonIdent PersonIdent serverIdent,
Provider<IdentifiedUser> identifiedUser) {
this.factory = factory;
@@ -65,20 +65,18 @@
return create(name, user, null);
}
- /**
- * Create an update using an existing batch ref update.
- * <p>
- * This allows batching together updates to multiple metadata refs. For making
- * multiple commits to a single metadata ref, see
- * {@link VersionedMetaData#openUpdate(MetaDataUpdate)}.
- *
- * @param name project name.
- * @param user user for the update.
- * @param batch batch update to use; the caller is responsible for committing
- * the update.
- */
- public MetaDataUpdate create(Project.NameKey name, IdentifiedUser user,
- BatchRefUpdate batch) throws RepositoryNotFoundException, IOException {
+ /**
+ * Create an update using an existing batch ref update.
+ *
+ * <p>This allows batching together updates to multiple metadata refs. For making multiple
+ * commits to a single metadata ref, see {@link VersionedMetaData#openUpdate(MetaDataUpdate)}.
+ *
+ * @param name project name.
+ * @param user user for the update.
+ * @param batch batch update to use; the caller is responsible for committing the update.
+ */
+ public MetaDataUpdate create(Project.NameKey name, IdentifiedUser user, BatchRefUpdate batch)
+ throws RepositoryNotFoundException, IOException {
Repository repo = mgr.openRepository(name);
MetaDataUpdate md = create(name, repo, user, batch);
md.setCloseRepository(true);
@@ -87,12 +85,12 @@
/**
* Create an update using an existing batch ref update.
- * <p>
- * This allows batching together updates to multiple metadata refs. For making
- * multiple commits to a single metadata ref, see
- * {@link VersionedMetaData#openUpdate(MetaDataUpdate)}.
*
- * Important: Create a new MetaDataUpdate instance for each update:
+ * <p>This allows batching together updates to multiple metadata refs. For making multiple
+ * commits to a single metadata ref, see {@link VersionedMetaData#openUpdate(MetaDataUpdate)}.
+ *
+ * <p>Important: Create a new MetaDataUpdate instance for each update:
+ *
* <pre>
* <code>
* try (Repository repo = repoMgr.openRepository(allUsersName);
@@ -120,14 +118,13 @@
* </pre>
*
* @param name project name.
- * @param repository the repository to update; the caller is responsible for
- * closing the repository.
+ * @param repository the repository to update; the caller is responsible for closing the
+ * repository.
* @param user user for the update.
- * @param batch batch update to use; the caller is responsible for committing
- * the update.
+ * @param batch batch update to use; the caller is responsible for committing the update.
*/
- public MetaDataUpdate create(Project.NameKey name, Repository repository,
- IdentifiedUser user, BatchRefUpdate batch) {
+ public MetaDataUpdate create(
+ Project.NameKey name, Repository repository, IdentifiedUser user, BatchRefUpdate batch) {
MetaDataUpdate md = factory.create(name, repository, batch);
md.getCommitBuilder().setCommitter(serverIdent);
md.setAuthor(user);
@@ -135,8 +132,7 @@
}
private PersonIdent createPersonIdent(IdentifiedUser user) {
- return user.newCommitterIdent(
- serverIdent.getWhen(), serverIdent.getTimeZone());
+ return user.newCommitterIdent(serverIdent.getWhen(), serverIdent.getTimeZone());
}
}
@@ -146,7 +142,9 @@
private final PersonIdent serverIdent;
@Inject
- Server(InternalFactory factory, GitRepositoryManager mgr,
+ Server(
+ InternalFactory factory,
+ GitRepositoryManager mgr,
@GerritPersonIdent PersonIdent serverIdent) {
this.factory = factory;
this.mgr = mgr;
@@ -171,7 +169,8 @@
}
interface InternalFactory {
- MetaDataUpdate create(@Assisted Project.NameKey projectName,
+ MetaDataUpdate create(
+ @Assisted Project.NameKey projectName,
@Assisted Repository repository,
@Assisted @Nullable BatchRefUpdate batch);
}
@@ -187,8 +186,10 @@
private IdentifiedUser author;
@AssistedInject
- public MetaDataUpdate(GitReferenceUpdated gitRefUpdated,
- @Assisted Project.NameKey projectName, @Assisted Repository repository,
+ public MetaDataUpdate(
+ GitReferenceUpdated gitRefUpdated,
+ @Assisted Project.NameKey projectName,
+ @Assisted Repository repository,
@Assisted @Nullable BatchRefUpdate batch) {
this.gitRefUpdated = gitRefUpdated;
this.projectName = projectName;
@@ -197,8 +198,8 @@
this.commit = new CommitBuilder();
}
- public MetaDataUpdate(GitReferenceUpdated gitRefUpdated,
- Project.NameKey projectName, Repository repository) {
+ public MetaDataUpdate(
+ GitReferenceUpdated gitRefUpdated, Project.NameKey projectName, Repository repository) {
this(gitRefUpdated, projectName, repository, null);
}
@@ -209,9 +210,11 @@
public void setAuthor(IdentifiedUser author) {
this.author = author;
- getCommitBuilder().setAuthor(author.newCommitterIdent(
- getCommitBuilder().getCommitter().getWhen(),
- getCommitBuilder().getCommitter().getTimeZone()));
+ getCommitBuilder()
+ .setAuthor(
+ author.newCommitterIdent(
+ getCommitBuilder().getCommitter().getWhen(),
+ getCommitBuilder().getCommitter().getTimeZone()));
}
public void setAllowEmpty(boolean allowEmpty) {
@@ -260,7 +263,6 @@
}
protected void fireGitRefUpdatedEvent(RefUpdate ru) {
- gitRefUpdated.fire(
- projectName, ru, author == null ? null : author.getAccount());
+ gitRefUpdated.fire(projectName, ru, author == null ? null : author.getAccount());
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/MultiBaseLocalDiskRepositoryManager.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/MultiBaseLocalDiskRepositoryManager.java
index db739b1..7928ac2 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/MultiBaseLocalDiskRepositoryManager.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/MultiBaseLocalDiskRepositoryManager.java
@@ -22,19 +22,15 @@
import com.google.gerrit.server.config.RepositoryConfig;
import com.google.gerrit.server.config.SitePaths;
import com.google.inject.Inject;
-
+import java.nio.file.Path;
import org.eclipse.jgit.lib.Config;
-import java.nio.file.Path;
-
-public class MultiBaseLocalDiskRepositoryManager extends
- LocalDiskRepositoryManager {
+public class MultiBaseLocalDiskRepositoryManager extends LocalDiskRepositoryManager {
public static class Module extends LifecycleModule {
@Override
protected void configure() {
- bind(GitRepositoryManager.class).to(
- MultiBaseLocalDiskRepositoryManager.class);
+ bind(GitRepositoryManager.class).to(MultiBaseLocalDiskRepositoryManager.class);
listener().to(MultiBaseLocalDiskRepositoryManager.Lifecycle.class);
}
}
@@ -42,24 +38,23 @@
private final RepositoryConfig config;
@Inject
- MultiBaseLocalDiskRepositoryManager(SitePaths site,
- @GerritServerConfig Config cfg,
- RepositoryConfig config) {
+ MultiBaseLocalDiskRepositoryManager(
+ SitePaths site, @GerritServerConfig Config cfg, RepositoryConfig config) {
super(site, cfg);
this.config = config;
for (Path alternateBasePath : config.getAllBasePaths()) {
- checkState(alternateBasePath.isAbsolute(),
- "repository.<name>.basePath must be absolute: %s", alternateBasePath);
+ checkState(
+ alternateBasePath.isAbsolute(),
+ "repository.<name>.basePath must be absolute: %s",
+ alternateBasePath);
}
}
@Override
public Path getBasePath(NameKey name) {
Path alternateBasePath = config.getBasePath(name);
- return alternateBasePath != null
- ? alternateBasePath
- : super.getBasePath(name);
+ return alternateBasePath != null ? alternateBasePath : super.getBasePath(name);
}
@Override
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/MultiProgressMonitor.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/MultiProgressMonitor.java
index 9810fec..a994af0 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/MultiProgressMonitor.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/MultiProgressMonitor.java
@@ -17,12 +17,6 @@
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import com.google.common.base.Strings;
-
-import org.eclipse.jgit.lib.Constants;
-import org.eclipse.jgit.lib.ProgressMonitor;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
@@ -32,31 +26,34 @@
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
+import org.eclipse.jgit.lib.Constants;
+import org.eclipse.jgit.lib.ProgressMonitor;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* Progress reporting interface that multiplexes multiple sub-tasks.
- * <p>
- * Output is of the format:
+ *
+ * <p>Output is of the format:
+ *
* <pre>
* Task: subA: 1, subB: 75% (3/4) (-)\r
* Task: subA: 2, subB: 75% (3/4), subC: 1 (\)\r
* Task: subA: 2, subB: 100% (4/4), subC: 1 (|)\r
* Task: subA: 4, subB: 100% (4/4), subC: 4, done \n
* </pre>
- * <p>
- * Callers should try to keep task and sub-task descriptions short, since the
- * output should fit on one terminal line. (Note that git clients do not accept
- * terminal control characters, so true multi-line progress messages would be
- * impossible.)
+ *
+ * <p>Callers should try to keep task and sub-task descriptions short, since the output should fit
+ * on one terminal line. (Note that git clients do not accept terminal control characters, so true
+ * multi-line progress messages would be impossible.)
*/
public class MultiProgressMonitor {
- private static final Logger log =
- LoggerFactory.getLogger(MultiProgressMonitor.class);
+ private static final Logger log = LoggerFactory.getLogger(MultiProgressMonitor.class);
/** Constant indicating the total work units cannot be predicted. */
public static final int UNKNOWN = 0;
- private static final char[] SPINNER_STATES = new char[]{'-', '\\', '|', '/'};
+ private static final char[] SPINNER_STATES = new char[] {'-', '\\', '|', '/'};
private static final char NO_SPINNER = ' ';
/** Handle for a sub-task. */
@@ -73,8 +70,8 @@
/**
* Indicate that work has been completed on this sub-task.
- * <p>
- * Must be called from a worker thread.
+ *
+ * <p>Must be called from a worker thread.
*
* @param completed number of work units completed.
*/
@@ -98,8 +95,8 @@
/**
* Indicate that this sub-task is finished.
- * <p>
- * Must be called from a worker thread.
+ *
+ * <p>Must be called from a worker thread.
*/
public void end() {
if (total == UNKNOWN && getCount() > 0) {
@@ -108,16 +105,13 @@
}
@Override
- public void start(int totalTasks) {
- }
+ public void start(int totalTasks) {}
@Override
- public void beginTask(String title, int totalWork) {
- }
+ public void beginTask(String title, int totalWork) {}
@Override
- public void endTask() {
- }
+ public void endTask() {}
@Override
public boolean isCancelled() {
@@ -125,7 +119,7 @@
}
public int getCount() {
- synchronized(MultiProgressMonitor.this) {
+ synchronized (MultiProgressMonitor.this) {
return count;
}
}
@@ -159,8 +153,11 @@
* @param maxIntervalTime maximum interval between progress messages.
* @param maxIntervalUnit time unit for progress interval.
*/
- public MultiProgressMonitor(final OutputStream out, final String taskName,
- long maxIntervalTime, TimeUnit maxIntervalUnit) {
+ public MultiProgressMonitor(
+ final OutputStream out,
+ final String taskName,
+ long maxIntervalTime,
+ TimeUnit maxIntervalUnit) {
this.out = out;
this.taskName = taskName;
maxIntervalNanos = NANOSECONDS.convert(maxIntervalTime, maxIntervalUnit);
@@ -177,23 +174,21 @@
/**
* Wait for a task managed by a {@link Future}.
- * <p>
- * Must be called from the main thread, <em>not</em> a worker thread. Once a
- * worker thread calls {@link #end()}, the future has an additional
- * {@code maxInterval} to finish before it is forcefully cancelled and
- * {@link ExecutionException} is thrown.
+ *
+ * <p>Must be called from the main thread, <em>not</em> a worker thread. Once a worker thread
+ * calls {@link #end()}, the future has an additional {@code maxInterval} to finish before it is
+ * forcefully cancelled and {@link ExecutionException} is thrown.
*
* @param workerFuture a future that returns when worker threads are finished.
- * @param timeoutTime overall timeout for the task; the future is forcefully
- * cancelled if the task exceeds the timeout. Non-positive values indicate
- * no timeout.
+ * @param timeoutTime overall timeout for the task; the future is forcefully cancelled if the task
+ * exceeds the timeout. Non-positive values indicate no timeout.
* @param timeoutUnit unit for overall task timeout.
- * @throws ExecutionException if this thread or a worker thread was
- * interrupted, the worker was cancelled, or timed out waiting for a
- * worker to call {@link #end()}.
+ * @throws ExecutionException if this thread or a worker thread was interrupted, the worker was
+ * cancelled, or timed out waiting for a worker to call {@link #end()}.
*/
- public void waitFor(final Future<?> workerFuture, final long timeoutTime,
- final TimeUnit timeoutUnit) throws ExecutionException {
+ public void waitFor(
+ final Future<?> workerFuture, final long timeoutTime, final TimeUnit timeoutUnit)
+ throws ExecutionException {
long overallStart = System.nanoTime();
long deadline;
String detailMessage = "";
@@ -220,10 +215,12 @@
if (deadline > 0 && now > deadline) {
workerFuture.cancel(true);
if (workerFuture.isCancelled()) {
- detailMessage = String.format(
+ detailMessage =
+ String.format(
"(timeout %sms, cancelled)",
TimeUnit.MILLISECONDS.convert(now - deadline, NANOSECONDS));
- log.warn(String.format(
+ log.warn(
+ String.format(
"MultiProgressMonitor worker killed after %sms" + detailMessage, //
TimeUnit.MILLISECONDS.convert(now - overallStart, NANOSECONDS)));
}
@@ -239,8 +236,7 @@
if (!done && workerFuture.isDone()) {
// The worker may not have called end() explicitly, which is likely a
// programming error.
- log.warn("MultiProgressMonitor worker did not call end()"
- + " before returning");
+ log.warn("MultiProgressMonitor worker did not call end()" + " before returning");
end();
}
}
@@ -280,8 +276,8 @@
/**
* End the overall task.
- * <p>
- * Must be called from a worker thread.
+ *
+ * <p>Must be called from a worker thread.
*/
public synchronized void end() {
done = true;
@@ -315,8 +311,7 @@
}
private StringBuilder format() {
- StringBuilder s = new StringBuilder().append("\r").append(taskName)
- .append(':');
+ StringBuilder s = new StringBuilder().append("\r").append(taskName).append(':');
if (!tasks.isEmpty()) {
boolean first = true;
@@ -339,9 +334,7 @@
if (t.total == UNKNOWN) {
s.append(count);
} else {
- s.append(String.format("%d%% (%d/%d)",
- count * 100 / t.total,
- count, t.total));
+ s.append(String.format("%d%% (%d/%d)", count * 100 / t.total, count, t.total));
}
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/NotesBranchUtil.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/NotesBranchUtil.java
index 99abbc8..2020550 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/NotesBranchUtil.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/NotesBranchUtil.java
@@ -19,7 +19,7 @@
import com.google.gerrit.server.extensions.events.GitReferenceUpdated;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
-
+import java.io.IOException;
import org.eclipse.jgit.api.errors.ConcurrentRefUpdateException;
import org.eclipse.jgit.errors.CorruptObjectException;
import org.eclipse.jgit.errors.IncorrectObjectTypeException;
@@ -41,16 +41,10 @@
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;
-import java.io.IOException;
-
-/**
- * A utility class for updating a notes branch with automatic merge of note
- * trees.
- */
+/** A utility class for updating a notes branch with automatic merge of note trees. */
public class NotesBranchUtil {
public interface Factory {
- NotesBranchUtil create(Project.NameKey project, Repository db,
- ObjectInserter inserter);
+ NotesBranchUtil create(Project.NameKey project, Repository db, ObjectInserter inserter);
}
private static final int MAX_LOCK_FAILURE_CALLS = 10;
@@ -75,7 +69,8 @@
private ReviewNoteMerger noteMerger;
@Inject
- public NotesBranchUtil(@GerritPersonIdent final PersonIdent gerritIdent,
+ public NotesBranchUtil(
+ @GerritPersonIdent final PersonIdent gerritIdent,
final GitReferenceUpdated gitRefUpdated,
@Assisted Project.NameKey project,
@Assisted Repository db,
@@ -88,8 +83,8 @@
}
/**
- * Create a new commit in the {@code notesBranch} by updating existing
- * or creating new notes from the {@code notes} map.
+ * Create a new commit in the {@code notesBranch} by updating existing or creating new notes from
+ * the {@code notes} map.
*
* @param notes map of notes
* @param notesBranch notes branch to update
@@ -98,31 +93,29 @@
* @throws IOException
* @throws ConcurrentRefUpdateException
*/
- public final void commitAllNotes(NoteMap notes, String notesBranch,
- PersonIdent commitAuthor, String commitMessage) throws IOException,
- ConcurrentRefUpdateException {
+ public final void commitAllNotes(
+ NoteMap notes, String notesBranch, PersonIdent commitAuthor, String commitMessage)
+ throws IOException, ConcurrentRefUpdateException {
this.overwrite = true;
commitNotes(notes, notesBranch, commitAuthor, commitMessage);
}
/**
- * Create a new commit in the {@code notesBranch} by creating not yet
- * existing notes from the {@code notes} map. The notes from the
- * {@code notes} map which already exist in the note-tree of the
- * tip of the {@code notesBranch} will not be updated.
+ * Create a new commit in the {@code notesBranch} by creating not yet existing notes from the
+ * {@code notes} map. The notes from the {@code notes} map which already exist in the note-tree of
+ * the tip of the {@code notesBranch} will not be updated.
*
* @param notes map of notes
* @param notesBranch notes branch to update
* @param commitAuthor author of the commit in the notes branch
* @param commitMessage for the commit in the notes branch
- * @return map with those notes from the {@code notes} that were newly
- * created
+ * @return map with those notes from the {@code notes} that were newly created
* @throws IOException
* @throws ConcurrentRefUpdateException
*/
- public final NoteMap commitNewNotes(NoteMap notes, String notesBranch,
- PersonIdent commitAuthor, String commitMessage) throws IOException,
- ConcurrentRefUpdateException {
+ public final NoteMap commitNewNotes(
+ NoteMap notes, String notesBranch, PersonIdent commitAuthor, String commitMessage)
+ throws IOException, ConcurrentRefUpdateException {
this.overwrite = false;
commitNotes(notes, notesBranch, commitAuthor, commitMessage);
NoteMap newlyCreated = NoteMap.newEmptyMap();
@@ -134,9 +127,9 @@
return newlyCreated;
}
- private void commitNotes(NoteMap notes, String notesBranch,
- PersonIdent commitAuthor, String commitMessage) throws IOException,
- ConcurrentRefUpdateException {
+ private void commitNotes(
+ NoteMap notes, String notesBranch, PersonIdent commitAuthor, String commitMessage)
+ throws IOException, ConcurrentRefUpdateException {
try {
revWalk = new RevWalk(db);
reader = db.newObjectReader();
@@ -160,7 +153,7 @@
private void addNewNotes(NoteMap notes) throws IOException {
for (Note n : notes) {
- if (! ours.contains(n)) {
+ if (!ours.contains(n)) {
ours.set(n, n.getData());
}
}
@@ -172,8 +165,8 @@
// Merge the existing and the new note as if they are both new,
// means: base == null
// There is no really a common ancestry for these two note revisions
- ObjectId noteContent = getNoteMerger().merge(null, n, ours.getNote(n),
- reader, inserter).getData();
+ ObjectId noteContent =
+ getNoteMerger().merge(null, n, ours.getNote(n), reader, inserter).getData();
ours.set(n, noteContent);
} else {
ours.set(n, n.getData());
@@ -201,8 +194,8 @@
}
}
- private RevCommit createCommit(NoteMap map, PersonIdent author,
- String message, RevCommit... parents) throws IOException {
+ private RevCommit createCommit(
+ NoteMap map, PersonIdent author, String message, RevCommit... parents) throws IOException {
CommitBuilder b = new CommitBuilder();
b.setTreeId(map.writeTree(inserter));
b.setAuthor(author != null ? author : gerritIdent);
@@ -216,9 +209,9 @@
return revWalk.parseCommit(commitId);
}
- private void updateRef(String notesBranch) throws IOException,
- MissingObjectException, IncorrectObjectTypeException,
- CorruptObjectException, ConcurrentRefUpdateException {
+ private void updateRef(String notesBranch)
+ throws IOException, MissingObjectException, IncorrectObjectTypeException,
+ CorruptObjectException, ConcurrentRefUpdateException {
if (baseCommit != null && oursCommit.getTree().equals(baseCommit.getTree())) {
// If the trees are identical, there is no change in the notes.
// Avoid saving this commit as it has no new information.
@@ -228,7 +221,7 @@
int remainingLockFailureCalls = MAX_LOCK_FAILURE_CALLS;
RefUpdate refUpdate = createRefUpdate(notesBranch, oursCommit, baseCommit);
- for (;;) {
+ for (; ; ) {
Result result = refUpdate.update();
if (result == Result.LOCK_FAILURE) {
@@ -239,27 +232,22 @@
// ignore
}
} else {
- throw new ConcurrentRefUpdateException("Failed to lock the ref: "
- + notesBranch, refUpdate.getRef(), result);
+ throw new ConcurrentRefUpdateException(
+ "Failed to lock the ref: " + notesBranch, refUpdate.getRef(), result);
}
} else if (result == Result.REJECTED) {
- RevCommit theirsCommit =
- revWalk.parseCommit(refUpdate.getOldObjectId());
- NoteMap theirs =
- NoteMap.read(revWalk.getObjectReader(), theirsCommit);
- NoteMapMerger merger =
- new NoteMapMerger(db, getNoteMerger(), MergeStrategy.RESOLVE);
+ RevCommit theirsCommit = revWalk.parseCommit(refUpdate.getOldObjectId());
+ NoteMap theirs = NoteMap.read(revWalk.getObjectReader(), theirsCommit);
+ NoteMapMerger merger = new NoteMapMerger(db, getNoteMerger(), MergeStrategy.RESOLVE);
NoteMap merged = merger.merge(base, ours, theirs);
RevCommit mergeCommit =
- createCommit(merged, gerritIdent, "Merged note commits\n",
- theirsCommit, oursCommit);
+ createCommit(merged, gerritIdent, "Merged note commits\n", theirsCommit, oursCommit);
refUpdate = createRefUpdate(notesBranch, mergeCommit, theirsCommit);
remainingLockFailureCalls = MAX_LOCK_FAILURE_CALLS;
} else if (result == Result.IO_FAILURE) {
- throw new IOException("Couldn't update " + notesBranch + ". "
- + result.name());
+ throw new IOException("Couldn't update " + notesBranch + ". " + result.name());
} else {
gitRefUpdated.fire(project, refUpdate, null);
break;
@@ -267,8 +255,8 @@
}
}
- private RefUpdate createRefUpdate(String notesBranch, ObjectId newObjectId,
- ObjectId expectedOldObjectId) throws IOException {
+ private RefUpdate createRefUpdate(
+ String notesBranch, ObjectId newObjectId, ObjectId expectedOldObjectId) throws IOException {
RefUpdate refUpdate = db.updateRef(notesBranch);
refUpdate.setNewObjectId(newObjectId);
if (expectedOldObjectId == null) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/NotifyConfig.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/NotifyConfig.java
index b04b0f7..55b94e5 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/NotifyConfig.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/NotifyConfig.java
@@ -18,14 +18,15 @@
import com.google.gerrit.common.data.GroupReference;
import com.google.gerrit.server.account.WatchConfig.NotifyType;
import com.google.gerrit.server.mail.Address;
-
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Set;
public class NotifyConfig implements Comparable<NotifyConfig> {
public enum Header {
- TO, CC, BCC
+ TO,
+ CC,
+ BCC
}
private String name;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/PerThreadRequestScope.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/PerThreadRequestScope.java
index 91bc428..20f053a 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/PerThreadRequestScope.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/PerThreadRequestScope.java
@@ -23,7 +23,6 @@
import com.google.inject.OutOfScopeException;
import com.google.inject.Provider;
import com.google.inject.Scope;
-
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
@@ -53,7 +52,8 @@
public static class Propagator extends ThreadLocalRequestScopePropagator<Context> {
@Inject
- Propagator(ThreadLocalRequestContext local,
+ Propagator(
+ ThreadLocalRequestContext local,
Provider<RequestScopedReviewDbProvider> dbProviderProvider) {
super(REQUEST, current, local, dbProviderProvider);
}
@@ -91,25 +91,26 @@
return ctx;
}
- public static final Scope REQUEST = new Scope() {
- @Override
- public <T> Provider<T> scope(final Key<T> key, final Provider<T> creator) {
- return new Provider<T>() {
+ public static final Scope REQUEST =
+ new Scope() {
@Override
- public T get() {
- return requireContext().get(key, creator);
+ public <T> Provider<T> scope(final Key<T> key, final Provider<T> creator) {
+ return new Provider<T>() {
+ @Override
+ public T get() {
+ return requireContext().get(key, creator);
+ }
+
+ @Override
+ public String toString() {
+ return String.format("%s[%s]", creator, REQUEST);
+ }
+ };
}
@Override
public String toString() {
- return String.format("%s[%s]", creator, REQUEST);
+ return "PerThreadRequestScope.REQUEST";
}
};
- }
-
- @Override
- public String toString() {
- return "PerThreadRequestScope.REQUEST";
- }
- };
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/ProjectConfig.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/ProjectConfig.java
index c101bbb..e9b22a7 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/ProjectConfig.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/ProjectConfig.java
@@ -55,14 +55,6 @@
import com.google.gerrit.server.mail.Address;
import com.google.gerrit.server.project.CommentLinkInfoImpl;
import com.google.gerrit.server.project.RefPattern;
-
-import org.eclipse.jgit.errors.ConfigInvalidException;
-import org.eclipse.jgit.lib.CommitBuilder;
-import org.eclipse.jgit.lib.Config;
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.transport.RefSpec;
-import org.eclipse.jgit.util.StringUtils;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
@@ -78,6 +70,12 @@
import java.util.Set;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
+import org.eclipse.jgit.errors.ConfigInvalidException;
+import org.eclipse.jgit.lib.CommitBuilder;
+import org.eclipse.jgit.lib.Config;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.transport.RefSpec;
+import org.eclipse.jgit.util.StringUtils;
public class ProjectConfig extends VersionedMetaData implements ValidationError.Sink {
public static final String COMMENTLINK = "commentlink";
@@ -117,11 +115,9 @@
private static final String RECEIVE = "receive";
private static final String KEY_REQUIRE_SIGNED_OFF_BY = "requireSignedOffBy";
private static final String KEY_REQUIRE_CHANGE_ID = "requireChangeId";
- private static final String KEY_USE_ALL_NOT_IN_TARGET =
- "createNewChangeForAllNotInTarget";
+ private static final String KEY_USE_ALL_NOT_IN_TARGET = "createNewChangeForAllNotInTarget";
private static final String KEY_MAX_OBJECT_SIZE_LIMIT = "maxObjectSizeLimit";
- private static final String KEY_REQUIRE_CONTRIBUTOR_AGREEMENT =
- "requireContributorAgreement";
+ private static final String KEY_REQUIRE_CONTRIBUTOR_AGREEMENT = "requireContributorAgreement";
private static final String KEY_CHECK_RECEIVED_OBJECTS = "checkReceivedObjects";
private static final String KEY_ENABLE_SIGNED_PUSH = "enableSignedPush";
private static final String KEY_REQUIRE_SIGNED_PUSH = "requireSignedPush";
@@ -146,25 +142,26 @@
private static final String KEY_COPY_MIN_SCORE = "copyMinScore";
private static final String KEY_ALLOW_POST_SUBMIT = "allowPostSubmit";
private static final String KEY_COPY_MAX_SCORE = "copyMaxScore";
- private static final String KEY_COPY_ALL_SCORES_ON_MERGE_FIRST_PARENT_UPDATE = "copyAllScoresOnMergeFirstParentUpdate";
- private static final String KEY_COPY_ALL_SCORES_ON_TRIVIAL_REBASE = "copyAllScoresOnTrivialRebase";
+ private static final String KEY_COPY_ALL_SCORES_ON_MERGE_FIRST_PARENT_UPDATE =
+ "copyAllScoresOnMergeFirstParentUpdate";
+ private static final String KEY_COPY_ALL_SCORES_ON_TRIVIAL_REBASE =
+ "copyAllScoresOnTrivialRebase";
private static final String KEY_COPY_ALL_SCORES_IF_NO_CODE_CHANGE = "copyAllScoresIfNoCodeChange";
private static final String KEY_COPY_ALL_SCORES_IF_NO_CHANGE = "copyAllScoresIfNoChange";
private static final String KEY_VALUE = "value";
private static final String KEY_CAN_OVERRIDE = "canOverride";
private static final String KEY_BRANCH = "branch";
- private static final Set<String> LABEL_FUNCTIONS = ImmutableSet.of(
- "MaxWithBlock", "AnyWithBlock", "MaxNoBlock", "NoBlock", "NoOp", "PatchSetLock");
+ private static final Set<String> LABEL_FUNCTIONS =
+ ImmutableSet.of(
+ "MaxWithBlock", "AnyWithBlock", "MaxNoBlock", "NoBlock", "NoOp", "PatchSetLock");
private static final String LEGACY_PERMISSION_PUSH_TAG = "pushTag";
private static final String LEGACY_PERMISSION_PUSH_SIGNED_TAG = "pushSignedTag";
private static final String PLUGIN = "plugin";
- private static final SubmitType DEFAULT_SUBMIT_ACTION =
- SubmitType.MERGE_IF_NECESSARY;
- private static final ProjectState DEFAULT_STATE_VALUE =
- ProjectState.ACTIVE;
+ private static final SubmitType DEFAULT_SUBMIT_ACTION = SubmitType.MERGE_IF_NECESSARY;
+ private static final ProjectState DEFAULT_STATE_VALUE = ProjectState.ACTIVE;
private Project.NameKey projectName;
private Project project;
@@ -186,8 +183,8 @@
private Set<String> sectionsWithUnknownPermissions;
private boolean hasLegacyPermissions;
- public static ProjectConfig read(MetaDataUpdate update) throws IOException,
- ConfigInvalidException {
+ public static ProjectConfig read(MetaDataUpdate update)
+ throws IOException, ConfigInvalidException {
ProjectConfig r = new ProjectConfig(update.getProjectName());
r.load(update);
return r;
@@ -200,8 +197,8 @@
return r;
}
- public static CommentLinkInfoImpl buildCommentLink(Config cfg, String name,
- boolean allowRaw) throws IllegalArgumentException {
+ public static CommentLinkInfoImpl buildCommentLink(Config cfg, String name, boolean allowRaw)
+ throws IllegalArgumentException {
String match = cfg.getString(COMMENTLINK, name, KEY_MATCH);
if (match != null) {
// Unfortunately this validation isn't entirely complete. Clients
@@ -225,7 +222,9 @@
}
checkArgument(allowRaw || !hasHtml, "Raw html replacement not allowed");
- if (Strings.isNullOrEmpty(match) && Strings.isNullOrEmpty(link) && !hasHtml
+ if (Strings.isNullOrEmpty(match)
+ && Strings.isNullOrEmpty(link)
+ && !hasHtml
&& enabled != null) {
if (enabled) {
return new CommentLinkInfoImpl.Enabled(name);
@@ -276,8 +275,7 @@
return subscribeSections;
}
- public Collection<SubscribeSection> getSubscribeSections(
- Branch.NameKey branch) {
+ public Collection<SubscribeSection> getSubscribeSections(Branch.NameKey branch) {
Collection<SubscribeSection> ret = new ArrayList<>();
for (SubscribeSection s : subscribeSections.values()) {
if (s.appliesTo(branch)) {
@@ -315,8 +313,7 @@
}
}
- public void remove(AccessSection section,
- Permission permission, PermissionRule rule) {
+ public void remove(AccessSection section, Permission permission, PermissionRule rule) {
if (rule == null) {
remove(section, permission);
} else if (section != null && permission != null) {
@@ -419,24 +416,21 @@
}
/**
- * @return the project's rules.pl ObjectId, if present in the branch.
- * Null if it doesn't exist.
+ * @return the project's rules.pl ObjectId, if present in the branch. Null if it doesn't exist.
*/
public ObjectId getRulesId() {
return rulesId;
}
/**
- * @return the maxObjectSizeLimit for this project, if set. Zero if this
- * project doesn't define own maxObjectSizeLimit.
+ * @return the maxObjectSizeLimit for this project, if set. Zero if this project doesn't define
+ * own maxObjectSizeLimit.
*/
public long getMaxObjectSizeLimit() {
return maxObjectSizeLimit;
}
- /**
- * @return the checkReceivedObjects for this project, default is true.
- */
+ /** @return the checkReceivedObjects for this project, default is true. */
public boolean getCheckReceivedObjects() {
return checkReceivedObjects;
}
@@ -494,25 +488,27 @@
if (rc.getStringList(ACCESS, null, KEY_INHERIT_FROM).length > 1) {
// The config must not contain more than one parent to inherit from
// as there is no guarantee which of the parents would be used then.
- error(new ValidationError(PROJECT_CONFIG,
- "Cannot inherit from multiple projects"));
+ error(new ValidationError(PROJECT_CONFIG, "Cannot inherit from multiple projects"));
}
p.setParentName(rc.getString(ACCESS, null, KEY_INHERIT_FROM));
- p.setUseContributorAgreements(getEnum(rc, RECEIVE, null, KEY_REQUIRE_CONTRIBUTOR_AGREEMENT, InheritableBoolean.INHERIT));
- p.setUseSignedOffBy(getEnum(rc, RECEIVE, null, KEY_REQUIRE_SIGNED_OFF_BY, InheritableBoolean.INHERIT));
- p.setRequireChangeID(getEnum(rc, RECEIVE, null, KEY_REQUIRE_CHANGE_ID, InheritableBoolean.INHERIT));
- p.setCreateNewChangeForAllNotInTarget(getEnum(rc, RECEIVE, null, KEY_USE_ALL_NOT_IN_TARGET, InheritableBoolean.INHERIT));
- p.setEnableSignedPush(getEnum(rc, RECEIVE, null,
- KEY_ENABLE_SIGNED_PUSH, InheritableBoolean.INHERIT));
- p.setRequireSignedPush(getEnum(rc, RECEIVE, null,
- KEY_REQUIRE_SIGNED_PUSH, InheritableBoolean.INHERIT));
+ p.setUseContributorAgreements(
+ getEnum(rc, RECEIVE, null, KEY_REQUIRE_CONTRIBUTOR_AGREEMENT, InheritableBoolean.INHERIT));
+ p.setUseSignedOffBy(
+ getEnum(rc, RECEIVE, null, KEY_REQUIRE_SIGNED_OFF_BY, InheritableBoolean.INHERIT));
+ p.setRequireChangeID(
+ getEnum(rc, RECEIVE, null, KEY_REQUIRE_CHANGE_ID, InheritableBoolean.INHERIT));
+ p.setCreateNewChangeForAllNotInTarget(
+ getEnum(rc, RECEIVE, null, KEY_USE_ALL_NOT_IN_TARGET, InheritableBoolean.INHERIT));
+ p.setEnableSignedPush(
+ getEnum(rc, RECEIVE, null, KEY_ENABLE_SIGNED_PUSH, InheritableBoolean.INHERIT));
+ p.setRequireSignedPush(
+ getEnum(rc, RECEIVE, null, KEY_REQUIRE_SIGNED_PUSH, InheritableBoolean.INHERIT));
p.setMaxObjectSizeLimit(rc.getString(RECEIVE, null, KEY_MAX_OBJECT_SIZE_LIMIT));
- p.setRejectImplicitMerges(getEnum(rc, RECEIVE, null,
- KEY_REJECT_IMPLICIT_MERGES, InheritableBoolean.INHERIT));
+ p.setRejectImplicitMerges(
+ getEnum(rc, RECEIVE, null, KEY_REJECT_IMPLICIT_MERGES, InheritableBoolean.INHERIT));
- p.setSubmitType(getEnum(rc, SUBMIT, null, KEY_ACTION,
- DEFAULT_SUBMIT_ACTION));
+ p.setSubmitType(getEnum(rc, SUBMIT, null, KEY_ACTION, DEFAULT_SUBMIT_ACTION));
p.setUseContentMerge(getEnum(rc, SUBMIT, null, KEY_MERGE_CONTENT, InheritableBoolean.INHERIT));
p.setState(getEnum(rc, PROJECT, null, KEY_STATE, DEFAULT_STATE_VALUE));
@@ -532,39 +528,48 @@
loadReceiveSection(rc);
}
- private void loadAccountsSection(
- Config rc, Map<String, GroupReference> groupsByName) {
+ private void loadAccountsSection(Config rc, Map<String, GroupReference> groupsByName) {
accountsSection = new AccountsSection();
- accountsSection.setSameGroupVisibility(loadPermissionRules(
- rc, ACCOUNTS, null, KEY_SAME_GROUP_VISIBILITY, groupsByName, false));
+ accountsSection.setSameGroupVisibility(
+ loadPermissionRules(rc, ACCOUNTS, null, KEY_SAME_GROUP_VISIBILITY, groupsByName, false));
}
- private void loadContributorAgreements(
- Config rc, Map<String, GroupReference> groupsByName) {
+ private void loadContributorAgreements(Config rc, Map<String, GroupReference> groupsByName) {
contributorAgreements = new HashMap<>();
for (String name : rc.getSubsections(CONTRIBUTOR_AGREEMENT)) {
ContributorAgreement ca = getContributorAgreement(name, true);
ca.setDescription(rc.getString(CONTRIBUTOR_AGREEMENT, name, KEY_DESCRIPTION));
ca.setAgreementUrl(rc.getString(CONTRIBUTOR_AGREEMENT, name, KEY_AGREEMENT_URL));
- ca.setAccepted(loadPermissionRules(
- rc, CONTRIBUTOR_AGREEMENT, name, KEY_ACCEPTED, groupsByName, false));
+ ca.setAccepted(
+ loadPermissionRules(rc, CONTRIBUTOR_AGREEMENT, name, KEY_ACCEPTED, groupsByName, false));
- List<PermissionRule> rules = loadPermissionRules(
- rc, CONTRIBUTOR_AGREEMENT, name, KEY_AUTO_VERIFY, groupsByName, false);
+ List<PermissionRule> rules =
+ loadPermissionRules(
+ rc, CONTRIBUTOR_AGREEMENT, name, KEY_AUTO_VERIFY, groupsByName, false);
if (rules.isEmpty()) {
ca.setAutoVerify(null);
} else if (rules.size() > 1) {
- error(new ValidationError(PROJECT_CONFIG, "Invalid rule in "
- + CONTRIBUTOR_AGREEMENT
- + "." + name
- + "." + KEY_AUTO_VERIFY
- + ": at most one group may be set"));
+ error(
+ new ValidationError(
+ PROJECT_CONFIG,
+ "Invalid rule in "
+ + CONTRIBUTOR_AGREEMENT
+ + "."
+ + name
+ + "."
+ + KEY_AUTO_VERIFY
+ + ": at most one group may be set"));
} else if (rules.get(0).getAction() != Action.ALLOW) {
- error(new ValidationError(PROJECT_CONFIG, "Invalid rule in "
- + CONTRIBUTOR_AGREEMENT
- + "." + name
- + "." + KEY_AUTO_VERIFY
- + ": the group must be allowed"));
+ error(
+ new ValidationError(
+ PROJECT_CONFIG,
+ "Invalid rule in "
+ + CONTRIBUTOR_AGREEMENT
+ + "."
+ + name
+ + "."
+ + KEY_AUTO_VERIFY
+ + ": the group must be allowed"));
} else {
ca.setAutoVerify(rules.get(0).getGroup());
}
@@ -589,8 +594,7 @@
* type = submitted_changes
* </pre>
*/
- private void loadNotifySections(
- Config rc, Map<String, GroupReference> groupsByName) {
+ private void loadNotifySections(Config rc, Map<String, GroupReference> groupsByName) {
notifySections = new HashMap<>();
for (String sectionName : rc.getSubsections(NOTIFY)) {
NotifyConfig n = new NotifyConfig();
@@ -598,12 +602,9 @@
n.setFilter(rc.getString(NOTIFY, sectionName, KEY_FILTER));
EnumSet<NotifyType> types = EnumSet.noneOf(NotifyType.class);
- types.addAll(ConfigUtil.getEnumList(rc,
- NOTIFY, sectionName, KEY_TYPE,
- NotifyType.ALL));
+ types.addAll(ConfigUtil.getEnumList(rc, NOTIFY, sectionName, KEY_TYPE, NotifyType.ALL));
n.setTypes(types);
- n.setHeader(rc.getEnum(NOTIFY, sectionName, KEY_HEADER,
- NotifyConfig.Header.BCC));
+ n.setHeader(rc.getEnum(NOTIFY, sectionName, KEY_HEADER, NotifyConfig.Header.BCC));
for (String dst : rc.getStringList(NOTIFY, sectionName, KEY_EMAIL)) {
if (dst.startsWith("group ")) {
@@ -616,8 +617,10 @@
if (ref.getUUID() != null) {
n.addEmail(ref);
} else {
- error(new ValidationError(PROJECT_CONFIG,
- "group \"" + ref.getName() + "\" not in " + GroupList.FILE_NAME));
+ error(
+ new ValidationError(
+ PROJECT_CONFIG,
+ "group \"" + ref.getName() + "\" not in " + GroupList.FILE_NAME));
}
} else if (dst.startsWith("user ")) {
error(new ValidationError(PROJECT_CONFIG, dst + " not supported"));
@@ -625,8 +628,10 @@
try {
n.addEmail(Address.parse(dst));
} catch (IllegalArgumentException err) {
- error(new ValidationError(PROJECT_CONFIG,
- "notify section \"" + sectionName + "\" has invalid email \"" + dst + "\""));
+ error(
+ new ValidationError(
+ PROJECT_CONFIG,
+ "notify section \"" + sectionName + "\" has invalid email \"" + dst + "\""));
}
}
}
@@ -634,8 +639,7 @@
}
}
- private void loadAccessSections(
- Config rc, Map<String, GroupReference> groupsByName) {
+ private void loadAccessSections(Config rc, Map<String, GroupReference> groupsByName) {
accessSections = new HashMap<>();
sectionsWithUnknownPermissions = new HashSet<>();
for (String refName : rc.getSubsections(ACCESS)) {
@@ -655,8 +659,14 @@
String convertedName = convertLegacyPermission(varName);
if (isPermission(convertedName)) {
Permission perm = as.getPermission(convertedName, true);
- loadPermissionRules(rc, ACCESS, refName, varName, groupsByName,
- perm, Permission.hasRange(convertedName));
+ loadPermissionRules(
+ rc,
+ ACCESS,
+ refName,
+ varName,
+ groupsByName,
+ perm,
+ Permission.hasRange(convertedName));
} else {
sectionsWithUnknownPermissions.add(as.getName());
}
@@ -671,8 +681,8 @@
accessSections.put(AccessSection.GLOBAL_CAPABILITIES, capability);
}
Permission perm = capability.getPermission(varName, true);
- loadPermissionRules(rc, CAPABILITY, null, varName, groupsByName, perm,
- GlobalCapability.hasRange(varName));
+ loadPermissionRules(
+ rc, CAPABILITY, null, varName, groupsByName, perm, GlobalCapability.hasRange(varName));
}
}
@@ -680,8 +690,7 @@
try {
RefPattern.validateRegExp(refPattern);
} catch (InvalidNameException e) {
- error(new ValidationError(PROJECT_CONFIG, "Invalid ref name: "
- + e.getMessage()));
+ error(new ValidationError(PROJECT_CONFIG, "Invalid ref name: " + e.getMessage()));
return false;
}
return true;
@@ -689,13 +698,15 @@
private void loadBranchOrderSection(Config rc) {
if (rc.getSections().contains(BRANCH_ORDER)) {
- branchOrderSection = new BranchOrderSection(
- rc.getStringList(BRANCH_ORDER, null, BRANCH));
+ branchOrderSection = new BranchOrderSection(rc.getStringList(BRANCH_ORDER, null, BRANCH));
}
}
- private List<PermissionRule> loadPermissionRules(Config rc, String section,
- String subsection, String varName,
+ private List<PermissionRule> loadPermissionRules(
+ Config rc,
+ String section,
+ String subsection,
+ String varName,
Map<String, GroupReference> groupsByName,
boolean useRange) {
Permission perm = new Permission(varName);
@@ -703,20 +714,29 @@
return perm.getRules();
}
- private void loadPermissionRules(Config rc, String section,
- String subsection, String varName,
- Map<String, GroupReference> groupsByName, Permission perm,
+ private void loadPermissionRules(
+ Config rc,
+ String section,
+ String subsection,
+ String varName,
+ Map<String, GroupReference> groupsByName,
+ Permission perm,
boolean useRange) {
for (String ruleString : rc.getStringList(section, subsection, varName)) {
PermissionRule rule;
try {
rule = PermissionRule.fromString(ruleString, useRange);
} catch (IllegalArgumentException notRule) {
- error(new ValidationError(PROJECT_CONFIG, "Invalid rule in "
- + section
- + (subsection != null ? "." + subsection : "")
- + "." + varName + ": "
- + notRule.getMessage()));
+ error(
+ new ValidationError(
+ PROJECT_CONFIG,
+ "Invalid rule in "
+ + section
+ + (subsection != null ? "." + subsection : "")
+ + "."
+ + varName
+ + ": "
+ + notRule.getMessage()));
continue;
}
@@ -728,8 +748,9 @@
//
ref = rule.getGroup();
groupsByName.put(ref.getName(), ref);
- error(new ValidationError(PROJECT_CONFIG,
- "group \"" + ref.getName() + "\" not in " + GroupList.FILE_NAME));
+ error(
+ new ValidationError(
+ PROJECT_CONFIG, "group \"" + ref.getName() + "\" not in " + GroupList.FILE_NAME));
}
rule.setGroup(ref);
@@ -738,16 +759,14 @@
}
private static LabelValue parseLabelValue(String src) {
- List<String> parts = ImmutableList.copyOf(
- Splitter.on(CharMatcher.whitespace()).omitEmptyStrings().limit(2)
- .split(src));
+ List<String> parts =
+ ImmutableList.copyOf(
+ Splitter.on(CharMatcher.whitespace()).omitEmptyStrings().limit(2).split(src));
if (parts.isEmpty()) {
throw new IllegalArgumentException("empty value");
}
String valueText = parts.size() > 1 ? parts.get(1) : "";
- return new LabelValue(
- Shorts.checkedCast(PermissionRule.parseInt(parts.get(0))),
- valueText);
+ return new LabelValue(Shorts.checkedCast(PermissionRule.parseInt(parts.get(0))), valueText);
}
private void loadLabelSections(Config rc) {
@@ -756,9 +775,10 @@
for (String name : rc.getSubsections(LABEL)) {
String lower = name.toLowerCase();
if (lowerNames.containsKey(lower)) {
- error(new ValidationError(PROJECT_CONFIG, String.format(
- "Label \"%s\" conflicts with \"%s\"",
- name, lowerNames.get(lower))));
+ error(
+ new ValidationError(
+ PROJECT_CONFIG,
+ String.format("Label \"%s\" conflicts with \"%s\"", name, lowerNames.get(lower))));
}
lowerNames.put(lower, name);
@@ -767,9 +787,12 @@
try {
values.add(parseLabelValue(value));
} catch (IllegalArgumentException notValue) {
- error(new ValidationError(PROJECT_CONFIG, String.format(
- "Invalid %s \"%s\" for label \"%s\": %s",
- KEY_VALUE, value, name, notValue.getMessage())));
+ error(
+ new ValidationError(
+ PROJECT_CONFIG,
+ String.format(
+ "Invalid %s \"%s\" for label \"%s\": %s",
+ KEY_VALUE, value, name, notValue.getMessage())));
}
}
@@ -777,19 +800,21 @@
try {
label = new LabelType(name, values);
} catch (IllegalArgumentException badName) {
- error(new ValidationError(PROJECT_CONFIG, String.format(
- "Invalid label \"%s\"", name)));
+ error(new ValidationError(PROJECT_CONFIG, String.format("Invalid label \"%s\"", name)));
continue;
}
- String functionName = MoreObjects.firstNonNull(
- rc.getString(LABEL, name, KEY_FUNCTION), "MaxWithBlock");
+ String functionName =
+ MoreObjects.firstNonNull(rc.getString(LABEL, name, KEY_FUNCTION), "MaxWithBlock");
if (LABEL_FUNCTIONS.contains(functionName)) {
label.setFunctionName(functionName);
} else {
- error(new ValidationError(PROJECT_CONFIG, String.format(
- "Invalid %s for label \"%s\". Valid names are: %s",
- KEY_FUNCTION, name, Joiner.on(", ").join(LABEL_FUNCTIONS))));
+ error(
+ new ValidationError(
+ PROJECT_CONFIG,
+ String.format(
+ "Invalid %s for label \"%s\". Valid names are: %s",
+ KEY_FUNCTION, name, Joiner.on(", ").join(LABEL_FUNCTIONS))));
label.setFunctionName(null);
}
@@ -798,35 +823,45 @@
if (isInRange(dv, values)) {
label.setDefaultValue(dv);
} else {
- error(new ValidationError(PROJECT_CONFIG, String.format(
- "Invalid %s \"%s\" for label \"%s\"",
- KEY_DEFAULT_VALUE, dv, name)));
+ error(
+ new ValidationError(
+ PROJECT_CONFIG,
+ String.format(
+ "Invalid %s \"%s\" for label \"%s\"", KEY_DEFAULT_VALUE, dv, name)));
}
}
label.setAllowPostSubmit(
- rc.getBoolean(LABEL, name, KEY_ALLOW_POST_SUBMIT,
- LabelType.DEF_ALLOW_POST_SUBMIT));
+ rc.getBoolean(LABEL, name, KEY_ALLOW_POST_SUBMIT, LabelType.DEF_ALLOW_POST_SUBMIT));
label.setCopyMinScore(
- rc.getBoolean(LABEL, name, KEY_COPY_MIN_SCORE,
- LabelType.DEF_COPY_MIN_SCORE));
+ rc.getBoolean(LABEL, name, KEY_COPY_MIN_SCORE, LabelType.DEF_COPY_MIN_SCORE));
label.setCopyMaxScore(
- rc.getBoolean(LABEL, name, KEY_COPY_MAX_SCORE,
- LabelType.DEF_COPY_MAX_SCORE));
+ rc.getBoolean(LABEL, name, KEY_COPY_MAX_SCORE, LabelType.DEF_COPY_MAX_SCORE));
label.setCopyAllScoresOnMergeFirstParentUpdate(
- rc.getBoolean(LABEL, name, KEY_COPY_ALL_SCORES_ON_MERGE_FIRST_PARENT_UPDATE,
+ rc.getBoolean(
+ LABEL,
+ name,
+ KEY_COPY_ALL_SCORES_ON_MERGE_FIRST_PARENT_UPDATE,
LabelType.DEF_COPY_ALL_SCORES_ON_MERGE_FIRST_PARENT_UPDATE));
label.setCopyAllScoresOnTrivialRebase(
- rc.getBoolean(LABEL, name, KEY_COPY_ALL_SCORES_ON_TRIVIAL_REBASE,
+ rc.getBoolean(
+ LABEL,
+ name,
+ KEY_COPY_ALL_SCORES_ON_TRIVIAL_REBASE,
LabelType.DEF_COPY_ALL_SCORES_ON_TRIVIAL_REBASE));
label.setCopyAllScoresIfNoCodeChange(
- rc.getBoolean(LABEL, name, KEY_COPY_ALL_SCORES_IF_NO_CODE_CHANGE,
+ rc.getBoolean(
+ LABEL,
+ name,
+ KEY_COPY_ALL_SCORES_IF_NO_CODE_CHANGE,
LabelType.DEF_COPY_ALL_SCORES_IF_NO_CODE_CHANGE));
label.setCopyAllScoresIfNoChange(
- rc.getBoolean(LABEL, name, KEY_COPY_ALL_SCORES_IF_NO_CHANGE,
+ rc.getBoolean(
+ LABEL,
+ name,
+ KEY_COPY_ALL_SCORES_IF_NO_CHANGE,
LabelType.DEF_COPY_ALL_SCORES_IF_NO_CHANGE));
label.setCanOverride(
- rc.getBoolean(LABEL, name, KEY_CAN_OVERRIDE,
- LabelType.DEF_CAN_OVERRIDE));
+ rc.getBoolean(LABEL, name, KEY_CAN_OVERRIDE, LabelType.DEF_CAN_OVERRIDE));
label.setRefPatterns(getStringListOrNull(rc, LABEL, name, KEY_BRANCH));
labelSections.put(name, label);
}
@@ -841,8 +876,8 @@
return false;
}
- private List<String> getStringListOrNull(Config rc, String section,
- String subSection, String name) {
+ private List<String> getStringListOrNull(
+ Config rc, String section, String subSection, String name) {
String[] ac = rc.getStringList(section, subSection, name);
return ac.length == 0 ? null : Arrays.asList(ac);
}
@@ -854,13 +889,19 @@
try {
commentLinkSections.add(buildCommentLink(rc, name, false));
} catch (PatternSyntaxException e) {
- error(new ValidationError(PROJECT_CONFIG, String.format(
- "Invalid pattern \"%s\" in commentlink.%s.match: %s",
- rc.getString(COMMENTLINK, name, KEY_MATCH), name, e.getMessage())));
+ error(
+ new ValidationError(
+ PROJECT_CONFIG,
+ String.format(
+ "Invalid pattern \"%s\" in commentlink.%s.match: %s",
+ rc.getString(COMMENTLINK, name, KEY_MATCH), name, e.getMessage())));
} catch (IllegalArgumentException e) {
- error(new ValidationError(PROJECT_CONFIG, String.format(
- "Error in pattern \"%s\" in commentlink.%s.match: %s",
- rc.getString(COMMENTLINK, name, KEY_MATCH), name, e.getMessage())));
+ error(
+ new ValidationError(
+ PROJECT_CONFIG,
+ String.format(
+ "Error in pattern \"%s\" in commentlink.%s.match: %s",
+ rc.getString(COMMENTLINK, name, KEY_MATCH), name, e.getMessage())));
}
}
commentLinkSections = ImmutableList.copyOf(commentLinkSections);
@@ -873,12 +914,11 @@
for (String projectName : subsections) {
Project.NameKey p = new Project.NameKey(projectName);
SubscribeSection ss = new SubscribeSection(p);
- for (String s : rc.getStringList(SUBSCRIBE_SECTION,
- projectName, SUBSCRIBE_MULTI_MATCH_REFS)) {
+ for (String s :
+ rc.getStringList(SUBSCRIBE_SECTION, projectName, SUBSCRIBE_MULTI_MATCH_REFS)) {
ss.addMultiMatchRefSpec(s);
}
- for (String s : rc.getStringList(SUBSCRIBE_SECTION,
- projectName, SUBSCRIBE_MATCH_REFS)) {
+ for (String s : rc.getStringList(SUBSCRIBE_SECTION, projectName, SUBSCRIBE_MATCH_REFS)) {
ss.addMatchingRefSpec(s);
}
subscribeSections.put(p, ss);
@@ -905,13 +945,15 @@
GroupReference ref = groupList.byUUID(refFromString.getUUID());
if (ref == null) {
ref = refFromString;
- error(new ValidationError(PROJECT_CONFIG,
- "group \"" + ref.getName() + "\" not in " + GroupList.FILE_NAME));
+ error(
+ new ValidationError(
+ PROJECT_CONFIG,
+ "group \"" + ref.getName() + "\" not in " + GroupList.FILE_NAME));
}
rc.setString(PLUGIN, plugin, name, ref.toString());
}
- pluginConfig.setStringList(PLUGIN, plugin, name,
- Arrays.asList(rc.getStringList(PLUGIN, plugin, name)));
+ pluginConfig.setStringList(
+ PLUGIN, plugin, name, Arrays.asList(rc.getStringList(PLUGIN, plugin, name)));
}
}
}
@@ -926,8 +968,7 @@
}
private void readGroupList() throws IOException {
- groupList = GroupList.parse(
- projectName, readUTF8(GroupList.FILE_NAME), this);
+ groupList = GroupList.parse(projectName, readUTF8(GroupList.FILE_NAME), this);
}
private Map<String, GroupReference> mapGroupReferences() {
@@ -941,8 +982,7 @@
}
@Override
- protected boolean onSave(CommitBuilder commit) throws IOException,
- ConfigInvalidException {
+ protected boolean onSave(CommitBuilder commit) throws IOException, ConfigInvalidException {
if (commit.getMessage() == null || "".equals(commit.getMessage())) {
commit.setMessage("Updated project configuration\n");
}
@@ -957,17 +997,61 @@
}
set(rc, ACCESS, null, KEY_INHERIT_FROM, p.getParentName());
- set(rc, RECEIVE, null, KEY_REQUIRE_CONTRIBUTOR_AGREEMENT, p.getUseContributorAgreements(), InheritableBoolean.INHERIT);
- set(rc, RECEIVE, null, KEY_REQUIRE_SIGNED_OFF_BY, p.getUseSignedOffBy(), InheritableBoolean.INHERIT);
- set(rc, RECEIVE, null, KEY_REQUIRE_CHANGE_ID, p.getRequireChangeID(), InheritableBoolean.INHERIT);
- set(rc, RECEIVE, null, KEY_USE_ALL_NOT_IN_TARGET, p.getCreateNewChangeForAllNotInTarget(), InheritableBoolean.INHERIT);
- set(rc, RECEIVE, null, KEY_MAX_OBJECT_SIZE_LIMIT, validMaxObjectSizeLimit(p.getMaxObjectSizeLimit()));
- set(rc, RECEIVE, null, KEY_ENABLE_SIGNED_PUSH,
- p.getEnableSignedPush(), InheritableBoolean.INHERIT);
- set(rc, RECEIVE, null, KEY_REQUIRE_SIGNED_PUSH,
- p.getRequireSignedPush(), InheritableBoolean.INHERIT);
- set(rc, RECEIVE, null, KEY_REJECT_IMPLICIT_MERGES,
- p.getRejectImplicitMerges(), InheritableBoolean.INHERIT);
+ set(
+ rc,
+ RECEIVE,
+ null,
+ KEY_REQUIRE_CONTRIBUTOR_AGREEMENT,
+ p.getUseContributorAgreements(),
+ InheritableBoolean.INHERIT);
+ set(
+ rc,
+ RECEIVE,
+ null,
+ KEY_REQUIRE_SIGNED_OFF_BY,
+ p.getUseSignedOffBy(),
+ InheritableBoolean.INHERIT);
+ set(
+ rc,
+ RECEIVE,
+ null,
+ KEY_REQUIRE_CHANGE_ID,
+ p.getRequireChangeID(),
+ InheritableBoolean.INHERIT);
+ set(
+ rc,
+ RECEIVE,
+ null,
+ KEY_USE_ALL_NOT_IN_TARGET,
+ p.getCreateNewChangeForAllNotInTarget(),
+ InheritableBoolean.INHERIT);
+ set(
+ rc,
+ RECEIVE,
+ null,
+ KEY_MAX_OBJECT_SIZE_LIMIT,
+ validMaxObjectSizeLimit(p.getMaxObjectSizeLimit()));
+ set(
+ rc,
+ RECEIVE,
+ null,
+ KEY_ENABLE_SIGNED_PUSH,
+ p.getEnableSignedPush(),
+ InheritableBoolean.INHERIT);
+ set(
+ rc,
+ RECEIVE,
+ null,
+ KEY_REQUIRE_SIGNED_PUSH,
+ p.getRequireSignedPush(),
+ InheritableBoolean.INHERIT);
+ set(
+ rc,
+ RECEIVE,
+ null,
+ KEY_REJECT_IMPLICIT_MERGES,
+ p.getRejectImplicitMerges(),
+ InheritableBoolean.INHERIT);
set(rc, SUBMIT, null, KEY_ACTION, p.getSubmitType(), DEFAULT_SUBMIT_ACTION);
set(rc, SUBMIT, null, KEY_MERGE_CONTENT, p.getUseContentMerge(), InheritableBoolean.INHERIT);
@@ -992,8 +1076,7 @@
return true;
}
- public static final String validMaxObjectSizeLimit(String value)
- throws ConfigInvalidException {
+ public static final String validMaxObjectSizeLimit(String value) throws ConfigInvalidException {
if (value == null) {
return null;
}
@@ -1006,9 +1089,9 @@
try {
long s = cfg.getLong("s", "n", 0);
if (s < 0) {
- throw new ConfigInvalidException(String.format(
- "Negative value '%s' not allowed as %s", value,
- KEY_MAX_OBJECT_SIZE_LIMIT));
+ throw new ConfigInvalidException(
+ String.format(
+ "Negative value '%s' not allowed as %s", value, KEY_MAX_OBJECT_SIZE_LIMIT));
}
if (s == 0) {
// return null for the default so that it is not persisted
@@ -1023,13 +1106,15 @@
private void saveAccountsSection(Config rc, Set<AccountGroup.UUID> keepGroups) {
if (accountsSection != null) {
- rc.setStringList(ACCOUNTS, null, KEY_SAME_GROUP_VISIBILITY,
+ rc.setStringList(
+ ACCOUNTS,
+ null,
+ KEY_SAME_GROUP_VISIBILITY,
ruleToStringList(accountsSection.getSameGroupVisibility(), keepGroups));
}
}
- private void saveContributorAgreements(
- Config rc, Set<AccountGroup.UUID> keepGroups) {
+ private void saveContributorAgreements(Config rc, Set<AccountGroup.UUID> keepGroups) {
for (ContributorAgreement ca : sort(contributorAgreements.values())) {
set(rc, CONTRIBUTOR_AGREEMENT, ca.getName(), KEY_DESCRIPTION, ca.getDescription());
set(rc, CONTRIBUTOR_AGREEMENT, ca.getName(), KEY_AGREEMENT_URL, ca.getAgreementUrl());
@@ -1044,13 +1129,15 @@
rc.unset(CONTRIBUTOR_AGREEMENT, ca.getName(), KEY_AUTO_VERIFY);
}
- rc.setStringList(CONTRIBUTOR_AGREEMENT, ca.getName(), KEY_ACCEPTED,
+ rc.setStringList(
+ CONTRIBUTOR_AGREEMENT,
+ ca.getName(),
+ KEY_ACCEPTED,
ruleToStringList(ca.getAccepted(), keepGroups));
}
}
- private void saveNotifySections(
- Config rc, Set<AccountGroup.UUID> keepGroups) {
+ private void saveNotifySections(Config rc, Set<AccountGroup.UUID> keepGroups) {
for (NotifyConfig nc : sort(notifySections.values())) {
List<String> email = new ArrayList<>();
for (GroupReference gr : nc.getGroups()) {
@@ -1068,8 +1155,7 @@
Collections.sort(addrs);
email.addAll(addrs);
- set(rc, NOTIFY, nc.getName(), KEY_HEADER,
- nc.getHeader(), NotifyConfig.Header.BCC);
+ set(rc, NOTIFY, nc.getName(), KEY_HEADER, nc.getHeader(), NotifyConfig.Header.BCC);
if (email.isEmpty()) {
rc.unset(NOTIFY, nc.getName(), KEY_EMAIL);
} else {
@@ -1104,8 +1190,7 @@
return rules;
}
- private void saveAccessSections(
- Config rc, Set<AccountGroup.UUID> keepGroups) {
+ private void saveAccessSections(Config rc, Set<AccountGroup.UUID> keepGroups) {
AccessSection capability = accessSections.get(AccessSection.GLOBAL_CAPABILITIES);
if (capability != null) {
Set<String> have = new HashSet<>();
@@ -1201,28 +1286,43 @@
rc.setString(LABEL, name, KEY_FUNCTION, label.getFunctionName());
rc.setInt(LABEL, name, KEY_DEFAULT_VALUE, label.getDefaultValue());
- setBooleanConfigKey(rc, name, KEY_ALLOW_POST_SUBMIT, label.allowPostSubmit(),
+ setBooleanConfigKey(
+ rc,
+ name,
+ KEY_ALLOW_POST_SUBMIT,
+ label.allowPostSubmit(),
LabelType.DEF_ALLOW_POST_SUBMIT);
- setBooleanConfigKey(rc, name, KEY_COPY_MIN_SCORE, label.isCopyMinScore(),
- LabelType.DEF_COPY_MIN_SCORE);
- setBooleanConfigKey(rc, name, KEY_COPY_MAX_SCORE, label.isCopyMaxScore(),
- LabelType.DEF_COPY_MAX_SCORE);
- setBooleanConfigKey(rc, name, KEY_COPY_ALL_SCORES_ON_TRIVIAL_REBASE,
+ setBooleanConfigKey(
+ rc, name, KEY_COPY_MIN_SCORE, label.isCopyMinScore(), LabelType.DEF_COPY_MIN_SCORE);
+ setBooleanConfigKey(
+ rc, name, KEY_COPY_MAX_SCORE, label.isCopyMaxScore(), LabelType.DEF_COPY_MAX_SCORE);
+ setBooleanConfigKey(
+ rc,
+ name,
+ KEY_COPY_ALL_SCORES_ON_TRIVIAL_REBASE,
label.isCopyAllScoresOnTrivialRebase(),
LabelType.DEF_COPY_ALL_SCORES_ON_TRIVIAL_REBASE);
- setBooleanConfigKey(rc, name, KEY_COPY_ALL_SCORES_IF_NO_CODE_CHANGE,
+ setBooleanConfigKey(
+ rc,
+ name,
+ KEY_COPY_ALL_SCORES_IF_NO_CODE_CHANGE,
label.isCopyAllScoresIfNoCodeChange(),
LabelType.DEF_COPY_ALL_SCORES_IF_NO_CODE_CHANGE);
- setBooleanConfigKey(rc, name, KEY_COPY_ALL_SCORES_IF_NO_CHANGE,
+ setBooleanConfigKey(
+ rc,
+ name,
+ KEY_COPY_ALL_SCORES_IF_NO_CHANGE,
label.isCopyAllScoresIfNoChange(),
LabelType.DEF_COPY_ALL_SCORES_IF_NO_CHANGE);
- setBooleanConfigKey(rc, name, KEY_COPY_ALL_SCORES_ON_MERGE_FIRST_PARENT_UPDATE,
+ setBooleanConfigKey(
+ rc,
+ name,
+ KEY_COPY_ALL_SCORES_ON_MERGE_FIRST_PARENT_UPDATE,
label.isCopyAllScoresOnMergeFirstParentUpdate(),
LabelType.DEF_COPY_ALL_SCORES_ON_MERGE_FIRST_PARENT_UPDATE);
- setBooleanConfigKey(rc, name, KEY_CAN_OVERRIDE, label.canOverride(),
- LabelType.DEF_CAN_OVERRIDE);
- List<String> values =
- Lists.newArrayListWithCapacity(label.getValues().size());
+ setBooleanConfigKey(
+ rc, name, KEY_CAN_OVERRIDE, label.canOverride(), LabelType.DEF_CAN_OVERRIDE);
+ List<String> values = Lists.newArrayListWithCapacity(label.getValues().size());
for (LabelValue value : label.getValues()) {
values.add(value.format());
}
@@ -1261,8 +1361,8 @@
pluginConfig.setString(PLUGIN, plugin, name, ref.toString());
}
}
- rc.setStringList(PLUGIN, plugin, name,
- Arrays.asList(pluginConfig.getStringList(PLUGIN, plugin, name)));
+ rc.setStringList(
+ PLUGIN, plugin, name, Arrays.asList(pluginConfig.getStringList(PLUGIN, plugin, name)));
}
}
}
@@ -1278,20 +1378,18 @@
for (RefSpec r : s.getMatchingRefSpecs()) {
matchings.add(r.toString());
}
- rc.setStringList(SUBSCRIBE_SECTION, p.get(), SUBSCRIBE_MATCH_REFS,
- matchings);
+ rc.setStringList(SUBSCRIBE_SECTION, p.get(), SUBSCRIBE_MATCH_REFS, matchings);
List<String> multimatchs = new ArrayList<>();
for (RefSpec r : s.getMultiMatchRefSpecs()) {
multimatchs.add(r.toString());
}
- rc.setStringList(SUBSCRIBE_SECTION, p.get(),
- SUBSCRIBE_MULTI_MATCH_REFS, multimatchs);
+ rc.setStringList(SUBSCRIBE_SECTION, p.get(), SUBSCRIBE_MULTI_MATCH_REFS, multimatchs);
}
}
- private <E extends Enum<?>> E getEnum(Config rc, String section,
- String subsection, String name, E defaultValue) {
+ private <E extends Enum<?>> E getEnum(
+ Config rc, String section, String subsection, String name, E defaultValue) {
try {
return rc.getEnum(section, subsection, name, defaultValue);
} catch (IllegalArgumentException err) {
@@ -1319,7 +1417,7 @@
}
private String convertLegacyPermission(String permissionName) {
- switch(permissionName) {
+ switch (permissionName) {
case LEGACY_PERMISSION_PUSH_TAG:
hasLegacyPermissions = true;
return Permission.CREATE_TAG;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/ProjectLevelConfig.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/ProjectLevelConfig.java
index b4f41a0..18dcef8 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/ProjectLevelConfig.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/ProjectLevelConfig.java
@@ -17,14 +17,12 @@
import com.google.common.collect.Iterables;
import com.google.gerrit.reviewdb.client.RefNames;
import com.google.gerrit.server.project.ProjectState;
-
-import org.eclipse.jgit.errors.ConfigInvalidException;
-import org.eclipse.jgit.lib.CommitBuilder;
-import org.eclipse.jgit.lib.Config;
-
import java.io.IOException;
import java.util.Arrays;
import java.util.Set;
+import org.eclipse.jgit.errors.ConfigInvalidException;
+import org.eclipse.jgit.lib.CommitBuilder;
+import org.eclipse.jgit.lib.Config;
/** Configuration file in the projects refs/meta/config branch. */
public class ProjectLevelConfig extends VersionedMetaData {
@@ -68,8 +66,8 @@
Set<String> allNames = get().getNames(section);
for (String name : parentCfg.getNames(section)) {
if (!allNames.contains(name)) {
- cfgWithInheritance.setStringList(section, null, name,
- Arrays.asList(parentCfg.getStringList(section, null, name)));
+ cfgWithInheritance.setStringList(
+ section, null, name, Arrays.asList(parentCfg.getStringList(section, null, name)));
}
}
@@ -77,7 +75,10 @@
allNames = get().getNames(section, subsection);
for (String name : parentCfg.getNames(section, subsection)) {
if (!allNames.contains(name)) {
- cfgWithInheritance.setStringList(section, subsection, name,
+ cfgWithInheritance.setStringList(
+ section,
+ subsection,
+ name,
Arrays.asList(parentCfg.getStringList(section, subsection, name)));
}
}
@@ -88,8 +89,7 @@
}
@Override
- protected boolean onSave(CommitBuilder commit) throws IOException,
- ConfigInvalidException {
+ protected boolean onSave(CommitBuilder commit) throws IOException, ConfigInvalidException {
if (commit.getMessage() == null || "".equals(commit.getMessage())) {
commit.setMessage("Updated configuration\n");
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/ProjectRunnable.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/ProjectRunnable.java
index 7032878..23d2326 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/ProjectRunnable.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/ProjectRunnable.java
@@ -15,7 +15,7 @@
import com.google.gerrit.reviewdb.client.Project;
-/** Used to retrieve the project name from an operation **/
+/** Used to retrieve the project name from an operation * */
public interface ProjectRunnable extends Runnable {
Project.NameKey getProjectNameKey();
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/QueryList.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/QueryList.java
index dffb18a..1666bae 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/QueryList.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/QueryList.java
@@ -26,8 +26,7 @@
this.queriesByName = toMap(queriesByName);
}
- public static QueryList parse(String text, ValidationError.Sink errors)
- throws IOException {
+ public static QueryList parse(String text, ValidationError.Sink errors) throws IOException {
return new QueryList(parse(text, FILE_NAME, TRIM, TRIM, errors));
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/QueueProvider.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/QueueProvider.java
index 06b87f2..28425e0 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/QueueProvider.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/QueueProvider.java
@@ -16,7 +16,8 @@
public interface QueueProvider {
enum QueueType {
- INTERACTIVE, BATCH
+ INTERACTIVE,
+ BATCH
}
WorkQueue.Executor getQueue(QueueType type);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/ReadOnlyRepository.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/ReadOnlyRepository.java
index 2a16148..f78a604 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/ReadOnlyRepository.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/ReadOnlyRepository.java
@@ -16,6 +16,9 @@
import static com.google.common.base.Preconditions.checkNotNull;
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
import org.eclipse.jgit.attributes.AttributesNodeProvider;
import org.eclipse.jgit.lib.BaseRepositoryBuilder;
import org.eclipse.jgit.lib.ObjectDatabase;
@@ -29,23 +32,16 @@
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.lib.StoredConfig;
-import java.io.IOException;
-import java.util.List;
-import java.util.Map;
-
class ReadOnlyRepository extends Repository {
- private static final String MSG =
- "Cannot modify a " + ReadOnlyRepository.class.getSimpleName();
+ private static final String MSG = "Cannot modify a " + ReadOnlyRepository.class.getSimpleName();
private static BaseRepositoryBuilder<?, ?> builder(Repository r) {
checkNotNull(r);
- BaseRepositoryBuilder<?, ?> builder = new BaseRepositoryBuilder<>()
- .setFS(r.getFS())
- .setGitDir(r.getDirectory());
+ BaseRepositoryBuilder<?, ?> builder =
+ new BaseRepositoryBuilder<>().setFS(r.getFS()).setGitDir(r.getDirectory());
if (!r.isBare()) {
- builder.setWorkTree(r.getWorkTree())
- .setIndexFile(r.getIndexFile());
+ builder.setWorkTree(r.getWorkTree()).setIndexFile(r.getIndexFile());
}
return builder;
}
@@ -134,8 +130,7 @@
}
@Override
- public RefRename newRename(String fromName, String toName)
- throws IOException {
+ public RefRename newRename(String fromName, String toName) throws IOException {
throw new UnsupportedOperationException(MSG);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/RebaseSorter.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/RebaseSorter.java
index 3284c12..576f473 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/RebaseSorter.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/RebaseSorter.java
@@ -24,12 +24,6 @@
import com.google.gerrit.server.query.change.ChangeData;
import com.google.gerrit.server.query.change.InternalChangeQuery;
import com.google.gwtorm.server.OrmException;
-
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.lib.Repository;
-import org.eclipse.jgit.revwalk.RevCommit;
-import org.eclipse.jgit.revwalk.RevFlag;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
@@ -38,6 +32,10 @@
import java.util.Iterator;
import java.util.List;
import java.util.Set;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.lib.Repository;
+import org.eclipse.jgit.revwalk.RevCommit;
+import org.eclipse.jgit.revwalk.RevFlag;
public class RebaseSorter {
private final CodeReviewRevWalk rw;
@@ -48,10 +46,14 @@
private final ChangeKindCache changeKindCache;
private final Repository repo;
- public RebaseSorter(CodeReviewRevWalk rw, RevCommit initialTip,
- Set<RevCommit> alreadyAccepted, RevFlag canMergeFlag,
+ public RebaseSorter(
+ CodeReviewRevWalk rw,
+ RevCommit initialTip,
+ Set<RevCommit> alreadyAccepted,
+ RevFlag canMergeFlag,
InternalChangeQuery internalChangeQuery,
- ChangeKindCache changeKindCache, Repository repo) {
+ ChangeKindCache changeKindCache,
+ Repository repo) {
this.rw = rw;
this.canMergeFlag = canMergeFlag;
this.initialTip = initialTip;
@@ -61,8 +63,7 @@
this.repo = repo;
}
- public List<CodeReviewCommit> sort(Collection<CodeReviewCommit> incoming)
- throws IOException {
+ public List<CodeReviewCommit> sort(Collection<CodeReviewCommit> incoming) throws IOException {
final List<CodeReviewCommit> sorted = new ArrayList<>();
final Set<CodeReviewCommit> sort = new HashSet<>(incoming);
while (!sort.isEmpty()) {
@@ -105,16 +106,13 @@
return sorted;
}
- private boolean isAlreadyMerged(CodeReviewCommit commit, Branch.NameKey dest)
- throws IOException {
- try (CodeReviewRevWalk mirw =
- CodeReviewCommit.newRevWalk(rw.getObjectReader())) {
+ private boolean isAlreadyMerged(CodeReviewCommit commit, Branch.NameKey dest) throws IOException {
+ try (CodeReviewRevWalk mirw = CodeReviewCommit.newRevWalk(rw.getObjectReader())) {
mirw.reset();
mirw.markStart(commit);
// check if the commit is merged in other branches
for (RevCommit accepted : alreadyAccepted) {
- if (mirw.isMergedInto(mirw.parseCommit(accepted),
- mirw.parseCommit(commit))) {
+ if (mirw.isMergedInto(mirw.parseCommit(accepted), mirw.parseCommit(commit))) {
return true;
}
}
@@ -134,12 +132,12 @@
}
}
- private boolean isRework(Project.NameKey project, RevCommit oldCommit,
- ChangeData change) throws OrmException, IOException {
- RevCommit currentCommit = rw.parseCommit(
- ObjectId.fromString(change.currentPatchSet().getRevision().get()));
- return ChangeKind.REWORK == changeKindCache
- .getChangeKind(project, repo, oldCommit, currentCommit);
+ private boolean isRework(Project.NameKey project, RevCommit oldCommit, ChangeData change)
+ throws OrmException, IOException {
+ RevCommit currentCommit =
+ rw.parseCommit(ObjectId.fromString(change.currentPatchSet().getRevision().get()));
+ return ChangeKind.REWORK
+ == changeKindCache.getChangeKind(project, repo, oldCommit, currentCommit);
}
private static <T> T removeOne(final Collection<T> c) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/ReceiveCommits.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/ReceiveCommits.java
index bc7c522..f983288 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/ReceiveCommits.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/ReceiveCommits.java
@@ -123,7 +123,23 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.assistedinject.Assisted;
-
+import java.io.IOException;
+import java.io.StringWriter;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.ExecutionException;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
import org.eclipse.jgit.errors.IncorrectObjectTypeException;
import org.eclipse.jgit.errors.MissingObjectException;
import org.eclipse.jgit.lib.BatchRefUpdate;
@@ -155,31 +171,12 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.io.StringWriter;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-import java.util.Set;
-import java.util.concurrent.ExecutionException;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
/** Receives change upload using the Git receive-pack protocol. */
public class ReceiveCommits {
- private static final Logger log =
- LoggerFactory.getLogger(ReceiveCommits.class);
+ private static final Logger log = LoggerFactory.getLogger(ReceiveCommits.class);
- public static final Pattern NEW_PATCHSET = Pattern.compile(
- "^" + REFS_CHANGES + "(?:[0-9][0-9]/)?([1-9][0-9]*)(?:/new)?$");
+ public static final Pattern NEW_PATCHSET =
+ Pattern.compile("^" + REFS_CHANGES + "(?:[0-9][0-9]/)?([1-9][0-9]*)(?:/new)?$");
private static final String COMMAND_REJECTION_MESSAGE_FOOTER =
"Please read the documentation and contact an administrator\n"
@@ -191,15 +188,18 @@
+ "ensure Change-Ids are unique for each commit";
private enum Error {
- CONFIG_UPDATE("You are not allowed to perform this operation.\n"
- + "Configuration changes can only be pushed by project owners\n"
- + "who also have 'Push' rights on " + RefNames.REFS_CONFIG),
- UPDATE("You are not allowed to perform this operation.\n"
- + "To push into this reference you need 'Push' rights."),
- DELETE("You need 'Push' rights with the 'Force Push'\n"
- + "flag set to delete references."),
- DELETE_CHANGES("Cannot delete from '" + REFS_CHANGES + "'"),
- CODE_REVIEW("You need 'Push' rights to upload code review requests.\n"
+ CONFIG_UPDATE(
+ "You are not allowed to perform this operation.\n"
+ + "Configuration changes can only be pushed by project owners\n"
+ + "who also have 'Push' rights on "
+ + RefNames.REFS_CONFIG),
+ UPDATE(
+ "You are not allowed to perform this operation.\n"
+ + "To push into this reference you need 'Push' rights."),
+ DELETE("You need 'Push' rights with the 'Force Push'\n" + "flag set to delete references."),
+ DELETE_CHANGES("Cannot delete from '" + REFS_CHANGES + "'"),
+ CODE_REVIEW(
+ "You need 'Push' rights to upload code review requests.\n"
+ "Verify that you are pushing to the right branch.");
private final String value;
@@ -219,9 +219,13 @@
public interface MessageSender {
void sendMessage(String what);
+
void sendError(String what);
+
void sendBytes(byte[] what);
+
void sendBytes(byte[] what, int off, int len);
+
void flush();
}
@@ -313,12 +317,10 @@
private final RequestId receiveId;
private MagicBranchInput magicBranch;
private boolean newChangeForAllNotInTarget;
- private final ListMultimap<String, String> pushOptions =
- LinkedListMultimap.create();
+ private final ListMultimap<String, String> pushOptions = LinkedListMultimap.create();
private List<CreateRequest> newChanges = Collections.emptyList();
- private final Map<Change.Id, ReplaceRequest> replaceByChange =
- new LinkedHashMap<>();
+ private final Map<Change.Id, ReplaceRequest> replaceByChange = new LinkedHashMap<>();
private final List<UpdateGroupsRequest> updateGroups = new ArrayList<>();
private final Set<ObjectId> validCommits = new HashSet<>();
@@ -344,7 +346,8 @@
private BatchRefUpdate batch;
@Inject
- ReceiveCommits(ReviewDb db,
+ ReceiveCommits(
+ ReviewDb db,
Sequences seq,
Provider<InternalChangeQuery> queryProvider,
ChangeNotes.Factory notesFactory,
@@ -380,7 +383,8 @@
BatchUpdate.Factory batchUpdateFactory,
SetHashtagsOp.Factory hashtagsFactory,
ReplaceOp.Factory replaceOpFactory,
- MergedByPushOp.Factory mergedByPushOpFactory) throws IOException {
+ MergedByPushOp.Factory mergedByPushOpFactory)
+ throws IOException {
this.user = projectControl.getUser().asIdentifiedUser();
this.db = db;
this.seq = seq;
@@ -435,59 +439,57 @@
rp.setAllowNonFastForwards(true);
rp.setRefLogIdent(user.newRefLogIdent());
rp.setTimeout(transferConfig.getTimeout());
- rp.setMaxObjectSizeLimit(transferConfig.getEffectiveMaxObjectSizeLimit(
- projectControl.getProjectState()));
+ rp.setMaxObjectSizeLimit(
+ transferConfig.getEffectiveMaxObjectSizeLimit(projectControl.getProjectState()));
rp.setCheckReceivedObjects(ps.getConfig().getCheckReceivedObjects());
- rp.setRefFilter(new RefFilter() {
- @Override
- public Map<String, Ref> filter(Map<String, Ref> refs) {
- Map<String, Ref> filteredRefs =
- Maps.newHashMapWithExpectedSize(refs.size());
- for (Map.Entry<String, Ref> e : refs.entrySet()) {
- String name = e.getKey();
- if (!name.startsWith(REFS_CHANGES)
- && !name.startsWith(RefNames.REFS_CACHE_AUTOMERGE)) {
- filteredRefs.put(name, e.getValue());
+ rp.setRefFilter(
+ new RefFilter() {
+ @Override
+ public Map<String, Ref> filter(Map<String, Ref> refs) {
+ Map<String, Ref> filteredRefs = Maps.newHashMapWithExpectedSize(refs.size());
+ for (Map.Entry<String, Ref> e : refs.entrySet()) {
+ String name = e.getKey();
+ if (!name.startsWith(REFS_CHANGES)
+ && !name.startsWith(RefNames.REFS_CACHE_AUTOMERGE)) {
+ filteredRefs.put(name, e.getValue());
+ }
+ }
+ return filteredRefs;
}
- }
- return filteredRefs;
- }
- });
+ });
if (!projectControl.allRefsAreVisible()) {
- rp.setCheckReferencedObjectsAreReachable(
- receiveConfig.checkReferencedObjectsAreReachable);
+ rp.setCheckReferencedObjectsAreReachable(receiveConfig.checkReferencedObjectsAreReachable);
}
- rp.setAdvertiseRefsHook(new VisibleRefFilter(tagCache, notesFactory,
- changeCache, repo, projectControl, db, false));
+ rp.setAdvertiseRefsHook(
+ new VisibleRefFilter(tagCache, notesFactory, changeCache, repo, projectControl, db, false));
List<AdvertiseRefsHook> advHooks = new ArrayList<>(3);
- advHooks.add(new AdvertiseRefsHook() {
- @Override
- public void advertiseRefs(BaseReceivePack rp)
- throws ServiceMayNotContinueException {
- allRefs = rp.getAdvertisedRefs();
- if (allRefs == null) {
- try {
- allRefs = rp.getRepository().getRefDatabase().getRefs(ALL);
- } catch (ServiceMayNotContinueException e) {
- throw e;
- } catch (IOException e) {
- ServiceMayNotContinueException ex =
- new ServiceMayNotContinueException();
- ex.initCause(e);
- throw ex;
+ advHooks.add(
+ new AdvertiseRefsHook() {
+ @Override
+ public void advertiseRefs(BaseReceivePack rp) throws ServiceMayNotContinueException {
+ allRefs = rp.getAdvertisedRefs();
+ if (allRefs == null) {
+ try {
+ allRefs = rp.getRepository().getRefDatabase().getRefs(ALL);
+ } catch (ServiceMayNotContinueException e) {
+ throw e;
+ } catch (IOException e) {
+ ServiceMayNotContinueException ex = new ServiceMayNotContinueException();
+ ex.initCause(e);
+ throw ex;
+ }
+ }
+ rp.setAdvertisedRefs(allRefs, rp.getAdvertisedObjects());
}
- }
- rp.setAdvertisedRefs(allRefs, rp.getAdvertisedObjects());
- }
- @Override
- public void advertiseRefs(UploadPack uploadPack) {
- }
- });
+ @Override
+ public void advertiseRefs(UploadPack uploadPack) {}
+ });
advHooks.add(rp.getAdvertiseRefsHook());
- advHooks.add(new ReceiveCommitsAdvertiseRefsHook(
- queryProvider, projectControl.getProject().getNameKey()));
+ advHooks.add(
+ new ReceiveCommitsAdvertiseRefsHook(
+ queryProvider, projectControl.getProject().getNameKey()));
advHooks.add(new HackPushNegotiateHook());
rp.setAdvertiseRefsHook(AdvertiseRefsHookChain.newChain(advHooks));
rp.setPostReceiveHook(lazyPostReceive.get());
@@ -561,8 +563,7 @@
}
}
- void processCommands(Collection<ReceiveCommand> commands,
- MultiProgressMonitor progress) {
+ void processCommands(Collection<ReceiveCommand> commands, MultiProgressMonitor progress) {
newProgress = progress.beginSubTask("new", UNKNOWN);
replaceProgress = progress.beginSubTask("updated", UNKNOWN);
closeProgress = progress.beginSubTask("closed", UNKNOWN);
@@ -582,8 +583,7 @@
logDebug("Executing batch with {} commands", batch.getCommands().size());
if (!batch.getCommands().isEmpty()) {
try {
- if (!batch.isAllowNonFastForwards() && magicBranch != null
- && magicBranch.edit) {
+ if (!batch.isAllowNonFastForwards() && magicBranch != null && magicBranch.edit) {
logDebug("Allowing non-fast-forward for edit ref");
batch.setAllowNonFastForwards(true);
}
@@ -596,8 +596,7 @@
cnt++;
}
}
- logError(String.format(
- "Failed to store %d refs in %s", cnt, project.getName()), err);
+ logError(String.format("Failed to store %d refs in %s", cnt, project.getName()), err);
}
}
@@ -620,10 +619,7 @@
String refName = c.getRefName();
if (c.getType() == ReceiveCommand.Type.UPDATE) { // aka fast-forward
logDebug("Updating tag cache on fast-forward of {}", c.getRefName());
- tagCache.updateFastForward(project.getNameKey(),
- refName,
- c.getOldId(),
- c.getNewId());
+ tagCache.updateFastForward(project.getNameKey(), refName, c.getOldId(), c.getNewId());
}
if (isHead(c) || isConfig(c)) {
@@ -632,8 +628,7 @@
case UPDATE:
case UPDATE_NONFASTFORWARD:
autoCloseChanges(c);
- branches.add(new Branch.NameKey(project.getNameKey(),
- refName));
+ branches.add(new Branch.NameKey(project.getNameKey(), refName));
break;
case DELETE:
@@ -656,8 +651,7 @@
logDebug("Firing ref update for {}", c.getRefName());
gitRefUpdated.fire(project.getNameKey(), c, user.getAccount());
} else {
- logDebug("Assuming ref update event for {} has fired",
- c.getRefName());
+ logDebug("Assuming ref update event for {} has fired", c.getRefName());
}
}
}
@@ -685,16 +679,23 @@
addMessage("New Changes:");
for (CreateRequest c : created) {
addMessage(
- formatChangeUrl(canonicalWebUrl, c.change, c.change.getSubject(),
- c.change.getStatus() == Change.Status.DRAFT, false));
+ formatChangeUrl(
+ canonicalWebUrl,
+ c.change,
+ c.change.getSubject(),
+ c.change.getStatus() == Change.Status.DRAFT,
+ false));
}
addMessage("");
}
- List<ReplaceRequest> updated = replaceByChange.values().stream()
- .filter(r -> !r.skip && r.inputCommand.getResult() == OK)
- .sorted(comparingInt(r -> r.notes.getChangeId().get()))
- .collect(toList());
+ List<ReplaceRequest> updated =
+ replaceByChange
+ .values()
+ .stream()
+ .filter(r -> !r.skip && r.inputCommand.getResult() == OK)
+ .sorted(comparingInt(r -> r.notes.getChangeId().get()))
+ .collect(toList());
if (!updated.isEmpty()) {
addMessage("");
addMessage("Updated Changes:");
@@ -703,8 +704,7 @@
String subject;
if (edit) {
try {
- subject =
- rp.getRevWalk().parseCommit(u.newCommitId).getShortMessage();
+ subject = rp.getRevWalk().parseCommit(u.newCommitId).getShortMessage();
} catch (IOException e) {
// Log and fall back to original change subject
logWarn("failed to get subject for edit patch set", e);
@@ -713,22 +713,27 @@
} else {
subject = u.info.getSubject();
}
- addMessage(formatChangeUrl(canonicalWebUrl, u.notes.getChange(),
- subject, u.replaceOp != null && u.replaceOp.getPatchSet().isDraft(),
- edit));
+ addMessage(
+ formatChangeUrl(
+ canonicalWebUrl,
+ u.notes.getChange(),
+ subject,
+ u.replaceOp != null && u.replaceOp.getPatchSet().isDraft(),
+ edit));
}
addMessage("");
}
}
- private static String formatChangeUrl(String url, Change change,
- String subject, boolean draft, boolean edit) {
- StringBuilder m = new StringBuilder()
- .append(" ")
- .append(url)
- .append(change.getChangeId())
- .append(" ")
- .append(ChangeUtil.cropSubject(subject));
+ private static String formatChangeUrl(
+ String url, Change change, String subject, boolean draft, boolean edit) {
+ StringBuilder m =
+ new StringBuilder()
+ .append(" ")
+ .append(url)
+ .append(change.getChangeId())
+ .append(" ")
+ .append(ChangeUtil.cropSubject(subject));
if (draft) {
m.append(" [DRAFT]");
}
@@ -754,23 +759,24 @@
String refName = replace.inputCommand.getRefName();
checkState(
NEW_PATCHSET.matcher(refName).matches(),
- "expected a new patch set command as input when creating %s;"
- + " got %s",
- replace.cmd.getRefName(), refName);
+ "expected a new patch set command as input when creating %s;" + " got %s",
+ replace.cmd.getRefName(),
+ refName);
try {
logDebug("One-off insertion of patch set for {}", refName);
replace.insertPatchSetWithoutBatchUpdate();
replace.inputCommand.setResult(OK);
} catch (IOException | UpdateException | RestApiException err) {
reject(replace.inputCommand, "internal server error");
- logError(String.format(
- "Cannot add patch set to change %d in project %s",
- e.getKey().get(), project.getName()), err);
+ logError(
+ String.format(
+ "Cannot add patch set to change %d in project %s",
+ e.getKey().get(), project.getName()),
+ err);
}
} else if (replace.inputCommand.getResult() == NOT_ATTEMPTED) {
reject(replace.inputCommand, "internal server error");
- logError(String.format("Replacement for project %s was not attempted",
- project.getName()));
+ logError(String.format("Replacement for project %s was not attempted", project.getName()));
}
}
@@ -780,10 +786,12 @@
logDebug("No magic branch, nothing more to do");
return;
} else if (magicBranch.cmd.getResult() != NOT_ATTEMPTED) {
- logWarn(String.format(
- "Skipping change updates on %s because ref update failed: %s %s",
- project.getName(), magicBranch.cmd.getResult(),
- Strings.nullToEmpty(magicBranch.cmd.getMessage())));
+ logWarn(
+ String.format(
+ "Skipping change updates on %s because ref update failed: %s %s",
+ project.getName(),
+ magicBranch.cmd.getResult(),
+ Strings.nullToEmpty(magicBranch.cmd.getMessage())));
return;
}
@@ -793,38 +801,44 @@
okToInsert++;
} else {
String createChangeResult =
- String.format("%s %s",
- create.cmd.getResult(),
- Strings.nullToEmpty(create.cmd.getMessage())).trim();
+ String.format(
+ "%s %s", create.cmd.getResult(), Strings.nullToEmpty(create.cmd.getMessage()))
+ .trim();
lastCreateChangeErrors.add(createChangeResult);
- logError(String.format("Command %s on %s:%s not completed: %s",
- create.cmd.getType(),
- project.getName(),
- create.cmd.getRefName(),
- createChangeResult));
+ logError(
+ String.format(
+ "Command %s on %s:%s not completed: %s",
+ create.cmd.getType(),
+ project.getName(),
+ create.cmd.getRefName(),
+ createChangeResult));
}
}
- logDebug("Counted {} ok to insert, out of {} to replace and {} new",
- okToInsert, replaceCount, newChanges.size());
+ logDebug(
+ "Counted {} ok to insert, out of {} to replace and {} new",
+ okToInsert,
+ replaceCount,
+ newChanges.size());
if (okToInsert != replaceCount + newChanges.size()) {
// One or more new references failed to create. Assume the
// system isn't working correctly anymore and abort.
- reject(magicBranch.cmd, "Unable to create changes: "
- + lastCreateChangeErrors.stream().collect(joining(" ")));
- logError(String.format(
- "Only %d of %d new change refs created in %s; aborting",
- okToInsert, replaceCount + newChanges.size(), project.getName()));
+ reject(
+ magicBranch.cmd,
+ "Unable to create changes: " + lastCreateChangeErrors.stream().collect(joining(" ")));
+ logError(
+ String.format(
+ "Only %d of %d new change refs created in %s; aborting",
+ okToInsert, replaceCount + newChanges.size(), project.getName()));
return;
}
try (BatchUpdate bu =
- batchUpdateFactory.create(db, magicBranch.dest.getParentKey(),
- user.materializedCopy(), TimeUtil.nowTs());
+ batchUpdateFactory.create(
+ db, magicBranch.dest.getParentKey(), user.materializedCopy(), TimeUtil.nowTs());
ObjectInserter ins = repo.newObjectInserter()) {
- bu.setRepository(repo, rp.getRevWalk(), ins)
- .updateChangesInParallel();
+ bu.setRepository(repo, rp.getRevWalk(), ins).updateChangesInParallel();
bu.setRequestId(receiveId);
for (ReplaceRequest replace : replaceByChange.values()) {
if (replace.inputCommand == magicBranch.cmd) {
@@ -921,8 +935,7 @@
continue;
}
- if (!Repository.isValidRefName(cmd.getRefName())
- || cmd.getRefName().contains("//")) {
+ if (!Repository.isValidRefName(cmd.getRefName()) || cmd.getRefName().contains("//")) {
reject(cmd, "not valid ref");
continue;
}
@@ -935,17 +948,16 @@
if (projectControl.getProjectState().isAllUsers()
&& RefNames.REFS_USERS_SELF.equals(cmd.getRefName())) {
String newName = RefNames.refsUsers(user.getAccountId());
- logDebug("Swapping out command for {} to {}",
- RefNames.REFS_USERS_SELF, newName);
+ logDebug("Swapping out command for {} to {}", RefNames.REFS_USERS_SELF, newName);
final ReceiveCommand orgCmd = cmd;
- cmd = new ReceiveCommand(cmd.getOldId(), cmd.getNewId(), newName,
- cmd.getType()) {
- @Override
- public void setResult(Result s, String m) {
- super.setResult(s, m);
- orgCmd.setResult(s, m);
- }
- };
+ cmd =
+ new ReceiveCommand(cmd.getOldId(), cmd.getNewId(), newName, cmd.getType()) {
+ @Override
+ public void setResult(Result s, String m) {
+ super.setResult(s, m);
+ orgCmd.setResult(s, m);
+ }
+ };
}
Matcher m = NEW_PATCHSET.matcher(cmd.getRefName());
@@ -1003,9 +1015,13 @@
addError(" " + err.getMessage());
}
reject(cmd, "invalid project configuration");
- logError("User " + user.getUserName()
- + " tried to push invalid project configuration "
- + cmd.getNewId().name() + " for " + project.getName());
+ logError(
+ "User "
+ + user.getUserName()
+ + " tried to push invalid project configuration "
+ + cmd.getNewId().name()
+ + " for "
+ + project.getName());
continue;
}
Project.NameKey newParent = cfg.getProject().getParent(allProjectsName);
@@ -1034,40 +1050,54 @@
ProjectConfigEntry configEntry = e.getProvider().get();
String value = pluginCfg.getString(e.getExportName());
String oldValue =
- projectControl.getProjectState().getConfig()
+ projectControl
+ .getProjectState()
+ .getConfig()
.getPluginConfig(e.getPluginName())
.getString(e.getExportName());
if (configEntry.getType() == ProjectConfigEntryType.ARRAY) {
oldValue =
- Arrays.stream(
- projectControl.getProjectState()
- .getConfig().getPluginConfig(e.getPluginName())
- .getStringList(e.getExportName()))
- .collect(joining("\n"));
+ Arrays.stream(
+ projectControl
+ .getProjectState()
+ .getConfig()
+ .getPluginConfig(e.getPluginName())
+ .getStringList(e.getExportName()))
+ .collect(joining("\n"));
}
- if ((value == null ? oldValue != null : !value.equals(oldValue)) &&
- !configEntry.isEditable(projectControl.getProjectState())) {
- reject(cmd, String.format(
- "invalid project configuration: Not allowed to set parameter"
- + " '%s' of plugin '%s' on project '%s'.",
- e.getExportName(), e.getPluginName(), project.getName()));
+ if ((value == null ? oldValue != null : !value.equals(oldValue))
+ && !configEntry.isEditable(projectControl.getProjectState())) {
+ reject(
+ cmd,
+ String.format(
+ "invalid project configuration: Not allowed to set parameter"
+ + " '%s' of plugin '%s' on project '%s'.",
+ e.getExportName(), e.getPluginName(), project.getName()));
continue;
}
if (ProjectConfigEntryType.LIST.equals(configEntry.getType())
- && value != null && !configEntry.getPermittedValues().contains(value)) {
- reject(cmd, String.format(
- "invalid project configuration: The value '%s' is "
- + "not permitted for parameter '%s' of plugin '%s'.",
- value, e.getExportName(), e.getPluginName()));
+ && value != null
+ && !configEntry.getPermittedValues().contains(value)) {
+ reject(
+ cmd,
+ String.format(
+ "invalid project configuration: The value '%s' is "
+ + "not permitted for parameter '%s' of plugin '%s'.",
+ value, e.getExportName(), e.getPluginName()));
}
}
} catch (Exception e) {
reject(cmd, "invalid project configuration");
- logError("User " + user.getUserName()
- + " tried to push invalid project configuration "
- + cmd.getNewId().name() + " for " + project.getName(), e);
+ logError(
+ "User "
+ + user.getUserName()
+ + " tried to push invalid project configuration "
+ + cmd.getNewId().name()
+ + " for "
+ + project.getName(),
+ e);
continue;
}
break;
@@ -1088,8 +1118,9 @@
try {
obj = rp.getRevWalk().parseAny(cmd.getNewId());
} catch (IOException err) {
- logError("Invalid object " + cmd.getNewId().name() + " for "
- + cmd.getRefName() + " creation", err);
+ logError(
+ "Invalid object " + cmd.getNewId().name() + " for " + cmd.getRefName() + " creation",
+ err);
reject(cmd, "invalid object");
return;
}
@@ -1139,8 +1170,7 @@
try {
obj = rp.getRevWalk().parseAny(cmd.getNewId());
} catch (IOException err) {
- logError("Invalid object " + cmd.getNewId().name() + " for "
- + cmd.getRefName(), err);
+ logError("Invalid object " + cmd.getNewId().name() + " for " + cmd.getRefName(), err);
reject(cmd, "invalid object");
return false;
}
@@ -1180,8 +1210,9 @@
} catch (IncorrectObjectTypeException notCommit) {
newObject = null;
} catch (IOException err) {
- logError("Invalid object " + cmd.getNewId().name() + " for "
- + cmd.getRefName() + " forced update", err);
+ logError(
+ "Invalid object " + cmd.getNewId().name() + " for " + cmd.getRefName() + " forced update",
+ err);
reject(cmd, "invalid object");
return;
}
@@ -1201,8 +1232,8 @@
}
batch.setAllowNonFastForwards(true).addCommand(cmd);
} else {
- cmd.setResult(REJECTED_NONFASTFORWARD, " need '"
- + PermissionRule.FORCE_PUSH + "' privilege.");
+ cmd.setResult(
+ REJECTED_NONFASTFORWARD, " need '" + PermissionRule.FORCE_PUSH + "' privilege.");
}
}
@@ -1231,7 +1262,11 @@
@Option(name = "--draft", usage = "mark new/updated changes as draft")
boolean draft;
- @Option(name = "--edit", aliases = {"-e"}, usage = "upload as change edit")
+ @Option(
+ name = "--edit",
+ aliases = {"-e"},
+ usage = "upload as change edit"
+ )
boolean edit;
@Option(name = "--submit", usage = "immediately submit the change")
@@ -1240,26 +1275,30 @@
@Option(name = "--merged", usage = "create single change for a merged commit")
boolean merged;
- @Option(name = "--notify",
- usage = "Notify handling that defines to whom email notifications "
- + "should be sent. Allowed values are NONE, OWNER, "
- + "OWNER_REVIEWERS, ALL. If not set, the default is ALL.")
+ @Option(
+ name = "--notify",
+ usage =
+ "Notify handling that defines to whom email notifications "
+ + "should be sent. Allowed values are NONE, OWNER, "
+ + "OWNER_REVIEWERS, ALL. If not set, the default is ALL."
+ )
NotifyHandling notify = NotifyHandling.ALL;
- @Option(name = "--notify-to", metaVar = "USER",
- usage = "user that should be notified")
+ @Option(name = "--notify-to", metaVar = "USER", usage = "user that should be notified")
List<Account.Id> tos = new ArrayList<>();
- @Option(name = "--notify-cc", metaVar = "USER",
- usage = "user that should be CC'd")
+ @Option(name = "--notify-cc", metaVar = "USER", usage = "user that should be CC'd")
List<Account.Id> ccs = new ArrayList<>();
- @Option(name = "--notify-bcc", metaVar = "USER",
- usage = "user that should be BCC'd")
+ @Option(name = "--notify-bcc", metaVar = "USER", usage = "user that should be BCC'd")
List<Account.Id> bccs = new ArrayList<>();
- @Option(name = "--reviewer", aliases = {"-r"}, metaVar = "EMAIL",
- usage = "add reviewer to changes")
+ @Option(
+ name = "--reviewer",
+ aliases = {"-r"},
+ metaVar = "EMAIL",
+ usage = "add reviewer to changes"
+ )
void reviewer(Account.Id id) {
reviewer.add(id);
}
@@ -1274,8 +1313,12 @@
draft = !publish;
}
- @Option(name = "--label", aliases = {"-l"}, metaVar = "LABEL+VALUE",
- usage = "label(s) to assign (defaults to +1 if no value provided")
+ @Option(
+ name = "--label",
+ aliases = {"-l"},
+ metaVar = "LABEL+VALUE",
+ usage = "label(s) to assign (defaults to +1 if no value provided"
+ )
void addLabel(String token) throws CmdLineException {
LabelVote v = LabelVote.parse(token);
try {
@@ -1287,15 +1330,23 @@
labels.put(v.label(), v.value());
}
- @Option(name = "--message", aliases = {"-m"}, metaVar = "MESSAGE",
- usage = "Comment message to apply to the review")
+ @Option(
+ name = "--message",
+ aliases = {"-m"},
+ metaVar = "MESSAGE",
+ usage = "Comment message to apply to the review"
+ )
void addMessage(final String token) {
// git push does not allow spaces in refs.
message = token.replace("_", " ");
}
- @Option(name = "--hashtag", aliases = {"-t"}, metaVar = "HASHTAG",
- usage = "add hashtag to changes")
+ @Option(
+ name = "--hashtag",
+ aliases = {"-t"},
+ metaVar = "HASHTAG",
+ usage = "add hashtag to changes"
+ )
void addHashtag(String token) throws CmdLineException {
if (!notesMigration.readChanges()) {
throw clp.reject("cannot add hashtags; noteDb is disabled");
@@ -1307,8 +1358,7 @@
//TODO(dpursehouse): validate hashtags
}
- MagicBranchInput(ReceiveCommand cmd, LabelTypes labelTypes,
- NotesMigration notesMigration) {
+ MagicBranchInput(ReceiveCommand cmd, LabelTypes labelTypes, NotesMigration notesMigration) {
this.cmd = cmd;
this.draft = cmd.getRefName().startsWith(MagicBranch.NEW_DRAFT_CHANGE);
this.labelTypes = labelTypes;
@@ -1328,10 +1378,13 @@
return accountsToNotify;
}
- String parse(CmdLineParser clp, Repository repo, Set<String> refs,
- ListMultimap<String, String> pushOptions) throws CmdLineException {
- String ref = RefNames.fullName(
- MagicBranch.getDestBranchName(cmd.getRefName()));
+ String parse(
+ CmdLineParser clp,
+ Repository repo,
+ Set<String> refs,
+ ListMultimap<String, String> pushOptions)
+ throws CmdLineException {
+ String ref = RefNames.fullName(MagicBranch.getDestBranchName(cmd.getRefName()));
ListMultimap<String, String> options = LinkedListMultimap.create(pushOptions);
int optionStart = ref.indexOf('%');
@@ -1355,7 +1408,7 @@
// suffix is entirely optional, so it might not even exist.
String head = readHEAD(repo);
int split = ref.length();
- for (;;) {
+ for (; ; ) {
String name = ref.substring(0, split);
if (refs.contains(name) || name.equals(head)) {
break;
@@ -1375,9 +1428,9 @@
/**
* Gets an unmodifiable view of the pushOptions.
- * <p>
- * The collection is empty if the client does not support push options, or if
- * the client did not send any options.
+ *
+ * <p>The collection is empty if the client does not support push options, or if the client did
+ * not send any options.
*
* @return an unmodifiable view of pushOptions.
*/
@@ -1403,8 +1456,7 @@
magicBranch.clp = clp;
try {
- ref = magicBranch.parse(
- clp, repo, rp.getAdvertisedRefs().keySet(), pushOptions);
+ ref = magicBranch.parse(clp, repo, rp.getAdvertisedRefs().keySet(), pushOptions);
} catch (CmdLineException e) {
if (!clp.wasHelpRequestedByOption()) {
logDebug("Invalid branch syntax");
@@ -1421,8 +1473,7 @@
reject(cmd, "see help");
return;
}
- if (projectControl.getProjectState().isAllUsers()
- && RefNames.REFS_USERS_SELF.equals(ref)) {
+ if (projectControl.getProjectState().isAllUsers() && RefNames.REFS_USERS_SELF.equals(ref)) {
logDebug("Handling {}", RefNames.REFS_USERS_SELF);
ref = RefNames.refsUsers(user.getAccountId());
}
@@ -1469,8 +1520,8 @@
return;
}
- if (magicBranch.submit && !projectControl.controlForRef(
- MagicBranch.NEW_CHANGE + ref).canSubmit(true)) {
+ if (magicBranch.submit
+ && !projectControl.controlForRef(MagicBranch.NEW_CHANGE + ref).canSubmit(true)) {
reject(cmd, "submit not allowed");
return;
}
@@ -1519,8 +1570,7 @@
if (magicBranch.base != null) {
logDebug("Handling %base: {}", magicBranch.base);
- magicBranch.baseCommit = Lists.newArrayListWithCapacity(
- magicBranch.base.size());
+ magicBranch.baseCommit = Lists.newArrayListWithCapacity(magicBranch.base.size());
for (ObjectId id : magicBranch.base) {
try {
magicBranch.baseCommit.add(walk.parseCommit(id));
@@ -1531,9 +1581,7 @@
reject(cmd, "base not found");
return;
} catch (IOException e) {
- logWarn(String.format(
- "Project %s cannot read %s",
- project.getName(), id.name()), e);
+ logWarn(String.format("Project %s cannot read %s", project.getName(), id.name()), e);
reject(cmd, "internal server error");
return;
}
@@ -1547,8 +1595,8 @@
logDebug("Set baseCommit = {}", magicBranch.baseCommit.get(0).name());
}
} catch (IOException ex) {
- logWarn(String.format("Error walking to %s in project %s",
- destBranch, project.getName()), ex);
+ logWarn(
+ String.format("Error walking to %s in project %s", destBranch, project.getName()), ex);
reject(cmd, "internal server error");
return;
}
@@ -1597,8 +1645,7 @@
}
}
- private RevCommit readBranchTip(ReceiveCommand cmd, Branch.NameKey branch)
- throws IOException {
+ private RevCommit readBranchTip(ReceiveCommand cmd, Branch.NameKey branch) throws IOException {
Ref r = allRefs.get(branch.get());
if (r == null) {
reject(cmd, branch.get() + " not found");
@@ -1626,8 +1673,7 @@
Change changeEnt;
try {
- changeEnt = notesFactory.createChecked(db, project.getNameKey(), changeId)
- .getChange();
+ changeEnt = notesFactory.createChecked(db, project.getNameKey(), changeId).getChange();
} catch (NoSuchChangeException e) {
logError("Change not found " + changeId, e);
reject(cmd, "change " + changeId + " not found");
@@ -1646,15 +1692,14 @@
requestReplace(cmd, true, changeEnt, newCommit);
}
- private boolean requestReplace(ReceiveCommand cmd, boolean checkMergedInto,
- Change change, RevCommit newCommit) {
+ private boolean requestReplace(
+ ReceiveCommand cmd, boolean checkMergedInto, Change change, RevCommit newCommit) {
if (change.getStatus().isClosed()) {
reject(cmd, "change " + canonicalWebUrl + change.getId() + " closed");
return false;
}
- ReplaceRequest req =
- new ReplaceRequest(change.getId(), newCommit, cmd, checkMergedInto);
+ ReplaceRequest req = new ReplaceRequest(change.getId(), newCommit, cmd, checkMergedInto);
if (replaceByChange.containsKey(req.ontoChange)) {
reject(cmd, "duplicate request");
return false;
@@ -1668,9 +1713,8 @@
newChanges = new ArrayList<>();
ListMultimap<ObjectId, Ref> existing = changeRefsById();
- GroupCollector groupCollector = GroupCollector.create(
- changeRefsById(), db, psUtil,
- notesFactory, project.getNameKey());
+ GroupCollector groupCollector =
+ GroupCollector.create(changeRefsById(), db, psUtil, notesFactory, project.getNameKey());
try {
RevCommit start = setUpWalkForSelectingChanges();
@@ -1680,16 +1724,16 @@
List<ChangeLookup> pending = new ArrayList<>();
Set<Change.Key> newChangeIds = new HashSet<>();
- int maxBatchChanges =
- receiveConfig.getEffectiveMaxBatchChangesLimit(user);
+ int maxBatchChanges = receiveConfig.getEffectiveMaxBatchChangesLimit(user);
int total = 0;
int alreadyTracked = 0;
- boolean rejectImplicitMerges = start.getParentCount() == 1
- && projectCache.get(project.getNameKey()).isRejectImplicitMerges()
- // Don't worry about implicit merges when creating changes for
- // already-merged commits; they're already in history, so it's too
- // late.
- && !magicBranch.merged;
+ boolean rejectImplicitMerges =
+ start.getParentCount() == 1
+ && projectCache.get(project.getNameKey()).isRejectImplicitMerges()
+ // Don't worry about implicit merges when creating changes for
+ // already-merged commits; they're already in history, so it's too
+ // late.
+ && !magicBranch.merged;
Set<RevCommit> mergedParents;
if (rejectImplicitMerges) {
mergedParents = new HashSet<>();
@@ -1697,7 +1741,7 @@
mergedParents = null;
}
- for (;;) {
+ for (; ; ) {
RevCommit c = rp.getRevWalk().next();
if (c == null) {
break;
@@ -1733,12 +1777,10 @@
if (!(newChangeForAllNotInTarget || magicBranch.base != null)) {
continue;
}
- logDebug("Creating new change for {} even though it is already tracked",
- name);
+ logDebug("Creating new change for {} even though it is already tracked", name);
}
- if (!validCommit(
- rp.getRevWalk(), magicBranch.ctl, magicBranch.cmd, c)) {
+ if (!validCommit(rp.getRevWalk(), magicBranch.ctl, magicBranch.cmd, c)) {
// Not a change the user can propose? Abort as early as possible.
newChanges = Collections.emptyList();
logDebug("Aborting early due to invalid commit");
@@ -1747,11 +1789,11 @@
// Don't allow merges to be uploaded in commit chain via all-not-in-target
if (newChangeForAllNotInTarget && c.getParentCount() > 1) {
- reject(magicBranch.cmd,
+ reject(
+ magicBranch.cmd,
"Pushing merges in commit chains with 'all not in target' is not allowed,\n"
- + "to override please set the base manually");
- logDebug("Rejecting merge commit {} with newChangeForAllNotInTarget",
- name);
+ + "to override please set the base manually");
+ logDebug("Rejecting merge commit {} with newChangeForAllNotInTarget", name);
// TODO(dborowitz): Should we early return here?
}
@@ -1766,23 +1808,27 @@
int n = pending.size() + newChanges.size();
if (maxBatchChanges != 0 && n > maxBatchChanges) {
logDebug("{} changes exceeds limit of {}", n, maxBatchChanges);
- reject(magicBranch.cmd,
- "the number of pushed changes in a batch exceeds the max limit "
- + maxBatchChanges);
+ reject(
+ magicBranch.cmd,
+ "the number of pushed changes in a batch exceeds the max limit " + maxBatchChanges);
newChanges = Collections.emptyList();
return;
}
}
- logDebug("Finished initial RevWalk with {} commits total: {} already"
- + " tracked, {} new changes with no Change-Id, and {} deferred"
- + " lookups", total, alreadyTracked, newChanges.size(),
+ logDebug(
+ "Finished initial RevWalk with {} commits total: {} already"
+ + " tracked, {} new changes with no Change-Id, and {} deferred"
+ + " lookups",
+ total,
+ alreadyTracked,
+ newChanges.size(),
pending.size());
if (rejectImplicitMerges) {
rejectImplicitMerges(mergedParents);
}
- for (Iterator<ChangeLookup> itr = pending.iterator(); itr.hasNext();) {
+ for (Iterator<ChangeLookup> itr = pending.iterator(); itr.hasNext(); ) {
ChangeLookup p = itr.next();
if (newChangeIds.contains(p.changeKey)) {
logDebug("Multiple commits with Change-Id {}", p.changeKey);
@@ -1793,12 +1839,11 @@
List<ChangeData> changes = p.destChanges;
if (changes.size() > 1) {
- logDebug("Multiple changes in branch {} with Change-Id {}: {}",
+ logDebug(
+ "Multiple changes in branch {} with Change-Id {}: {}",
magicBranch.dest,
p.changeKey,
- changes.stream()
- .map(cd -> cd.getId().toString())
- .collect(joining()));
+ changes.stream().map(cd -> cd.getId().toString()).collect(joining()));
// WTF, multiple changes in this branch have the same key?
// Since the commit is new, the user should recreate it with
// a different Change-Id. In practice, we should never see
@@ -1827,8 +1872,7 @@
continue;
}
}
- if (requestReplace(
- magicBranch.cmd, false, changes.get(0).change(), p.commit)) {
+ if (requestReplace(magicBranch.cmd, false, changes.get(0).change(), p.commit)) {
continue;
}
newChanges = Collections.emptyList();
@@ -1846,8 +1890,7 @@
// double check against the existing refs
if (foundInExistingRef(existing.get(p.commit))) {
if (pending.size() == 1) {
- reject(magicBranch.cmd,
- "commit(s) already exists (as current patchset)");
+ reject(magicBranch.cmd, "commit(s) already exists (as current patchset)");
newChanges = Collections.emptyList();
return;
}
@@ -1858,8 +1901,10 @@
}
newChanges.add(new CreateRequest(p.commit, magicBranch.dest.get()));
}
- logDebug("Finished deferred lookups with {} updates and {} new changes",
- replaceByChange.size(), newChanges.size());
+ logDebug(
+ "Finished deferred lookups with {} updates and {} new changes",
+ replaceByChange.size(),
+ newChanges.size());
} catch (IOException e) {
// Should never happen, the core receive process would have
// identified the missing object earlier before we got control.
@@ -1907,11 +1952,10 @@
}
}
- private boolean foundInExistingRef(Collection<Ref> existingRefs)
- throws OrmException {
+ private boolean foundInExistingRef(Collection<Ref> existingRefs) throws OrmException {
for (Ref ref : existingRefs) {
- ChangeNotes notes = notesFactory.create(db, project.getNameKey(),
- Change.Id.fromRef(ref.getName()));
+ ChangeNotes notes =
+ notesFactory.create(db, project.getNameKey(), Change.Id.fromRef(ref.getName()));
Change change = notes.getChange();
if (change.getDest().equals(magicBranch.dest)) {
logDebug("Found change {} from existing refs.", change.getKey());
@@ -1934,35 +1978,32 @@
if (magicBranch.baseCommit != null) {
markExplicitBasesUninteresting();
} else if (magicBranch.merged) {
- logDebug(
- "Marking parents of merged commit {} uninteresting", start.name());
+ logDebug("Marking parents of merged commit {} uninteresting", start.name());
for (RevCommit c : start.getParents()) {
rw.markUninteresting(c);
}
} else {
- markHeadsAsUninteresting(
- rw, magicBranch.ctl != null ? magicBranch.ctl.getRefName() : null);
+ markHeadsAsUninteresting(rw, magicBranch.ctl != null ? magicBranch.ctl.getRefName() : null);
}
return start;
}
private void markExplicitBasesUninteresting() throws IOException {
- logDebug("Marking {} base commits uninteresting",
- magicBranch.baseCommit.size());
+ logDebug("Marking {} base commits uninteresting", magicBranch.baseCommit.size());
for (RevCommit c : magicBranch.baseCommit) {
rp.getRevWalk().markUninteresting(c);
}
Ref targetRef = allRefs.get(magicBranch.ctl.getRefName());
if (targetRef != null) {
- logDebug("Marking target ref {} ({}) uninteresting",
- magicBranch.ctl.getRefName(), targetRef.getObjectId().name());
- rp.getRevWalk().markUninteresting(
- rp.getRevWalk().parseCommit(targetRef.getObjectId()));
+ logDebug(
+ "Marking target ref {} ({}) uninteresting",
+ magicBranch.ctl.getRefName(),
+ targetRef.getObjectId().name());
+ rp.getRevWalk().markUninteresting(rp.getRevWalk().parseCommit(targetRef.getObjectId()));
}
}
- private void rejectImplicitMerges(Set<RevCommit> mergedParents)
- throws IOException {
+ private void rejectImplicitMerges(Set<RevCommit> mergedParents) throws IOException {
if (!mergedParents.isEmpty()) {
Ref targetRef = allRefs.get(magicBranch.ctl.getRefName());
if (targetRef != null) {
@@ -1982,10 +2023,13 @@
RevCommit c;
while ((c = rw.next()) != null) {
rw.parseBody(c);
- messages.add(new CommitValidationMessage(
- "ERROR: Implicit Merge of " + c.abbreviate(7).name()
- + " " + c.getShortMessage(), false));
-
+ messages.add(
+ new CommitValidationMessage(
+ "ERROR: Implicit Merge of "
+ + c.abbreviate(7).name()
+ + " "
+ + c.getShortMessage(),
+ false));
}
reject(magicBranch.cmd, "implicit merges detected");
}
@@ -2002,8 +2046,7 @@
rw.markUninteresting(rw.parseCommit(ref.getObjectId()));
i++;
} catch (IOException e) {
- logWarn(String.format("Invalid ref %s in %s",
- ref.getName(), project.getName()), e);
+ logWarn(String.format("Invalid ref %s in %s", ref.getName(), project.getName()), e);
}
}
}
@@ -2044,18 +2087,19 @@
private void setChangeId(int id) {
changeId = new Change.Id(id);
- ins = changeInserterFactory.create(changeId, commit, refName)
- .setTopic(magicBranch.topic)
- // Changes already validated in validateNewCommits.
- .setValidatePolicy(CommitValidators.Policy.NONE);
+ ins =
+ changeInserterFactory
+ .create(changeId, commit, refName)
+ .setTopic(magicBranch.topic)
+ // Changes already validated in validateNewCommits.
+ .setValidatePolicy(CommitValidators.Policy.NONE);
if (magicBranch.draft) {
ins.setDraft(magicBranch.draft);
} else if (magicBranch.merged) {
ins.setStatus(Change.Status.MERGED);
}
- cmd = new ReceiveCommand(ObjectId.zeroId(), commit,
- ins.getPatchSetId().toRefName());
+ cmd = new ReceiveCommand(ObjectId.zeroId(), commit, ins.getPatchSetId().toRefName());
if (rp.getPushCertificate() != null) {
ins.setPushCertificate(rp.getPushCertificate().toTextWithSignature());
}
@@ -2074,34 +2118,33 @@
checkNotNull(magicBranch);
recipients.add(magicBranch.getMailRecipients());
approvals = magicBranch.labels;
- recipients.add(getRecipientsFromFooters(
- db, accountResolver, magicBranch.draft, footerLines));
+ recipients.add(
+ getRecipientsFromFooters(db, accountResolver, magicBranch.draft, footerLines));
recipients.remove(me);
- StringBuilder msg = new StringBuilder(
- ApprovalsUtil.renderMessageWithApprovals(
- psId.get(), approvals,
- Collections.<String, PatchSetApproval> emptyMap()));
+ StringBuilder msg =
+ new StringBuilder(
+ ApprovalsUtil.renderMessageWithApprovals(
+ psId.get(), approvals, Collections.<String, PatchSetApproval>emptyMap()));
msg.append('.');
if (!Strings.isNullOrEmpty(magicBranch.message)) {
msg.append("\n").append(magicBranch.message);
}
- bu.insertChange(ins
- .setReviewers(recipients.getReviewers())
- .setExtraCC(recipients.getCcOnly())
- .setApprovals(approvals)
- .setMessage(msg.toString())
- .setNotify(magicBranch.notify)
- .setAccountsToNotify(magicBranch.getAccountsToNotify())
- .setRequestScopePropagator(requestScopePropagator)
- .setSendMail(true)
- .setUpdateRef(false)
- .setPatchSetDescription(magicBranch.message));
+ bu.insertChange(
+ ins.setReviewers(recipients.getReviewers())
+ .setExtraCC(recipients.getCcOnly())
+ .setApprovals(approvals)
+ .setMessage(msg.toString())
+ .setNotify(magicBranch.notify)
+ .setAccountsToNotify(magicBranch.getAccountsToNotify())
+ .setRequestScopePropagator(requestScopePropagator)
+ .setSendMail(true)
+ .setUpdateRef(false)
+ .setPatchSetDescription(magicBranch.message));
if (!magicBranch.hashtags.isEmpty()) {
bu.addOp(
changeId,
- hashtagsFactory.create(new HashtagsInput(magicBranch.hashtags))
- .setFireEvent(false));
+ hashtagsFactory.create(new HashtagsInput(magicBranch.hashtags)).setFireEvent(false));
}
if (!Strings.isNullOrEmpty(magicBranch.topic)) {
bu.addOp(
@@ -2114,13 +2157,15 @@
}
});
}
- bu.addOp(changeId, new BatchUpdate.Op() {
- @Override
- public boolean updateChange(ChangeContext ctx) {
- change = ctx.getChange();
- return false;
- }
- });
+ bu.addOp(
+ changeId,
+ new BatchUpdate.Op() {
+ @Override
+ public boolean updateChange(ChangeContext ctx) {
+ change = ctx.getChange();
+ return false;
+ }
+ });
bu.addOp(changeId, new ChangeProgressOp(newProgress));
} catch (Exception e) {
throw INSERT_EXCEPTION.apply(e);
@@ -2128,26 +2173,22 @@
}
}
- private void submit(
- Collection<CreateRequest> create, Collection<ReplaceRequest> replace)
+ private void submit(Collection<CreateRequest> create, Collection<ReplaceRequest> replace)
throws OrmException, RestApiException {
- Map<ObjectId, Change> bySha =
- Maps.newHashMapWithExpectedSize(create.size() + replace.size());
+ Map<ObjectId, Change> bySha = Maps.newHashMapWithExpectedSize(create.size() + replace.size());
for (CreateRequest r : create) {
- checkNotNull(r.change,
- "cannot submit new change %s; op may not have run", r.changeId);
+ checkNotNull(r.change, "cannot submit new change %s; op may not have run", r.changeId);
bySha.put(r.commit, r.change);
}
for (ReplaceRequest r : replace) {
bySha.put(r.newCommitId, r.notes.getChange());
}
Change tipChange = bySha.get(magicBranch.cmd.getNewId());
- checkNotNull(tipChange,
- "tip of push does not correspond to a change; found these changes: %s",
- bySha);
- logDebug("Processing submit with tip change {} ({})",
- tipChange.getId(), magicBranch.cmd.getNewId());
- try (MergeOp op = mergeOpProvider.get()) {
+ checkNotNull(
+ tipChange, "tip of push does not correspond to a change; found these changes: %s", bySha);
+ logDebug(
+ "Processing submit with tip change {} ({})", tipChange.getId(), magicBranch.cmd.getNewId());
+ try (MergeOp op = mergeOpProvider.get()) {
op.merge(db, tipChange, user, false, new SubmitInput(), false);
}
}
@@ -2155,8 +2196,7 @@
private void preparePatchSetsForReplace() {
try {
readChangesForReplace();
- for (Iterator<ReplaceRequest> itr = replaceByChange.values().iterator();
- itr.hasNext();) {
+ for (Iterator<ReplaceRequest> itr = replaceByChange.values().iterator(); itr.hasNext(); ) {
ReplaceRequest req = itr.next();
if (req.inputCommand.getResult() == NOT_ATTEMPTED) {
req.validate(false);
@@ -2166,18 +2206,20 @@
}
}
} catch (OrmException err) {
- logError(String.format(
- "Cannot read database before replacement for project %s",
- project.getName()), err);
+ logError(
+ String.format(
+ "Cannot read database before replacement for project %s", project.getName()),
+ err);
for (ReplaceRequest req : replaceByChange.values()) {
if (req.inputCommand.getResult() == NOT_ATTEMPTED) {
req.inputCommand.setResult(REJECTED_OTHER_REASON, "internal server error");
}
}
} catch (IOException err) {
- logError(String.format(
- "Cannot read repository before replacement for project %s",
- project.getName()), err);
+ logError(
+ String.format(
+ "Cannot read repository before replacement for project %s", project.getName()),
+ err);
for (ReplaceRequest req : replaceByChange.values()) {
if (req.inputCommand.getResult() == NOT_ATTEMPTED) {
req.inputCommand.setResult(REJECTED_OTHER_REASON, "internal server error");
@@ -2211,9 +2253,7 @@
private void readChangesForReplace() throws OrmException {
Collection<ChangeNotes> allNotes =
notesFactory.create(
- db,
- replaceByChange.values().stream()
- .map(r -> r.ontoChange).collect(toList()));
+ db, replaceByChange.values().stream().map(r -> r.ontoChange).collect(toList()));
for (ChangeNotes notes : allNotes) {
replaceByChange.get(notes.getChangeId()).notes = notes;
}
@@ -2236,8 +2276,8 @@
List<String> groups = ImmutableList.of();
private ReplaceOp replaceOp;
- ReplaceRequest(Change.Id toChange, RevCommit newCommit, ReceiveCommand cmd,
- boolean checkMergedInto) {
+ ReplaceRequest(
+ Change.Id toChange, RevCommit newCommit, ReceiveCommand cmd, boolean checkMergedInto) {
this.ontoChange = toChange;
this.newCommitId = newCommit.copy();
this.inputCommand = cmd;
@@ -2247,29 +2287,29 @@
for (Ref ref : refs(toChange)) {
try {
revisions.forcePut(
- rp.getRevWalk().parseCommit(ref.getObjectId()),
- PatchSet.Id.fromRef(ref.getName()));
+ rp.getRevWalk().parseCommit(ref.getObjectId()), PatchSet.Id.fromRef(ref.getName()));
} catch (IOException err) {
- logWarn(String.format(
- "Project %s contains invalid change ref %s",
- project.getName(), ref.getName()), err);
+ logWarn(
+ String.format(
+ "Project %s contains invalid change ref %s", project.getName(), ref.getName()),
+ err);
}
}
}
/**
* Validate the new patch set commit for this change.
- * <p>
- * <strong>Side effects:</strong>
+ *
+ * <p><strong>Side effects:</strong>
+ *
* <ul>
- * <li>May add error or warning messages to the progress monitor</li>
- * <li>Will reject {@code cmd} prior to returning false</li>
- * <li>May reset {@code rp.getRevWalk()}; do not call in the middle of a
- * walk.</li>
+ * <li>May add error or warning messages to the progress monitor
+ * <li>Will reject {@code cmd} prior to returning false
+ * <li>May reset {@code rp.getRevWalk()}; do not call in the middle of a walk.
* </ul>
*
- * @param autoClose whether the caller intends to auto-close the change
- * after adding a new patch set.
+ * @param autoClose whether the caller intends to auto-close the change after adding a new patch
+ * set.
* @return whether the new commit is valid
* @throws IOException
* @throws OrmException
@@ -2297,8 +2337,7 @@
if (changeCtl.isPatchSetLocked(db)) {
locked = ". Change is patch set locked.";
}
- reject(inputCommand, "cannot add patch set to "
- + ontoChange + locked);
+ reject(inputCommand, "cannot add patch set to " + ontoChange + locked);
return false;
} else if (notes.getChange().getStatus().isClosed()) {
reject(inputCommand, "change " + ontoChange + " closed");
@@ -2308,8 +2347,7 @@
return false;
}
- for (Ref r : rp.getRepository().getRefDatabase()
- .getRefs("refs/changes").values()) {
+ for (Ref r : rp.getRepository().getRefDatabase().getRefs("refs/changes").values()) {
if (r.getObjectId().equals(newCommit)) {
reject(inputCommand, "commit already exists (in the project)");
return false;
@@ -2326,8 +2364,7 @@
}
}
- if (!validCommit(rp.getRevWalk(), changeCtl.getRefControl(), inputCommand,
- newCommit)) {
+ if (!validCommit(rp.getRevWalk(), changeCtl.getRefControl(), inputCommand, newCommit)) {
return false;
}
rp.getRevWalk().parseBody(priorCommit);
@@ -2336,17 +2373,16 @@
// or no parents were updated (rebase), else warn that only part
// of the commit was modified.
if (newCommit.getTree().equals(priorCommit.getTree())) {
- boolean messageEq =
- eq(newCommit.getFullMessage(), priorCommit.getFullMessage());
+ boolean messageEq = eq(newCommit.getFullMessage(), priorCommit.getFullMessage());
boolean parentsEq = parentsEqual(newCommit, priorCommit);
boolean authorEq = authorEqual(newCommit, priorCommit);
ObjectReader reader = rp.getRevWalk().getObjectReader();
if (messageEq && parentsEq && authorEq && !autoClose) {
- addMessage(String.format(
- "(W) No changes between prior commit %s and new commit %s",
- reader.abbreviate(priorCommit).name(),
- reader.abbreviate(newCommit).name()));
+ addMessage(
+ String.format(
+ "(W) No changes between prior commit %s and new commit %s",
+ reader.abbreviate(priorCommit).name(), reader.abbreviate(newCommit).name()));
} else {
StringBuilder msg = new StringBuilder();
msg.append("(I) ");
@@ -2388,16 +2424,14 @@
if (edit.isPresent()) {
if (edit.get().getBasePatchSet().getId().equals(psId)) {
// replace edit
- cmd = new ReceiveCommand(
- edit.get().getRef().getObjectId(),
- newCommitId,
- edit.get().getRefName());
+ cmd =
+ new ReceiveCommand(
+ edit.get().getRef().getObjectId(), newCommitId, edit.get().getRefName());
} else {
// delete old edit ref on rebase
- prev = new ReceiveCommand(
- edit.get().getRef().getObjectId(),
- ObjectId.zeroId(),
- edit.get().getRefName());
+ prev =
+ new ReceiveCommand(
+ edit.get().getRef().getObjectId(), ObjectId.zeroId(), edit.get().getRefName());
createEditCommand();
}
} else {
@@ -2409,29 +2443,21 @@
private void createEditCommand() {
// create new edit
- cmd = new ReceiveCommand(
- ObjectId.zeroId(),
- newCommitId,
- RefNames.refsEdit(
- user.getAccountId(),
- notes.getChangeId(),
- psId));
+ cmd =
+ new ReceiveCommand(
+ ObjectId.zeroId(),
+ newCommitId,
+ RefNames.refsEdit(user.getAccountId(), notes.getChangeId(), psId));
}
private void newPatchSet() throws IOException {
RevCommit newCommit = rp.getRevWalk().parseCommit(newCommitId);
- psId = ChangeUtil.nextPatchSetId(
- allRefs, notes.getChange().currentPatchSetId());
- info = patchSetInfoFactory.get(
- rp.getRevWalk(), newCommit, psId);
- cmd = new ReceiveCommand(
- ObjectId.zeroId(),
- newCommitId,
- psId.toRefName());
+ psId = ChangeUtil.nextPatchSetId(allRefs, notes.getChange().currentPatchSetId());
+ info = patchSetInfoFactory.get(rp.getRevWalk(), newCommit, psId);
+ cmd = new ReceiveCommand(ObjectId.zeroId(), newCommitId, psId.toRefName());
}
- void addOps(BatchUpdate bu, @Nullable Task progress)
- throws IOException {
+ void addOps(BatchUpdate bu, @Nullable Task progress) throws IOException {
if (cmd.getResult() == NOT_ATTEMPTED) {
// TODO(dborowitz): When does this happen? Only when an edit ref is
// involved?
@@ -2446,22 +2472,32 @@
rw.parseBody(newCommit);
RevCommit priorCommit = revisions.inverse().get(priorPatchSet);
- replaceOp = replaceOpFactory
- .create(projectControl, notes.getChange().getDest(), checkMergedInto,
- priorPatchSet, priorCommit, psId, newCommit, info, groups,
- magicBranch, rp.getPushCertificate())
- .setRequestScopePropagator(requestScopePropagator)
- .setUpdateRef(false);
+ replaceOp =
+ replaceOpFactory
+ .create(
+ projectControl,
+ notes.getChange().getDest(),
+ checkMergedInto,
+ priorPatchSet,
+ priorCommit,
+ psId,
+ newCommit,
+ info,
+ groups,
+ magicBranch,
+ rp.getPushCertificate())
+ .setRequestScopePropagator(requestScopePropagator)
+ .setUpdateRef(false);
bu.addOp(notes.getChangeId(), replaceOp);
if (progress != null) {
bu.addOp(notes.getChangeId(), new ChangeProgressOp(progress));
}
}
- void insertPatchSetWithoutBatchUpdate()
- throws IOException, UpdateException, RestApiException {
- try (BatchUpdate bu = batchUpdateFactory.create(db,
- projectControl.getProject().getNameKey(), user, TimeUtil.nowTs());
+ void insertPatchSetWithoutBatchUpdate() throws IOException, UpdateException, RestApiException {
+ try (BatchUpdate bu =
+ batchUpdateFactory.create(
+ db, projectControl.getProject().getNameKey(), user, TimeUtil.nowTs());
ObjectInserter ins = repo.newObjectInserter()) {
bu.setRepository(repo, rp.getRevWalk(), ins);
bu.setRequestId(receiveId);
@@ -2486,22 +2522,24 @@
}
private void addOps(BatchUpdate bu) {
- bu.addOp(psId.getParentKey(), new BatchUpdate.Op() {
- @Override
- public boolean updateChange(ChangeContext ctx) throws OrmException {
- PatchSet ps = psUtil.get(ctx.getDb(), ctx.getNotes(), psId);
- List<String> oldGroups = ps.getGroups();
- if (oldGroups == null) {
- if (groups == null) {
- return false;
+ bu.addOp(
+ psId.getParentKey(),
+ new BatchUpdate.Op() {
+ @Override
+ public boolean updateChange(ChangeContext ctx) throws OrmException {
+ PatchSet ps = psUtil.get(ctx.getDb(), ctx.getNotes(), psId);
+ List<String> oldGroups = ps.getGroups();
+ if (oldGroups == null) {
+ if (groups == null) {
+ return false;
+ }
+ } else if (sameGroups(oldGroups, groups)) {
+ return false;
+ }
+ psUtil.setGroups(ctx.getDb(), ctx.getUpdate(psId), ps, groups);
+ return true;
}
- } else if (sameGroups(oldGroups, groups)) {
- return false;
- }
- psUtil.setGroups(ctx.getDb(), ctx.getUpdate(psId), ps, groups);
- return true;
- }
- });
+ });
}
private boolean sameGroups(List<String> a, List<String> b) {
@@ -2581,8 +2619,7 @@
}
private boolean validRefOperation(ReceiveCommand cmd) {
- RefOperationValidators refValidators =
- refValidatorsFactory.create(getProject(), user, cmd);
+ RefOperationValidators refValidators = refValidatorsFactory.create(getProject(), user, cmd);
try {
messages.addAll(refValidators.validateForRefOperation());
@@ -2609,8 +2646,7 @@
return;
}
- boolean defaultName =
- Strings.isNullOrEmpty(user.getAccount().getFullName());
+ boolean defaultName = Strings.isNullOrEmpty(user.getAccount().getFullName());
RevWalk walk = rp.getRevWalk();
walk.reset();
walk.sort(RevSort.NONE);
@@ -2620,10 +2656,10 @@
return;
}
ListMultimap<ObjectId, Ref> existing = changeRefsById();
- walk.markStart((RevCommit)parsedObject);
+ walk.markStart((RevCommit) parsedObject);
markHeadsAsUninteresting(walk, cmd.getRefName());
int i = 0;
- for (RevCommit c; (c = walk.next()) != null;) {
+ for (RevCommit c; (c = walk.next()) != null; ) {
i++;
if (existing.keySet().contains(c)) {
continue;
@@ -2631,8 +2667,7 @@
break;
}
- if (defaultName && user.hasEmailAddress(
- c.getCommitterIdent().getEmailAddress())) {
+ if (defaultName && user.hasEmailAddress(c.getCommitterIdent().getEmailAddress())) {
try {
Account a = db.accounts().get(user.getAccountId());
if (a != null && Strings.isNullOrEmpty(a.getFullName())) {
@@ -2655,8 +2690,8 @@
}
}
- private boolean validCommit(RevWalk rw, RefControl ctl, ReceiveCommand cmd,
- ObjectId id) throws IOException {
+ private boolean validCommit(RevWalk rw, RefControl ctl, ReceiveCommand cmd, ObjectId id)
+ throws IOException {
if (validCommits.contains(id)) {
return true;
@@ -2678,8 +2713,7 @@
try {
messages.addAll(
- commitValidatorsFactory.create(policy, ctl, sshInfo, repo)
- .validate(receiveEvent));
+ commitValidatorsFactory.create(policy, ctl, sshInfo, repo).validate(receiveEvent));
} catch (CommitValidationException e) {
logDebug("Commit validation failed on {}", c.name());
messages.addAll(e.getMessages());
@@ -2693,22 +2727,23 @@
private void autoCloseChanges(final ReceiveCommand cmd) {
logDebug("Starting auto-closing of changes");
String refName = cmd.getRefName();
- checkState(!MagicBranch.isMagicBranch(refName),
- "shouldn't be auto-closing changes on magic branch %s", refName);
+ checkState(
+ !MagicBranch.isMagicBranch(refName),
+ "shouldn't be auto-closing changes on magic branch %s",
+ refName);
RevWalk rw = rp.getRevWalk();
// TODO(dborowitz): Combine this BatchUpdate with the main one in
// insertChangesAndPatchSets.
- try (BatchUpdate bu = batchUpdateFactory.create(db,
- projectControl.getProject().getNameKey(), user, TimeUtil.nowTs());
+ try (BatchUpdate bu =
+ batchUpdateFactory.create(
+ db, projectControl.getProject().getNameKey(), user, TimeUtil.nowTs());
ObjectInserter ins = repo.newObjectInserter()) {
- bu.setRepository(repo, rp.getRevWalk(), ins)
- .updateChangesInParallel();
+ bu.setRepository(repo, rp.getRevWalk(), ins).updateChangesInParallel();
bu.setRequestId(receiveId);
// TODO(dborowitz): Teach BatchUpdate to ignore missing changes.
RevCommit newTip = rw.parseCommit(cmd.getNewId());
- Branch.NameKey branch =
- new Branch.NameKey(project.getNameKey(), refName);
+ Branch.NameKey branch = new Branch.NameKey(project.getNameKey(), refName);
rw.reset();
rw.markStart(newTip);
@@ -2722,7 +2757,8 @@
int existingPatchSets = 0;
int newPatchSets = 0;
- COMMIT: for (RevCommit c; (c = rw.next()) != null;) {
+ COMMIT:
+ for (RevCommit c; (c = rw.next()) != null; ) {
rw.parseBody(c);
for (Ref ref : byCommit.get(c.copy())) {
@@ -2730,8 +2766,7 @@
PatchSet.Id psId = PatchSet.Id.fromRef(ref.getName());
bu.addOp(
psId.getParentKey(),
- mergedByPushOpFactory.create(
- requestScopePropagator, psId, refName));
+ mergedByPushOpFactory.create(requestScopePropagator, psId, refName));
continue COMMIT;
}
@@ -2745,8 +2780,7 @@
newPatchSets++;
// Hold onto this until we're done with the walk, as the call to
// req.validate below calls isMergedInto which resets the walk.
- ReplaceRequest req =
- new ReplaceRequest(onto.getChangeId(), c, cmd, false);
+ ReplaceRequest req = new ReplaceRequest(onto.getChangeId(), c, cmd, false);
req.notes = onto;
replaceAndClose.add(req);
continue COMMIT;
@@ -2763,19 +2797,22 @@
req.addOps(bu, null);
bu.addOp(
id,
- mergedByPushOpFactory.create(
- requestScopePropagator, req.psId, refName)
- .setPatchSetProvider(new Provider<PatchSet>() {
- @Override
- public PatchSet get() {
- return req.replaceOp.getPatchSet();
- }
- }));
+ mergedByPushOpFactory
+ .create(requestScopePropagator, req.psId, refName)
+ .setPatchSetProvider(
+ new Provider<PatchSet>() {
+ @Override
+ public PatchSet get() {
+ return req.replaceOp.getPatchSet();
+ }
+ }));
bu.addOp(id, new ChangeProgressOp(closeProgress));
}
- logDebug("Auto-closing {} changes with existing patch sets and {} with"
- + " new patch sets", existingPatchSets, newPatchSets);
+ logDebug(
+ "Auto-closing {} changes with existing patch sets and {} with" + " new patch sets",
+ existingPatchSets,
+ newPatchSets);
bu.execute();
} catch (RestApiException e) {
logError("Can't insert patchset", e);
@@ -2784,8 +2821,8 @@
}
}
- private Map<Change.Key, ChangeNotes> openChangesByBranch(
- Branch.NameKey branch) throws OrmException {
+ private Map<Change.Key, ChangeNotes> openChangesByBranch(Branch.NameKey branch)
+ throws OrmException {
Map<Change.Key, ChangeNotes> r = new HashMap<>();
for (ChangeData cd : queryProvider.get().byBranchOpen(branch)) {
r.put(cd.change().getKey(), cd.notes());
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/ReceiveCommitsAdvertiseRefsHook.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/ReceiveCommitsAdvertiseRefsHook.java
index 5871299..f4c0867 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/ReceiveCommitsAdvertiseRefsHook.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/ReceiveCommitsAdvertiseRefsHook.java
@@ -30,7 +30,10 @@
import com.google.gerrit.server.util.MagicBranch;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Provider;
-
+import java.io.IOException;
+import java.util.Collections;
+import java.util.Map;
+import java.util.Set;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.transport.AdvertiseRefsHook;
@@ -40,20 +43,15 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.util.Collections;
-import java.util.Map;
-import java.util.Set;
-
/** Exposes only the non refs/changes/ reference names. */
public class ReceiveCommitsAdvertiseRefsHook implements AdvertiseRefsHook {
- private static final Logger log = LoggerFactory
- .getLogger(ReceiveCommitsAdvertiseRefsHook.class);
+ private static final Logger log = LoggerFactory.getLogger(ReceiveCommitsAdvertiseRefsHook.class);
@VisibleForTesting
@AutoValue
public abstract static class Result {
public abstract Map<String, Ref> allRefs();
+
public abstract Set<ObjectId> additionalHaves();
}
@@ -61,8 +59,7 @@
private final Project.NameKey projectName;
public ReceiveCommitsAdvertiseRefsHook(
- Provider<InternalChangeQuery> queryProvider,
- Project.NameKey projectName) {
+ Provider<InternalChangeQuery> queryProvider, Project.NameKey projectName) {
this.queryProvider = queryProvider;
this.projectName = projectName;
}
@@ -74,8 +71,7 @@
}
@Override
- public void advertiseRefs(BaseReceivePack rp)
- throws ServiceMayNotContinueException {
+ public void advertiseRefs(BaseReceivePack rp) throws ServiceMayNotContinueException {
Map<String, Ref> oldRefs = rp.getAdvertisedRefs();
if (oldRefs == null) {
try {
@@ -121,11 +117,13 @@
int limit = 32;
try {
Set<ObjectId> r = Sets.newHashSetWithExpectedSize(limit);
- for (ChangeData cd : queryProvider.get()
- .setRequestedFields(OPEN_CHANGES_FIELDS)
- .enforceVisibility(true)
- .setLimit(limit)
- .byProjectOpen(projectName)) {
+ for (ChangeData cd :
+ queryProvider
+ .get()
+ .setRequestedFields(OPEN_CHANGES_FIELDS)
+ .enforceVisibility(true)
+ .setLimit(limit)
+ .byProjectOpen(projectName)) {
PatchSet ps = cd.currentPatchSet();
if (ps != null) {
ObjectId id = ObjectId.fromString(ps.getRevision().get());
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/ReceiveCommitsExecutor.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/ReceiveCommitsExecutor.java
index 2049cea..ddf24cde 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/ReceiveCommitsExecutor.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/ReceiveCommitsExecutor.java
@@ -17,14 +17,9 @@
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import com.google.inject.BindingAnnotation;
-
import java.lang.annotation.Retention;
-/**
- * Marker on the global {@link WorkQueue.Executor} used by
- * {@link ReceiveCommits}.
- */
+/** Marker on the global {@link WorkQueue.Executor} used by {@link ReceiveCommits}. */
@Retention(RUNTIME)
@BindingAnnotation
-public @interface ReceiveCommitsExecutor {
-}
+public @interface ReceiveCommitsExecutor {}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/ReceiveCommitsExecutorModule.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/ReceiveCommitsExecutorModule.java
index 8c428a2..da1c36c 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/ReceiveCommitsExecutorModule.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/ReceiveCommitsExecutorModule.java
@@ -21,28 +21,25 @@
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.lib.Config;
-
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
+import org.eclipse.jgit.lib.Config;
/** Module providing the {@link ReceiveCommitsExecutor}. */
public class ReceiveCommitsExecutorModule extends AbstractModule {
@Override
- protected void configure() {
- }
+ protected void configure() {}
@Provides
@Singleton
@ReceiveCommitsExecutor
public WorkQueue.Executor createReceiveCommitsExecutor(
- @GerritServerConfig Config config,
- WorkQueue queues) {
- int poolSize = config.getInt("receive", null, "threadPoolSize",
- Runtime.getRuntime().availableProcessors());
+ @GerritServerConfig Config config, WorkQueue queues) {
+ int poolSize =
+ config.getInt(
+ "receive", null, "threadPoolSize", Runtime.getRuntime().availableProcessors());
return queues.createQueue(poolSize, "ReceiveCommits");
}
@@ -68,13 +65,13 @@
}
return MoreExecutors.listeningDecorator(
MoreExecutors.getExitingExecutorService(
- new ThreadPoolExecutor(1, poolSize,
- 10, TimeUnit.MINUTES,
- new ArrayBlockingQueue<Runnable>(poolSize),
- new ThreadFactoryBuilder()
- .setNameFormat("ChangeUpdate-%d")
- .setDaemon(true)
- .build(),
- new ThreadPoolExecutor.CallerRunsPolicy())));
+ new ThreadPoolExecutor(
+ 1,
+ poolSize,
+ 10,
+ TimeUnit.MINUTES,
+ new ArrayBlockingQueue<Runnable>(poolSize),
+ new ThreadFactoryBuilder().setNameFormat("ChangeUpdate-%d").setDaemon(true).build(),
+ new ThreadPoolExecutor.CallerRunsPolicy())));
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/ReceiveConfig.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/ReceiveConfig.java
index ac6116c..063f395 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/ReceiveConfig.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/ReceiveConfig.java
@@ -20,7 +20,6 @@
import com.google.gerrit.server.config.GerritServerConfig;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
import org.eclipse.jgit.lib.Config;
@Singleton
@@ -32,15 +31,10 @@
@Inject
ReceiveConfig(@GerritServerConfig Config config) {
- checkMagicRefs = config.getBoolean(
- "receive", null, "checkMagicRefs",
- true);
- checkReferencedObjectsAreReachable = config.getBoolean(
- "receive", null, "checkReferencedObjectsAreReachable",
- true);
- allowDrafts = config.getBoolean(
- "change", null, "allowDrafts",
- true);
+ checkMagicRefs = config.getBoolean("receive", null, "checkMagicRefs", true);
+ checkReferencedObjectsAreReachable =
+ config.getBoolean("receive", null, "checkReferencedObjectsAreReachable", true);
+ allowDrafts = config.getBoolean("change", null, "allowDrafts", true);
systemMaxBatchChanges = config.getInt("receive", "maxBatchChanges", 0);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/ReceivePackInitializer.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/ReceivePackInitializer.java
index ee229d4..f374215 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/ReceivePackInitializer.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/ReceivePackInitializer.java
@@ -16,7 +16,6 @@
import com.google.gerrit.extensions.annotations.ExtensionPoint;
import com.google.gerrit.reviewdb.client.Project;
-
import org.eclipse.jgit.transport.ReceivePack;
@ExtensionPoint
@@ -25,9 +24,9 @@
/**
* ReceivePack initialization.
*
- * Invoked by Gerrit when a new ReceivePack instance is created and just
- * before it is used. Implementors will usually call setXXX methods on the
- * receivePack parameter in order to set additional properties on it.
+ * <p>Invoked by Gerrit when a new ReceivePack instance is created and just before it is used.
+ * Implementors will usually call setXXX methods on the receivePack parameter in order to set
+ * additional properties on it.
*
* @param project project for which the ReceivePack is created
* @param receivePack the ReceivePack instance which is being initialized
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/RefCache.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/RefCache.java
index 96593ac..5a5cae9 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/RefCache.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/RefCache.java
@@ -14,30 +14,27 @@
package com.google.gerrit.server.git;
-import org.eclipse.jgit.lib.ObjectId;
-
import java.io.IOException;
import java.util.Optional;
+import org.eclipse.jgit.lib.ObjectId;
/**
* Simple short-lived cache of individual refs read from a repo.
- * <p>
- * Within a single request that is known to read a small bounded number of refs,
- * this class can be used to ensure a consistent view of one ref, and avoid
- * multiple system calls to read refs multiple times.
- * <p>
- * <strong>Note:</strong> Implementations of this class are only appropriate
- * for short-term caching, and do not support invalidation. It is also not
- * threadsafe.
+ *
+ * <p>Within a single request that is known to read a small bounded number of refs, this class can
+ * be used to ensure a consistent view of one ref, and avoid multiple system calls to read refs
+ * multiple times.
+ *
+ * <p><strong>Note:</strong> Implementations of this class are only appropriate for short-term
+ * caching, and do not support invalidation. It is also not threadsafe.
*/
public interface RefCache {
/**
* Get the possibly-cached value of a ref.
*
* @param refName name of the ref.
- * @return value of the ref; absent if the ref does not exist in the repo.
- * Never null, and never present with a value of {@link
- * ObjectId#zeroId()}.
+ * @return value of the ref; absent if the ref does not exist in the repo. Never null, and never
+ * present with a value of {@link ObjectId#zeroId()}.
*/
Optional<ObjectId> get(String refName) throws IOException;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/RenameGroupOp.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/RenameGroupOp.java
index 00c9a7c..63d8641 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/RenameGroupOp.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/RenameGroupOp.java
@@ -20,28 +20,27 @@
import com.google.gerrit.server.project.ProjectCache;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
-
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
import org.eclipse.jgit.lib.PersonIdent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.TimeUnit;
-
public class RenameGroupOp extends DefaultQueueOp {
public interface Factory {
- RenameGroupOp create(@Assisted("author") PersonIdent author,
- @Assisted AccountGroup.UUID uuid, @Assisted("oldName") String oldName,
+ RenameGroupOp create(
+ @Assisted("author") PersonIdent author,
+ @Assisted AccountGroup.UUID uuid,
+ @Assisted("oldName") String oldName,
@Assisted("newName") String newName);
}
private static final int MAX_TRIES = 10;
- private static final Logger log =
- LoggerFactory.getLogger(RenameGroupOp.class);
+ private static final Logger log = LoggerFactory.getLogger(RenameGroupOp.class);
private final ProjectCache projectCache;
private final MetaDataUpdate.Server metaDataUpdateFactory;
@@ -55,11 +54,14 @@
private boolean tryingAgain;
@Inject
- public RenameGroupOp(WorkQueue workQueue, ProjectCache projectCache,
+ public RenameGroupOp(
+ WorkQueue workQueue,
+ ProjectCache projectCache,
MetaDataUpdate.Server metaDataUpdateFactory,
-
- @Assisted("author") PersonIdent author, @Assisted AccountGroup.UUID uuid,
- @Assisted("oldName") String oldName, @Assisted("newName") String newName) {
+ @Assisted("author") PersonIdent author,
+ @Assisted AccountGroup.UUID uuid,
+ @Assisted("oldName") String oldName,
+ @Assisted("newName") String newName) {
super(workQueue);
this.projectCache = projectCache;
this.metaDataUpdateFactory = metaDataUpdateFactory;
@@ -73,9 +75,7 @@
@Override
public void run() {
- Iterable<Project.NameKey> names = tryingAgain
- ? retryOn
- : projectCache.all();
+ Iterable<Project.NameKey> names = tryingAgain ? retryOn : projectCache.all();
for (Project.NameKey projectName : names) {
ProjectConfig config = projectCache.get(projectName).getConfig();
GroupReference ref = config.getGroup(uuid);
@@ -100,8 +100,7 @@
}
}
- private void rename(MetaDataUpdate md) throws IOException,
- ConfigInvalidException {
+ private void rename(MetaDataUpdate md) throws IOException, ConfigInvalidException {
boolean success = false;
for (int attempts = 0; !success && attempts < MAX_TRIES; attempts++) {
ProjectConfig config = ProjectConfig.read(md);
@@ -122,8 +121,14 @@
projectCache.evict(config.getProject());
success = true;
} catch (IOException e) {
- log.error("Could not commit rename of group " + oldName + " to "
- + newName + " in " + md.getProjectName().get(), e);
+ log.error(
+ "Could not commit rename of group "
+ + oldName
+ + " to "
+ + newName
+ + " in "
+ + md.getProjectName().get(),
+ e);
try {
Thread.sleep(25 /* milliseconds */);
} catch (InterruptedException wakeUp) {
@@ -134,8 +139,13 @@
if (!success) {
if (tryingAgain) {
- log.warn("Could not rename group " + oldName + " to " + newName
- + " in " + md.getProjectName().get());
+ log.warn(
+ "Could not rename group "
+ + oldName
+ + " to "
+ + newName
+ + " in "
+ + md.getProjectName().get());
} else {
retryOn.add(md.getProjectName());
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/ReplaceOp.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/ReplaceOp.java
index 2de5378..bd1f2cd0 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/ReplaceOp.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/ReplaceOp.java
@@ -55,7 +55,12 @@
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
import com.google.inject.util.Providers;
-
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ExecutorService;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Ref;
@@ -67,13 +72,6 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.ExecutorService;
-
public class ReplaceOp extends BatchUpdate.Op {
public interface Factory {
ReplaceOp create(
@@ -90,8 +88,7 @@
@Nullable PushCertificate pushCertificate);
}
- private static final Logger log =
- LoggerFactory.getLogger(ReplaceOp.class);
+ private static final Logger log = LoggerFactory.getLogger(ReplaceOp.class);
private static final String CHANGE_IS_CLOSED = "change is closed";
@@ -134,7 +131,8 @@
private boolean updateRef;
@AssistedInject
- ReplaceOp(AccountResolver accountResolver,
+ ReplaceOp(
+ AccountResolver accountResolver,
ApprovalCopier approvalCopier,
ApprovalsUtil approvalsUtil,
ChangeControl.GenericFactory changeControlFactory,
@@ -190,28 +188,25 @@
@Override
public void updateRepo(RepoContext ctx) throws Exception {
- changeKind = changeKindCache.getChangeKind(
- projectControl.getProject().getNameKey(),
- ctx.getRepository(), priorCommit, commit);
+ changeKind =
+ changeKindCache.getChangeKind(
+ projectControl.getProject().getNameKey(), ctx.getRepository(), priorCommit, commit);
if (checkMergedInto) {
Ref mergedInto = findMergedInto(ctx, dest.get(), commit);
if (mergedInto != null) {
- mergedByPushOp = mergedByPushOpFactory.create(
- requestScopePropagator, patchSetId, mergedInto.getName());
+ mergedByPushOp =
+ mergedByPushOpFactory.create(requestScopePropagator, patchSetId, mergedInto.getName());
}
}
if (updateRef) {
- ctx.addRefUpdate(
- new ReceiveCommand(ObjectId.zeroId(), commit,
- patchSetId.toRefName()));
+ ctx.addRefUpdate(new ReceiveCommand(ObjectId.zeroId(), commit, patchSetId.toRefName()));
}
}
@Override
- public boolean updateChange(ChangeContext ctx)
- throws OrmException, IOException {
+ public boolean updateChange(ChangeContext ctx) throws OrmException, IOException {
change = ctx.getChange();
if (change == null || change.getStatus().isClosed()) {
rejectMessage = CHANGE_IS_CLOSED;
@@ -219,9 +214,7 @@
}
if (groups.isEmpty()) {
PatchSet prevPs = psUtil.current(ctx.getDb(), ctx.getNotes());
- groups = prevPs != null
- ? prevPs.getGroups()
- : ImmutableList.<String> of();
+ groups = prevPs != null ? prevPs.getGroups() : ImmutableList.<String>of();
}
ChangeUpdate update = ctx.getUpdate(patchSetId);
@@ -239,8 +232,7 @@
hashtags.addAll(ctx.getNotes().getHashtags());
update.setHashtags(hashtags);
}
- if (magicBranch.topic != null
- && !magicBranch.topic.equals(ctx.getChange().getTopic())) {
+ if (magicBranch.topic != null && !magicBranch.topic.equals(ctx.getChange().getTopic())) {
update.setTopic(magicBranch.topic);
}
}
@@ -249,32 +241,47 @@
if (change.getStatus() == Change.Status.DRAFT && !draft) {
update.setStatus(Change.Status.NEW);
}
- newPatchSet = psUtil.insert(
- ctx.getDb(), ctx.getRevWalk(), update, patchSetId, commit, draft, groups,
- pushCertificate != null
- ? pushCertificate.toTextWithSignature()
- : null, psDescription);
+ newPatchSet =
+ psUtil.insert(
+ ctx.getDb(),
+ ctx.getRevWalk(),
+ update,
+ patchSetId,
+ commit,
+ draft,
+ groups,
+ pushCertificate != null ? pushCertificate.toTextWithSignature() : null,
+ psDescription);
update.setPsDescription(psDescription);
- recipients.add(getRecipientsFromFooters(
- ctx.getDb(), accountResolver, draft, commit.getFooterLines()));
+ recipients.add(
+ getRecipientsFromFooters(ctx.getDb(), accountResolver, draft, commit.getFooterLines()));
recipients.remove(ctx.getAccountId());
ChangeData cd = changeDataFactory.create(ctx.getDb(), ctx.getControl());
- MailRecipients oldRecipients =
- getRecipientsFromReviewers(cd.reviewers());
+ MailRecipients oldRecipients = getRecipientsFromReviewers(cd.reviewers());
Iterable<PatchSetApproval> newApprovals =
- approvalsUtil.addApprovalsForNewPatchSet(ctx.getDb(), update,
- projectControl.getLabelTypes(), newPatchSet, ctx.getControl(),
+ approvalsUtil.addApprovalsForNewPatchSet(
+ ctx.getDb(),
+ update,
+ projectControl.getLabelTypes(),
+ newPatchSet,
+ ctx.getControl(),
approvals);
- approvalCopier.copy(ctx.getDb(), ctx.getControl(), newPatchSet,
- newApprovals);
- approvalsUtil.addReviewers(ctx.getDb(), update,
- projectControl.getLabelTypes(), change, newPatchSet, info,
- recipients.getReviewers(), oldRecipients.getAll());
+ approvalCopier.copy(ctx.getDb(), ctx.getControl(), newPatchSet, newApprovals);
+ approvalsUtil.addReviewers(
+ ctx.getDb(),
+ update,
+ projectControl.getLabelTypes(),
+ change,
+ newPatchSet,
+ info,
+ recipients.getReviewers(),
+ oldRecipients.getAll());
recipients.add(oldRecipients);
- String approvalMessage = ApprovalsUtil.renderMessageWithApprovals(
- patchSetId.get(), approvals, scanLabels(ctx, approvals));
+ String approvalMessage =
+ ApprovalsUtil.renderMessageWithApprovals(
+ patchSetId.get(), approvals, scanLabels(ctx, approvals));
String kindMessage = changeKindMessage(changeKind);
StringBuilder message = new StringBuilder(approvalMessage);
if (!Strings.isNullOrEmpty(kindMessage)) {
@@ -285,15 +292,19 @@
if (!Strings.isNullOrEmpty(reviewMessage)) {
message.append("\n").append(reviewMessage);
}
- msg = ChangeMessagesUtil.newMessage(patchSetId, ctx.getUser(),
- ctx.getWhen(), message.toString(), ChangeMessagesUtil.TAG_UPLOADED_PATCH_SET);
+ msg =
+ ChangeMessagesUtil.newMessage(
+ patchSetId,
+ ctx.getUser(),
+ ctx.getWhen(),
+ message.toString(),
+ ChangeMessagesUtil.TAG_UPLOADED_PATCH_SET);
cmUtil.addChangeMessage(ctx.getDb(), update, msg);
if (mergedByPushOp == null) {
resetChange(ctx);
} else {
- mergedByPushOp.setPatchSetProvider(Providers.of(newPatchSet))
- .updateChange(ctx);
+ mergedByPushOp.setPatchSetProvider(Providers.of(newPatchSet)).updateChange(ctx);
}
return true;
@@ -313,14 +324,14 @@
}
}
- private Map<String, PatchSetApproval> scanLabels(ChangeContext ctx,
- Map<String, Short> approvals) throws OrmException {
+ private Map<String, PatchSetApproval> scanLabels(ChangeContext ctx, Map<String, Short> approvals)
+ throws OrmException {
Map<String, PatchSetApproval> current = new HashMap<>();
// We optimize here and only retrieve current when approvals provided
if (!approvals.isEmpty()) {
- for (PatchSetApproval a : approvalsUtil.byPatchSetUser(ctx.getDb(),
- ctx.getControl(), priorPatchSetId,
- ctx.getAccountId())) {
+ for (PatchSetApproval a :
+ approvalsUtil.byPatchSetUser(
+ ctx.getDb(), ctx.getControl(), priorPatchSetId, ctx.getAccountId())) {
if (a.isLegacySubmit()) {
continue;
}
@@ -366,37 +377,39 @@
// manually.
final Account account = ctx.getAccount();
if (!updateRef) {
- gitRefUpdated.fire(ctx.getProject(), newPatchSet.getRefName(),
- ObjectId.zeroId(), commit, account);
+ gitRefUpdated.fire(
+ ctx.getProject(), newPatchSet.getRefName(), ObjectId.zeroId(), commit, account);
}
if (changeKind != ChangeKind.TRIVIAL_REBASE) {
- Runnable sender = new Runnable() {
- @Override
- public void run() {
- try {
- ReplacePatchSetSender cm = replacePatchSetFactory.create(
- projectControl.getProject().getNameKey(), change.getId());
- cm.setFrom(account.getId());
- cm.setPatchSet(newPatchSet, info);
- cm.setChangeMessage(msg.getMessage(), ctx.getWhen());
- if (magicBranch != null) {
- cm.setNotify(magicBranch.notify);
- cm.setAccountsToNotify(magicBranch.getAccountsToNotify());
+ Runnable sender =
+ new Runnable() {
+ @Override
+ public void run() {
+ try {
+ ReplacePatchSetSender cm =
+ replacePatchSetFactory.create(
+ projectControl.getProject().getNameKey(), change.getId());
+ cm.setFrom(account.getId());
+ cm.setPatchSet(newPatchSet, info);
+ cm.setChangeMessage(msg.getMessage(), ctx.getWhen());
+ if (magicBranch != null) {
+ cm.setNotify(magicBranch.notify);
+ cm.setAccountsToNotify(magicBranch.getAccountsToNotify());
+ }
+ cm.addReviewers(recipients.getReviewers());
+ cm.addExtraCC(recipients.getCcOnly());
+ cm.send();
+ } catch (Exception e) {
+ log.error("Cannot send email for new patch set " + newPatchSet.getId(), e);
+ }
}
- cm.addReviewers(recipients.getReviewers());
- cm.addExtraCC(recipients.getCcOnly());
- cm.send();
- } catch (Exception e) {
- log.error("Cannot send email for new patch set " + newPatchSet.getId(), e);
- }
- }
- @Override
- public String toString() {
- return "send-email newpatchset";
- }
- };
+ @Override
+ public String toString() {
+ return "send-email newpatchset";
+ }
+ };
if (requestScopePropagator != null) {
sendEmailExecutor.submit(requestScopePropagator.wrap(sender));
@@ -405,11 +418,9 @@
}
}
- NotifyHandling notify = magicBranch != null && magicBranch.notify != null
- ? magicBranch.notify
- : NotifyHandling.ALL;
- revisionCreated.fire(change, newPatchSet, ctx.getAccount(),
- ctx.getWhen(), notify);
+ NotifyHandling notify =
+ magicBranch != null && magicBranch.notify != null ? magicBranch.notify : NotifyHandling.ALL;
+ revisionCreated.fire(change, newPatchSet, ctx.getAccount(), ctx.getWhen(), notify);
try {
fireCommentAddedEvent(ctx);
} catch (Exception e) {
@@ -430,8 +441,8 @@
* For labels that are set in this operation, the value was modified, so
* show a transition from an oldValue of 0 to the new value.
*/
- ChangeControl changeControl = changeControlFactory.controlFor(
- ctx.getDb(), change, ctx.getUser());
+ ChangeControl changeControl =
+ changeControlFactory.controlFor(ctx.getDb(), change, ctx.getUser());
List<LabelType> labels = changeControl.getLabelTypes().getLabelTypes();
Map<String, Short> allApprovals = new HashMap<>();
Map<String, Short> oldApprovals = new HashMap<>();
@@ -446,9 +457,8 @@
}
}
- commentAdded.fire(change, newPatchSet,
- ctx.getAccount(), null,
- allApprovals, oldApprovals, ctx.getWhen());
+ commentAdded.fire(
+ change, newPatchSet, ctx.getAccount(), null, allApprovals, oldApprovals, ctx.getWhen());
}
public PatchSet getPatchSet() {
@@ -468,8 +478,7 @@
return this;
}
- public ReplaceOp setRequestScopePropagator(
- RequestScopePropagator requestScopePropagator) {
+ public ReplaceOp setRequestScopePropagator(RequestScopePropagator requestScopePropagator) {
this.requestScopePropagator = requestScopePropagator;
return this;
}
@@ -479,8 +488,7 @@
RefDatabase refDatabase = ctx.getRepository().getRefDatabase();
Ref firstRef = refDatabase.exactRef(first);
- if (firstRef != null
- && isMergedInto(ctx.getRevWalk(), commit, firstRef)) {
+ if (firstRef != null && isMergedInto(ctx.getRevWalk(), commit, firstRef)) {
return firstRef;
}
@@ -496,8 +504,7 @@
}
}
- private static boolean isMergedInto(RevWalk rw, RevCommit commit, Ref ref)
- throws IOException {
+ private static boolean isMergedInto(RevWalk rw, RevCommit commit, Ref ref) throws IOException {
return rw.isMergedInto(commit, rw.parseCommit(ref.getObjectId()));
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/RepoRefCache.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/RepoRefCache.java
index 77f697a..e7a86f1 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/RepoRefCache.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/RepoRefCache.java
@@ -14,15 +14,14 @@
package com.google.gerrit.server.git;
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.lib.Ref;
-import org.eclipse.jgit.lib.RefDatabase;
-import org.eclipse.jgit.lib.Repository;
-
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.lib.Ref;
+import org.eclipse.jgit.lib.RefDatabase;
+import org.eclipse.jgit.lib.Repository;
/** {@link RefCache} backed directly by a repository. */
public class RepoRefCache implements RefCache {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/RepositoryCaseMismatchException.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/RepositoryCaseMismatchException.java
index 98ddf80..45ec769 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/RepositoryCaseMismatchException.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/RepositoryCaseMismatchException.java
@@ -15,26 +15,20 @@
package com.google.gerrit.server.git;
import com.google.gerrit.reviewdb.client.Project;
-
import org.eclipse.jgit.errors.RepositoryNotFoundException;
/**
- * This exception is thrown if a project cannot be created because a project
- * with the same name in a different case already exists. This can only happen
- * if the OS has a case insensitive file system (e.g. Windows), because in this
- * case the name for the git repository in the file system is already occupied
- * by the existing project.
+ * This exception is thrown if a project cannot be created because a project with the same name in a
+ * different case already exists. This can only happen if the OS has a case insensitive file system
+ * (e.g. Windows), because in this case the name for the git repository in the file system is
+ * already occupied by the existing project.
*/
-public class RepositoryCaseMismatchException extends
- RepositoryNotFoundException {
+public class RepositoryCaseMismatchException extends RepositoryNotFoundException {
private static final long serialVersionUID = 1L;
- /**
- * @param projectName name of the project that cannot be created
- */
+ /** @param projectName name of the project that cannot be created */
public RepositoryCaseMismatchException(final Project.NameKey projectName) {
- super("Name occupied in other case. Project " + projectName.get()
- + " cannot be created.");
+ super("Name occupied in other case. Project " + projectName.get() + " cannot be created.");
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/ReviewNoteMerger.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/ReviewNoteMerger.java
index 8b6da7b..2c30203 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/ReviewNoteMerger.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/ReviewNoteMerger.java
@@ -38,6 +38,8 @@
package com.google.gerrit.server.git;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.ObjectInserter;
@@ -48,13 +50,10 @@
import org.eclipse.jgit.notes.NoteMerger;
import org.eclipse.jgit.util.io.UnionInputStream;
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-
class ReviewNoteMerger implements NoteMerger {
@Override
- public Note merge(Note base, Note ours, Note theirs, ObjectReader reader,
- ObjectInserter inserter) throws IOException {
+ public Note merge(Note base, Note ours, Note theirs, ObjectReader reader, ObjectInserter inserter)
+ throws IOException {
if (ours == null) {
return theirs;
}
@@ -72,8 +71,8 @@
ByteArrayInputStream b = new ByteArrayInputStream(sep);
ObjectStream ts = lt.openStream();
UnionInputStream union = new UnionInputStream(os, b, ts)) {
- ObjectId noteData = inserter.insert(Constants.OBJ_BLOB,
- lo.getSize() + sep.length + lt.getSize(), union);
+ ObjectId noteData =
+ inserter.insert(Constants.OBJ_BLOB, lo.getSize() + sep.length + lt.getSize(), union);
return new Note(ours, noteData);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/SearchingChangeCacheImpl.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/SearchingChangeCacheImpl.java
index 54ec249..947382b 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/SearchingChangeCacheImpl.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/SearchingChangeCacheImpl.java
@@ -37,19 +37,16 @@
import com.google.inject.TypeLiteral;
import com.google.inject.name.Named;
import com.google.inject.util.Providers;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutionException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
@Singleton
public class SearchingChangeCacheImpl implements GitReferenceUpdatedListener {
- private static final Logger log =
- LoggerFactory.getLogger(SearchingChangeCacheImpl.class);
+ private static final Logger log = LoggerFactory.getLogger(SearchingChangeCacheImpl.class);
static final String ID_CACHE = "changes";
public static class Module extends CacheModule {
@@ -67,13 +64,11 @@
protected void configure() {
if (slave) {
bind(SearchingChangeCacheImpl.class)
- .toProvider(Providers.<SearchingChangeCacheImpl> of(null));
+ .toProvider(Providers.<SearchingChangeCacheImpl>of(null));
} else {
- cache(ID_CACHE,
- Project.NameKey.class,
- new TypeLiteral<List<CachedChange>>() {})
- .maximumWeight(0)
- .loader(Loader.class);
+ cache(ID_CACHE, Project.NameKey.class, new TypeLiteral<List<CachedChange>>() {})
+ .maximumWeight(0)
+ .loader(Loader.class);
bind(SearchingChangeCacheImpl.class);
DynamicSet.bind(binder(), GitReferenceUpdatedListener.class)
@@ -88,7 +83,9 @@
// VisibleRefFilter without touching the database. More can be added as
// necessary.
abstract Change change();
- @Nullable abstract ReviewerSet reviewers();
+
+ @Nullable
+ abstract ReviewerSet reviewers();
}
private final LoadingCache<Project.NameKey, List<CachedChange>> cache;
@@ -104,12 +101,11 @@
/**
* Read changes for the project from the secondary index.
- * <p>
- * Returned changes only include the {@code Change} object (with id, branch)
- * and the reviewers. Additional stored fields are not loaded from the index.
*
- * @param db database handle to populate missing change data (probably
- * unused).
+ * <p>Returned changes only include the {@code Change} object (with id, branch) and the reviewers.
+ * Additional stored fields are not loaded from the index.
+ *
+ * @param db database handle to populate missing change data (probably unused).
* @param project project to read.
* @return list of known changes; empty if no changes.
*/
@@ -141,8 +137,7 @@
private final Provider<InternalChangeQuery> queryProvider;
@Inject
- Loader(OneOffRequestContext requestContext,
- Provider<InternalChangeQuery> queryProvider) {
+ Loader(OneOffRequestContext requestContext, Provider<InternalChangeQuery> queryProvider) {
this.requestContext = requestContext;
this.queryProvider = queryProvider;
}
@@ -150,15 +145,16 @@
@Override
public List<CachedChange> load(Project.NameKey key) throws Exception {
try (AutoCloseable ctx = requestContext.open()) {
- List<ChangeData> cds = queryProvider.get()
- .setRequestedFields(ImmutableSet.of(
- ChangeField.CHANGE.getName(),
- ChangeField.REVIEWER.getName()))
- .byProject(key);
+ List<ChangeData> cds =
+ queryProvider
+ .get()
+ .setRequestedFields(
+ ImmutableSet.of(ChangeField.CHANGE.getName(), ChangeField.REVIEWER.getName()))
+ .byProject(key);
List<CachedChange> result = new ArrayList<>(cds.size());
for (ChangeData cd : cds) {
- result.add(new AutoValue_SearchingChangeCacheImpl_CachedChange(
- cd.change(), cd.getReviewers()));
+ result.add(
+ new AutoValue_SearchingChangeCacheImpl_CachedChange(cd.change(), cd.getReviewers()));
}
return Collections.unmodifiableList(result);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/SendEmailExecutor.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/SendEmailExecutor.java
index 68fa98a..feb32fa 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/SendEmailExecutor.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/SendEmailExecutor.java
@@ -17,13 +17,9 @@
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import com.google.inject.BindingAnnotation;
-
import java.lang.annotation.Retention;
-/**
- * Marker on the global {@link WorkQueue.Executor} used to send email.
- */
+/** Marker on the global {@link WorkQueue.Executor} used to send email. */
@Retention(RUNTIME)
@BindingAnnotation
-public @interface SendEmailExecutor {
-}
+public @interface SendEmailExecutor {}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/SubmoduleOp.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/SubmoduleOp.java
index bd53ff5..5ed3f977 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/SubmoduleOp.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/SubmoduleOp.java
@@ -34,7 +34,18 @@
import com.google.gerrit.server.project.ProjectState;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
-
+import java.io.IOException;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Deque;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedHashSet;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
import org.eclipse.jgit.dircache.DirCache;
import org.eclipse.jgit.dircache.DirCacheBuilder;
import org.eclipse.jgit.dircache.DirCacheEditor;
@@ -54,24 +65,9 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.util.ArrayDeque;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Deque;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.LinkedHashSet;
-import java.util.Map;
-import java.util.Objects;
-import java.util.Set;
-
public class SubmoduleOp {
- /**
- * Only used for branches without code review changes
- */
+ /** Only used for branches without code review changes */
public class GitlinkOp extends BatchUpdate.RepoOnlyOp {
private final Branch.NameKey branch;
@@ -90,8 +86,7 @@
}
public interface Factory {
- SubmoduleOp create(
- Set<Branch.NameKey> updatedBranches, MergeOpRepoManager orm);
+ SubmoduleOp create(Set<Branch.NameKey> updatedBranches, MergeOpRepoManager orm);
}
private static final Logger log = LoggerFactory.getLogger(SubmoduleOp.class);
@@ -126,16 +121,16 @@
ProjectCache projectCache,
ProjectState.Factory projectStateFactory,
@Assisted Set<Branch.NameKey> updatedBranches,
- @Assisted MergeOpRepoManager orm) throws SubmoduleException {
+ @Assisted MergeOpRepoManager orm)
+ throws SubmoduleException {
this.gitmodulesFactory = gitmodulesFactory;
this.myIdent = myIdent;
this.projectCache = projectCache;
this.projectStateFactory = projectStateFactory;
this.verboseSuperProject =
- cfg.getEnum("submodule", null, "verboseSuperprojectUpdate",
- VerboseSuperprojectUpdate.TRUE);
- this.enableSuperProjectSubscriptions = cfg.getBoolean("submodule",
- "enableSuperProjectSubscriptions", true);
+ cfg.getEnum("submodule", null, "verboseSuperprojectUpdate", VerboseSuperprojectUpdate.TRUE);
+ this.enableSuperProjectSubscriptions =
+ cfg.getBoolean("submodule", "enableSuperProjectSubscriptions", true);
this.orm = orm;
this.updatedBranches = updatedBranches;
this.targets = MultimapBuilder.hashKeys().hashSetValues().build();
@@ -146,8 +141,7 @@
this.sortedBranches = calculateSubscriptionMap();
}
- private ImmutableSet<Branch.NameKey> calculateSubscriptionMap()
- throws SubmoduleException {
+ private ImmutableSet<Branch.NameKey> calculateSubscriptionMap() throws SubmoduleException {
if (!enableSuperProjectSubscriptions) {
logDebug("Updating superprojects disabled");
return null;
@@ -160,8 +154,7 @@
continue;
}
- searchForSuperprojects(updatedBranch, new LinkedHashSet<Branch.NameKey>(),
- allVisited);
+ searchForSuperprojects(updatedBranch, new LinkedHashSet<Branch.NameKey>(), allVisited);
}
// Since the searchForSuperprojects will add all branches (related or
@@ -173,7 +166,8 @@
return ImmutableSet.copyOf(allVisited);
}
- private void searchForSuperprojects(Branch.NameKey current,
+ private void searchForSuperprojects(
+ Branch.NameKey current,
LinkedHashSet<Branch.NameKey> currentVisited,
LinkedHashSet<Branch.NameKey> allVisited)
throws SubmoduleException {
@@ -181,8 +175,8 @@
if (currentVisited.contains(current)) {
throw new SubmoduleException(
- "Branch level circular subscriptions detected: " +
- printCircularPath(currentVisited, current));
+ "Branch level circular subscriptions detected: "
+ + printCircularPath(currentVisited, current));
}
if (allVisited.contains(current)) {
@@ -202,8 +196,7 @@
affectedBranches.add(sub.getSubmodule());
}
} catch (IOException e) {
- throw new SubmoduleException("Cannot find superprojects for " + current,
- e);
+ throw new SubmoduleException("Cannot find superprojects for " + current, e);
}
currentVisited.remove(current);
allVisited.add(current);
@@ -237,8 +230,8 @@
return sb.toString();
}
- private Collection<Branch.NameKey> getDestinationBranches(Branch.NameKey src,
- SubscribeSection s) throws IOException {
+ private Collection<Branch.NameKey> getDestinationBranches(Branch.NameKey src, SubscribeSection s)
+ throws IOException {
Collection<Branch.NameKey> ret = new HashSet<>();
logDebug("Inspecting SubscribeSection " + s);
for (RefSpec r : s.getMatchingRefSpecs()) {
@@ -248,8 +241,7 @@
}
if (r.isWildcard()) {
// refs/heads/*[:refs/somewhere/*]
- ret.add(new Branch.NameKey(s.getProject(),
- r.expandFromSource(src.get()).getDestination()));
+ ret.add(new Branch.NameKey(s.getProject(), r.expandFromSource(src.get()).getDestination()));
} else {
// e.g. refs/heads/master[:refs/heads/stable]
String dest = r.getDestination();
@@ -275,8 +267,7 @@
continue;
}
- for (Ref ref : or.repo.getRefDatabase().getRefs(
- RefNames.REFS_HEADS).values()) {
+ for (Ref ref : or.repo.getRefDatabase().getRefs(RefNames.REFS_HEADS).values()) {
if (r.getDestination() != null && !r.matchDestination(ref.getName())) {
continue;
}
@@ -286,23 +277,19 @@
}
}
}
- logDebug("Returning possible branches: " + ret +
- "for project " + s.getProject());
+ logDebug("Returning possible branches: " + ret + "for project " + s.getProject());
return ret;
}
- public Collection<SubmoduleSubscription>
- superProjectSubscriptionsForSubmoduleBranch(Branch.NameKey srcBranch)
- throws IOException {
+ public Collection<SubmoduleSubscription> superProjectSubscriptionsForSubmoduleBranch(
+ Branch.NameKey srcBranch) throws IOException {
logDebug("Calculating possible superprojects for " + srcBranch);
Collection<SubmoduleSubscription> ret = new ArrayList<>();
Project.NameKey srcProject = srcBranch.getParentKey();
ProjectConfig cfg = projectCache.get(srcProject).getConfig();
- for (SubscribeSection s : projectStateFactory.create(cfg)
- .getSubscribeSections(srcBranch)) {
+ for (SubscribeSection s : projectStateFactory.create(cfg).getSubscribeSections(srcBranch)) {
logDebug("Checking subscribe section " + s);
- Collection<Branch.NameKey> branches =
- getDestinationBranches(srcBranch, s);
+ Collection<Branch.NameKey> branches = getDestinationBranches(srcBranch, s);
for (Branch.NameKey targetBranch : branches) {
Project.NameKey targetProject = targetBranch.getParentKey();
try {
@@ -348,17 +335,14 @@
}
}
}
- BatchUpdate.execute(orm.batchUpdates(superProjects), Listener.NONE,
- orm.getSubmissionId(), false);
- } catch (RestApiException | UpdateException | IOException |
- NoSuchProjectException e) {
+ BatchUpdate.execute(
+ orm.batchUpdates(superProjects), Listener.NONE, orm.getSubmissionId(), false);
+ } catch (RestApiException | UpdateException | IOException | NoSuchProjectException e) {
throw new SubmoduleException("Cannot update gitlinks", e);
}
}
- /**
- * Create a separate gitlink commit
- */
+ /** Create a separate gitlink commit */
public CodeReviewCommit composeGitlinksCommit(final Branch.NameKey subscriber)
throws IOException, SubmoduleException {
OpenRepo or;
@@ -416,9 +400,7 @@
return or.rw.parseCommit(id);
}
- /**
- * Amend an existing commit with gitlink updates
- */
+ /** Amend an existing commit with gitlink updates */
public CodeReviewCommit composeGitlinksCommit(
final Branch.NameKey subscriber, CodeReviewCommit currentCommit)
throws IOException, SubmoduleException {
@@ -448,8 +430,7 @@
commit.setParentIds(currentCommit.getParents());
if (verboseSuperProject != VerboseSuperprojectUpdate.FALSE) {
//TODO:czhen handle cherrypick footer
- commit.setMessage(currentCommit.getFullMessage()
- + "\n\n* submodules:\n" + msgbuf.toString());
+ commit.setMessage(currentCommit.getFullMessage() + "\n\n* submodules:\n" + msgbuf.toString());
} else {
commit.setMessage(currentCommit.getFullMessage());
}
@@ -461,8 +442,8 @@
return newCommit;
}
- private RevCommit updateSubmodule(DirCache dc, DirCacheEditor ed,
- StringBuilder msgbuf, final SubmoduleSubscription s)
+ private RevCommit updateSubmodule(
+ DirCache dc, DirCacheEditor ed, StringBuilder msgbuf, final SubmoduleSubscription s)
throws SubmoduleException, IOException {
OpenRepo subOr;
try {
@@ -475,9 +456,13 @@
RevCommit oldCommit = null;
if (dce != null) {
if (!dce.getFileMode().equals(FileMode.GITLINK)) {
- String errMsg = "Requested to update gitlink " + s.getPath() + " in "
- + s.getSubmodule().getParentKey().get() + " but entry "
- + "doesn't have gitlink file mode.";
+ String errMsg =
+ "Requested to update gitlink "
+ + s.getPath()
+ + " in "
+ + s.getSubmodule().getParentKey().get()
+ + " but entry "
+ + "doesn't have gitlink file mode.";
throw new SubmoduleException(errMsg);
}
oldCommit = subOr.rw.parseCommit(dce.getObjectId());
@@ -500,13 +485,14 @@
// gitlink have already been updated for this submodule
return null;
}
- ed.add(new PathEdit(s.getPath()) {
- @Override
- public void apply(DirCacheEntry ent) {
- ent.setFileMode(FileMode.GITLINK);
- ent.setObjectId(newCommit.getId());
- }
- });
+ ed.add(
+ new PathEdit(s.getPath()) {
+ @Override
+ public void apply(DirCacheEntry ent) {
+ ent.setFileMode(FileMode.GITLINK);
+ ent.setObjectId(newCommit.getId());
+ }
+ });
if (verboseSuperProject != VerboseSuperprojectUpdate.FALSE) {
createSubmoduleCommitMsg(msgbuf, s, subOr, newCommit, oldCommit);
@@ -515,8 +501,12 @@
return newCommit;
}
- private void createSubmoduleCommitMsg(StringBuilder msgbuf,
- SubmoduleSubscription s, OpenRepo subOr, RevCommit newCommit, RevCommit oldCommit)
+ private void createSubmoduleCommitMsg(
+ StringBuilder msgbuf,
+ SubmoduleSubscription s,
+ OpenRepo subOr,
+ RevCommit newCommit,
+ RevCommit oldCommit)
throws SubmoduleException {
msgbuf.append("* Update " + s.getPath());
msgbuf.append(" from branch '" + s.getSubmodule().getShortName() + "'");
@@ -539,24 +529,24 @@
}
}
} catch (IOException e) {
- throw new SubmoduleException("Could not perform a revwalk to "
- + "create superproject commit message", e);
+ throw new SubmoduleException(
+ "Could not perform a revwalk to " + "create superproject commit message", e);
}
}
- private static DirCache readTree(RevWalk rw, ObjectId base)
- throws IOException {
+ private static DirCache readTree(RevWalk rw, ObjectId base) throws IOException {
final DirCache dc = DirCache.newInCore();
final DirCacheBuilder b = dc.builder();
- b.addTree(new byte[0], // no prefix path
+ b.addTree(
+ new byte[0], // no prefix path
DirCacheEntry.STAGE_0, // standard stage
- rw.getObjectReader(), rw.parseTree(base));
+ rw.getObjectReader(),
+ rw.parseTree(base));
b.finish();
return dc;
}
- public ImmutableSet<Project.NameKey> getProjectsInOrder()
- throws SubmoduleException {
+ public ImmutableSet<Project.NameKey> getProjectsInOrder() throws SubmoduleException {
LinkedHashSet<Project.NameKey> projects = new LinkedHashSet<>();
for (Project.NameKey project : branchesByProject.keySet()) {
addAllSubmoduleProjects(project, new LinkedHashSet<>(), projects);
@@ -568,14 +558,14 @@
return ImmutableSet.copyOf(projects);
}
- private void addAllSubmoduleProjects(Project.NameKey project,
+ private void addAllSubmoduleProjects(
+ Project.NameKey project,
LinkedHashSet<Project.NameKey> current,
LinkedHashSet<Project.NameKey> projects)
throws SubmoduleException {
if (current.contains(project)) {
throw new SubmoduleException(
- "Project level circular subscriptions detected: " +
- printCircularPath(current, project));
+ "Project level circular subscriptions detected: " + printCircularPath(current, project));
}
if (projects.contains(project)) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/TabFile.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/TabFile.java
index d77c7e2..ea041f4 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/TabFile.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/TabFile.java
@@ -14,8 +14,6 @@
package com.google.gerrit.server.git;
-import org.slf4j.Logger;
-
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
@@ -25,18 +23,20 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import org.slf4j.Logger;
public class TabFile {
public interface Parser {
String parse(String str);
}
- public static Parser TRIM = new Parser() {
- @Override
- public String parse(String str) {
- return str.trim();
- }
- };
+ public static Parser TRIM =
+ new Parser() {
+ @Override
+ public String parse(String str) {
+ return str.trim();
+ }
+ };
protected static class Row {
public String left;
@@ -48,8 +48,9 @@
}
}
- protected static List<Row> parse(String text, String filename, Parser left,
- Parser right, ValidationError.Sink errors) throws IOException {
+ protected static List<Row> parse(
+ String text, String filename, Parser left, Parser right, ValidationError.Sink errors)
+ throws IOException {
List<Row> rows = new ArrayList<>();
BufferedReader br = new BufferedReader(new StringReader(text));
String s;
@@ -60,8 +61,7 @@
int tab = s.indexOf('\t');
if (tab < 0) {
- errors.error(new ValidationError(filename, lineNumber,
- "missing tab delimiter"));
+ errors.error(new ValidationError(filename, lineNumber, "missing tab delimiter"));
continue;
}
@@ -86,8 +86,7 @@
return map;
}
- protected static String asText(String left, String right,
- Map<String, String> entries) {
+ protected static String asText(String left, String right, Map<String, String> entries) {
if (entries.isEmpty()) {
return null;
}
@@ -148,7 +147,6 @@
}
public static ValidationError.Sink createLoggerSink(String file, Logger log) {
- return ValidationError.createLoggerSink("Error parsing file " + file + ": ",
- log);
+ return ValidationError.createLoggerSink("Error parsing file " + file + ": ", log);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/TagCache.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/TagCache.java
index dec1768..0822161 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/TagCache.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/TagCache.java
@@ -21,13 +21,11 @@
import com.google.inject.Module;
import com.google.inject.Singleton;
import com.google.inject.name.Named;
-
-import org.eclipse.jgit.lib.ObjectId;
-
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
+import org.eclipse.jgit.lib.ObjectId;
@Singleton
public class TagCache {
@@ -53,20 +51,19 @@
/**
* Advise the cache that a reference fast-forwarded.
- * <p>
- * This operation is not necessary, the cache will automatically detect changes
- * made to references and update itself on demand. However, this method may
- * allow the cache to update more quickly and reuse the caller's computation of
- * the fast-forward status of a branch.
+ *
+ * <p>This operation is not necessary, the cache will automatically detect changes made to
+ * references and update itself on demand. However, this method may allow the cache to update more
+ * quickly and reuse the caller's computation of the fast-forward status of a branch.
*
* @param name project the branch is contained in.
* @param refName the branch name.
- * @param oldValue the old value, before the fast-forward. The cache
- * will only update itself if it is still using this old value.
+ * @param oldValue the old value, before the fast-forward. The cache will only update itself if it
+ * is still using this old value.
* @param newValue the current value, after the fast-forward.
*/
- public void updateFastForward(Project.NameKey name, String refName,
- ObjectId oldValue, ObjectId newValue) {
+ public void updateFastForward(
+ Project.NameKey name, String refName, ObjectId oldValue, ObjectId newValue) {
// Be really paranoid and null check everything. This method should
// never fail with an exception. Some of these references can be null
// (e.g. not all projects are cached, or the cache is not current).
@@ -111,8 +108,7 @@
transient TagSetHolder holder;
- private void readObject(ObjectInputStream in) throws IOException,
- ClassNotFoundException {
+ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
holder = new TagSetHolder(new Project.NameKey(in.readUTF()));
if (in.readBoolean()) {
TagSet tags = new TagSet(holder.getProjectName());
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/TagMatcher.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/TagMatcher.java
index e550927..6e46d76 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/TagMatcher.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/TagMatcher.java
@@ -15,15 +15,13 @@
package com.google.gerrit.server.git;
import com.google.gerrit.server.git.TagSet.Tag;
-
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.lib.Ref;
-import org.eclipse.jgit.lib.Repository;
-
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collection;
import java.util.List;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.lib.Ref;
+import org.eclipse.jgit.lib.Repository;
class TagMatcher {
final BitSet mask = new BitSet();
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/TagSet.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/TagSet.java
index 3c7666e..f131bc9 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/TagSet.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/TagSet.java
@@ -19,7 +19,13 @@
import com.google.gerrit.reviewdb.client.PatchSet;
import com.google.gerrit.reviewdb.client.Project;
-
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.util.BitSet;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicReference;
import org.eclipse.jgit.errors.IncorrectObjectTypeException;
import org.eclipse.jgit.lib.AnyObjectId;
import org.eclipse.jgit.lib.Constants;
@@ -34,14 +40,6 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.util.BitSet;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.concurrent.atomic.AtomicReference;
-
class TagSet {
private static final Logger log = LoggerFactory.getLogger(TagSet.class);
@@ -59,8 +57,7 @@
return tags.get(id);
}
- boolean updateFastForward(String refName, ObjectId oldValue,
- ObjectId newValue) {
+ boolean updateFastForward(String refName, ObjectId oldValue, ObjectId newValue) {
CachedRef ref = refs.get(refName);
if (ref != null) {
// compareAndSet works on reference equality, but this operation
@@ -191,8 +188,7 @@
}
}
- void readObject(ObjectInputStream in) throws IOException,
- ClassNotFoundException {
+ void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
int refCnt = in.readInt();
for (int i = 0; i < refCnt; i++) {
String name = in.readUTF();
@@ -331,8 +327,7 @@
}
static boolean skip(Ref ref) {
- return ref.isSymbolic() || ref.getObjectId() == null
- || PatchSet.isChangeRef(ref.getName());
+ return ref.isSymbolic() || ref.getObjectId() == null || PatchSet.isChangeRef(ref.getName());
}
private static boolean isTag(Ref ref) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/TagSetHolder.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/TagSetHolder.java
index ad650c3..e1faa65 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/TagSetHolder.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/TagSetHolder.java
@@ -17,12 +17,10 @@
import static java.util.stream.Collectors.toList;
import com.google.gerrit.reviewdb.client.Project;
-
+import java.util.Collection;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
-import java.util.Collection;
-
class TagSetHolder {
private final Object buildLock = new Object();
private final Project.NameKey projectName;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/TransferConfig.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/TransferConfig.java
index bc805c4..4ac9071 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/TransferConfig.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/TransferConfig.java
@@ -19,12 +19,10 @@
import com.google.gerrit.server.project.ProjectState;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
+import java.util.concurrent.TimeUnit;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.storage.pack.PackConfig;
-import java.util.concurrent.TimeUnit;
-
@Singleton
public class TransferConfig {
private final int timeout;
@@ -34,8 +32,15 @@
@Inject
TransferConfig(@GerritServerConfig final Config cfg) {
- timeout = (int) ConfigUtil.getTimeUnit(cfg, "transfer", null, "timeout", //
- 0, TimeUnit.SECONDS);
+ timeout =
+ (int)
+ ConfigUtil.getTimeUnit(
+ cfg,
+ "transfer",
+ null,
+ "timeout", //
+ 0,
+ TimeUnit.SECONDS);
maxObjectSizeLimit = cfg.getLong("receive", "maxObjectSizeLimit", 0);
maxObjectSizeLimitFormatted = cfg.getString("receive", null, "maxObjectSizeLimit");
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/UploadPackMetricsHook.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/UploadPackMetricsHook.java
index d4fcbcd..aa02fba 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/UploadPackMetricsHook.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/UploadPackMetricsHook.java
@@ -25,7 +25,6 @@
import com.google.gerrit.metrics.Timer1;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
import org.eclipse.jgit.storage.pack.PackStatistics;
import org.eclipse.jgit.transport.PostUploadHook;
@@ -45,47 +44,51 @@
@Inject
UploadPackMetricsHook(MetricMaker metricMaker) {
Field<Operation> operation = Field.ofEnum(Operation.class, "operation");
- requestCount = metricMaker.newCounter(
- "git/upload-pack/request_count",
- new Description("Total number of git-upload-pack requests")
- .setRate()
- .setUnit("requests"),
- operation);
+ requestCount =
+ metricMaker.newCounter(
+ "git/upload-pack/request_count",
+ new Description("Total number of git-upload-pack requests")
+ .setRate()
+ .setUnit("requests"),
+ operation);
- counting = metricMaker.newTimer(
- "git/upload-pack/phase_counting",
- new Description("Time spent in the 'Counting...' phase")
- .setCumulative()
- .setUnit(Units.MILLISECONDS),
- operation);
+ counting =
+ metricMaker.newTimer(
+ "git/upload-pack/phase_counting",
+ new Description("Time spent in the 'Counting...' phase")
+ .setCumulative()
+ .setUnit(Units.MILLISECONDS),
+ operation);
- compressing = metricMaker.newTimer(
- "git/upload-pack/phase_compressing",
- new Description("Time spent in the 'Compressing...' phase")
- .setCumulative()
- .setUnit(Units.MILLISECONDS),
- operation);
+ compressing =
+ metricMaker.newTimer(
+ "git/upload-pack/phase_compressing",
+ new Description("Time spent in the 'Compressing...' phase")
+ .setCumulative()
+ .setUnit(Units.MILLISECONDS),
+ operation);
- writing = metricMaker.newTimer(
- "git/upload-pack/phase_writing",
- new Description("Time spent transferring bytes to client")
- .setCumulative()
- .setUnit(Units.MILLISECONDS),
- operation);
+ writing =
+ metricMaker.newTimer(
+ "git/upload-pack/phase_writing",
+ new Description("Time spent transferring bytes to client")
+ .setCumulative()
+ .setUnit(Units.MILLISECONDS),
+ operation);
- packBytes = metricMaker.newHistogram(
- "git/upload-pack/pack_bytes",
- new Description("Distribution of sizes of packs sent to clients")
- .setCumulative()
- .setUnit(Units.BYTES),
- operation);
+ packBytes =
+ metricMaker.newHistogram(
+ "git/upload-pack/pack_bytes",
+ new Description("Distribution of sizes of packs sent to clients")
+ .setCumulative()
+ .setUnit(Units.BYTES),
+ operation);
}
@Override
public void onPostUpload(PackStatistics stats) {
Operation op = Operation.FETCH;
- if (stats.getUninterestingObjects() == null
- || stats.getUninterestingObjects().isEmpty()) {
+ if (stats.getUninterestingObjects() == null || stats.getUninterestingObjects().isEmpty()) {
op = Operation.CLONE;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/UserConfigSections.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/UserConfigSections.java
index bbd55f0..859e40d 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/UserConfigSections.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/UserConfigSections.java
@@ -31,6 +31,7 @@
/** The table column user preferences. */
public static final String CHANGE_TABLE = "changeTable";
+
public static final String CHANGE_TABLE_COLUMN = "column";
/** The edit user preferences. */
@@ -39,6 +40,5 @@
/** The diff user preferences. */
public static final String DIFF = "diff";
- private UserConfigSections() {
- }
+ private UserConfigSections() {}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/ValidationError.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/ValidationError.java
index e6a8ae4..4185141 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/ValidationError.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/ValidationError.java
@@ -47,10 +47,10 @@
public static Sink createLoggerSink(final String message, final Logger log) {
return new ValidationError.Sink() {
- @Override
- public void error(ValidationError error) {
- log.error(message + error.getMessage());
- }
- };
+ @Override
+ public void error(ValidationError error) {
+ log.error(message + error.getMessage());
+ }
+ };
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/VersionedMetaData.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/VersionedMetaData.java
index 2d63fd6..9d8d1ac 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/VersionedMetaData.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/VersionedMetaData.java
@@ -15,7 +15,12 @@
package com.google.gerrit.server.git;
import com.google.common.base.MoreObjects;
-
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.StringReader;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
import org.eclipse.jgit.dircache.DirCache;
import org.eclipse.jgit.dircache.DirCacheBuilder;
import org.eclipse.jgit.dircache.DirCacheEditor;
@@ -46,25 +51,16 @@
import org.eclipse.jgit.util.ChangeIdUtil;
import org.eclipse.jgit.util.RawParseUtils;
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.StringReader;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Objects;
-
/**
* Support for metadata stored within a version controlled branch.
- * <p>
- * Implementors are responsible for supplying implementations of the onLoad and
- * onSave methods to read from the repository, or format an update that can
- * later be written back to the repository.
+ *
+ * <p>Implementors are responsible for supplying implementations of the onLoad and onSave methods to
+ * read from the repository, or format an update that can later be written back to the repository.
*/
public abstract class VersionedMetaData {
/**
- * Path information that does not hold references to any repository
- * data structures, allowing the application to retain this object
- * for long periods of time.
+ * Path information that does not hold references to any repository data structures, allowing the
+ * application to retain this object for long periods of time.
*/
public static class PathInfo {
public final FileMode fileMode;
@@ -96,8 +92,8 @@
* @throws IOException
* @throws ConfigInvalidException
*/
- protected abstract boolean onSave(CommitBuilder commit) throws IOException,
- ConfigInvalidException;
+ protected abstract boolean onSave(CommitBuilder commit)
+ throws IOException, ConfigInvalidException;
/** @return revision of the metadata that was loaded. */
public ObjectId getRevision() {
@@ -106,9 +102,9 @@
/**
* Load the current version from the branch.
- * <p>
- * The repository is not held after the call completes, allowing the
- * application to retain this object for long periods of time.
+ *
+ * <p>The repository is not held after the call completes, allowing the application to retain this
+ * object for long periods of time.
*
* @param db repository to access.
* @throws IOException
@@ -121,22 +117,20 @@
/**
* Load a specific version from the repository.
- * <p>
- * This method is primarily useful for applying updates to a specific revision
- * that was shown to an end-user in the user interface. If there are conflicts
- * with another user's concurrent changes, these will be automatically
- * detected at commit time.
- * <p>
- * The repository is not held after the call completes, allowing the
- * application to retain this object for long periods of time.
+ *
+ * <p>This method is primarily useful for applying updates to a specific revision that was shown
+ * to an end-user in the user interface. If there are conflicts with another user's concurrent
+ * changes, these will be automatically detected at commit time.
+ *
+ * <p>The repository is not held after the call completes, allowing the application to retain this
+ * object for long periods of time.
*
* @param db repository to access.
* @param id revision to load.
* @throws IOException
* @throws ConfigInvalidException
*/
- public void load(Repository db, ObjectId id) throws IOException,
- ConfigInvalidException {
+ public void load(Repository db, ObjectId id) throws IOException, ConfigInvalidException {
try (RevWalk walk = new RevWalk(db)) {
load(walk, id);
}
@@ -144,24 +138,21 @@
/**
* Load a specific version from an open walk.
- * <p>
- * This method is primarily useful for applying updates to a specific revision
- * that was shown to an end-user in the user interface. If there are conflicts
- * with another user's concurrent changes, these will be automatically
- * detected at commit time.
- * <p>
- * The caller retains ownership of the walk and is responsible for closing
- * it. However, this instance does not hold a reference to the walk or the
- * repository after the call completes, allowing the application to retain
- * this object for long periods of time.
+ *
+ * <p>This method is primarily useful for applying updates to a specific revision that was shown
+ * to an end-user in the user interface. If there are conflicts with another user's concurrent
+ * changes, these will be automatically detected at commit time.
+ *
+ * <p>The caller retains ownership of the walk and is responsible for closing it. However, this
+ * instance does not hold a reference to the walk or the repository after the call completes,
+ * allowing the application to retain this object for long periods of time.
*
* @param walk open walk to access to access.
* @param id revision to load.
* @throws IOException
* @throws ConfigInvalidException
*/
- public void load(RevWalk walk, ObjectId id) throws IOException,
- ConfigInvalidException {
+ public void load(RevWalk walk, ObjectId id) throws IOException, ConfigInvalidException {
this.reader = walk.getObjectReader();
try {
revision = id != null ? new RevWalk(reader).parseCommit(id) : null;
@@ -171,13 +162,11 @@
}
}
- public void load(MetaDataUpdate update) throws IOException,
- ConfigInvalidException {
+ public void load(MetaDataUpdate update) throws IOException, ConfigInvalidException {
load(update.getRepository());
}
- public void load(MetaDataUpdate update, ObjectId id) throws IOException,
- ConfigInvalidException {
+ public void load(MetaDataUpdate update, ObjectId id) throws IOException, ConfigInvalidException {
load(update.getRepository(), id);
}
@@ -186,9 +175,8 @@
*
* @param update helper information to define the update that will occur.
* @return the commit that was created
- * @throws IOException if there is a storage problem and the update cannot be
- * executed as requested or if it failed because of a concurrent
- * update to the same reference
+ * @throws IOException if there is a storage problem and the update cannot be executed as
+ * requested or if it failed because of a concurrent update to the same reference
*/
public RevCommit commit(MetaDataUpdate update) throws IOException {
BatchMetaDataUpdate batch = openUpdate(update);
@@ -206,9 +194,8 @@
* @param update helper information to define the update that will occur.
* @param refName name of the ref that should be created
* @return the commit that was created
- * @throws IOException if there is a storage problem and the update cannot be
- * executed as requested or if it failed because of a concurrent
- * update to the same reference
+ * @throws IOException if there is a storage problem and the update cannot be executed as
+ * requested or if it failed because of a concurrent update to the same reference
*/
public RevCommit commitToNewRef(MetaDataUpdate update, String refName) throws IOException {
BatchMetaDataUpdate batch = openUpdate(update);
@@ -222,25 +209,31 @@
public interface BatchMetaDataUpdate {
void write(CommitBuilder commit) throws IOException;
+
void write(VersionedMetaData config, CommitBuilder commit) throws IOException;
+
RevCommit createRef(String refName) throws IOException;
+
void removeRef(String refName) throws IOException;
+
RevCommit commit() throws IOException;
+
RevCommit commitAt(ObjectId revision) throws IOException;
+
void close();
}
/**
* Open a batch of updates to the same metadata ref.
- * <p>
- * This allows making multiple commits to a single metadata ref, at the end of
- * which is a single ref update. For batching together updates to multiple
- * refs (each consisting of one or more commits against their respective
- * refs), create the {@link MetaDataUpdate} with a {@link BatchRefUpdate}.
- * <p>
- * A ref update produced by this {@link BatchMetaDataUpdate} is only committed
- * if there is no associated {@link BatchRefUpdate}. As a result, the
- * configured ref updated event is not fired if there is an associated batch.
+ *
+ * <p>This allows making multiple commits to a single metadata ref, at the end of which is a
+ * single ref update. For batching together updates to multiple refs (each consisting of one or
+ * more commits against their respective refs), create the {@link MetaDataUpdate} with a {@link
+ * BatchRefUpdate}.
+ *
+ * <p>A ref update produced by this {@link BatchMetaDataUpdate} is only committed if there is no
+ * associated {@link BatchRefUpdate}. As a result, the configured ref updated event is not fired
+ * if there is an associated batch.
*
* @param update helper info about the update.
* @throws IOException if the update failed.
@@ -272,8 +265,9 @@
config.inserter = inserter;
return config.onSave(commit);
} catch (ConfigInvalidException e) {
- throw new IOException("Cannot update " + getRefName() + " in "
- + db.getDirectory() + ": " + e.getMessage(), e);
+ throw new IOException(
+ "Cannot update " + getRefName() + " in " + db.getDirectory() + ": " + e.getMessage(),
+ e);
} finally {
config.newTree = nt;
config.reader = r;
@@ -289,10 +283,11 @@
// Reuse tree from parent commit unless there are contents in newTree or
// there is no tree for a parent commit.
- ObjectId res = newTree.getEntryCount() != 0 || srcTree == null
- ? newTree.writeTree(inserter) : srcTree.copy();
- if (res.equals(srcTree) && !update.allowEmpty()
- && (commit.getTreeId() == null)) {
+ ObjectId res =
+ newTree.getEntryCount() != 0 || srcTree == null
+ ? newTree.writeTree(inserter)
+ : srcTree.copy();
+ if (res.equals(srcTree) && !update.allowEmpty() && (commit.getTreeId() == null)) {
// If there are no changes to the content, don't create the commit.
return;
}
@@ -317,8 +312,11 @@
if (update.insertChangeId()) {
ObjectId id =
- ChangeIdUtil.computeChangeId(res, getRevision(),
- commit.getAuthor(), commit.getCommitter(),
+ ChangeIdUtil.computeChangeId(
+ res,
+ getRevision(),
+ commit.getAuthor(),
+ commit.getCommitter(),
commit.getMessage());
commit.setMessage(ChangeIdUtil.insertId(commit.getMessage(), id));
}
@@ -348,8 +346,13 @@
update.fireGitRefUpdatedEvent(ru);
return;
case LOCK_FAILURE:
- throw new LockFailureException("Cannot delete " + ru.getName()
- + " in " + db.getDirectory() + ": " + ru.getResult());
+ throw new LockFailureException(
+ "Cannot delete "
+ + ru.getName()
+ + " in "
+ + db.getDirectory()
+ + ": "
+ + ru.getResult());
case FAST_FORWARD:
case IO_FAILURE:
case NEW:
@@ -359,8 +362,13 @@
case REJECTED_CURRENT_BRANCH:
case RENAMED:
default:
- throw new IOException("Cannot delete " + ru.getName() + " in "
- + db.getDirectory() + ": " + ru.getResult());
+ throw new IOException(
+ "Cannot delete "
+ + ru.getName()
+ + " in "
+ + db.getDirectory()
+ + ": "
+ + ru.getResult());
}
}
@@ -374,8 +382,7 @@
if (Objects.equals(src, expected)) {
return revision;
}
- return updateRef(MoreObjects.firstNonNull(expected, ObjectId.zeroId()),
- src, getRefName());
+ return updateRef(MoreObjects.firstNonNull(expected, ObjectId.zeroId()), src, getRefName());
}
@Override
@@ -394,12 +401,11 @@
}
}
- private RevCommit updateRef(AnyObjectId oldId, AnyObjectId newId,
- String refName) throws IOException {
+ private RevCommit updateRef(AnyObjectId oldId, AnyObjectId newId, String refName)
+ throws IOException {
BatchRefUpdate bru = update.getBatch();
if (bru != null) {
- bru.addCommand(new ReceiveCommand(
- oldId.toObjectId(), newId.toObjectId(), refName));
+ bru.addCommand(new ReceiveCommand(oldId.toObjectId(), newId.toObjectId(), refName));
inserter.flush();
revision = rw.parseCommit(newId);
return revision;
@@ -413,8 +419,7 @@
if (message == null) {
message = "meta data update";
}
- try (BufferedReader reader = new BufferedReader(
- new StringReader(message))) {
+ try (BufferedReader reader = new BufferedReader(new StringReader(message))) {
// read the subject line and use it as reflog message
ru.setRefLogMessage("commit: " + reader.readLine(), true);
}
@@ -427,8 +432,13 @@
update.fireGitRefUpdatedEvent(ru);
return revision;
case LOCK_FAILURE:
- throw new LockFailureException("Cannot update " + ru.getName()
- + " in " + db.getDirectory() + ": " + ru.getResult());
+ throw new LockFailureException(
+ "Cannot update "
+ + ru.getName()
+ + " in "
+ + db.getDirectory()
+ + ": "
+ + ru.getResult());
case FORCED:
case IO_FAILURE:
case NOT_ATTEMPTED:
@@ -437,15 +447,20 @@
case REJECTED_CURRENT_BRANCH:
case RENAMED:
default:
- throw new IOException("Cannot update " + ru.getName() + " in "
- + db.getDirectory() + ": " + ru.getResult());
+ throw new IOException(
+ "Cannot update "
+ + ru.getName()
+ + " in "
+ + db.getDirectory()
+ + ": "
+ + ru.getResult());
}
}
};
}
- protected DirCache readTree(RevTree tree) throws IOException,
- MissingObjectException, IncorrectObjectTypeException {
+ protected DirCache readTree(RevTree tree)
+ throws IOException, MissingObjectException, IncorrectObjectTypeException {
DirCache dc = DirCache.newInCore();
if (tree != null) {
DirCacheBuilder b = dc.builder();
@@ -455,18 +470,18 @@
return dc;
}
- protected Config readConfig(String fileName) throws IOException,
- ConfigInvalidException {
+ protected Config readConfig(String fileName) throws IOException, ConfigInvalidException {
Config rc = new Config();
String text = readUTF8(fileName);
if (!text.isEmpty()) {
try {
rc.fromText(text);
} catch (ConfigInvalidException err) {
- StringBuilder msg = new StringBuilder("Invalid config file ")
- .append(fileName)
- .append(" in commit ")
- .append(revision.name());
+ StringBuilder msg =
+ new StringBuilder("Invalid config file ")
+ .append(fileName)
+ .append(" in commit ")
+ .append(revision.name());
if (err.getCause() != null) {
msg.append(": ").append(err.getCause());
}
@@ -490,7 +505,6 @@
if (tw != null) {
ObjectLoader obj = reader.open(tw.getObjectId(0), Constants.OBJ_BLOB);
return obj.getCachedBytes(Integer.MAX_VALUE);
-
}
return new byte[] {};
}
@@ -502,7 +516,7 @@
TreeWalk tw = TreeWalk.forPath(reader, fileName, revision.getTree());
if (tw != null) {
- return tw.getObjectId(0);
+ return tw.getObjectId(0);
}
return null;
@@ -520,8 +534,8 @@
}
}
- protected static void set(Config rc, String section, String subsection,
- String name, String value) {
+ protected static void set(
+ Config rc, String section, String subsection, String name, String value) {
if (value != null) {
rc.setString(section, subsection, name, value);
} else {
@@ -529,8 +543,8 @@
}
}
- protected static void set(Config rc, String section, String subsection,
- String name, boolean value) {
+ protected static void set(
+ Config rc, String section, String subsection, String name, boolean value) {
if (value) {
rc.setBoolean(section, subsection, name, value);
} else {
@@ -538,8 +552,8 @@
}
}
- protected static <E extends Enum<?>> void set(Config rc, String section,
- String subsection, String name, E value, E defaultValue) {
+ protected static <E extends Enum<?>> void set(
+ Config rc, String section, String subsection, String name, E value, E defaultValue) {
if (value != defaultValue) {
rc.setEnum(section, subsection, name, value);
} else {
@@ -559,13 +573,14 @@
DirCacheEditor editor = newTree.editor();
if (raw != null && 0 < raw.length) {
final ObjectId blobId = inserter.insert(Constants.OBJ_BLOB, raw);
- editor.add(new PathEdit(fileName) {
- @Override
- public void apply(DirCacheEntry ent) {
- ent.setFileMode(FileMode.REGULAR_FILE);
- ent.setObjectId(blobId);
- }
- });
+ editor.add(
+ new PathEdit(fileName) {
+ @Override
+ public void apply(DirCacheEntry ent) {
+ ent.setFileMode(FileMode.REGULAR_FILE);
+ ent.setObjectId(blobId);
+ }
+ });
} else {
editor.add(new DeletePath(fileName));
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/VisibleRefFilter.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/VisibleRefFilter.java
index c339d70..e55deda 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/VisibleRefFilter.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/VisibleRefFilter.java
@@ -31,7 +31,14 @@
import com.google.gerrit.server.project.ProjectControl;
import com.google.gerrit.server.query.change.ChangeData;
import com.google.gwtorm.server.OrmException;
-
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.RefDatabase;
@@ -43,18 +50,8 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
public class VisibleRefFilter extends AbstractAdvertiseRefsHook {
- private static final Logger log =
- LoggerFactory.getLogger(VisibleRefFilter.class);
+ private static final Logger log = LoggerFactory.getLogger(VisibleRefFilter.class);
private final TagCache tagCache;
private final ChangeNotes.Factory changeNotesFactory;
@@ -113,8 +110,7 @@
String name = ref.getName();
Change.Id changeId;
Account.Id accountId;
- if (name.startsWith(REFS_CACHE_AUTOMERGE)
- || (!showMetadata && isMetadata(name))) {
+ if (name.startsWith(REFS_CACHE_AUTOMERGE) || (!showMetadata && isMetadata(name))) {
continue;
} else if (RefNames.isRefsEdit(name)) {
// Edits are visible only to the owning user, if change is visible.
@@ -128,8 +124,8 @@
}
} else if ((accountId = Account.Id.fromRef(name)) != null) {
// Account ref is visible only to corresponding account.
- if (viewMetadata || (accountId.equals(userId)
- && projectCtl.controlForRef(name).isVisible())) {
+ if (viewMetadata
+ || (accountId.equals(userId) && projectCtl.controlForRef(name).isVisible())) {
result.put(name, ref);
}
} else if (isTag(ref)) {
@@ -154,10 +150,13 @@
// to identify what tags we can actually reach, and what we cannot.
//
if (!deferredTags.isEmpty() && (!result.isEmpty() || filterTagsSeparately)) {
- TagMatcher tags = tagCache.get(projectName).matcher(
- tagCache,
- db,
- filterTagsSeparately ? filter(db.getAllRefs()).values() : result.values());
+ TagMatcher tags =
+ tagCache
+ .get(projectName)
+ .matcher(
+ tagCache,
+ db,
+ filterTagsSeparately ? filter(db.getAllRefs()).values() : result.values());
for (Ref tag : deferredTags) {
if (tags.isReachable(tag)) {
result.put(tag.getName(), tag);
@@ -169,8 +168,7 @@
}
private Map<String, Ref> fastHideRefsMetaConfig(Map<String, Ref> refs) {
- if (refs.containsKey(REFS_CONFIG)
- && !projectCtl.controlForRef(REFS_CONFIG).isVisible()) {
+ if (refs.containsKey(REFS_CONFIG) && !projectCtl.controlForRef(REFS_CONFIG).isVisible()) {
Map<String, Ref> r = new HashMap<>(refs);
r.remove(REFS_CONFIG);
return r;
@@ -191,8 +189,8 @@
}
@Override
- protected Map<String, Ref> getAdvertisedRefs(Repository repository,
- RevWalk revWalk) throws ServiceMayNotContinueException {
+ protected Map<String, Ref> getAdvertisedRefs(Repository repository, RevWalk revWalk)
+ throws ServiceMayNotContinueException {
try {
return filter(repository.getRefDatabase().getRefs(RefDatabase.ALL));
} catch (ServiceMayNotContinueException e) {
@@ -233,17 +231,18 @@
Project project = projectCtl.getProject();
try {
Set<Change.Id> visibleChanges = new HashSet<>();
- for (ChangeData cd : changeCache.getChangeData(
- reviewDb, project.getNameKey())) {
- if (projectCtl.controlForIndexedChange(cd.change())
- .isVisible(reviewDb, cd)) {
+ for (ChangeData cd : changeCache.getChangeData(reviewDb, project.getNameKey())) {
+ if (projectCtl.controlForIndexedChange(cd.change()).isVisible(reviewDb, cd)) {
visibleChanges.add(cd.getId());
}
}
return visibleChanges;
} catch (OrmException e) {
- log.error("Cannot load changes for project " + project.getName()
- + ", assuming no changes are visible", e);
+ log.error(
+ "Cannot load changes for project "
+ + project.getName()
+ + ", assuming no changes are visible",
+ e);
return Collections.emptySet();
}
}
@@ -259,8 +258,8 @@
}
return visibleChanges;
} catch (IOException | OrmException e) {
- log.error("Cannot load changes for project " + project
- + ", assuming no changes are visible", e);
+ log.error(
+ "Cannot load changes for project " + project + ", assuming no changes are visible", e);
return Collections.emptySet();
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/WorkQueue.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/WorkQueue.java
index 220df8c..99af21d 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/WorkQueue.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/WorkQueue.java
@@ -21,11 +21,6 @@
import com.google.gerrit.server.util.IdGenerator;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.lib.Config;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.lang.Thread.UncaughtExceptionHandler;
import java.lang.reflect.Field;
import java.util.ArrayList;
@@ -46,6 +41,9 @@
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
+import org.eclipse.jgit.lib.Config;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/** Delayed execution of tasks using a background thread pool. */
@Singleton
@@ -59,8 +57,7 @@
}
@Override
- public void start() {
- }
+ public void start() {}
@Override
public void stop() {
@@ -183,24 +180,27 @@
private final String queueName;
Executor(int corePoolSize, final String prefix) {
- super(corePoolSize, new ThreadFactory() {
- private final ThreadFactory parent = Executors.defaultThreadFactory();
- private final AtomicInteger tid = new AtomicInteger(1);
+ super(
+ corePoolSize,
+ new ThreadFactory() {
+ private final ThreadFactory parent = Executors.defaultThreadFactory();
+ private final AtomicInteger tid = new AtomicInteger(1);
- @Override
- public Thread newThread(final Runnable task) {
- final Thread t = parent.newThread(task);
- t.setName(prefix + "-" + tid.getAndIncrement());
- t.setUncaughtExceptionHandler(LOG_UNCAUGHT_EXCEPTION);
- return t;
- }
- });
+ @Override
+ public Thread newThread(final Runnable task) {
+ final Thread t = parent.newThread(task);
+ t.setName(prefix + "-" + tid.getAndIncrement());
+ t.setUncaughtExceptionHandler(LOG_UNCAUGHT_EXCEPTION);
+ return t;
+ }
+ });
- all = new ConcurrentHashMap<>( //
- corePoolSize << 1, // table size
- 0.75f, // load factor
- corePoolSize + 4 // concurrency level
- );
+ all =
+ new ConcurrentHashMap<>( //
+ corePoolSize << 1, // table size
+ 0.75f, // load factor
+ corePoolSize + 4 // concurrency level
+ );
queueName = prefix;
}
@@ -212,7 +212,7 @@
protected <V> RunnableScheduledFuture<V> decorateTask(
final Runnable runnable, RunnableScheduledFuture<V> r) {
r = super.decorateTask(runnable, r);
- for (;;) {
+ for (; ; ) {
final int id = idGenerator.next();
Task<V> task;
@@ -253,9 +253,8 @@
}
/**
- * Runnable needing to know it was canceled.
- * Note that cancel is called only in case the task is not in
- * progress already.
+ * Runnable needing to know it was canceled. Note that cancel is called only in case the task is
+ * not in progress already.
*/
public interface CancelableRunnable extends Runnable {
/** Notifies the runnable it was canceled. */
@@ -263,15 +262,13 @@
}
/**
- * Base interface handles the case when task was canceled before
- * actual execution and in case it was started cancel method is
- * not called yet the task itself will be destroyed anyway (it
- * will result in resource opening errors).
- * This interface gives a chance to implementing classes for
+ * Base interface handles the case when task was canceled before actual execution and in case it
+ * was started cancel method is not called yet the task itself will be destroyed anyway (it will
+ * result in resource opening errors). This interface gives a chance to implementing classes for
* handling such scenario and act accordingly.
*/
public interface CanceledWhileRunning extends CancelableRunnable {
- /** Notifies the runnable it was canceled during execution. **/
+ /** Notifies the runnable it was canceled during execution. * */
void setCanceledWhileRunning();
}
@@ -279,13 +276,14 @@
public static class Task<V> implements RunnableScheduledFuture<V> {
/**
* Summarized status of a single task.
- * <p>
- * Tasks have the following state flow:
+ *
+ * <p>Tasks have the following state flow:
+ *
* <ol>
- * <li>{@link #SLEEPING}: if scheduled with a non-zero delay.</li>
- * <li>{@link #READY}: waiting for an available worker thread.</li>
- * <li>{@link #RUNNING}: actively executing on a worker thread.</li>
- * <li>{@link #DONE}: finished executing, if not periodic.</li>
+ * <li>{@link #SLEEPING}: if scheduled with a non-zero delay.
+ * <li>{@link #READY}: waiting for an available worker thread.
+ * <li>{@link #RUNNING}: actively executing on a worker thread.
+ * <li>{@link #DONE}: finished executing, if not periodic.
* </ol>
*/
public enum State {
@@ -293,7 +291,12 @@
// prefer to see tasks sorted in: done before running,
// running before ready, ready before sleeping.
//
- DONE, CANCELLED, RUNNING, READY, SLEEPING, OTHER
+ DONE,
+ CANCELLED,
+ RUNNING,
+ READY,
+ SLEEPING,
+ OTHER
}
private final Runnable runnable;
@@ -303,8 +306,7 @@
private final AtomicBoolean running;
private final Date startTime;
- Task(Runnable runnable, RunnableScheduledFuture<V> task, Executor executor,
- int taskId) {
+ Task(Runnable runnable, RunnableScheduledFuture<V> task, Executor executor, int taskId) {
this.runnable = runnable;
this.task = task;
this.executor = executor;
@@ -369,7 +371,6 @@
executor.remove(this);
executor.purge();
return true;
-
}
return false;
}
@@ -385,8 +386,8 @@
}
@Override
- public V get(long timeout, TimeUnit unit) throws InterruptedException,
- ExecutionException, TimeoutException {
+ public V get(long timeout, TimeUnit unit)
+ throws InterruptedException, ExecutionException, TimeoutException {
return task.get(timeout, unit);
}
@@ -430,10 +431,13 @@
//This is a workaround to be able to print a proper name when the task
//is wrapped into a TrustedListenableFutureTask.
try {
- if (runnable.getClass().isAssignableFrom(Class.forName(
- "com.google.common.util.concurrent.TrustedListenableFutureTask"))) {
- Class<?> trustedFutureInterruptibleTask = Class.forName(
- "com.google.common.util.concurrent.TrustedListenableFutureTask$TrustedFutureInterruptibleTask");
+ if (runnable
+ .getClass()
+ .isAssignableFrom(
+ Class.forName("com.google.common.util.concurrent.TrustedListenableFutureTask"))) {
+ Class<?> trustedFutureInterruptibleTask =
+ Class.forName(
+ "com.google.common.util.concurrent.TrustedListenableFutureTask$TrustedFutureInterruptibleTask");
for (Field field : runnable.getClass().getDeclaredFields()) {
if (field.getType().isAssignableFrom(trustedFutureInterruptibleTask)) {
field.setAccessible(true);
@@ -449,25 +453,23 @@
}
}
}
- } catch (ClassNotFoundException | IllegalArgumentException
- | IllegalAccessException e) {
- log.debug("Cannot get a proper name for TrustedListenableFutureTask: {}",
- e.getMessage());
+ } catch (ClassNotFoundException | IllegalArgumentException | IllegalAccessException e) {
+ log.debug("Cannot get a proper name for TrustedListenableFutureTask: {}", e.getMessage());
}
return runnable.toString();
}
}
/**
- * Same as Task class, but with a reference to ProjectRunnable, used to
- * retrieve the project name from the operation queued
- **/
+ * Same as Task class, but with a reference to ProjectRunnable, used to retrieve the project name
+ * from the operation queued
+ */
public static class ProjectTask<V> extends Task<V> implements ProjectRunnable {
private final ProjectRunnable runnable;
- ProjectTask(ProjectRunnable runnable, RunnableScheduledFuture<V> task,
- Executor executor, int taskId) {
+ ProjectTask(
+ ProjectRunnable runnable, RunnableScheduledFuture<V> task, Executor executor, int taskId) {
super(runnable, task, executor, taskId);
this.runnable = runnable;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/strategy/CherryPick.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/strategy/CherryPick.java
index d5760e6..30e842a 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/strategy/CherryPick.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/strategy/CherryPick.java
@@ -30,16 +30,14 @@
import com.google.gerrit.server.git.MergeTip;
import com.google.gerrit.server.project.NoSuchChangeException;
import com.google.gwtorm.server.OrmException;
-
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.lib.PersonIdent;
-import org.eclipse.jgit.revwalk.RevCommit;
-import org.eclipse.jgit.transport.ReceiveCommand;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.lib.PersonIdent;
+import org.eclipse.jgit.revwalk.RevCommit;
+import org.eclipse.jgit.transport.ReceiveCommand;
public class CherryPick extends SubmitStrategy {
@@ -48,8 +46,8 @@
}
@Override
- public List<SubmitStrategyOp> buildOps(
- Collection<CodeReviewCommit> toMerge) throws IntegrationException {
+ public List<SubmitStrategyOp> buildOps(Collection<CodeReviewCommit> toMerge)
+ throws IntegrationException {
List<CodeReviewCommit> sorted = CodeReviewCommit.ORDER.sortedCopy(toMerge);
List<SubmitStrategyOp> ops = new ArrayList<>(sorted.size());
boolean first = true;
@@ -92,25 +90,30 @@
}
@Override
- protected void updateRepoImpl(RepoContext ctx)
- throws IntegrationException, IOException {
+ protected void updateRepoImpl(RepoContext ctx) throws IntegrationException, IOException {
// If there is only one parent, a cherry-pick can be done by taking the
// delta relative to that one parent and redoing that on the current merge
// tip.
args.rw.parseBody(toMerge);
- psId = ChangeUtil.nextPatchSetId(
- args.repo, toMerge.change().currentPatchSetId());
+ psId = ChangeUtil.nextPatchSetId(args.repo, toMerge.change().currentPatchSetId());
RevCommit mergeTip = args.mergeTip.getCurrentTip();
args.rw.parseBody(mergeTip);
- String cherryPickCmtMsg =
- args.mergeUtil.createCommitMessageOnSubmit(toMerge, mergeTip);
+ String cherryPickCmtMsg = args.mergeUtil.createCommitMessageOnSubmit(toMerge, mergeTip);
- PersonIdent committer = args.caller.newCommitterIdent(
- ctx.getWhen(), args.serverIdent.getTimeZone());
+ PersonIdent committer =
+ args.caller.newCommitterIdent(ctx.getWhen(), args.serverIdent.getTimeZone());
try {
- newCommit = args.mergeUtil.createCherryPickFromCommit(
- args.repo, args.inserter, args.mergeTip.getCurrentTip(), toMerge,
- committer, cherryPickCmtMsg, args.rw, 0, false);
+ newCommit =
+ args.mergeUtil.createCherryPickFromCommit(
+ args.repo,
+ args.inserter,
+ args.mergeTip.getCurrentTip(),
+ toMerge,
+ committer,
+ cherryPickCmtMsg,
+ args.rw,
+ 0,
+ false);
} catch (MergeConflictException mce) {
// Keep going in the case of a single merge failure; the goal is to
// cherry-pick as many commits as possible.
@@ -129,27 +132,32 @@
args.mergeTip.moveTipTo(newCommit, newCommit);
args.commitStatus.put(newCommit);
- ctx.addRefUpdate(
- new ReceiveCommand(ObjectId.zeroId(), newCommit, psId.toRefName()));
- patchSetInfo =
- args.patchSetInfoFactory.get(ctx.getRevWalk(), newCommit, psId);
+ ctx.addRefUpdate(new ReceiveCommand(ObjectId.zeroId(), newCommit, psId.toRefName()));
+ patchSetInfo = args.patchSetInfoFactory.get(ctx.getRevWalk(), newCommit, psId);
}
@Override
- public PatchSet updateChangeImpl(ChangeContext ctx) throws OrmException,
- NoSuchChangeException, IOException {
- if (newCommit == null
- && toMerge.getStatusCode() == SKIPPED_IDENTICAL_TREE) {
+ public PatchSet updateChangeImpl(ChangeContext ctx)
+ throws OrmException, NoSuchChangeException, IOException {
+ if (newCommit == null && toMerge.getStatusCode() == SKIPPED_IDENTICAL_TREE) {
return null;
}
- checkNotNull(newCommit,
+ checkNotNull(
+ newCommit,
"no new commit produced by CherryPick of %s, expected to fail fast",
toMerge.change().getId());
PatchSet prevPs = args.psUtil.current(ctx.getDb(), ctx.getNotes());
- PatchSet newPs = args.psUtil.insert(ctx.getDb(), ctx.getRevWalk(),
- ctx.getUpdate(psId), psId, newCommit, false,
- prevPs != null ? prevPs.getGroups() : ImmutableList.<String> of(),
- null, null);
+ PatchSet newPs =
+ args.psUtil.insert(
+ ctx.getDb(),
+ ctx.getRevWalk(),
+ ctx.getUpdate(psId),
+ psId,
+ newCommit,
+ false,
+ prevPs != null ? prevPs.getGroups() : ImmutableList.<String>of(),
+ null,
+ null);
ctx.getChange().setCurrentPatchSet(patchSetInfo);
// Don't copy approvals, as this is already taken care of by
@@ -166,8 +174,7 @@
}
@Override
- public void updateRepoImpl(RepoContext ctx)
- throws IntegrationException, IOException {
+ public void updateRepoImpl(RepoContext ctx) throws IntegrationException, IOException {
if (args.mergeUtil.hasMissingDependencies(args.mergeSorter, toMerge)) {
// One or more dependencies were not met. The status was already marked
// on the commit so we have nothing further to perform at this time.
@@ -179,26 +186,32 @@
// different first parent. So instead behave as though MERGE_IF_NECESSARY
// was configured.
MergeTip mergeTip = args.mergeTip;
- if (args.rw.isMergedInto(mergeTip.getCurrentTip(), toMerge) &&
- !args.submoduleOp.hasSubscription(args.destBranch)) {
+ if (args.rw.isMergedInto(mergeTip.getCurrentTip(), toMerge)
+ && !args.submoduleOp.hasSubscription(args.destBranch)) {
mergeTip.moveTipTo(toMerge, toMerge);
} else {
PersonIdent myIdent = new PersonIdent(args.serverIdent, ctx.getWhen());
- CodeReviewCommit result = args.mergeUtil.mergeOneCommit(myIdent,
- myIdent, args.repo, args.rw, args.inserter, args.destBranch,
- mergeTip.getCurrentTip(), toMerge);
+ CodeReviewCommit result =
+ args.mergeUtil.mergeOneCommit(
+ myIdent,
+ myIdent,
+ args.repo,
+ args.rw,
+ args.inserter,
+ args.destBranch,
+ mergeTip.getCurrentTip(),
+ toMerge);
result = amendGitlink(result);
mergeTip.moveTipTo(result, toMerge);
- args.mergeUtil.markCleanMerges(args.rw, args.canMergeFlag,
- mergeTip.getCurrentTip(), args.alreadyAccepted);
+ args.mergeUtil.markCleanMerges(
+ args.rw, args.canMergeFlag, mergeTip.getCurrentTip(), args.alreadyAccepted);
}
}
}
- static boolean dryRun(SubmitDryRun.Arguments args,
- CodeReviewCommit mergeTip, CodeReviewCommit toMerge)
+ static boolean dryRun(
+ SubmitDryRun.Arguments args, CodeReviewCommit mergeTip, CodeReviewCommit toMerge)
throws IntegrationException {
- return args.mergeUtil.canCherryPick(args.mergeSorter, args.repo,
- mergeTip, args.rw, toMerge);
+ return args.mergeUtil.canCherryPick(args.mergeSorter, args.repo, mergeTip, args.rw, toMerge);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/strategy/CommitMergeStatus.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/strategy/CommitMergeStatus.java
index bb9d359..7fbf4cd 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/strategy/CommitMergeStatus.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/strategy/CommitMergeStatus.java
@@ -15,8 +15,8 @@
package com.google.gerrit.server.git.strategy;
/**
- * Status codes set on {@link com.google.gerrit.server.git.CodeReviewCommit}s by
- * {@link SubmitStrategy} implementations.
+ * Status codes set on {@link com.google.gerrit.server.git.CodeReviewCommit}s by {@link
+ * SubmitStrategy} implementations.
*/
public enum CommitMergeStatus {
CLEAN_MERGE("Change has been successfully merged"),
@@ -27,9 +27,10 @@
ALREADY_MERGED(""),
- PATH_CONFLICT("Change could not be merged due to a path conflict.\n"
- + "\n"
- + "Please rebase the change locally and upload the rebased commit for review."),
+ PATH_CONFLICT(
+ "Change could not be merged due to a path conflict.\n"
+ + "\n"
+ + "Please rebase the change locally and upload the rebased commit for review."),
REBASE_MERGE_CONFLICT(
"Change could not be merged due to a conflict.\n"
@@ -41,21 +42,25 @@
MISSING_DEPENDENCY(""),
- MANUAL_RECURSIVE_MERGE("The change requires a local merge to resolve.\n"
- + "\n"
- + "Please merge (or rebase) the change locally and upload the resolution for review."),
+ MANUAL_RECURSIVE_MERGE(
+ "The change requires a local merge to resolve.\n"
+ + "\n"
+ + "Please merge (or rebase) the change locally and upload the resolution for review."),
- CANNOT_CHERRY_PICK_ROOT("Cannot cherry-pick an initial commit onto an existing branch.\n"
- + "\n"
- + "Please merge the change locally and upload the merge commit for review."),
+ CANNOT_CHERRY_PICK_ROOT(
+ "Cannot cherry-pick an initial commit onto an existing branch.\n"
+ + "\n"
+ + "Please merge the change locally and upload the merge commit for review."),
- CANNOT_REBASE_ROOT("Cannot rebase an initial commit onto an existing branch.\n"
- + "\n"
- + "Please merge the change locally and upload the merge commit for review."),
+ CANNOT_REBASE_ROOT(
+ "Cannot rebase an initial commit onto an existing branch.\n"
+ + "\n"
+ + "Please merge the change locally and upload the merge commit for review."),
- NOT_FAST_FORWARD("Project policy requires all submissions to be a fast-forward.\n"
- + "\n"
- + "Please rebase the change locally and upload again for review.");
+ NOT_FAST_FORWARD(
+ "Project policy requires all submissions to be a fast-forward.\n"
+ + "\n"
+ + "Please rebase the change locally and upload again for review.");
private String message;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/strategy/FastForwardOnly.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/strategy/FastForwardOnly.java
index 7c5702b..1214b76 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/strategy/FastForwardOnly.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/strategy/FastForwardOnly.java
@@ -17,7 +17,6 @@
import com.google.gerrit.server.git.BatchUpdate.RepoContext;
import com.google.gerrit.server.git.CodeReviewCommit;
import com.google.gerrit.server.git.IntegrationException;
-
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@@ -28,13 +27,13 @@
}
@Override
- public List<SubmitStrategyOp> buildOps(
- Collection<CodeReviewCommit> toMerge) throws IntegrationException {
- List<CodeReviewCommit> sorted = args.mergeUtil.reduceToMinimalMerge(
- args.mergeSorter, toMerge, args.incoming);
+ public List<SubmitStrategyOp> buildOps(Collection<CodeReviewCommit> toMerge)
+ throws IntegrationException {
+ List<CodeReviewCommit> sorted =
+ args.mergeUtil.reduceToMinimalMerge(args.mergeSorter, toMerge, args.incoming);
List<SubmitStrategyOp> ops = new ArrayList<>(sorted.size());
- CodeReviewCommit newTipCommit = args.mergeUtil.getFirstFastForward(
- args.mergeTip.getInitialTip(), args.rw, sorted);
+ CodeReviewCommit newTipCommit =
+ args.mergeUtil.getFirstFastForward(args.mergeTip.getInitialTip(), args.rw, sorted);
if (!newTipCommit.equals(args.mergeTip.getInitialTip())) {
ops.add(new FastForwardOp(args, newTipCommit));
}
@@ -55,10 +54,9 @@
}
}
- static boolean dryRun(SubmitDryRun.Arguments args,
- CodeReviewCommit mergeTip, CodeReviewCommit toMerge)
+ static boolean dryRun(
+ SubmitDryRun.Arguments args, CodeReviewCommit mergeTip, CodeReviewCommit toMerge)
throws IntegrationException {
- return args.mergeUtil.canFastForward(args.mergeSorter, mergeTip, args.rw,
- toMerge);
+ return args.mergeUtil.canFastForward(args.mergeSorter, mergeTip, args.rw, toMerge);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/strategy/ImplicitIntegrateOp.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/strategy/ImplicitIntegrateOp.java
index 12f5993..f252015 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/strategy/ImplicitIntegrateOp.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/strategy/ImplicitIntegrateOp.java
@@ -17,11 +17,10 @@
import com.google.gerrit.server.git.CodeReviewCommit;
/**
- * Operation for a change that is implicitly integrated by integrating another
- * commit.
- * <p>
- * Updates the change status and message based on {@link
- * CodeReviewCommit#getStatusCode()}, but does not touch the repository.
+ * Operation for a change that is implicitly integrated by integrating another commit.
+ *
+ * <p>Updates the change status and message based on {@link CodeReviewCommit#getStatusCode()}, but
+ * does not touch the repository.
*/
class ImplicitIntegrateOp extends SubmitStrategyOp {
ImplicitIntegrateOp(SubmitStrategy.Arguments args, CodeReviewCommit toMerge) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/strategy/MergeAlways.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/strategy/MergeAlways.java
index 621e3b9..ce045f8 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/strategy/MergeAlways.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/strategy/MergeAlways.java
@@ -16,7 +16,6 @@
import com.google.gerrit.server.git.CodeReviewCommit;
import com.google.gerrit.server.git.IntegrationException;
-
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@@ -27,10 +26,10 @@
}
@Override
- public List<SubmitStrategyOp> buildOps(
- Collection<CodeReviewCommit> toMerge) throws IntegrationException {
- List<CodeReviewCommit> sorted = args.mergeUtil.reduceToMinimalMerge(
- args.mergeSorter, toMerge, args.incoming);
+ public List<SubmitStrategyOp> buildOps(Collection<CodeReviewCommit> toMerge)
+ throws IntegrationException {
+ List<CodeReviewCommit> sorted =
+ args.mergeUtil.reduceToMinimalMerge(args.mergeSorter, toMerge, args.incoming);
List<SubmitStrategyOp> ops = new ArrayList<>(sorted.size());
if (args.mergeTip.getInitialTip() == null && !sorted.isEmpty()) {
// The branch is unborn. Take a fast-forward resolution to
@@ -45,10 +44,9 @@
return ops;
}
- static boolean dryRun(SubmitDryRun.Arguments args,
- CodeReviewCommit mergeTip, CodeReviewCommit toMerge)
+ static boolean dryRun(
+ SubmitDryRun.Arguments args, CodeReviewCommit mergeTip, CodeReviewCommit toMerge)
throws IntegrationException {
- return args.mergeUtil.canMerge(args.mergeSorter, args.repo, mergeTip,
- toMerge);
+ return args.mergeUtil.canMerge(args.mergeSorter, args.repo, mergeTip, toMerge);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/strategy/MergeIfNecessary.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/strategy/MergeIfNecessary.java
index 5cc2a89..e7db1a8 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/strategy/MergeIfNecessary.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/strategy/MergeIfNecessary.java
@@ -16,7 +16,6 @@
import com.google.gerrit.server.git.CodeReviewCommit;
import com.google.gerrit.server.git.IntegrationException;
-
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@@ -27,18 +26,17 @@
}
@Override
- public List<SubmitStrategyOp> buildOps(
- Collection<CodeReviewCommit> toMerge) throws IntegrationException {
- List<CodeReviewCommit> sorted = args.mergeUtil.reduceToMinimalMerge(
- args.mergeSorter, toMerge, args.incoming);
+ public List<SubmitStrategyOp> buildOps(Collection<CodeReviewCommit> toMerge)
+ throws IntegrationException {
+ List<CodeReviewCommit> sorted =
+ args.mergeUtil.reduceToMinimalMerge(args.mergeSorter, toMerge, args.incoming);
List<SubmitStrategyOp> ops = new ArrayList<>(sorted.size());
- if (args.mergeTip.getInitialTip() == null || !args.submoduleOp
- .hasSubscription(args.destBranch)) {
- CodeReviewCommit firstFastForward = args.mergeUtil.getFirstFastForward(
- args.mergeTip.getInitialTip(), args.rw, sorted);
- if (firstFastForward != null &&
- !firstFastForward.equals(args.mergeTip.getInitialTip())) {
+ if (args.mergeTip.getInitialTip() == null
+ || !args.submoduleOp.hasSubscription(args.destBranch)) {
+ CodeReviewCommit firstFastForward =
+ args.mergeUtil.getFirstFastForward(args.mergeTip.getInitialTip(), args.rw, sorted);
+ if (firstFastForward != null && !firstFastForward.equals(args.mergeTip.getInitialTip())) {
ops.add(new FastForwardOp(args, firstFastForward));
}
}
@@ -51,12 +49,10 @@
return ops;
}
- static boolean dryRun(SubmitDryRun.Arguments args,
- CodeReviewCommit mergeTip, CodeReviewCommit toMerge)
+ static boolean dryRun(
+ SubmitDryRun.Arguments args, CodeReviewCommit mergeTip, CodeReviewCommit toMerge)
throws IntegrationException {
- return args.mergeUtil.canFastForward(
- args.mergeSorter, mergeTip, args.rw, toMerge)
- || args.mergeUtil.canMerge(
- args.mergeSorter, args.repo, mergeTip, toMerge);
+ return args.mergeUtil.canFastForward(args.mergeSorter, mergeTip, args.rw, toMerge)
+ || args.mergeUtil.canMerge(args.mergeSorter, args.repo, mergeTip, toMerge);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/strategy/MergeOneOp.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/strategy/MergeOneOp.java
index b1590bf..e6d7d21 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/strategy/MergeOneOp.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/strategy/MergeOneOp.java
@@ -17,10 +17,8 @@
import com.google.gerrit.server.git.BatchUpdate.RepoContext;
import com.google.gerrit.server.git.CodeReviewCommit;
import com.google.gerrit.server.git.IntegrationException;
-
-import org.eclipse.jgit.lib.PersonIdent;
-
import java.io.IOException;
+import org.eclipse.jgit.lib.PersonIdent;
class MergeOneOp extends SubmitStrategyOp {
MergeOneOp(SubmitStrategy.Arguments args, CodeReviewCommit toMerge) {
@@ -28,22 +26,29 @@
}
@Override
- public void updateRepoImpl(RepoContext ctx)
- throws IntegrationException, IOException {
- PersonIdent caller = ctx.getIdentifiedUser().newCommitterIdent(
- ctx.getWhen(), ctx.getTimeZone());
+ public void updateRepoImpl(RepoContext ctx) throws IntegrationException, IOException {
+ PersonIdent caller =
+ ctx.getIdentifiedUser().newCommitterIdent(ctx.getWhen(), ctx.getTimeZone());
if (args.mergeTip.getCurrentTip() == null) {
- throw new IllegalStateException("cannot merge commit " + toMerge.name()
- + " onto a null tip; expected at least one fast-forward prior to"
- + " this operation");
+ throw new IllegalStateException(
+ "cannot merge commit "
+ + toMerge.name()
+ + " onto a null tip; expected at least one fast-forward prior to"
+ + " this operation");
}
// TODO(dborowitz): args.rw is needed because it's a CodeReviewRevWalk.
// When hoisting BatchUpdate into MergeOp, we will need to teach
// BatchUpdate how to produce CodeReviewRevWalks.
CodeReviewCommit merged =
- args.mergeUtil.mergeOneCommit(caller, args.serverIdent,
- ctx.getRepository(), args.rw, ctx.getInserter(), args.destBranch,
- args.mergeTip.getCurrentTip(), toMerge);
+ args.mergeUtil.mergeOneCommit(
+ caller,
+ args.serverIdent,
+ ctx.getRepository(),
+ args.rw,
+ ctx.getInserter(),
+ args.destBranch,
+ args.mergeTip.getCurrentTip(),
+ toMerge);
args.mergeTip.moveTipTo(amendGitlink(merged), toMerge);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/strategy/RebaseSubmitStrategy.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/strategy/RebaseSubmitStrategy.java
index ee19958..931ad71 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/strategy/RebaseSubmitStrategy.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/strategy/RebaseSubmitStrategy.java
@@ -36,20 +36,16 @@
import com.google.gerrit.server.project.InvalidChangeOperationException;
import com.google.gerrit.server.project.NoSuchChangeException;
import com.google.gwtorm.server.OrmException;
-
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.PersonIdent;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.transport.ReceiveCommand;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
-/**
- * This strategy covers RebaseAlways and RebaseIfNecessary ones.
- */
+/** This strategy covers RebaseAlways and RebaseIfNecessary ones. */
public class RebaseSubmitStrategy extends SubmitStrategy {
private final boolean rebaseAlways;
@@ -59,8 +55,8 @@
}
@Override
- public List<SubmitStrategyOp> buildOps(
- Collection<CodeReviewCommit> toMerge) throws IntegrationException {
+ public List<SubmitStrategyOp> buildOps(Collection<CodeReviewCommit> toMerge)
+ throws IntegrationException {
List<CodeReviewCommit> sorted = sort(toMerge);
List<SubmitStrategyOp> ops = new ArrayList<>(sorted.size());
boolean first = true;
@@ -71,8 +67,7 @@
// MERGE_IF_NECESSARY semantics to avoid creating duplicate
// commits.
//
- sorted = args.mergeUtil.reduceToMinimalMerge(
- args.mergeSorter, sorted, args.incoming);
+ sorted = args.mergeUtil.reduceToMinimalMerge(args.mergeSorter, sorted, args.incoming);
break;
}
}
@@ -119,15 +114,14 @@
@Override
public void updateRepoImpl(RepoContext ctx)
- throws IntegrationException, InvalidChangeOperationException,
- RestApiException, IOException, OrmException {
+ throws IntegrationException, InvalidChangeOperationException, RestApiException, IOException,
+ OrmException {
// TODO(dborowitz): args.rw is needed because it's a CodeReviewRevWalk.
// When hoisting BatchUpdate into MergeOp, we will need to teach
// BatchUpdate how to produce CodeReviewRevWalks.
- if (args.mergeUtil
- .canFastForward(args.mergeSorter, args.mergeTip.getCurrentTip(),
- args.rw, toMerge)) {
- if (!rebaseAlways){
+ if (args.mergeUtil.canFastForward(
+ args.mergeSorter, args.mergeTip.getCurrentTip(), args.rw, toMerge)) {
+ if (!rebaseAlways) {
args.mergeTip.moveTipTo(amendGitlink(toMerge), toMerge);
toMerge.setStatusCode(CommitMergeStatus.CLEAN_MERGE);
acceptMergeTip(args.mergeTip);
@@ -135,48 +129,54 @@
}
// RebaseAlways means we modify commit message.
args.rw.parseBody(toMerge);
- newPatchSetId = ChangeUtil.nextPatchSetId(
- args.repo, toMerge.change().currentPatchSetId());
+ newPatchSetId = ChangeUtil.nextPatchSetId(args.repo, toMerge.change().currentPatchSetId());
RevCommit mergeTip = args.mergeTip.getCurrentTip();
args.rw.parseBody(mergeTip);
- String cherryPickCmtMsg =
- args.mergeUtil.createCommitMessageOnSubmit(toMerge, mergeTip);
- PersonIdent committer = args.caller.newCommitterIdent(ctx.getWhen(),
- args.serverIdent.getTimeZone());
+ String cherryPickCmtMsg = args.mergeUtil.createCommitMessageOnSubmit(toMerge, mergeTip);
+ PersonIdent committer =
+ args.caller.newCommitterIdent(ctx.getWhen(), args.serverIdent.getTimeZone());
try {
- newCommit = args.mergeUtil.createCherryPickFromCommit(args.repo,
- args.inserter, args.mergeTip.getCurrentTip(), toMerge, committer,
- cherryPickCmtMsg, args.rw, 0, true);
+ newCommit =
+ args.mergeUtil.createCherryPickFromCommit(
+ args.repo,
+ args.inserter,
+ args.mergeTip.getCurrentTip(),
+ toMerge,
+ committer,
+ cherryPickCmtMsg,
+ args.rw,
+ 0,
+ true);
} catch (MergeConflictException mce) {
// Unlike in Cherry-pick case, this should never happen.
toMerge.setStatusCode(CommitMergeStatus.REBASE_MERGE_CONFLICT);
- throw new IllegalStateException(
- "MergeConflictException on message edit must not happen");
+ throw new IllegalStateException("MergeConflictException on message edit must not happen");
} catch (MergeIdenticalTreeException mie) {
// this should not happen
toMerge.setStatusCode(SKIPPED_IDENTICAL_TREE);
return;
}
- ctx.addRefUpdate(new ReceiveCommand(ObjectId.zeroId(), newCommit,
- newPatchSetId.toRefName()));
+ ctx.addRefUpdate(
+ new ReceiveCommand(ObjectId.zeroId(), newCommit, newPatchSetId.toRefName()));
} else {
// Stale read of patch set is ok; see comments in RebaseChangeOp.
- PatchSet origPs = args.psUtil.get(ctx.getDb(),
- toMerge.getControl().getNotes(), toMerge.getPatchsetId());
- rebaseOp = args.rebaseFactory.create(
- toMerge.getControl(), origPs, args.mergeTip.getCurrentTip().name())
- .setFireRevisionCreated(false)
- // Bypass approval copier since SubmitStrategyOp copy all approvals
- // later anyway.
- .setCopyApprovals(false)
- .setValidatePolicy(CommitValidators.Policy.NONE)
- .setCheckAddPatchSetPermission(false)
- // RebaseAlways should set always modify commit message like
- // Cherry-Pick strategy.
- .setDetailedCommitMessage(rebaseAlways)
- // Do not post message after inserting new patchset because there
- // will be one about change being merged already.
- .setPostMessage(false);
+ PatchSet origPs =
+ args.psUtil.get(ctx.getDb(), toMerge.getControl().getNotes(), toMerge.getPatchsetId());
+ rebaseOp =
+ args.rebaseFactory
+ .create(toMerge.getControl(), origPs, args.mergeTip.getCurrentTip().name())
+ .setFireRevisionCreated(false)
+ // Bypass approval copier since SubmitStrategyOp copy all approvals
+ // later anyway.
+ .setCopyApprovals(false)
+ .setValidatePolicy(CommitValidators.Policy.NONE)
+ .setCheckAddPatchSetPermission(false)
+ // RebaseAlways should set always modify commit message like
+ // Cherry-Pick strategy.
+ .setDetailedCommitMessage(rebaseAlways)
+ // Do not post message after inserting new patchset because there
+ // will be one about change being merged already.
+ .setPostMessage(false);
try {
rebaseOp.updateRepo(ctx);
} catch (MergeConflictException | NoSuchChangeException e) {
@@ -198,8 +198,7 @@
@Override
public PatchSet updateChangeImpl(ChangeContext ctx)
- throws NoSuchChangeException, ResourceConflictException,
- OrmException, IOException {
+ throws NoSuchChangeException, ResourceConflictException, OrmException, IOException {
if (newCommit == null) {
checkState(!rebaseAlways, "RebaseAlways must never fast forward");
// otherwise, took the fast-forward option, nothing to do.
@@ -213,13 +212,21 @@
} else {
// CherryPick
PatchSet prevPs = args.psUtil.current(ctx.getDb(), ctx.getNotes());
- newPs = args.psUtil.insert(ctx.getDb(), ctx.getRevWalk(),
- ctx.getUpdate(newPatchSetId), newPatchSetId, newCommit, false,
- prevPs != null ? prevPs.getGroups() : ImmutableList.<String> of(),
- null, null);
+ newPs =
+ args.psUtil.insert(
+ ctx.getDb(),
+ ctx.getRevWalk(),
+ ctx.getUpdate(newPatchSetId),
+ newPatchSetId,
+ newCommit,
+ false,
+ prevPs != null ? prevPs.getGroups() : ImmutableList.<String>of(),
+ null,
+ null);
}
- ctx.getChange().setCurrentPatchSet(args.patchSetInfoFactory
- .get(ctx.getRevWalk(), newCommit, newPatchSetId));
+ ctx.getChange()
+ .setCurrentPatchSet(
+ args.patchSetInfoFactory.get(ctx.getRevWalk(), newCommit, newPatchSetId));
newCommit.setControl(ctx.getControl());
return newPs;
}
@@ -238,8 +245,7 @@
}
@Override
- public void updateRepoImpl(RepoContext ctx)
- throws IntegrationException, IOException {
+ public void updateRepoImpl(RepoContext ctx) throws IntegrationException, IOException {
// There are multiple parents, so this is a merge commit. We don't want
// to rebase the merge as clients can't easily rebase their history with
// that merge present and replaced by an equivalent merge with a different
@@ -253,17 +259,24 @@
// are important would be well advised to prohibit uploading patches with
// merge commits.
MergeTip mergeTip = args.mergeTip;
- if (args.rw.isMergedInto(mergeTip.getCurrentTip(), toMerge) &&
- !args.submoduleOp.hasSubscription(args.destBranch)) {
+ if (args.rw.isMergedInto(mergeTip.getCurrentTip(), toMerge)
+ && !args.submoduleOp.hasSubscription(args.destBranch)) {
mergeTip.moveTipTo(toMerge, toMerge);
} else {
- CodeReviewCommit newTip = args.mergeUtil.mergeOneCommit(
- args.serverIdent, args.serverIdent, args.repo, args.rw,
- args.inserter, args.destBranch, mergeTip.getCurrentTip(), toMerge);
+ CodeReviewCommit newTip =
+ args.mergeUtil.mergeOneCommit(
+ args.serverIdent,
+ args.serverIdent,
+ args.repo,
+ args.rw,
+ args.inserter,
+ args.destBranch,
+ mergeTip.getCurrentTip(),
+ toMerge);
mergeTip.moveTipTo(amendGitlink(newTip), toMerge);
}
- args.mergeUtil.markCleanMerges(args.rw, args.canMergeFlag,
- mergeTip.getCurrentTip(), args.alreadyAccepted);
+ args.mergeUtil.markCleanMerges(
+ args.rw, args.canMergeFlag, mergeTip.getCurrentTip(), args.alreadyAccepted);
acceptMergeTip(mergeTip);
}
}
@@ -276,20 +289,25 @@
throws IntegrationException {
try {
return new RebaseSorter(
- args.rw, args.mergeTip.getInitialTip(), args.alreadyAccepted, args.canMergeFlag,
- args.internalChangeQuery, args.changeKindCache, args.repo).sort(toSort);
+ args.rw,
+ args.mergeTip.getInitialTip(),
+ args.alreadyAccepted,
+ args.canMergeFlag,
+ args.internalChangeQuery,
+ args.changeKindCache,
+ args.repo)
+ .sort(toSort);
} catch (IOException e) {
throw new IntegrationException("Commit sorting failed", e);
}
}
- static boolean dryRun(SubmitDryRun.Arguments args,
- CodeReviewCommit mergeTip, CodeReviewCommit toMerge)
+ static boolean dryRun(
+ SubmitDryRun.Arguments args, CodeReviewCommit mergeTip, CodeReviewCommit toMerge)
throws IntegrationException {
// Test for merge instead of cherry pick to avoid false negatives
// on commit chains.
return !args.mergeUtil.hasMissingDependencies(args.mergeSorter, toMerge)
- && args.mergeUtil.canMerge(args.mergeSorter, args.repo, mergeTip,
- toMerge);
+ && args.mergeUtil.canMerge(args.mergeSorter, args.repo, mergeTip, toMerge);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/strategy/SubmitDryRun.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/strategy/SubmitDryRun.java
index a7dc367..d375b6e 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/strategy/SubmitDryRun.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/strategy/SubmitDryRun.java
@@ -26,7 +26,10 @@
import com.google.gerrit.server.project.ProjectCache;
import com.google.gerrit.server.project.ProjectState;
import com.google.inject.Inject;
-
+import java.io.IOException;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.Set;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Ref;
@@ -38,11 +41,6 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.Set;
-
/** Dry run of a submit strategy. */
public class SubmitDryRun {
private static final Logger log = LoggerFactory.getLogger(SubmitDryRun.class);
@@ -53,10 +51,7 @@
final MergeUtil mergeUtil;
final MergeSorter mergeSorter;
- Arguments(Repository repo,
- CodeReviewRevWalk rw,
- MergeUtil mergeUtil,
- MergeSorter mergeSorter) {
+ Arguments(Repository repo, CodeReviewRevWalk rw, MergeUtil mergeUtil, MergeSorter mergeSorter) {
this.repo = repo;
this.rw = rw;
this.mergeUtil = mergeUtil;
@@ -64,23 +59,20 @@
}
}
- public static Iterable<ObjectId> getAlreadyAccepted(Repository repo)
- throws IOException {
- return FluentIterable
- .from(repo.getRefDatabase().getRefs(Constants.R_HEADS).values())
+ public static Iterable<ObjectId> getAlreadyAccepted(Repository repo) throws IOException {
+ return FluentIterable.from(repo.getRefDatabase().getRefs(Constants.R_HEADS).values())
.append(repo.getRefDatabase().getRefs(Constants.R_TAGS).values())
.transform(Ref::getObjectId);
}
- public static Set<RevCommit> getAlreadyAccepted(Repository repo, RevWalk rw)
- throws IOException {
+ public static Set<RevCommit> getAlreadyAccepted(Repository repo, RevWalk rw) throws IOException {
Set<RevCommit> accepted = new HashSet<>();
addCommits(getAlreadyAccepted(repo), rw, accepted);
return accepted;
}
- public static void addCommits(Iterable<ObjectId> ids, RevWalk rw,
- Collection<RevCommit> out) throws IOException {
+ public static void addCommits(Iterable<ObjectId> ids, RevWalk rw, Collection<RevCommit> out)
+ throws IOException {
for (ObjectId id : ids) {
RevObject obj = rw.parseAny(id);
if (obj instanceof RevCommit) {
@@ -93,23 +85,30 @@
private final MergeUtil.Factory mergeUtilFactory;
@Inject
- SubmitDryRun(ProjectCache projectCache,
- MergeUtil.Factory mergeUtilFactory) {
+ SubmitDryRun(ProjectCache projectCache, MergeUtil.Factory mergeUtilFactory) {
this.projectCache = projectCache;
this.mergeUtilFactory = mergeUtilFactory;
}
- public boolean run(SubmitType submitType, Repository repo,
- CodeReviewRevWalk rw, Branch.NameKey destBranch, ObjectId tip,
- ObjectId toMerge, Set<RevCommit> alreadyAccepted)
+ public boolean run(
+ SubmitType submitType,
+ Repository repo,
+ CodeReviewRevWalk rw,
+ Branch.NameKey destBranch,
+ ObjectId tip,
+ ObjectId toMerge,
+ Set<RevCommit> alreadyAccepted)
throws IntegrationException, NoSuchProjectException, IOException {
CodeReviewCommit tipCommit = rw.parseCommit(tip);
CodeReviewCommit toMergeCommit = rw.parseCommit(toMerge);
RevFlag canMerge = rw.newFlag("CAN_MERGE");
toMergeCommit.add(canMerge);
- Arguments args = new Arguments(repo, rw,
- mergeUtilFactory.create(getProject(destBranch)),
- new MergeSorter(rw, alreadyAccepted, canMerge));
+ Arguments args =
+ new Arguments(
+ repo,
+ rw,
+ mergeUtilFactory.create(getProject(destBranch)),
+ new MergeSorter(rw, alreadyAccepted, canMerge));
switch (submitType) {
case CHERRY_PICK:
@@ -131,8 +130,7 @@
}
}
- private ProjectState getProject(Branch.NameKey branch)
- throws NoSuchProjectException {
+ private ProjectState getProject(Branch.NameKey branch) throws NoSuchProjectException {
ProjectState p = projectCache.get(branch.getParentKey());
if (p == null) {
throw new NoSuchProjectException(branch.getParentKey());
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/strategy/SubmitStrategy.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/strategy/SubmitStrategy.java
index 441897c..4461642 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/strategy/SubmitStrategy.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/strategy/SubmitStrategy.java
@@ -57,24 +57,22 @@
import com.google.inject.Module;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
-
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
import org.eclipse.jgit.lib.ObjectInserter;
import org.eclipse.jgit.lib.PersonIdent;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevFlag;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
-import java.util.Set;
-
/**
* Base class that submit strategies must extend.
- * <p>
- * A submit strategy for a certain {@link SubmitType} defines how the submitted
- * commits should be merged.
+ *
+ * <p>A submit strategy for a certain {@link SubmitType} defines how the submitted commits should be
+ * merged.
*/
public abstract class SubmitStrategy {
public static Module module() {
@@ -223,8 +221,11 @@
this.submoduleOp = submoduleOp;
this.dryrun = dryrun;
- this.project = checkNotNull(projectCache.get(destBranch.getParentKey()),
- "project not found: %s", destBranch.getParentKey());
+ this.project =
+ checkNotNull(
+ projectCache.get(destBranch.getParentKey()),
+ "project not found: %s",
+ destBranch.getParentKey());
this.mergeSorter = new MergeSorter(rw, alreadyAccepted, canMergeFlag);
this.mergeUtil = mergeUtilFactory.create(project);
this.onSubmitValidatorsFactory = onSubmitValidatorsFactory;
@@ -239,17 +240,16 @@
/**
* Add operations to a batch update that execute this submit strategy.
- * <p>
- * Guarantees exactly one op is added to the update for each change in the
- * input set.
+ *
+ * <p>Guarantees exactly one op is added to the update for each change in the input set.
*
* @param bu batch update to add operations to.
- * @param toMerge the set of submitted commits that should be merged using
- * this submit strategy. Implementations are responsible for ordering of
- * commits, and will not modify the input in place.
- * @throws IntegrationException if an error occurred initializing the
- * operations (as opposed to an error during execution, which will be
- * reported only when the batch update executes the operations).
+ * @param toMerge the set of submitted commits that should be merged using this submit strategy.
+ * Implementations are responsible for ordering of commits, and will not modify the input in
+ * place.
+ * @throws IntegrationException if an error occurred initializing the operations (as opposed to an
+ * error during execution, which will be reported only when the batch update executes the
+ * operations).
*/
public final void addOps(BatchUpdate bu, Set<CodeReviewCommit> toMerge)
throws IntegrationException {
@@ -261,8 +261,7 @@
}
// First add ops for any implicitly merged changes.
- List<CodeReviewCommit> difference =
- new ArrayList<>(Sets.difference(toMerge, added));
+ List<CodeReviewCommit> difference = new ArrayList<>(Sets.difference(toMerge, added));
Collections.reverse(difference);
for (CodeReviewCommit c : difference) {
bu.addOp(c.change().getId(), new ImplicitIntegrateOp(args, c));
@@ -274,6 +273,6 @@
}
}
- protected abstract List<SubmitStrategyOp> buildOps(
- Collection<CodeReviewCommit> toMerge) throws IntegrationException;
+ protected abstract List<SubmitStrategyOp> buildOps(Collection<CodeReviewCommit> toMerge)
+ throws IntegrationException;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/strategy/SubmitStrategyFactory.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/strategy/SubmitStrategyFactory.java
index fc22cfc..fc4817d 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/strategy/SubmitStrategyFactory.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/strategy/SubmitStrategyFactory.java
@@ -31,7 +31,7 @@
import com.google.gerrit.server.util.RequestId;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
+import java.util.Set;
import org.eclipse.jgit.lib.ObjectInserter;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
@@ -39,13 +39,10 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.util.Set;
-
/** Factory to create a {@link SubmitStrategy} for a {@link SubmitType}. */
@Singleton
public class SubmitStrategyFactory {
- private static final Logger log = LoggerFactory
- .getLogger(SubmitStrategyFactory.class);
+ private static final Logger log = LoggerFactory.getLogger(SubmitStrategyFactory.class);
private final SubmitStrategy.Arguments.Factory argsFactory;
@@ -54,18 +51,44 @@
this.argsFactory = argsFactory;
}
- public SubmitStrategy create(SubmitType submitType, ReviewDb db,
- Repository repo, CodeReviewRevWalk rw, ObjectInserter inserter,
- RevFlag canMergeFlag, Set<RevCommit> alreadyAccepted,
- Set<CodeReviewCommit> incoming, Branch.NameKey destBranch,
- IdentifiedUser caller, MergeTip mergeTip, CommitStatus commitStatus,
- RequestId submissionId, NotifyHandling notifyHandling,
+ public SubmitStrategy create(
+ SubmitType submitType,
+ ReviewDb db,
+ Repository repo,
+ CodeReviewRevWalk rw,
+ ObjectInserter inserter,
+ RevFlag canMergeFlag,
+ Set<RevCommit> alreadyAccepted,
+ Set<CodeReviewCommit> incoming,
+ Branch.NameKey destBranch,
+ IdentifiedUser caller,
+ MergeTip mergeTip,
+ CommitStatus commitStatus,
+ RequestId submissionId,
+ NotifyHandling notifyHandling,
ListMultimap<RecipientType, Account.Id> accountsToNotify,
- SubmoduleOp submoduleOp, boolean dryrun) throws IntegrationException {
- SubmitStrategy.Arguments args = argsFactory.create(submitType, destBranch,
- commitStatus, rw, caller, mergeTip, inserter, repo, canMergeFlag, db,
- alreadyAccepted, incoming, submissionId, notifyHandling,
- accountsToNotify, submoduleOp, dryrun);
+ SubmoduleOp submoduleOp,
+ boolean dryrun)
+ throws IntegrationException {
+ SubmitStrategy.Arguments args =
+ argsFactory.create(
+ submitType,
+ destBranch,
+ commitStatus,
+ rw,
+ caller,
+ mergeTip,
+ inserter,
+ repo,
+ canMergeFlag,
+ db,
+ alreadyAccepted,
+ incoming,
+ submissionId,
+ notifyHandling,
+ accountsToNotify,
+ submoduleOp,
+ dryrun);
switch (submitType) {
case CHERRY_PICK:
return new CherryPick(args);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/strategy/SubmitStrategyListener.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/strategy/SubmitStrategyListener.java
index 68ee8c8..270e98e 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/strategy/SubmitStrategyListener.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/strategy/SubmitStrategyListener.java
@@ -24,21 +24,19 @@
import com.google.gerrit.server.git.CodeReviewCommit;
import com.google.gerrit.server.git.IntegrationException;
import com.google.gerrit.server.git.MergeOp.CommitStatus;
-
-import org.eclipse.jgit.revwalk.RevCommit;
-
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
+import org.eclipse.jgit.revwalk.RevCommit;
public class SubmitStrategyListener extends BatchUpdate.Listener {
private final Collection<SubmitStrategy> strategies;
private final CommitStatus commitStatus;
private final boolean failAfterRefUpdates;
- public SubmitStrategyListener(SubmitInput input,
- Collection<SubmitStrategy> strategies, CommitStatus commitStatus) {
+ public SubmitStrategyListener(
+ SubmitInput input, Collection<SubmitStrategy> strategies, CommitStatus commitStatus) {
this.strategies = strategies;
this.commitStatus = commitStatus;
if (input instanceof TestSubmitInput) {
@@ -76,13 +74,16 @@
continue;
}
SubmitStrategy.Arguments args = strategy.args;
- Set<Change.Id> unmerged = args.mergeUtil.findUnmergedChanges(
- args.commitStatus.getChangeIds(args.destBranch), args.rw,
- args.canMergeFlag, args.mergeTip.getInitialTip(),
- args.mergeTip.getCurrentTip(), alreadyMerged);
+ Set<Change.Id> unmerged =
+ args.mergeUtil.findUnmergedChanges(
+ args.commitStatus.getChangeIds(args.destBranch),
+ args.rw,
+ args.canMergeFlag,
+ args.mergeTip.getInitialTip(),
+ args.mergeTip.getCurrentTip(),
+ alreadyMerged);
for (Change.Id id : unmerged) {
- commitStatus.problem(id,
- "internal error: change not reachable from new branch tip");
+ commitStatus.problem(id, "internal error: change not reachable from new branch tip");
}
}
commitStatus.maybeFailVerbose();
@@ -92,21 +93,21 @@
for (SubmitStrategy strategy : strategies) {
SubmitStrategy.Arguments args = strategy.args;
RevCommit initialTip = args.mergeTip.getInitialTip();
- args.mergeUtil.markCleanMerges(args.rw, args.canMergeFlag,
- args.mergeTip.getCurrentTip(), initialTip == null ?
- ImmutableSet.<RevCommit>of() : ImmutableSet.of(initialTip));
+ args.mergeUtil.markCleanMerges(
+ args.rw,
+ args.canMergeFlag,
+ args.mergeTip.getCurrentTip(),
+ initialTip == null ? ImmutableSet.<RevCommit>of() : ImmutableSet.of(initialTip));
}
}
private List<Change.Id> checkCommitStatus() throws ResourceConflictException {
- List<Change.Id> alreadyMerged =
- new ArrayList<>(commitStatus.getChangeIds().size());
+ List<Change.Id> alreadyMerged = new ArrayList<>(commitStatus.getChangeIds().size());
for (Change.Id id : commitStatus.getChangeIds()) {
CodeReviewCommit commit = commitStatus.get(id);
CommitMergeStatus s = commit != null ? commit.getStatusCode() : null;
if (s == null) {
- commitStatus.problem(id,
- "internal error: change not processed by merge strategy");
+ commitStatus.problem(id, "internal error: change not processed by merge strategy");
continue;
}
switch (s) {
@@ -129,8 +130,7 @@
case NOT_FAST_FORWARD:
// TODO(dborowitz): Reformat these messages to be more appropriate for
// short problem descriptions.
- commitStatus.problem(id,
- CharMatcher.is('\n').collapseFrom(s.getMessage(), ' '));
+ commitStatus.problem(id, CharMatcher.is('\n').collapseFrom(s.getMessage(), ' '));
break;
case MISSING_DEPENDENCY:
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/strategy/SubmitStrategyOp.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/strategy/SubmitStrategyOp.java
index e9b9cbb..d0be2c0 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/strategy/SubmitStrategyOp.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/strategy/SubmitStrategyOp.java
@@ -51,7 +51,14 @@
import com.google.gerrit.server.notedb.ChangeUpdate;
import com.google.gerrit.server.project.ProjectState;
import com.google.gwtorm.server.OrmException;
-
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
import org.eclipse.jgit.errors.IncorrectObjectTypeException;
import org.eclipse.jgit.errors.MissingObjectException;
import org.eclipse.jgit.lib.ObjectId;
@@ -61,18 +68,8 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-
abstract class SubmitStrategyOp extends BatchUpdate.Op {
- private static final Logger log =
- LoggerFactory.getLogger(SubmitStrategyOp.class);
+ private static final Logger log = LoggerFactory.getLogger(SubmitStrategyOp.class);
protected final SubmitStrategy.Arguments args;
protected final CodeReviewCommit toMerge;
@@ -84,8 +81,7 @@
private Change updatedChange;
private CodeReviewCommit alreadyMerged;
- protected SubmitStrategyOp(SubmitStrategy.Arguments args,
- CodeReviewCommit toMerge) {
+ protected SubmitStrategyOp(SubmitStrategy.Arguments args, CodeReviewCommit toMerge) {
this.args = args;
this.toMerge = toMerge;
}
@@ -108,8 +104,7 @@
@Override
public final void updateRepo(RepoContext ctx) throws Exception {
- logDebug("{}#updateRepo for change {}", getClass().getSimpleName(),
- toMerge.change().getId());
+ logDebug("{}#updateRepo for change {}", getClass().getSimpleName(), toMerge.change().getId());
// Run the submit strategy implementation and record the merge tip state so
// we can create the ref update.
CodeReviewCommit tipBefore = args.mergeTip.getCurrentTip();
@@ -134,10 +129,8 @@
// Needed by postUpdate, at which point mergeTip will have advanced further,
// so it's easier to just snapshot the command.
- command = new ReceiveCommand(
- firstNonNull(tipBefore, ObjectId.zeroId()),
- tipAfter,
- getDest().get());
+ command =
+ new ReceiveCommand(firstNonNull(tipBefore, ObjectId.zeroId()), tipAfter, getDest().get());
ctx.addRefUpdate(command);
args.submoduleOp.addBranchTip(getDest(), tipAfter);
}
@@ -151,15 +144,18 @@
ProjectConfig cfg = new ProjectConfig(getProject());
cfg.load(ctx.getRevWalk(), commit);
} catch (Exception e) {
- throw new IntegrationException("Submit would store invalid"
- + " project configuration " + commit.name() + " for "
- + getProject(), e);
+ throw new IntegrationException(
+ "Submit would store invalid"
+ + " project configuration "
+ + commit.name()
+ + " for "
+ + getProject(),
+ e);
}
}
}
- private CodeReviewCommit getAlreadyMergedCommit(RepoContext ctx)
- throws IOException {
+ private CodeReviewCommit getAlreadyMergedCommit(RepoContext ctx) throws IOException {
CodeReviewCommit tip = args.mergeTip.getInitialTip();
if (tip == null) {
return null;
@@ -167,8 +163,7 @@
CodeReviewRevWalk rw = (CodeReviewRevWalk) ctx.getRevWalk();
Change.Id id = getId();
- Collection<Ref> refs = ctx.getRepository().getRefDatabase()
- .getRefs(id.toRefPrefix()).values();
+ Collection<Ref> refs = ctx.getRepository().getRefDatabase().getRefs(id.toRefPrefix()).values();
List<CodeReviewCommit> commits = new ArrayList<>(refs.size());
for (Ref ref : refs) {
PatchSet.Id psId = PatchSet.Id.fromRef(ref.getName());
@@ -183,8 +178,8 @@
continue; // Bogus ref, can't be merged into tip so we don't care.
}
}
- Collections.sort(commits, ReviewDbUtil.intKeyOrdering().reverse()
- .onResultOf(c -> c.getPatchsetId()));
+ Collections.sort(
+ commits, ReviewDbUtil.intKeyOrdering().reverse().onResultOf(c -> c.getPatchsetId()));
CodeReviewCommit result = MergeUtil.findAnyMergedInto(rw, commits, tip);
if (result == null) {
return null;
@@ -214,8 +209,7 @@
@Override
public final boolean updateChange(ChangeContext ctx) throws Exception {
- logDebug("{}#updateChange for change {}", getClass().getSimpleName(),
- toMerge.change().getId());
+ logDebug("{}#updateChange for change {}", getClass().getSimpleName(), toMerge.change().getId());
toMerge.setControl(ctx.getControl()); // Update change and notes from ctx.
PatchSet.Id oldPsId = checkNotNull(toMerge.getPatchsetId());
PatchSet.Id newPsId;
@@ -228,19 +222,28 @@
PatchSet newPatchSet = updateChangeImpl(ctx);
newPsId = checkNotNull(ctx.getChange().currentPatchSetId());
if (newPatchSet == null) {
- checkState(oldPsId.equals(newPsId),
+ checkState(
+ oldPsId.equals(newPsId),
"patch set advanced from %s to %s but updateChangeImpl did not"
- + " return new patch set instance", oldPsId, newPsId);
+ + " return new patch set instance",
+ oldPsId,
+ newPsId);
// Ok to use stale notes to get the old patch set, which didn't change
// during the submit strategy.
- mergedPatchSet = checkNotNull(
- args.psUtil.get(ctx.getDb(), ctx.getNotes(), oldPsId),
- "missing old patch set %s", oldPsId);
+ mergedPatchSet =
+ checkNotNull(
+ args.psUtil.get(ctx.getDb(), ctx.getNotes(), oldPsId),
+ "missing old patch set %s",
+ oldPsId);
} else {
PatchSet.Id n = newPatchSet.getId();
- checkState(!n.equals(oldPsId) && n.equals(newPsId),
+ checkState(
+ !n.equals(oldPsId) && n.equals(newPsId),
"current patch was %s and is now %s, but updateChangeImpl returned"
- + " new patch set instance at %s", oldPsId, newPsId, n);
+ + " new patch set instance at %s",
+ oldPsId,
+ newPsId,
+ n);
mergedPatchSet = newPatchSet;
}
}
@@ -250,19 +253,17 @@
CodeReviewCommit commit = args.commitStatus.get(id);
checkNotNull(commit, "missing commit for change " + id);
CommitMergeStatus s = commit.getStatusCode();
- checkNotNull(s,
- "status not set for change " + id
- + " expected to previously fail fast");
- logDebug("Status of change {} ({}) on {}: {}", id, commit.name(),
- c.getDest(), s);
+ checkNotNull(s, "status not set for change " + id + " expected to previously fail fast");
+ logDebug("Status of change {} ({}) on {}: {}", id, commit.name(), c.getDest(), s);
setApproval(ctx, args.caller);
- mergeResultRev = alreadyMerged == null
- ? args.mergeTip.getMergeResults().get(commit)
- // Our fixup code is not smart enough to find a merge commit
- // corresponding to the merge result. This results in a different
- // ChangeMergedEvent in the fixup case, but we'll just live with that.
- : alreadyMerged;
+ mergeResultRev =
+ alreadyMerged == null
+ ? args.mergeTip.getMergeResults().get(commit)
+ // Our fixup code is not smart enough to find a merge commit
+ // corresponding to the merge result. This results in a different
+ // ChangeMergedEvent in the fixup case, but we'll just live with that.
+ : alreadyMerged;
try {
setMerged(ctx, message(ctx, commit, s));
} catch (OrmException err) {
@@ -282,9 +283,9 @@
logDebug("Fixing up already-merged patch set {}", psId);
PatchSet prevPs = args.psUtil.current(ctx.getDb(), ctx.getNotes());
ctx.getRevWalk().parseBody(alreadyMerged);
- ctx.getChange().setCurrentPatchSet(psId,
- alreadyMerged.getShortMessage(),
- ctx.getChange().getOriginalSubject());
+ ctx.getChange()
+ .setCurrentPatchSet(
+ psId, alreadyMerged.getShortMessage(), ctx.getChange().getOriginalSubject());
PatchSet existing = args.psUtil.get(ctx.getDb(), ctx.getNotes(), psId);
if (existing != null) {
logDebug("Patch set row exists, only updating change");
@@ -293,15 +294,21 @@
// No patch set for the already merged commit, although we know it came form
// a patch set ref. Fix up the database. Note that this uses the current
// user as the uploader, which is as good a guess as any.
- List<String> groups = prevPs != null
- ? prevPs.getGroups()
- : GroupCollector.getDefaultGroups(alreadyMerged);
- return args.psUtil.insert(ctx.getDb(), ctx.getRevWalk(),
- ctx.getUpdate(psId), psId, alreadyMerged, false, groups, null, null);
+ List<String> groups =
+ prevPs != null ? prevPs.getGroups() : GroupCollector.getDefaultGroups(alreadyMerged);
+ return args.psUtil.insert(
+ ctx.getDb(),
+ ctx.getRevWalk(),
+ ctx.getUpdate(psId),
+ psId,
+ alreadyMerged,
+ false,
+ groups,
+ null,
+ null);
}
- private void setApproval(ChangeContext ctx, IdentifiedUser user)
- throws OrmException {
+ private void setApproval(ChangeContext ctx, IdentifiedUser user) throws OrmException {
Change.Id id = ctx.getChange().getId();
List<SubmitRecord> records = args.commitStatus.getSubmitRecords(id);
PatchSet.Id oldPsId = toMerge.getPatchsetId();
@@ -326,13 +333,13 @@
throws OrmException {
PatchSet.Id psId = update.getPatchSetId();
Map<PatchSetApproval.Key, PatchSetApproval> byKey = new HashMap<>();
- for (PatchSetApproval psa : args.approvalsUtil.byPatchSet(
- ctx.getDb(), ctx.getControl(), psId)) {
+ for (PatchSetApproval psa :
+ args.approvalsUtil.byPatchSet(ctx.getDb(), ctx.getControl(), psId)) {
byKey.put(psa.getKey(), psa);
}
- submitter = ApprovalsUtil.newApproval(
- psId, ctx.getUser(), LabelId.legacySubmit(), 1, ctx.getWhen());
+ submitter =
+ ApprovalsUtil.newApproval(psId, ctx.getUser(), LabelId.legacySubmit(), 1, ctx.getWhen());
byKey.put(submitter.getKey(), submitter);
// Flatten out existing approvals for this patch set based upon the current
@@ -347,14 +354,15 @@
return normalized;
}
- private void saveApprovals(LabelNormalizer.Result normalized,
- ChangeContext ctx, ChangeUpdate update, boolean includeUnchanged)
+ private void saveApprovals(
+ LabelNormalizer.Result normalized,
+ ChangeContext ctx,
+ ChangeUpdate update,
+ boolean includeUnchanged)
throws OrmException {
PatchSet.Id psId = update.getPatchSetId();
- ctx.getDb().patchSetApprovals().upsert(
- convertPatchSet(normalized.getNormalized(), psId));
- ctx.getDb().patchSetApprovals().upsert(
- zero(convertPatchSet(normalized.deleted(), psId)));
+ ctx.getDb().patchSetApprovals().upsert(convertPatchSet(normalized.getNormalized(), psId));
+ ctx.getDb().patchSetApprovals().upsert(zero(convertPatchSet(normalized.deleted(), psId)));
for (PatchSetApproval psa : normalized.updated()) {
update.putApprovalFor(psa.getAccountId(), psa.getLabel(), psa.getValue());
}
@@ -367,14 +375,13 @@
for (PatchSetApproval psa : normalized.unchanged()) {
if (includeUnchanged || psa.isLegacySubmit()) {
logDebug("Adding submit label " + psa);
- update.putApprovalFor(
- psa.getAccountId(), psa.getLabel(), psa.getValue());
+ update.putApprovalFor(psa.getAccountId(), psa.getLabel(), psa.getValue());
}
}
}
- private static Function<PatchSetApproval, PatchSetApproval>
- convertPatchSet(final PatchSet.Id psId) {
+ private static Function<PatchSetApproval, PatchSetApproval> convertPatchSet(
+ final PatchSet.Id psId) {
return psa -> {
if (psa.getPatchSetId().equals(psId)) {
return psa;
@@ -388,8 +395,7 @@
return Iterables.transform(approvals, convertPatchSet(psId));
}
- private static Iterable<PatchSetApproval> zero(
- Iterable<PatchSetApproval> approvals) {
+ private static Iterable<PatchSetApproval> zero(Iterable<PatchSetApproval> approvals) {
return Iterables.transform(
approvals,
a -> {
@@ -400,26 +406,23 @@
}
private String getByAccountName() {
- checkNotNull(submitter,
- "getByAccountName called before submitter populated");
- Account account =
- args.accountCache.get(submitter.getAccountId()).getAccount();
+ checkNotNull(submitter, "getByAccountName called before submitter populated");
+ Account account = args.accountCache.get(submitter.getAccountId()).getAccount();
if (account != null && account.getFullName() != null) {
return " by " + account.getFullName();
}
return "";
}
- private ChangeMessage message(ChangeContext ctx, CodeReviewCommit commit,
- CommitMergeStatus s) throws OrmException {
+ private ChangeMessage message(ChangeContext ctx, CodeReviewCommit commit, CommitMergeStatus s)
+ throws OrmException {
checkNotNull(s, "CommitMergeStatus may not be null");
String txt = s.getMessage();
if (s == CommitMergeStatus.CLEAN_MERGE) {
return message(ctx, commit.getPatchsetId(), txt + getByAccountName());
- } else if (s == CommitMergeStatus.CLEAN_REBASE
- || s == CommitMergeStatus.CLEAN_PICK) {
- return message(ctx, commit.getPatchsetId(),
- txt + " as " + commit.name() + getByAccountName());
+ } else if (s == CommitMergeStatus.CLEAN_REBASE || s == CommitMergeStatus.CLEAN_PICK) {
+ return message(
+ ctx, commit.getPatchsetId(), txt + " as " + commit.name() + getByAccountName());
} else if (s == CommitMergeStatus.SKIPPED_IDENTICAL_TREE) {
return message(ctx, commit.getPatchsetId(), txt);
} else if (s == CommitMergeStatus.ALREADY_MERGED) {
@@ -436,27 +439,28 @@
case REBASE_ALWAYS:
return message(ctx, commit, CommitMergeStatus.CLEAN_REBASE);
default:
- throw new IllegalStateException("unexpected submit type "
- + args.submitType.toString()
- + " for change "
- + commit.change().getId());
+ throw new IllegalStateException(
+ "unexpected submit type "
+ + args.submitType.toString()
+ + " for change "
+ + commit.change().getId());
}
} else {
- throw new IllegalStateException("unexpected status " + s
- + " for change " + commit.change().getId()
- + "; expected to previously fail fast");
+ throw new IllegalStateException(
+ "unexpected status "
+ + s
+ + " for change "
+ + commit.change().getId()
+ + "; expected to previously fail fast");
}
}
- private ChangeMessage message(ChangeContext ctx, PatchSet.Id psId,
- String body) {
+ private ChangeMessage message(ChangeContext ctx, PatchSet.Id psId, String body) {
return ChangeMessagesUtil.newMessage(
- psId, ctx.getUser(), ctx.getWhen(), body,
- ChangeMessagesUtil.TAG_MERGED);
+ psId, ctx.getUser(), ctx.getWhen(), body, ChangeMessagesUtil.TAG_MERGED);
}
- private void setMerged(ChangeContext ctx, ChangeMessage msg)
- throws OrmException {
+ private void setMerged(ChangeContext ctx, ChangeMessage msg) throws OrmException {
Change c = ctx.getChange();
ReviewDb db = ctx.getDb();
logDebug("Setting change {} merged", c.getId());
@@ -477,10 +481,7 @@
if (command != null) {
args.tagCache.updateFastForward(
- getProject(),
- command.getRefName(),
- command.getOldId(),
- command.getNewId());
+ getProject(), command.getRefName(), command.getOldId(), command.getNewId());
// TODO(dborowitz): Move to BatchUpdate? Would also allow us to run once
// per project even if multiple changes to refs/meta/config are submitted.
if (RefNames.REFS_CONFIG.equals(getDest().get())) {
@@ -498,8 +499,12 @@
// have failed fast in one of the other steps.
try {
args.mergedSenderFactory
- .create(ctx.getProject(), getId(), submitter.getAccountId(),
- args.notifyHandling, args.accountsToNotify)
+ .create(
+ ctx.getProject(),
+ getId(),
+ submitter.getAccountId(),
+ args.notifyHandling,
+ args.accountsToNotify)
.sendAsync();
} catch (Exception e) {
log.error("Cannot email merged notification for " + getId(), e);
@@ -518,14 +523,12 @@
* @see #updateRepo(RepoContext)
* @param ctx
*/
- protected void updateRepoImpl(RepoContext ctx) throws Exception {
- }
+ protected void updateRepoImpl(RepoContext ctx) throws Exception {}
/**
* @see #updateChange(ChangeContext)
* @param ctx
- * @return a new patch set if one was created by the submit strategy, or null
- * if not.
+ * @return a new patch set if one was created by the submit strategy, or null if not.
*/
protected PatchSet updateChangeImpl(ChangeContext ctx) throws Exception {
return null;
@@ -535,15 +538,14 @@
* @see #postUpdate(Context)
* @param ctx
*/
- protected void postUpdateImpl(Context ctx) throws Exception {
- }
+ protected void postUpdateImpl(Context ctx) throws Exception {}
/**
* Amend the commit with gitlink update
+ *
* @param commit
*/
- protected CodeReviewCommit amendGitlink(CodeReviewCommit commit)
- throws IntegrationException {
+ protected CodeReviewCommit amendGitlink(CodeReviewCommit commit) throws IntegrationException {
if (!args.submoduleOp.hasSubscription(args.destBranch)) {
return commit;
}
@@ -553,8 +555,7 @@
return args.submoduleOp.composeGitlinksCommit(args.destBranch, commit);
} catch (SubmoduleException | IOException e) {
throw new IntegrationException(
- "cannot update gitlink for the commit at branch: "
- + args.destBranch);
+ "cannot update gitlink for the commit at branch: " + args.destBranch);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/validators/CommitValidationException.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/validators/CommitValidationException.java
index 91c6a14..24ff379 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/validators/CommitValidationException.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/validators/CommitValidationException.java
@@ -15,7 +15,6 @@
package com.google.gerrit.server.git.validators;
import com.google.gerrit.server.validators.ValidationException;
-
import java.util.Collections;
import java.util.List;
@@ -23,8 +22,7 @@
private static final long serialVersionUID = 1L;
private final List<CommitValidationMessage> messages;
- public CommitValidationException(String reason,
- List<CommitValidationMessage> messages) {
+ public CommitValidationException(String reason, List<CommitValidationMessage> messages) {
super(reason);
this.messages = messages;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/validators/CommitValidationListener.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/validators/CommitValidationListener.java
index 9d7b3e6..d9fab05 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/validators/CommitValidationListener.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/validators/CommitValidationListener.java
@@ -16,14 +16,13 @@
import com.google.gerrit.extensions.annotations.ExtensionPoint;
import com.google.gerrit.server.events.CommitReceivedEvent;
-
import java.util.List;
/**
* Listener to provide validation on received commits.
*
- * Invoked by Gerrit when a new commit is received, has passed basic Gerrit
- * validation and can be then subject to extra validation checks.
+ * <p>Invoked by Gerrit when a new commit is received, has passed basic Gerrit validation and can be
+ * then subject to extra validation checks.
*/
@ExtensionPoint
public interface CommitValidationListener {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/validators/CommitValidators.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/validators/CommitValidators.java
index cb38096..1dd025f 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/validators/CommitValidators.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/validators/CommitValidators.java
@@ -42,9 +42,14 @@
import com.google.gerrit.server.util.MagicBranch;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
import com.jcraft.jsch.HostKey;
-
+import java.io.IOException;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.regex.Pattern;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.lib.PersonIdent;
@@ -58,17 +63,8 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.regex.Pattern;
-
public class CommitValidators {
- private static final Logger log = LoggerFactory
- .getLogger(CommitValidators.class);
+ private static final Logger log = LoggerFactory.getLogger(CommitValidators.class);
public enum Policy {
/** Use {@link Factory#forGerritCommits}. */
@@ -93,7 +89,8 @@
private final String installCommitMsgHookCommand;
@Inject
- Factory(@GerritPersonIdent PersonIdent gerritIdent,
+ Factory(
+ @GerritPersonIdent PersonIdent gerritIdent,
@CanonicalWebUrl @Nullable String canonicalWebUrl,
@GerritServerConfig Config cfg,
DynamicSet<CommitValidationListener> pluginValidators,
@@ -102,12 +99,12 @@
this.canonicalWebUrl = canonicalWebUrl;
this.pluginValidators = pluginValidators;
this.allUsers = allUsers;
- this.installCommitMsgHookCommand = cfg != null
- ? cfg.getString("gerrit", null, "installCommitMsgHookCommand") : null;
+ this.installCommitMsgHookCommand =
+ cfg != null ? cfg.getString("gerrit", null, "installCommitMsgHookCommand") : null;
}
- public CommitValidators create(Policy policy, RefControl refControl,
- SshInfo sshInfo, Repository repo) throws IOException {
+ public CommitValidators create(
+ Policy policy, RefControl refControl, SshInfo sshInfo, Repository repo) throws IOException {
switch (policy) {
case RECEIVE_COMMITS:
return forReceiveCommits(refControl, sshInfo, repo);
@@ -122,37 +119,37 @@
}
}
- private CommitValidators forReceiveCommits(RefControl refControl,
- SshInfo sshInfo, Repository repo) throws IOException {
+ private CommitValidators forReceiveCommits(
+ RefControl refControl, SshInfo sshInfo, Repository repo) throws IOException {
try (RevWalk rw = new RevWalk(repo)) {
NoteMap rejectCommits = BanCommit.loadRejectCommitsMap(repo, rw);
- return new CommitValidators(ImmutableList.of(
- new UploadMergesPermissionValidator(refControl),
- new AmendedGerritMergeCommitValidationListener(
- refControl, gerritIdent),
- new AuthorUploaderValidator(refControl, canonicalWebUrl),
- new CommitterUploaderValidator(refControl, canonicalWebUrl),
- new SignedOffByValidator(refControl),
- new ChangeIdValidator(refControl, canonicalWebUrl,
- installCommitMsgHookCommand, sshInfo),
- new ConfigValidator(refControl, repo, allUsers),
- new BannedCommitsValidator(rejectCommits),
- new PluginCommitValidationListener(pluginValidators)));
+ return new CommitValidators(
+ ImmutableList.of(
+ new UploadMergesPermissionValidator(refControl),
+ new AmendedGerritMergeCommitValidationListener(refControl, gerritIdent),
+ new AuthorUploaderValidator(refControl, canonicalWebUrl),
+ new CommitterUploaderValidator(refControl, canonicalWebUrl),
+ new SignedOffByValidator(refControl),
+ new ChangeIdValidator(
+ refControl, canonicalWebUrl, installCommitMsgHookCommand, sshInfo),
+ new ConfigValidator(refControl, repo, allUsers),
+ new BannedCommitsValidator(rejectCommits),
+ new PluginCommitValidationListener(pluginValidators)));
}
}
- private CommitValidators forGerritCommits(RefControl refControl,
- SshInfo sshInfo, Repository repo) {
- return new CommitValidators(ImmutableList.of(
- new UploadMergesPermissionValidator(refControl),
- new AmendedGerritMergeCommitValidationListener(
- refControl, gerritIdent),
- new AuthorUploaderValidator(refControl, canonicalWebUrl),
- new SignedOffByValidator(refControl),
- new ChangeIdValidator(refControl, canonicalWebUrl,
- installCommitMsgHookCommand, sshInfo),
- new ConfigValidator(refControl, repo, allUsers),
- new PluginCommitValidationListener(pluginValidators)));
+ private CommitValidators forGerritCommits(
+ RefControl refControl, SshInfo sshInfo, Repository repo) {
+ return new CommitValidators(
+ ImmutableList.of(
+ new UploadMergesPermissionValidator(refControl),
+ new AmendedGerritMergeCommitValidationListener(refControl, gerritIdent),
+ new AuthorUploaderValidator(refControl, canonicalWebUrl),
+ new SignedOffByValidator(refControl),
+ new ChangeIdValidator(
+ refControl, canonicalWebUrl, installCommitMsgHookCommand, sshInfo),
+ new ConfigValidator(refControl, repo, allUsers),
+ new PluginCommitValidationListener(pluginValidators)));
}
private CommitValidators forMergedCommits(RefControl refControl) {
@@ -169,10 +166,11 @@
// discuss what to do about it.
// - Plugin validators may do things like require certain commit message
// formats, so we play it safe and exclude them.
- return new CommitValidators(ImmutableList.of(
- new UploadMergesPermissionValidator(refControl),
- new AuthorUploaderValidator(refControl, canonicalWebUrl),
- new CommitterUploaderValidator(refControl, canonicalWebUrl)));
+ return new CommitValidators(
+ ImmutableList.of(
+ new UploadMergesPermissionValidator(refControl),
+ new AuthorUploaderValidator(refControl, canonicalWebUrl),
+ new CommitterUploaderValidator(refControl, canonicalWebUrl)));
}
private CommitValidators none() {
@@ -186,8 +184,8 @@
this.validators = validators;
}
- public List<CommitValidationMessage> validate(
- CommitReceivedEvent receiveEvent) throws CommitValidationException {
+ public List<CommitValidationMessage> validate(CommitReceivedEvent receiveEvent)
+ throws CommitValidationException {
List<CommitValidationMessage> messages = new ArrayList<>();
try {
for (CommitValidationListener commitValidator : validators) {
@@ -203,24 +201,19 @@
public static class ChangeIdValidator implements CommitValidationListener {
private static final int SHA1_LENGTH = 7;
- private static final String CHANGE_ID_PREFIX =
- FooterConstants.CHANGE_ID.getName() + ":";
+ private static final String CHANGE_ID_PREFIX = FooterConstants.CHANGE_ID.getName() + ":";
private static final String MISSING_CHANGE_ID_MSG =
- "[%s] missing "
- + FooterConstants.CHANGE_ID.getName()
- + " in commit message footer";
+ "[%s] missing " + FooterConstants.CHANGE_ID.getName() + " in commit message footer";
private static final String MISSING_SUBJECT_MSG =
"[%s] missing subject; "
- + FooterConstants.CHANGE_ID.getName()
- + " must be in commit message footer";
+ + FooterConstants.CHANGE_ID.getName()
+ + " must be in commit message footer";
private static final String MULTIPLE_CHANGE_ID_MSG =
- "[%s] multiple "
- + FooterConstants.CHANGE_ID.getName()
- + " lines in commit message footer";
+ "[%s] multiple " + FooterConstants.CHANGE_ID.getName() + " lines in commit message footer";
private static final String INVALID_CHANGE_ID_MSG =
"[%s] invalid "
- + FooterConstants.CHANGE_ID.getName() +
- " line format in commit message footer";
+ + FooterConstants.CHANGE_ID.getName()
+ + " line format in commit message footer";
private static final Pattern CHANGE_ID = Pattern.compile(CHANGE_ID_PATTERN);
private final ProjectControl projectControl;
@@ -229,8 +222,11 @@
private final SshInfo sshInfo;
private final IdentifiedUser user;
- public ChangeIdValidator(RefControl refControl, String canonicalWebUrl,
- String installCommitMsgHookCommand, SshInfo sshInfo) {
+ public ChangeIdValidator(
+ RefControl refControl,
+ String canonicalWebUrl,
+ String installCommitMsgHookCommand,
+ SshInfo sshInfo) {
this.projectControl = refControl.getProjectControl();
this.canonicalWebUrl = canonicalWebUrl;
this.installCommitMsgHookCommand = installCommitMsgHookCommand;
@@ -239,8 +235,8 @@
}
@Override
- public List<CommitValidationMessage> onCommitReceived(
- CommitReceivedEvent receiveEvent) throws CommitValidationException {
+ public List<CommitValidationMessage> onCommitReceived(CommitReceivedEvent receiveEvent)
+ throws CommitValidationException {
if (!shouldValidateChangeId(receiveEvent)) {
return Collections.emptyList();
}
@@ -253,8 +249,9 @@
if (projectControl.getProjectState().isRequireChangeID()) {
String shortMsg = commit.getShortMessage();
if (shortMsg.startsWith(CHANGE_ID_PREFIX)
- && CHANGE_ID.matcher(shortMsg.substring(
- CHANGE_ID_PREFIX.length()).trim()).matches()) {
+ && CHANGE_ID
+ .matcher(shortMsg.substring(CHANGE_ID_PREFIX.length()).trim())
+ .matches()) {
String errMsg = String.format(MISSING_SUBJECT_MSG, sha1);
throw new CommitValidationException(errMsg);
}
@@ -263,8 +260,7 @@
throw new CommitValidationException(errMsg, messages);
}
} else if (idList.size() > 1) {
- String errMsg = String.format(
- MULTIPLE_CHANGE_ID_MSG, sha1);
+ String errMsg = String.format(MULTIPLE_CHANGE_ID_MSG, sha1);
throw new CommitValidationException(errMsg, messages);
} else {
String v = idList.get(idList.size() - 1).trim();
@@ -272,8 +268,7 @@
// Egit (I0000000000000000000000000000000000000000).
if (!CHANGE_ID.matcher(v).matches() || v.matches("^I00*$")) {
String errMsg = String.format(INVALID_CHANGE_ID_MSG, sha1);
- messages.add(
- getMissingChangeIdErrorMsg(errMsg, receiveEvent.commit));
+ messages.add(getMissingChangeIdErrorMsg(errMsg, receiveEvent.commit));
throw new CommitValidationException(errMsg, messages);
}
}
@@ -327,8 +322,8 @@
if (hostKeys.isEmpty()) {
String p = "${gitdir}/hooks/commit-msg";
return String.format(
- " gitdir=$(git rev-parse --git-dir); curl -o %s %s/tools/hooks/commit-msg ; chmod +x %s", p,
- getGerritUrl(canonicalWebUrl), p);
+ " gitdir=$(git rev-parse --git-dir); curl -o %s %s/tools/hooks/commit-msg ; chmod +x %s",
+ p, getGerritUrl(canonicalWebUrl), p);
}
// SSH keys exist, so the hook can be installed with scp.
@@ -348,37 +343,34 @@
sshPort = 22;
}
- return String.format(" gitdir=$(git rev-parse --git-dir); scp -p -P %d %s@%s:hooks/commit-msg ${gitdir}/hooks/",
+ return String.format(
+ " gitdir=$(git rev-parse --git-dir); scp -p -P %d %s@%s:hooks/commit-msg ${gitdir}/hooks/",
sshPort, user.getUserName(), sshHost);
}
}
- /**
- * If this is the special project configuration branch, validate the config.
- */
+ /** If this is the special project configuration branch, validate the config. */
public static class ConfigValidator implements CommitValidationListener {
private final RefControl refControl;
private final Repository repo;
private final AllUsersName allUsers;
- public ConfigValidator(RefControl refControl, Repository repo,
- AllUsersName allUsers) {
+ public ConfigValidator(RefControl refControl, Repository repo, AllUsersName allUsers) {
this.refControl = refControl;
this.repo = repo;
this.allUsers = allUsers;
}
@Override
- public List<CommitValidationMessage> onCommitReceived(
- CommitReceivedEvent receiveEvent) throws CommitValidationException {
+ public List<CommitValidationMessage> onCommitReceived(CommitReceivedEvent receiveEvent)
+ throws CommitValidationException {
IdentifiedUser currentUser = refControl.getUser().asIdentifiedUser();
if (REFS_CONFIG.equals(refControl.getRefName())) {
List<CommitValidationMessage> messages = new ArrayList<>();
try {
- ProjectConfig cfg =
- new ProjectConfig(receiveEvent.project.getNameKey());
+ ProjectConfig cfg = new ProjectConfig(receiveEvent.project.getNameKey());
cfg.load(repo, receiveEvent.command.getNewId());
if (!cfg.getValidationErrors().isEmpty()) {
addError("Invalid project configuration:", messages);
@@ -388,17 +380,19 @@
throw new ConfigInvalidException("invalid project configuration");
}
} catch (ConfigInvalidException | IOException e) {
- log.error("User " + currentUser.getUserName()
- + " tried to push an invalid project configuration "
- + receiveEvent.command.getNewId().name() + " for project "
- + receiveEvent.project.getName(), e);
- throw new CommitValidationException("invalid project configuration",
- messages);
+ log.error(
+ "User "
+ + currentUser.getUserName()
+ + " tried to push an invalid project configuration "
+ + receiveEvent.command.getNewId().name()
+ + " for project "
+ + receiveEvent.project.getName(),
+ e);
+ throw new CommitValidationException("invalid project configuration", messages);
}
}
- if (allUsers.equals(
- refControl.getProjectControl().getProject().getNameKey())
+ if (allUsers.equals(refControl.getProjectControl().getProject().getNameKey())
&& RefNames.isRefsUsers(refControl.getRefName())) {
List<CommitValidationMessage> messages = new ArrayList<>();
Account.Id accountId = Account.Id.fromRef(refControl.getRefName());
@@ -414,12 +408,15 @@
throw new ConfigInvalidException("invalid watch configuration");
}
} catch (IOException | ConfigInvalidException e) {
- log.error("User " + currentUser.getUserName()
- + " tried to push an invalid watch configuration "
- + receiveEvent.command.getNewId().name() + " for account "
- + accountId.get(), e);
- throw new CommitValidationException("invalid watch configuration",
- messages);
+ log.error(
+ "User "
+ + currentUser.getUserName()
+ + " tried to push an invalid watch configuration "
+ + receiveEvent.command.getNewId().name()
+ + " for account "
+ + accountId.get(),
+ e);
+ throw new CommitValidationException("invalid watch configuration", messages);
}
}
}
@@ -429,8 +426,7 @@
}
/** Require permission to upload merges. */
- public static class UploadMergesPermissionValidator implements
- CommitValidationListener {
+ public static class UploadMergesPermissionValidator implements CommitValidationListener {
private final RefControl refControl;
public UploadMergesPermissionValidator(RefControl refControl) {
@@ -438,10 +434,9 @@
}
@Override
- public List<CommitValidationMessage> onCommitReceived(
- CommitReceivedEvent receiveEvent) throws CommitValidationException {
- if (receiveEvent.commit.getParentCount() > 1
- && !refControl.canUploadMerges()) {
+ public List<CommitValidationMessage> onCommitReceived(CommitReceivedEvent receiveEvent)
+ throws CommitValidationException {
+ if (receiveEvent.commit.getParentCount() > 1 && !refControl.canUploadMerges()) {
throw new CommitValidationException("you are not allowed to upload merges");
}
return Collections.emptyList();
@@ -449,8 +444,7 @@
}
/** Execute commit validation plug-ins */
- public static class PluginCommitValidationListener implements
- CommitValidationListener {
+ public static class PluginCommitValidationListener implements CommitValidationListener {
private final DynamicSet<CommitValidationListener> commitValidationListeners;
public PluginCommitValidationListener(
@@ -459,8 +453,8 @@
}
@Override
- public List<CommitValidationMessage> onCommitReceived(
- CommitReceivedEvent receiveEvent) throws CommitValidationException {
+ public List<CommitValidationMessage> onCommitReceived(CommitReceivedEvent receiveEvent)
+ throws CommitValidationException {
List<CommitValidationMessage> messages = new ArrayList<>();
for (CommitValidationListener validator : commitValidationListeners) {
@@ -483,8 +477,8 @@
}
@Override
- public List<CommitValidationMessage> onCommitReceived(
- CommitReceivedEvent receiveEvent) throws CommitValidationException {
+ public List<CommitValidationMessage> onCommitReceived(CommitReceivedEvent receiveEvent)
+ throws CommitValidationException {
IdentifiedUser currentUser = refControl.getUser().asIdentifiedUser();
final PersonIdent committer = receiveEvent.commit.getCommitterIdent();
final PersonIdent author = receiveEvent.commit.getAuthorIdent();
@@ -504,8 +498,7 @@
}
}
}
- if (!sboAuthor && !sboCommitter && !sboMe
- && !refControl.canForgeCommitter()) {
+ if (!sboAuthor && !sboCommitter && !sboMe && !refControl.canForgeCommitter()) {
throw new CommitValidationException(
"not Signed-off-by author/committer/uploader in commit message footer");
}
@@ -515,8 +508,7 @@
}
/** Require that author matches the uploader. */
- public static class AuthorUploaderValidator implements
- CommitValidationListener {
+ public static class AuthorUploaderValidator implements CommitValidationListener {
private final RefControl refControl;
private final String canonicalWebUrl;
@@ -526,17 +518,17 @@
}
@Override
- public List<CommitValidationMessage> onCommitReceived(
- CommitReceivedEvent receiveEvent) throws CommitValidationException {
+ public List<CommitValidationMessage> onCommitReceived(CommitReceivedEvent receiveEvent)
+ throws CommitValidationException {
IdentifiedUser currentUser = refControl.getUser().asIdentifiedUser();
final PersonIdent author = receiveEvent.commit.getAuthorIdent();
- if (!currentUser.hasEmailAddress(author.getEmailAddress())
- && !refControl.canForgeAuthor()) {
+ if (!currentUser.hasEmailAddress(author.getEmailAddress()) && !refControl.canForgeAuthor()) {
List<CommitValidationMessage> messages = new ArrayList<>();
- messages.add(getInvalidEmailError(receiveEvent.commit, "author", author,
- currentUser, canonicalWebUrl));
+ messages.add(
+ getInvalidEmailError(
+ receiveEvent.commit, "author", author, currentUser, canonicalWebUrl));
throw new CommitValidationException("invalid author", messages);
}
return Collections.emptyList();
@@ -544,27 +536,26 @@
}
/** Require that committer matches the uploader. */
- public static class CommitterUploaderValidator implements
- CommitValidationListener {
+ public static class CommitterUploaderValidator implements CommitValidationListener {
private final RefControl refControl;
private final String canonicalWebUrl;
- public CommitterUploaderValidator(RefControl refControl,
- String canonicalWebUrl) {
+ public CommitterUploaderValidator(RefControl refControl, String canonicalWebUrl) {
this.refControl = refControl;
this.canonicalWebUrl = canonicalWebUrl;
}
@Override
- public List<CommitValidationMessage> onCommitReceived(
- CommitReceivedEvent receiveEvent) throws CommitValidationException {
+ public List<CommitValidationMessage> onCommitReceived(CommitReceivedEvent receiveEvent)
+ throws CommitValidationException {
IdentifiedUser currentUser = refControl.getUser().asIdentifiedUser();
final PersonIdent committer = receiveEvent.commit.getCommitterIdent();
if (!currentUser.hasEmailAddress(committer.getEmailAddress())
&& !refControl.canForgeCommitter()) {
List<CommitValidationMessage> messages = new ArrayList<>();
- messages.add(getInvalidEmailError(receiveEvent.commit, "committer", committer,
- currentUser, canonicalWebUrl));
+ messages.add(
+ getInvalidEmailError(
+ receiveEvent.commit, "committer", committer, currentUser, canonicalWebUrl));
throw new CommitValidationException("invalid committer", messages);
}
return Collections.emptyList();
@@ -572,12 +563,11 @@
}
/**
- * Don't allow the user to amend a merge created by Gerrit Code Review. This
- * seems to happen all too often, due to users not paying any attention to
- * what they are doing.
+ * Don't allow the user to amend a merge created by Gerrit Code Review. This seems to happen all
+ * too often, due to users not paying any attention to what they are doing.
*/
- public static class AmendedGerritMergeCommitValidationListener implements
- CommitValidationListener {
+ public static class AmendedGerritMergeCommitValidationListener
+ implements CommitValidationListener {
private final PersonIdent gerritIdent;
private final RefControl refControl;
@@ -588,8 +578,8 @@
}
@Override
- public List<CommitValidationMessage> onCommitReceived(
- CommitReceivedEvent receiveEvent) throws CommitValidationException {
+ public List<CommitValidationMessage> onCommitReceived(CommitReceivedEvent receiveEvent)
+ throws CommitValidationException {
final PersonIdent author = receiveEvent.commit.getAuthorIdent();
if (receiveEvent.commit.getParentCount() > 1
@@ -603,8 +593,7 @@
}
/** Reject banned commits. */
- public static class BannedCommitsValidator implements
- CommitValidationListener {
+ public static class BannedCommitsValidator implements CommitValidationListener {
private final NoteMap rejectCommits;
public BannedCommitsValidator(NoteMap rejectCommits) {
@@ -612,12 +601,12 @@
}
@Override
- public List<CommitValidationMessage> onCommitReceived(
- CommitReceivedEvent receiveEvent) throws CommitValidationException {
+ public List<CommitValidationMessage> onCommitReceived(CommitReceivedEvent receiveEvent)
+ throws CommitValidationException {
try {
if (rejectCommits.contains(receiveEvent.commit)) {
- throw new CommitValidationException("contains banned commit "
- + receiveEvent.commit.getName());
+ throw new CommitValidationException(
+ "contains banned commit " + receiveEvent.commit.getName());
}
return Collections.emptyList();
} catch (IOException e) {
@@ -628,13 +617,20 @@
}
}
- private static CommitValidationMessage getInvalidEmailError(RevCommit c, String type,
- PersonIdent who, IdentifiedUser currentUser, String canonicalWebUrl) {
+ private static CommitValidationMessage getInvalidEmailError(
+ RevCommit c,
+ String type,
+ PersonIdent who,
+ IdentifiedUser currentUser,
+ String canonicalWebUrl) {
StringBuilder sb = new StringBuilder();
sb.append("\n");
sb.append("ERROR: In commit ").append(c.name()).append("\n");
- sb.append("ERROR: ").append(type).append(" email address ")
- .append(who.getEmailAddress()).append("\n");
+ sb.append("ERROR: ")
+ .append(type)
+ .append(" email address ")
+ .append(who.getEmailAddress())
+ .append("\n");
sb.append("ERROR: does not match your user account.\n");
sb.append("ERROR:\n");
if (currentUser.getEmailAddresses().isEmpty()) {
@@ -648,8 +644,11 @@
sb.append("ERROR:\n");
if (canonicalWebUrl != null) {
sb.append("ERROR: To register an email address, please visit:\n");
- sb.append("ERROR: ").append(canonicalWebUrl).append("#")
- .append(PageLinks.SETTINGS_CONTACT).append("\n");
+ sb.append("ERROR: ")
+ .append(canonicalWebUrl)
+ .append("#")
+ .append(PageLinks.SETTINGS_CONTACT)
+ .append("\n");
}
sb.append("\n");
return new CommitValidationMessage(sb.toString(), false);
@@ -658,9 +657,9 @@
/**
* Get the Gerrit URL.
*
- * @return the canonical URL (with any trailing slash removed) if it is
- * configured, otherwise fall back to "http://hostname" where hostname
- * is the value returned by {@link #getGerritHost(String)}.
+ * @return the canonical URL (with any trailing slash removed) if it is configured, otherwise fall
+ * back to "http://hostname" where hostname is the value returned by {@link
+ * #getGerritHost(String)}.
*/
private static String getGerritUrl(String canonicalWebUrl) {
if (canonicalWebUrl != null) {
@@ -672,8 +671,8 @@
/**
* Get the Gerrit hostname.
*
- * @return the hostname from the canonical URL if it is configured, otherwise
- * whatever the OS says the hostname is.
+ * @return the hostname from the canonical URL if it is configured, otherwise whatever the OS says
+ * the hostname is.
*/
private static String getGerritHost(String canonicalWebUrl) {
String host;
@@ -689,8 +688,7 @@
return host;
}
- private static void addError(String error,
- List<CommitValidationMessage> messages) {
+ private static void addError(String error, List<CommitValidationMessage> messages) {
messages.add(new CommitValidationMessage(error, true));
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/validators/MergeValidationException.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/validators/MergeValidationException.java
index 018ec1b..3624fe0 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/validators/MergeValidationException.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/validators/MergeValidationException.java
@@ -18,9 +18,9 @@
/**
* Exception that occurs during a validation step before merging changes.
- * <p>
- * Used by {@link MergeValidationListener}s provided by plugins. Messages should
- * be considered human-readable.
+ *
+ * <p>Used by {@link MergeValidationListener}s provided by plugins. Messages should be considered
+ * human-readable.
*/
public class MergeValidationException extends ValidationException {
private static final long serialVersionUID = 1L;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/validators/MergeValidationListener.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/validators/MergeValidationListener.java
index d89d3b3..6edd04e 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/validators/MergeValidationListener.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/validators/MergeValidationListener.java
@@ -20,13 +20,12 @@
import com.google.gerrit.server.IdentifiedUser;
import com.google.gerrit.server.git.CodeReviewCommit;
import com.google.gerrit.server.project.ProjectState;
-
import org.eclipse.jgit.lib.Repository;
/**
* Listener to provide validation of commits before merging.
*
- * Invoked by Gerrit before a commit is merged.
+ * <p>Invoked by Gerrit before a commit is merged.
*/
@ExtensionPoint
public interface MergeValidationListener {
@@ -41,7 +40,8 @@
* @param caller the user who initiated the merge request
* @throws MergeValidationException if the commit fails to validate
*/
- void onPreMerge(Repository repo,
+ void onPreMerge(
+ Repository repo,
CodeReviewCommit commit,
ProjectState destProject,
Branch.NameKey destBranch,
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/validators/MergeValidators.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/validators/MergeValidators.java
index 17a92ab..a84ab31 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/validators/MergeValidators.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/validators/MergeValidators.java
@@ -32,12 +32,10 @@
import com.google.gerrit.server.project.ProjectCache;
import com.google.gerrit.server.project.ProjectState;
import com.google.inject.Inject;
-
-import org.eclipse.jgit.errors.ConfigInvalidException;
-import org.eclipse.jgit.lib.Repository;
-
import java.io.IOException;
import java.util.List;
+import org.eclipse.jgit.errors.ConfigInvalidException;
+import org.eclipse.jgit.lib.Repository;
public class MergeValidators {
private final DynamicSet<MergeValidationListener> mergeValidationListeners;
@@ -48,50 +46,50 @@
}
@Inject
- MergeValidators(DynamicSet<MergeValidationListener> mergeValidationListeners,
+ MergeValidators(
+ DynamicSet<MergeValidationListener> mergeValidationListeners,
ProjectConfigValidator.Factory projectConfigValidatorFactory) {
this.mergeValidationListeners = mergeValidationListeners;
this.projectConfigValidatorFactory = projectConfigValidatorFactory;
}
- public void validatePreMerge(Repository repo,
+ public void validatePreMerge(
+ Repository repo,
CodeReviewCommit commit,
ProjectState destProject,
Branch.NameKey destBranch,
PatchSet.Id patchSetId,
IdentifiedUser caller)
throws MergeValidationException {
- List<MergeValidationListener> validators = ImmutableList.of(
- new PluginMergeValidationListener(mergeValidationListeners),
- projectConfigValidatorFactory.create());
+ List<MergeValidationListener> validators =
+ ImmutableList.of(
+ new PluginMergeValidationListener(mergeValidationListeners),
+ projectConfigValidatorFactory.create());
for (MergeValidationListener validator : validators) {
- validator.onPreMerge(repo, commit, destProject, destBranch, patchSetId,
- caller);
+ validator.onPreMerge(repo, commit, destProject, destBranch, patchSetId, caller);
}
}
- public static class ProjectConfigValidator implements
- MergeValidationListener {
+ public static class ProjectConfigValidator implements MergeValidationListener {
private static final String INVALID_CONFIG =
"Change contains an invalid project configuration.";
private static final String PARENT_NOT_FOUND =
- "Change contains an invalid project configuration:\n"
- + "Parent project does not exist.";
+ "Change contains an invalid project configuration:\n" + "Parent project does not exist.";
private static final String PLUGIN_VALUE_NOT_EDITABLE =
"Change contains an invalid project configuration:\n"
- + "One of the plugin configuration parameters is not editable.";
+ + "One of the plugin configuration parameters is not editable.";
private static final String PLUGIN_VALUE_NOT_PERMITTED =
"Change contains an invalid project configuration:\n"
- + "One of the plugin configuration parameters has a value that is not"
- + " permitted.";
+ + "One of the plugin configuration parameters has a value that is not"
+ + " permitted.";
private static final String ROOT_NO_PARENT =
"Change contains an invalid project configuration:\n"
- + "The root project cannot have a parent.";
+ + "The root project cannot have a parent.";
private static final String SET_BY_ADMIN =
"Change contains a project configuration that changes the parent"
- + " project.\n"
- + "The change must be submitted by a Gerrit administrator.";
+ + " project.\n"
+ + "The change must be submitted by a Gerrit administrator.";
private final AllProjectsName allProjectsName;
private final ProjectCache projectCache;
@@ -102,7 +100,8 @@
}
@Inject
- public ProjectConfigValidator(AllProjectsName allProjectsName,
+ public ProjectConfigValidator(
+ AllProjectsName allProjectsName,
ProjectCache projectCache,
DynamicMap<ProjectConfigEntry> pluginConfigEntries) {
this.allProjectsName = allProjectsName;
@@ -111,7 +110,8 @@
}
@Override
- public void onPreMerge(final Repository repo,
+ public void onPreMerge(
+ final Repository repo,
final CodeReviewCommit commit,
final ProjectState destProject,
final Branch.NameKey destBranch,
@@ -121,12 +121,10 @@
if (RefNames.REFS_CONFIG.equals(destBranch.get())) {
final Project.NameKey newParent;
try {
- ProjectConfig cfg =
- new ProjectConfig(destProject.getProject().getNameKey());
+ ProjectConfig cfg = new ProjectConfig(destProject.getProject().getNameKey());
cfg.load(repo, commit);
newParent = cfg.getProject().getParent(allProjectsName);
- final Project.NameKey oldParent =
- destProject.getProject().getParent(allProjectsName);
+ final Project.NameKey oldParent = destProject.getProject().getParent(allProjectsName);
if (oldParent == null) {
// update of the 'All-Projects' project
if (newParent != null) {
@@ -149,17 +147,20 @@
ProjectConfigEntry configEntry = e.getProvider().get();
String value = pluginCfg.getString(e.getExportName());
- String oldValue = destProject.getConfig()
- .getPluginConfig(e.getPluginName())
- .getString(e.getExportName());
+ String oldValue =
+ destProject
+ .getConfig()
+ .getPluginConfig(e.getPluginName())
+ .getString(e.getExportName());
- if ((value == null ? oldValue != null : !value.equals(oldValue)) &&
- !configEntry.isEditable(destProject)) {
+ if ((value == null ? oldValue != null : !value.equals(oldValue))
+ && !configEntry.isEditable(destProject)) {
throw new MergeValidationException(PLUGIN_VALUE_NOT_EDITABLE);
}
if (ProjectConfigEntryType.LIST.equals(configEntry.getType())
- && value != null && !configEntry.getPermittedValues().contains(value)) {
+ && value != null
+ && !configEntry.getPermittedValues().contains(value)) {
throw new MergeValidationException(PLUGIN_VALUE_NOT_PERMITTED);
}
}
@@ -171,8 +172,7 @@
}
/** Execute merge validation plug-ins */
- public static class PluginMergeValidationListener implements
- MergeValidationListener {
+ public static class PluginMergeValidationListener implements MergeValidationListener {
private final DynamicSet<MergeValidationListener> mergeValidationListeners;
public PluginMergeValidationListener(
@@ -181,7 +181,8 @@
}
@Override
- public void onPreMerge(Repository repo,
+ public void onPreMerge(
+ Repository repo,
CodeReviewCommit commit,
ProjectState destProject,
Branch.NameKey destBranch,
@@ -189,8 +190,7 @@
IdentifiedUser caller)
throws MergeValidationException {
for (MergeValidationListener validator : mergeValidationListeners) {
- validator.onPreMerge(repo, commit, destProject, destBranch, patchSetId,
- caller);
+ validator.onPreMerge(repo, commit, destProject, destBranch, patchSetId, caller);
}
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/validators/OnSubmitValidationListener.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/validators/OnSubmitValidationListener.java
index c736320..da3c123 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/validators/OnSubmitValidationListener.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/validators/OnSubmitValidationListener.java
@@ -17,23 +17,21 @@
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.reviewdb.client.Project.NameKey;
import com.google.gerrit.server.validators.ValidationException;
-
+import java.util.Map;
import org.eclipse.jgit.lib.ObjectReader;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.transport.ReceiveCommand;
-import java.util.Map;
-
/**
* Listener to validate ref updates performed during submit operation.
*
- * As submit strategies may generate new commits (e.g. Cherry Pick), this
- * listener allows validation of resulting new commit before destination branch
- * is updated and new patchset ref is created.
+ * <p>As submit strategies may generate new commits (e.g. Cherry Pick), this listener allows
+ * validation of resulting new commit before destination branch is updated and new patchset ref is
+ * created.
*
- * If you only care about validating the change being submitted and not the
- * resulting new commit, consider using {@link MergeValidationListener} instead.
+ * <p>If you only care about validating the change being submitted and not the resulting new commit,
+ * consider using {@link MergeValidationListener} instead.
*/
@ExtensionPoint
public interface OnSubmitValidationListener {
@@ -43,8 +41,11 @@
private ObjectReader objectReader;
private Map<String, ReceiveCommand> commands;
- public Arguments(NameKey project, Repository repository,
- ObjectReader objectReader, Map<String, ReceiveCommand> commands) {
+ public Arguments(
+ NameKey project,
+ Repository repository,
+ ObjectReader objectReader,
+ Map<String, ReceiveCommand> commands) {
this.project = project;
this.repository = repository;
this.objectReader = objectReader;
@@ -55,9 +56,7 @@
return project;
}
- /**
- * @return a read only repository
- */
+ /** @return a read only repository */
public Repository getRepository() {
return repository;
}
@@ -67,19 +66,18 @@
}
/**
- * @return a map from ref to op on it covering all ref ops to be performed
- * on this repository as part of ongoing submit operation.
+ * @return a map from ref to op on it covering all ref ops to be performed on this repository as
+ * part of ongoing submit operation.
*/
- public Map<String, ReceiveCommand> getCommands(){
+ public Map<String, ReceiveCommand> getCommands() {
return commands;
}
}
/**
- * Called right before branch is updated with new commit or commits as a
- * result of submit.
+ * Called right before branch is updated with new commit or commits as a result of submit.
*
- * If ValidationException is thrown, submitting is aborted.
+ * <p>If ValidationException is thrown, submitting is aborted.
*/
void preBranchUpdate(Arguments args) throws ValidationException;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/validators/OnSubmitValidators.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/validators/OnSubmitValidators.java
index 568c597..55935d1 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/validators/OnSubmitValidators.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/validators/OnSubmitValidators.java
@@ -19,13 +19,11 @@
import com.google.gerrit.server.git.validators.OnSubmitValidationListener.Arguments;
import com.google.gerrit.server.validators.ValidationException;
import com.google.inject.Inject;
-
+import java.util.Map;
import org.eclipse.jgit.lib.ObjectReader;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.transport.ReceiveCommand;
-import java.util.Map;
-
public class OnSubmitValidators {
public interface Factory {
OnSubmitValidators create();
@@ -38,13 +36,15 @@
this.listeners = listeners;
}
- public void validate(Project.NameKey project, Repository repo,
- ObjectReader objectReader, Map<String, ReceiveCommand> commands)
+ public void validate(
+ Project.NameKey project,
+ Repository repo,
+ ObjectReader objectReader,
+ Map<String, ReceiveCommand> commands)
throws IntegrationException {
try {
for (OnSubmitValidationListener listener : this.listeners) {
- listener.preBranchUpdate(
- new Arguments(project, repo, objectReader, commands));
+ listener.preBranchUpdate(new Arguments(project, repo, objectReader, commands));
}
} catch (ValidationException e) {
throw new IntegrationException(e.getMessage());
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/validators/RefOperationValidationException.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/validators/RefOperationValidationException.java
index 5864833..9eaf2d2 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/validators/RefOperationValidationException.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/validators/RefOperationValidationException.java
@@ -20,8 +20,7 @@
private static final long serialVersionUID = 1L;
private final Iterable<ValidationMessage> messages;
- public RefOperationValidationException(String reason,
- Iterable<ValidationMessage> messages) {
+ public RefOperationValidationException(String reason, Iterable<ValidationMessage> messages) {
super(reason);
this.messages = messages;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/validators/RefOperationValidationListener.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/validators/RefOperationValidationListener.java
index 5d04e2a..b57b254 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/validators/RefOperationValidationListener.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/validators/RefOperationValidationListener.java
@@ -16,13 +16,9 @@
import com.google.gerrit.extensions.annotations.ExtensionPoint;
import com.google.gerrit.server.events.RefReceivedEvent;
import com.google.gerrit.server.validators.ValidationException;
-
import java.util.List;
-/**
- * Listener to provide validation on operation that is going to be performed on
- * given ref
- */
+/** Listener to provide validation on operation that is going to be performed on given ref */
@ExtensionPoint
public interface RefOperationValidationListener {
/**
@@ -32,6 +28,5 @@
* @return empty list or informational messages on success
* @throws ValidationException if the ref operation fails to validate
*/
- List<ValidationMessage> onRefOperation(RefReceivedEvent refEvent)
- throws ValidationException;
+ List<ValidationMessage> onRefOperation(RefReceivedEvent refEvent) throws ValidationException;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/validators/RefOperationValidators.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/validators/RefOperationValidators.java
index 769c7d2..3641076 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/validators/RefOperationValidators.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/validators/RefOperationValidators.java
@@ -22,27 +22,24 @@
import com.google.gerrit.server.validators.ValidationException;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
-
+import java.util.ArrayList;
+import java.util.List;
import org.eclipse.jgit.lib.RefUpdate;
import org.eclipse.jgit.transport.ReceiveCommand;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.util.ArrayList;
-import java.util.List;
-
public class RefOperationValidators {
private static final GetErrorMessages GET_ERRORS = new GetErrorMessages();
- private static final Logger LOG = LoggerFactory
- .getLogger(RefOperationValidators.class);
+ private static final Logger LOG = LoggerFactory.getLogger(RefOperationValidators.class);
public interface Factory {
RefOperationValidators create(Project project, IdentifiedUser user, ReceiveCommand cmd);
}
public static ReceiveCommand getCommand(RefUpdate update, ReceiveCommand.Type type) {
- return new ReceiveCommand(update.getOldObjectId(), update.getNewObjectId(),
- update.getName(), type);
+ return new ReceiveCommand(
+ update.getOldObjectId(), update.getNewObjectId(), update.getName(), type);
}
private final RefReceivedEvent event;
@@ -51,7 +48,8 @@
@Inject
RefOperationValidators(
DynamicSet<RefOperationValidationListener> refOperationValidationListeners,
- @Assisted Project project, @Assisted IdentifiedUser user,
+ @Assisted Project project,
+ @Assisted IdentifiedUser user,
@Assisted ReceiveCommand cmd) {
this.refOperationValidationListeners = refOperationValidationListeners;
event = new RefReceivedEvent();
@@ -60,8 +58,7 @@
event.user = user;
}
- public List<ValidationMessage> validateForRefOperation()
- throws RefOperationValidationException {
+ public List<ValidationMessage> validateForRefOperation() throws RefOperationValidationException {
List<ValidationMessage> messages = new ArrayList<>();
boolean withException = false;
@@ -81,12 +78,13 @@
return messages;
}
- private void throwException(Iterable<ValidationMessage> messages,
- RefReceivedEvent event) throws RefOperationValidationException {
+ private void throwException(Iterable<ValidationMessage> messages, RefReceivedEvent event)
+ throws RefOperationValidationException {
Iterable<ValidationMessage> errors = Iterables.filter(messages, GET_ERRORS);
- String header = String.format(
- "Ref \"%s\" %S in project %s validation failed", event.command.getRefName(),
- event.command.getType(), event.project.getName());
+ String header =
+ String.format(
+ "Ref \"%s\" %S in project %s validation failed",
+ event.command.getRefName(), event.command.getType(), event.project.getName());
LOG.error(header);
throw new RefOperationValidationException(header, errors);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/validators/UploadValidationListener.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/validators/UploadValidationListener.java
index e6923c1..971f455 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/validators/UploadValidationListener.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/validators/UploadValidationListener.java
@@ -17,21 +17,18 @@
import com.google.gerrit.extensions.annotations.ExtensionPoint;
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.server.validators.ValidationException;
-
+import java.util.Collection;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.transport.UploadPack;
-import java.util.Collection;
-
/**
* Listener to provide validation for upload operations.
*
- * Invoked by Gerrit before it begins to send a pack to the client.
+ * <p>Invoked by Gerrit before it begins to send a pack to the client.
*
- * Implementors can block the upload operation by throwing a
- * ValidationException. The exception's message text will be reported to
- * the end-user over the client's protocol connection.
+ * <p>Implementors can block the upload operation by throwing a ValidationException. The exception's
+ * message text will be reported to the end-user over the client's protocol connection.
*/
@ExtensionPoint
public interface UploadValidationListener {
@@ -42,17 +39,20 @@
* @param repository The repository
* @param project The project
* @param remoteHost Remote address/hostname of the user
- * @param wants The list of wanted objects. These may be RevObject or
- * RevCommit if the processor parsed them. Implementors should not rely
- * on the values being parsed.
- * @param haves The list of common objects. Empty on an initial clone request.
- * These may be RevObject or RevCommit if the processor parsed them.
- * Implementors should not rely on the values being parsed.
- * @throws ValidationException to block the upload and send a message
- * back to the end-user over the client's protocol connection.
+ * @param wants The list of wanted objects. These may be RevObject or RevCommit if the processor
+ * parsed them. Implementors should not rely on the values being parsed.
+ * @param haves The list of common objects. Empty on an initial clone request. These may be
+ * RevObject or RevCommit if the processor parsed them. Implementors should not rely on the
+ * values being parsed.
+ * @throws ValidationException to block the upload and send a message back to the end-user over
+ * the client's protocol connection.
*/
- void onPreUpload(Repository repository, Project project,
- String remoteHost, UploadPack up, Collection<? extends ObjectId> wants,
+ void onPreUpload(
+ Repository repository,
+ Project project,
+ String remoteHost,
+ UploadPack up,
+ Collection<? extends ObjectId> wants,
Collection<? extends ObjectId> haves)
throws ValidationException;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/validators/UploadValidators.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/validators/UploadValidators.java
index eb2e136..52b76e8 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/validators/UploadValidators.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/validators/UploadValidators.java
@@ -19,15 +19,13 @@
import com.google.gerrit.server.validators.ValidationException;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
-
+import java.util.Collection;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.transport.PreUploadHook;
import org.eclipse.jgit.transport.ServiceMayNotContinueException;
import org.eclipse.jgit.transport.UploadPack;
-import java.util.Collection;
-
public class UploadValidators implements PreUploadHook {
private final DynamicSet<UploadValidationListener> uploadValidationListeners;
@@ -36,14 +34,14 @@
private final String remoteHost;
public interface Factory {
- UploadValidators create(Project project, Repository repository,
- String remoteAddress);
+ UploadValidators create(Project project, Repository repository, String remoteAddress);
}
@Inject
UploadValidators(
DynamicSet<UploadValidationListener> uploadValidationListeners,
- @Assisted Project project, @Assisted Repository repository,
+ @Assisted Project project,
+ @Assisted Repository repository,
@Assisted String remoteHost) {
this.uploadValidationListeners = uploadValidationListeners;
this.project = project;
@@ -52,8 +50,8 @@
}
@Override
- public void onSendPack(UploadPack up, Collection<? extends ObjectId> wants,
- Collection<? extends ObjectId> haves)
+ public void onSendPack(
+ UploadPack up, Collection<? extends ObjectId> wants, Collection<? extends ObjectId> haves)
throws ServiceMayNotContinueException {
for (UploadValidationListener validator : uploadValidationListeners) {
try {
@@ -61,19 +59,20 @@
} catch (ValidationException e) {
throw new UploadValidationException(e.getMessage());
}
-
}
}
@Override
- public void onBeginNegotiateRound(UploadPack up,
- Collection<? extends ObjectId> wants, int cntOffered)
- throws ServiceMayNotContinueException {
- }
+ public void onBeginNegotiateRound(
+ UploadPack up, Collection<? extends ObjectId> wants, int cntOffered)
+ throws ServiceMayNotContinueException {}
@Override
- public void onEndNegotiateRound(UploadPack up,
- Collection<? extends ObjectId> wants, int cntCommon, int cntNotFound,
- boolean ready) throws ServiceMayNotContinueException {
- }
+ public void onEndNegotiateRound(
+ UploadPack up,
+ Collection<? extends ObjectId> wants,
+ int cntCommon,
+ int cntNotFound,
+ boolean ready)
+ throws ServiceMayNotContinueException {}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/group/AddIncludedGroups.java b/gerrit-server/src/main/java/com/google/gerrit/server/group/AddIncludedGroups.java
index 84d1fad..040550c 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/group/AddIncludedGroups.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/group/AddIncludedGroups.java
@@ -37,7 +37,6 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@@ -46,8 +45,7 @@
@Singleton
public class AddIncludedGroups implements RestModifyView<GroupResource, Input> {
public static class Input {
- @DefaultInput
- String _oneGroup;
+ @DefaultInput String _oneGroup;
public List<String> groups;
@@ -78,9 +76,12 @@
private final AuditService auditService;
@Inject
- public AddIncludedGroups(GroupsCollection groupsCollection,
- GroupIncludeCache groupIncludeCache, Provider<ReviewDb> db,
- GroupJson json, AuditService auditService) {
+ public AddIncludedGroups(
+ GroupsCollection groupsCollection,
+ GroupIncludeCache groupIncludeCache,
+ Provider<ReviewDb> db,
+ GroupJson json,
+ AuditService auditService) {
this.groupsCollection = groupsCollection;
this.groupIncludeCache = groupIncludeCache;
this.db = db;
@@ -90,8 +91,7 @@
@Override
public List<GroupInfo> apply(GroupResource resource, Input input)
- throws MethodNotAllowedException, AuthException,
- UnprocessableEntityException, OrmException {
+ throws MethodNotAllowedException, AuthException, UnprocessableEntityException, OrmException {
AccountGroup group = resource.toAccountGroup();
if (group == null) {
throw new MethodNotAllowedException();
@@ -106,14 +106,11 @@
for (String includedGroup : input.groups) {
GroupDescription.Basic d = groupsCollection.parse(includedGroup);
if (!control.canAddGroup()) {
- throw new AuthException(String.format("Cannot add group: %s",
- d.getName()));
+ throw new AuthException(String.format("Cannot add group: %s", d.getName()));
}
if (!newIncludedGroups.containsKey(d.getGroupUUID())) {
- AccountGroupById.Key agiKey =
- new AccountGroupById.Key(group.getId(),
- d.getGroupUUID());
+ AccountGroupById.Key agiKey = new AccountGroupById.Key(group.getId(), d.getGroupUUID());
AccountGroupById agi = db.get().accountGroupById().get(agiKey);
if (agi == null) {
agi = new AccountGroupById(agiKey);
@@ -136,8 +133,7 @@
}
static class PutIncludedGroup implements RestModifyView<GroupResource, PutIncludedGroup.Input> {
- static class Input {
- }
+ static class Input {}
private final AddIncludedGroups put;
private final String id;
@@ -149,8 +145,7 @@
@Override
public GroupInfo apply(GroupResource resource, Input input)
- throws AuthException, MethodNotAllowedException,
- ResourceNotFoundException, OrmException {
+ throws AuthException, MethodNotAllowedException, ResourceNotFoundException, OrmException {
AddIncludedGroups.Input in = new AddIncludedGroups.Input();
in.groups = ImmutableList.of(id);
try {
@@ -166,7 +161,8 @@
}
@Singleton
- static class UpdateIncludedGroup implements RestModifyView<IncludedGroupResource, PutIncludedGroup.Input> {
+ static class UpdateIncludedGroup
+ implements RestModifyView<IncludedGroupResource, PutIncludedGroup.Input> {
private final Provider<GetIncludedGroup> get;
@Inject
@@ -175,8 +171,8 @@
}
@Override
- public GroupInfo apply(IncludedGroupResource resource,
- PutIncludedGroup.Input input) throws OrmException {
+ public GroupInfo apply(IncludedGroupResource resource, PutIncludedGroup.Input input)
+ throws OrmException {
// Do nothing, the group is already included.
return get.get().apply(resource);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/group/AddMembers.java b/gerrit-server/src/main/java/com/google/gerrit/server/group/AddMembers.java
index 55bb1e9..5c1a292 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/group/AddMembers.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/group/AddMembers.java
@@ -44,7 +44,6 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
@@ -57,10 +56,10 @@
@Singleton
public class AddMembers implements RestModifyView<GroupResource, Input> {
public static class Input {
- @DefaultInput
- String _oneMember;
+ @DefaultInput String _oneMember;
List<String> members;
+
public static Input fromMembers(List<String> members) {
Input in = new Input();
in.members = members;
@@ -92,7 +91,8 @@
private final AuditService auditService;
@Inject
- AddMembers(Provider<IdentifiedUser> self,
+ AddMembers(
+ Provider<IdentifiedUser> self,
AccountManager accountManager,
AuthConfig authConfig,
AccountsCollection accounts,
@@ -114,8 +114,8 @@
@Override
public List<AccountInfo> apply(GroupResource resource, Input input)
- throws AuthException, MethodNotAllowedException,
- UnprocessableEntityException, OrmException, IOException {
+ throws AuthException, MethodNotAllowedException, UnprocessableEntityException, OrmException,
+ IOException {
AccountGroup internalGroup = resource.toAccountGroup();
if (internalGroup == null) {
throw new MethodNotAllowedException();
@@ -128,8 +128,8 @@
for (String nameOrEmailOrId : input.members) {
Account a = findAccount(nameOrEmailOrId);
if (!a.isActive()) {
- throw new UnprocessableEntityException(String.format(
- "Account Inactive: %s", nameOrEmailOrId));
+ throw new UnprocessableEntityException(
+ String.format("Account Inactive: %s", nameOrEmailOrId));
}
if (!control.canAddMember()) {
@@ -142,8 +142,8 @@
return toAccountInfoList(newMemberIds);
}
- Account findAccount(String nameOrEmailOrId) throws AuthException,
- UnprocessableEntityException, OrmException, IOException {
+ Account findAccount(String nameOrEmailOrId)
+ throws AuthException, UnprocessableEntityException, OrmException, IOException {
try {
return accounts.parse(nameOrEmailOrId).getAccount();
} catch (UnprocessableEntityException e) {
@@ -174,14 +174,12 @@
}
}
- public void addMembers(AccountGroup.Id groupId,
- Collection<? extends Account.Id> newMemberIds)
- throws OrmException, IOException {
+ public void addMembers(AccountGroup.Id groupId, Collection<? extends Account.Id> newMemberIds)
+ throws OrmException, IOException {
Map<Account.Id, AccountGroupMember> newAccountGroupMembers = new HashMap<>();
for (Account.Id accId : newMemberIds) {
if (!newAccountGroupMembers.containsKey(accId)) {
- AccountGroupMember.Key key =
- new AccountGroupMember.Key(accId, groupId);
+ AccountGroupMember.Key key = new AccountGroupMember.Key(accId, groupId);
AccountGroupMember m = db.get().accountGroupMembers().get(key);
if (m == null) {
m = new AccountGroupMember(key);
@@ -190,8 +188,8 @@
}
}
if (!newAccountGroupMembers.isEmpty()) {
- auditService.dispatchAddAccountsToGroup(self.get().getAccountId(),
- newAccountGroupMembers.values());
+ auditService.dispatchAddAccountsToGroup(
+ self.get().getAccountId(), newAccountGroupMembers.values());
db.get().accountGroupMembers().insert(newAccountGroupMembers.values());
for (AccountGroupMember m : newAccountGroupMembers.values()) {
accountCache.evict(m.getAccountId());
@@ -207,15 +205,13 @@
try {
AuthRequest req = AuthRequest.forUser(user);
req.setSkipAuthentication(true);
- return accountCache.get(accountManager.authenticate(req).getAccountId())
- .getAccount();
+ return accountCache.get(accountManager.authenticate(req).getAccountId()).getAccount();
} catch (AccountException e) {
return null;
}
}
- private List<AccountInfo> toAccountInfoList(Set<Account.Id> accountIds)
- throws OrmException {
+ private List<AccountInfo> toAccountInfoList(Set<Account.Id> accountIds) throws OrmException {
List<AccountInfo> result = new ArrayList<>();
AccountLoader loader = infoFactory.create(true);
for (Account.Id accId : accountIds) {
@@ -226,8 +222,7 @@
}
static class PutMember implements RestModifyView<GroupResource, PutMember.Input> {
- static class Input {
- }
+ static class Input {}
private final AddMembers put;
private final String id;
@@ -239,8 +234,8 @@
@Override
public AccountInfo apply(GroupResource resource, PutMember.Input input)
- throws AuthException, MethodNotAllowedException,
- ResourceNotFoundException, OrmException, IOException {
+ throws AuthException, MethodNotAllowedException, ResourceNotFoundException, OrmException,
+ IOException {
AddMembers.Input in = new AddMembers.Input();
in._oneMember = id;
try {
@@ -265,8 +260,7 @@
}
@Override
- public AccountInfo apply(MemberResource resource, PutMember.Input input)
- throws OrmException {
+ public AccountInfo apply(MemberResource resource, PutMember.Input input) throws OrmException {
// Do nothing, the user is already a member.
return get.apply(resource);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/group/CreateGroup.java b/gerrit-server/src/main/java/com/google/gerrit/server/group/CreateGroup.java
index 70fc7f6..4d78a7d 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/group/CreateGroup.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/group/CreateGroup.java
@@ -48,16 +48,14 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.assistedinject.Assisted;
-
-import org.eclipse.jgit.lib.Config;
-import org.eclipse.jgit.lib.PersonIdent;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
+import org.eclipse.jgit.lib.Config;
+import org.eclipse.jgit.lib.PersonIdent;
@RequiresCapability(GlobalCapability.CREATE_GROUP)
public class CreateGroup implements RestModifyView<TopLevelResource, GroupInput> {
@@ -116,7 +114,7 @@
@Override
public GroupInfo apply(TopLevelResource resource, GroupInput input)
throws AuthException, BadRequestException, UnprocessableEntityException,
- ResourceConflictException, OrmException, IOException {
+ ResourceConflictException, OrmException, IOException {
if (input == null) {
input = new GroupInput();
}
@@ -128,24 +126,24 @@
CreateGroupArgs args = new CreateGroupArgs();
args.setGroupName(name);
args.groupDescription = Strings.emptyToNull(input.description);
- args.visibleToAll = MoreObjects.firstNonNull(input.visibleToAll,
- defaultVisibleToAll);
+ args.visibleToAll = MoreObjects.firstNonNull(input.visibleToAll, defaultVisibleToAll);
args.ownerGroupId = ownerId;
if (input.members != null && !input.members.isEmpty()) {
List<Account.Id> members = new ArrayList<>();
for (String nameOrEmailOrId : input.members) {
Account a = addMembers.findAccount(nameOrEmailOrId);
if (!a.isActive()) {
- throw new UnprocessableEntityException(String.format(
- "Account Inactive: %s", nameOrEmailOrId));
+ throw new UnprocessableEntityException(
+ String.format("Account Inactive: %s", nameOrEmailOrId));
}
members.add(a.getId());
}
args.initialMembers = members;
} else {
- args.initialMembers = ownerId == null
- ? Collections.singleton(self.get().getAccountId())
- : Collections.<Account.Id> emptySet();
+ args.initialMembers =
+ ownerId == null
+ ? Collections.singleton(self.get().getAccountId())
+ : Collections.<Account.Id>emptySet();
}
for (GroupCreationValidationListener l : groupCreationValidationListeners) {
@@ -159,8 +157,7 @@
return json.format(GroupDescriptions.forAccountGroup(createGroup(args)));
}
- private AccountGroup.Id owner(GroupInput input)
- throws UnprocessableEntityException {
+ private AccountGroup.Id owner(GroupInput input) throws UnprocessableEntityException {
if (input.ownerId != null) {
GroupDescription.Basic d = groups.parseInternal(Url.decode(input.ownerId));
return GroupDescriptions.toAccountGroup(d).getId();
@@ -173,18 +170,16 @@
// Do not allow creating groups with the same name as system groups
for (String name : systemGroupBackend.getNames()) {
- if (name.toLowerCase(Locale.US).equals(
- createGroupArgs.getGroupName().toLowerCase(Locale.US))) {
- throw new ResourceConflictException("group '" + name
- + "' already exists");
+ if (name.toLowerCase(Locale.US)
+ .equals(createGroupArgs.getGroupName().toLowerCase(Locale.US))) {
+ throw new ResourceConflictException("group '" + name + "' already exists");
}
}
for (String name : systemGroupBackend.getReservedNames()) {
- if (name.toLowerCase(Locale.US).equals(
- createGroupArgs.getGroupName().toLowerCase(Locale.US))) {
- throw new ResourceConflictException("group name '" + name
- + "' is reserved");
+ if (name.toLowerCase(Locale.US)
+ .equals(createGroupArgs.getGroupName().toLowerCase(Locale.US))) {
+ throw new ResourceConflictException("group name '" + name + "' is reserved");
}
}
@@ -192,10 +187,8 @@
AccountGroup.UUID uuid =
GroupUUID.make(
createGroupArgs.getGroupName(),
- self.get().newCommitterIdent(serverIdent.getWhen(),
- serverIdent.getTimeZone()));
- AccountGroup group =
- new AccountGroup(createGroupArgs.getGroup(), groupId, uuid);
+ self.get().newCommitterIdent(serverIdent.getWhen(), serverIdent.getTimeZone()));
+ AccountGroup group = new AccountGroup(createGroupArgs.getGroup(), groupId, uuid);
group.setVisibleToAll(createGroupArgs.visibleToAll);
if (createGroupArgs.ownerGroupId != null) {
AccountGroup ownerGroup = groupCache.get(createGroupArgs.ownerGroupId);
@@ -212,8 +205,8 @@
try {
db.accountGroupNames().insert(Collections.singleton(gn));
} catch (OrmDuplicateKeyException e) {
- throw new ResourceConflictException("group '"
- + createGroupArgs.getGroupName() + "' already exists");
+ throw new ResourceConflictException(
+ "group '" + createGroupArgs.getGroupName() + "' already exists");
}
db.accountGroups().insert(Collections.singleton(group));
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/group/DbGroupMemberAuditListener.java b/gerrit-server/src/main/java/com/google/gerrit/server/group/DbGroupMemberAuditListener.java
index 23d2b59..f88460b 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/group/DbGroupMemberAuditListener.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/group/DbGroupMemberAuditListener.java
@@ -30,17 +30,15 @@
import com.google.gwtorm.server.OrmException;
import com.google.gwtorm.server.SchemaFactory;
import com.google.inject.Inject;
-
-import org.slf4j.Logger;
-
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
+import org.slf4j.Logger;
class DbGroupMemberAuditListener implements GroupMemberAuditListener {
- private static final Logger log = org.slf4j.LoggerFactory
- .getLogger(DbGroupMemberAuditListener.class);
+ private static final Logger log =
+ org.slf4j.LoggerFactory.getLogger(DbGroupMemberAuditListener.class);
private final SchemaFactory<ReviewDb> schema;
private final AccountCache accountCache;
@@ -48,8 +46,10 @@
private final UniversalGroupBackend groupBackend;
@Inject
- DbGroupMemberAuditListener(SchemaFactory<ReviewDb> schema,
- AccountCache accountCache, GroupCache groupCache,
+ DbGroupMemberAuditListener(
+ SchemaFactory<ReviewDb> schema,
+ AccountCache accountCache,
+ GroupCache groupCache,
UniversalGroupBackend groupBackend) {
this.schema = schema;
this.accountCache = accountCache;
@@ -58,33 +58,29 @@
}
@Override
- public void onAddAccountsToGroup(Account.Id me,
- Collection<AccountGroupMember> added) {
+ public void onAddAccountsToGroup(Account.Id me, Collection<AccountGroupMember> added) {
List<AccountGroupMemberAudit> auditInserts = new ArrayList<>();
for (AccountGroupMember m : added) {
- AccountGroupMemberAudit audit =
- new AccountGroupMemberAudit(m, me, TimeUtil.nowTs());
+ AccountGroupMemberAudit audit = new AccountGroupMemberAudit(m, me, TimeUtil.nowTs());
auditInserts.add(audit);
}
try (ReviewDb db = schema.open()) {
db.accountGroupMembersAudit().insert(auditInserts);
} catch (OrmException e) {
logOrmExceptionForAccounts(
- "Cannot log add accounts to group event performed by user", me,
- added, e);
+ "Cannot log add accounts to group event performed by user", me, added, e);
}
}
@Override
- public void onDeleteAccountsFromGroup(Account.Id me,
- Collection<AccountGroupMember> removed) {
+ public void onDeleteAccountsFromGroup(Account.Id me, Collection<AccountGroupMember> removed) {
List<AccountGroupMemberAudit> auditInserts = new ArrayList<>();
List<AccountGroupMemberAudit> auditUpdates = new ArrayList<>();
try (ReviewDb db = schema.open()) {
for (AccountGroupMember m : removed) {
AccountGroupMemberAudit audit = null;
- for (AccountGroupMemberAudit a : db.accountGroupMembersAudit()
- .byGroupAccount(m.getAccountGroupId(), m.getAccountId())) {
+ for (AccountGroupMemberAudit a :
+ db.accountGroupMembersAudit().byGroupAccount(m.getAccountGroupId(), m.getAccountId())) {
if (a.isActive()) {
audit = a;
break;
@@ -104,38 +100,33 @@
db.accountGroupMembersAudit().insert(auditInserts);
} catch (OrmException e) {
logOrmExceptionForAccounts(
- "Cannot log delete accounts from group event performed by user", me,
- removed, e);
+ "Cannot log delete accounts from group event performed by user", me, removed, e);
}
}
@Override
- public void onAddGroupsToGroup(Account.Id me,
- Collection<AccountGroupById> added) {
+ public void onAddGroupsToGroup(Account.Id me, Collection<AccountGroupById> added) {
List<AccountGroupByIdAud> includesAudit = new ArrayList<>();
for (AccountGroupById groupInclude : added) {
- AccountGroupByIdAud audit =
- new AccountGroupByIdAud(groupInclude, me, TimeUtil.nowTs());
+ AccountGroupByIdAud audit = new AccountGroupByIdAud(groupInclude, me, TimeUtil.nowTs());
includesAudit.add(audit);
}
try (ReviewDb db = schema.open()) {
db.accountGroupByIdAud().insert(includesAudit);
} catch (OrmException e) {
logOrmExceptionForGroups(
- "Cannot log add groups to group event performed by user", me, added,
- e);
+ "Cannot log add groups to group event performed by user", me, added, e);
}
}
@Override
- public void onDeleteGroupsFromGroup(Account.Id me,
- Collection<AccountGroupById> removed) {
+ public void onDeleteGroupsFromGroup(Account.Id me, Collection<AccountGroupById> removed) {
final List<AccountGroupByIdAud> auditUpdates = new ArrayList<>();
try (ReviewDb db = schema.open()) {
for (final AccountGroupById g : removed) {
AccountGroupByIdAud audit = null;
- for (AccountGroupByIdAud a : db.accountGroupByIdAud()
- .byGroupInclude(g.getGroupId(), g.getIncludeUUID())) {
+ for (AccountGroupByIdAud a :
+ db.accountGroupByIdAud().byGroupInclude(g.getGroupId(), g.getIncludeUUID())) {
if (a.isActive()) {
audit = a;
break;
@@ -150,13 +141,12 @@
db.accountGroupByIdAud().update(auditUpdates);
} catch (OrmException e) {
logOrmExceptionForGroups(
- "Cannot log delete groups from group event performed by user", me,
- removed, e);
+ "Cannot log delete groups from group event performed by user", me, removed, e);
}
}
- private void logOrmExceptionForAccounts(String header, Account.Id me,
- Collection<AccountGroupMember> values, OrmException e) {
+ private void logOrmExceptionForAccounts(
+ String header, Account.Id me, Collection<AccountGroupMember> values, OrmException e) {
List<String> descriptions = new ArrayList<>();
for (AccountGroupMember m : values) {
Account.Id accountId = m.getAccountId();
@@ -164,14 +154,15 @@
AccountGroup.Id groupId = m.getAccountGroupId();
String groupName = groupCache.get(groupId).getName();
- descriptions.add(MessageFormat.format("account {0}/{1}, group {2}/{3}",
- accountId, userName, groupId, groupName));
+ descriptions.add(
+ MessageFormat.format(
+ "account {0}/{1}, group {2}/{3}", accountId, userName, groupId, groupName));
}
logOrmException(header, me, descriptions, e);
}
- private void logOrmExceptionForGroups(String header, Account.Id me,
- Collection<AccountGroupById> values, OrmException e) {
+ private void logOrmExceptionForGroups(
+ String header, Account.Id me, Collection<AccountGroupById> values, OrmException e) {
List<String> descriptions = new ArrayList<>();
for (AccountGroupById m : values) {
AccountGroup.UUID groupUuid = m.getIncludeUUID();
@@ -179,14 +170,15 @@
AccountGroup.Id targetGroupId = m.getGroupId();
String targetGroupName = groupCache.get(targetGroupId).getName();
- descriptions.add(MessageFormat.format("group {0}/{1}, group {2}/{3}",
- groupUuid, groupName, targetGroupId, targetGroupName));
+ descriptions.add(
+ MessageFormat.format(
+ "group {0}/{1}, group {2}/{3}",
+ groupUuid, groupName, targetGroupId, targetGroupName));
}
logOrmException(header, me, descriptions, e);
}
- private void logOrmException(String header, Account.Id me,
- Iterable<?> values, OrmException e) {
+ private void logOrmException(String header, Account.Id me, Iterable<?> values, OrmException e) {
StringBuilder message = new StringBuilder(header);
message.append(" ");
message.append(me);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/group/DeleteIncludedGroups.java b/gerrit-server/src/main/java/com/google/gerrit/server/group/DeleteIncludedGroups.java
index 3985c80..9f612bf 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/group/DeleteIncludedGroups.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/group/DeleteIncludedGroups.java
@@ -34,7 +34,6 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@@ -49,9 +48,12 @@
private final AuditService auditService;
@Inject
- DeleteIncludedGroups(GroupsCollection groupsCollection,
- GroupIncludeCache groupIncludeCache, Provider<ReviewDb> db,
- Provider<CurrentUser> self, AuditService auditService) {
+ DeleteIncludedGroups(
+ GroupsCollection groupsCollection,
+ GroupIncludeCache groupIncludeCache,
+ Provider<ReviewDb> db,
+ Provider<CurrentUser> self,
+ AuditService auditService) {
this.groupsCollection = groupsCollection;
this.groupIncludeCache = groupIncludeCache;
this.db = db;
@@ -61,8 +63,7 @@
@Override
public Response<?> apply(GroupResource resource, Input input)
- throws AuthException, MethodNotAllowedException,
- UnprocessableEntityException, OrmException {
+ throws AuthException, MethodNotAllowedException, UnprocessableEntityException, OrmException {
AccountGroup internalGroup = resource.toAccountGroup();
if (internalGroup == null) {
throw new MethodNotAllowedException();
@@ -70,14 +71,14 @@
input = Input.init(input);
final GroupControl control = resource.getControl();
- final Map<AccountGroup.UUID, AccountGroupById> includedGroups = getIncludedGroups(internalGroup.getId());
+ final Map<AccountGroup.UUID, AccountGroupById> includedGroups =
+ getIncludedGroups(internalGroup.getId());
final List<AccountGroupById> toRemove = new ArrayList<>();
for (final String includedGroup : input.groups) {
GroupDescription.Basic d = groupsCollection.parse(includedGroup);
if (!control.canRemoveGroup()) {
- throw new AuthException(String.format("Cannot delete group: %s",
- d.getName()));
+ throw new AuthException(String.format("Cannot delete group: %s", d.getName()));
}
AccountGroupById g = includedGroups.remove(d.getGroupUUID());
@@ -98,8 +99,8 @@
return Response.none();
}
- private Map<AccountGroup.UUID, AccountGroupById> getIncludedGroups(
- final AccountGroup.Id groupId) throws OrmException {
+ private Map<AccountGroup.UUID, AccountGroupById> getIncludedGroups(final AccountGroup.Id groupId)
+ throws OrmException {
final Map<AccountGroup.UUID, AccountGroupById> groups = new HashMap<>();
for (AccountGroupById g : db.get().accountGroupById().byGroup(groupId)) {
groups.put(g.getIncludeUUID(), g);
@@ -113,10 +114,9 @@
}
@Singleton
- static class DeleteIncludedGroup implements
- RestModifyView<IncludedGroupResource, DeleteIncludedGroup.Input> {
- static class Input {
- }
+ static class DeleteIncludedGroup
+ implements RestModifyView<IncludedGroupResource, DeleteIncludedGroup.Input> {
+ static class Input {}
private final Provider<DeleteIncludedGroups> delete;
@@ -127,8 +127,8 @@
@Override
public Response<?> apply(IncludedGroupResource resource, Input input)
- throws AuthException, MethodNotAllowedException,
- UnprocessableEntityException, OrmException {
+ throws AuthException, MethodNotAllowedException, UnprocessableEntityException,
+ OrmException {
AddIncludedGroups.Input in = new AddIncludedGroups.Input();
in.groups = ImmutableList.of(resource.getMember().get());
return delete.get().apply(resource, in);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/group/DeleteMembers.java b/gerrit-server/src/main/java/com/google/gerrit/server/group/DeleteMembers.java
index 107f1bb..e365ce3 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/group/DeleteMembers.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/group/DeleteMembers.java
@@ -33,7 +33,6 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
@@ -49,8 +48,10 @@
private final AuditService auditService;
@Inject
- DeleteMembers(AccountsCollection accounts,
- AccountCache accountCache, Provider<ReviewDb> db,
+ DeleteMembers(
+ AccountsCollection accounts,
+ AccountCache accountCache,
+ Provider<ReviewDb> db,
Provider<CurrentUser> self,
AuditService auditService) {
this.accounts = accounts;
@@ -62,8 +63,8 @@
@Override
public Response<?> apply(GroupResource resource, Input input)
- throws AuthException, MethodNotAllowedException,
- UnprocessableEntityException, OrmException, IOException {
+ throws AuthException, MethodNotAllowedException, UnprocessableEntityException, OrmException,
+ IOException {
AccountGroup internalGroup = resource.toAccountGroup();
if (internalGroup == null) {
throw new MethodNotAllowedException();
@@ -101,11 +102,10 @@
auditService.dispatchDeleteAccountsFromGroup(me, toRemove);
}
- private Map<Account.Id, AccountGroupMember> getMembers(
- final AccountGroup.Id groupId) throws OrmException {
+ private Map<Account.Id, AccountGroupMember> getMembers(final AccountGroup.Id groupId)
+ throws OrmException {
final Map<Account.Id, AccountGroupMember> members = new HashMap<>();
- for (final AccountGroupMember m : db.get().accountGroupMembers()
- .byGroup(groupId)) {
+ for (final AccountGroupMember m : db.get().accountGroupMembers().byGroup(groupId)) {
members.put(m.getAccountId(), m);
}
return members;
@@ -113,8 +113,7 @@
@Singleton
static class DeleteMember implements RestModifyView<MemberResource, DeleteMember.Input> {
- static class Input {
- }
+ static class Input {}
private final Provider<DeleteMembers> delete;
@@ -125,8 +124,8 @@
@Override
public Response<?> apply(MemberResource resource, Input input)
- throws AuthException, MethodNotAllowedException,
- UnprocessableEntityException, OrmException, IOException {
+ throws AuthException, MethodNotAllowedException, UnprocessableEntityException, OrmException,
+ IOException {
AddMembers.Input in = new AddMembers.Input();
in._oneMember = resource.getMember().getAccountId().toString();
return delete.get().apply(resource, in);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/group/GetAuditLog.java b/gerrit-server/src/main/java/com/google/gerrit/server/group/GetAuditLog.java
index f9ae694..e29b37f 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/group/GetAuditLog.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/group/GetAuditLog.java
@@ -35,7 +35,6 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
@@ -50,7 +49,8 @@
private final GroupBackend groupBackend;
@Inject
- public GetAuditLog(Provider<ReviewDb> db,
+ public GetAuditLog(
+ Provider<ReviewDb> db,
AccountLoader.Factory accountLoaderFactory,
GroupCache groupCache,
GroupJson groupJson,
@@ -64,16 +64,14 @@
@Override
public List<? extends GroupAuditEventInfo> apply(GroupResource rsrc)
- throws AuthException, ResourceNotFoundException,
- MethodNotAllowedException, OrmException {
+ throws AuthException, ResourceNotFoundException, MethodNotAllowedException, OrmException {
if (rsrc.toAccountGroup() == null) {
throw new MethodNotAllowedException();
} else if (!rsrc.getControl().isOwner()) {
throw new AuthException("Not group owner");
}
- AccountGroup group = db.get().accountGroups().get(
- rsrc.toAccountGroup().getId());
+ AccountGroup group = db.get().accountGroups().get(rsrc.toAccountGroup().getId());
if (group == null) {
throw new ResourceNotFoundException();
}
@@ -83,17 +81,19 @@
List<GroupAuditEventInfo> auditEvents = new ArrayList<>();
for (AccountGroupMemberAudit auditEvent :
- db.get().accountGroupMembersAudit().byGroup(group.getId()).toList()) {
+ db.get().accountGroupMembersAudit().byGroup(group.getId()).toList()) {
AccountInfo member = accountLoader.get(auditEvent.getKey().getParentKey());
- auditEvents.add(GroupAuditEventInfo.createAddUserEvent(
- accountLoader.get(auditEvent.getAddedBy()),
- auditEvent.getKey().getAddedOn(), member));
+ auditEvents.add(
+ GroupAuditEventInfo.createAddUserEvent(
+ accountLoader.get(auditEvent.getAddedBy()),
+ auditEvent.getKey().getAddedOn(),
+ member));
if (!auditEvent.isActive()) {
- auditEvents.add(GroupAuditEventInfo.createRemoveUserEvent(
- accountLoader.get(auditEvent.getRemovedBy()),
- auditEvent.getRemovedOn(), member));
+ auditEvents.add(
+ GroupAuditEventInfo.createRemoveUserEvent(
+ accountLoader.get(auditEvent.getRemovedBy()), auditEvent.getRemovedOn(), member));
}
}
@@ -105,33 +105,36 @@
if (includedGroup != null) {
member = groupJson.format(GroupDescriptions.forAccountGroup(includedGroup));
} else {
- GroupDescription.Basic groupDescription =
- groupBackend.get(includedGroupUUID);
+ GroupDescription.Basic groupDescription = groupBackend.get(includedGroupUUID);
member = new GroupInfo();
member.id = Url.encode(includedGroupUUID.get());
member.name = groupDescription.getName();
}
- auditEvents.add(GroupAuditEventInfo.createAddGroupEvent(
- accountLoader.get(auditEvent.getAddedBy()),
- auditEvent.getKey().getAddedOn(), member));
+ auditEvents.add(
+ GroupAuditEventInfo.createAddGroupEvent(
+ accountLoader.get(auditEvent.getAddedBy()),
+ auditEvent.getKey().getAddedOn(),
+ member));
if (!auditEvent.isActive()) {
- auditEvents.add(GroupAuditEventInfo.createRemoveGroupEvent(
- accountLoader.get(auditEvent.getRemovedBy()),
- auditEvent.getRemovedOn(), member));
+ auditEvents.add(
+ GroupAuditEventInfo.createRemoveGroupEvent(
+ accountLoader.get(auditEvent.getRemovedBy()), auditEvent.getRemovedOn(), member));
}
}
accountLoader.fill();
// sort by date in reverse order so that the newest audit event comes first
- Collections.sort(auditEvents, new Comparator<GroupAuditEventInfo>() {
- @Override
- public int compare(GroupAuditEventInfo e1, GroupAuditEventInfo e2) {
- return e2.date.compareTo(e1.date);
- }
- });
+ Collections.sort(
+ auditEvents,
+ new Comparator<GroupAuditEventInfo>() {
+ @Override
+ public int compare(GroupAuditEventInfo e1, GroupAuditEventInfo e2) {
+ return e2.date.compareTo(e1.date);
+ }
+ });
return auditEvents;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/group/GetDetail.java b/gerrit-server/src/main/java/com/google/gerrit/server/group/GetDetail.java
index 615c862..47fe319 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/group/GetDetail.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/group/GetDetail.java
@@ -27,8 +27,7 @@
@Inject
GetDetail(GroupJson json) {
- this.json = json.addOption(ListGroupsOption.MEMBERS)
- .addOption(ListGroupsOption.INCLUDES);
+ this.json = json.addOption(ListGroupsOption.MEMBERS).addOption(ListGroupsOption.INCLUDES);
}
@Override
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/group/GetIncludedGroup.java b/gerrit-server/src/main/java/com/google/gerrit/server/group/GetIncludedGroup.java
index dbc2e0c..4cf0cb2 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/group/GetIncludedGroup.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/group/GetIncludedGroup.java
@@ -21,7 +21,7 @@
import com.google.inject.Singleton;
@Singleton
-public class GetIncludedGroup implements RestReadView<IncludedGroupResource> {
+public class GetIncludedGroup implements RestReadView<IncludedGroupResource> {
private final GroupJson json;
@Inject
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/group/GroupJson.java b/gerrit-server/src/main/java/com/google/gerrit/server/group/GroupJson.java
index 8f339de..43e70ff 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/group/GroupJson.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/group/GroupJson.java
@@ -31,7 +31,6 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
-
import java.util.Collection;
import java.util.EnumSet;
@@ -52,7 +51,8 @@
private EnumSet<ListGroupsOption> options;
@Inject
- GroupJson(GroupBackend groupBackend,
+ GroupJson(
+ GroupBackend groupBackend,
GroupControl.Factory groupControlFactory,
Provider<ListMembers> listMembers,
Provider<ListIncludedGroups> listIncludes) {
@@ -83,8 +83,7 @@
public GroupInfo format(GroupDescription.Basic group) throws OrmException {
GroupInfo info = init(group);
if (options.contains(MEMBERS) || options.contains(INCLUDES)) {
- GroupResource rsrc =
- new GroupResource(groupControlFactory.controlFor(group));
+ GroupResource rsrc = new GroupResource(groupControlFactory.controlFor(group));
initMembersAndIncludes(rsrc, info);
}
return info;
@@ -113,8 +112,7 @@
return info;
}
- private GroupInfo initMembersAndIncludes(GroupResource rsrc, GroupInfo info)
- throws OrmException {
+ private GroupInfo initMembersAndIncludes(GroupResource rsrc, GroupInfo info) throws OrmException {
if (rsrc.toAccountGroup() == null) {
return info;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/group/GroupsCollection.java b/gerrit-server/src/main/java/com/google/gerrit/server/group/GroupsCollection.java
index 72c29d0..397bf08 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/group/GroupsCollection.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/group/GroupsCollection.java
@@ -39,9 +39,10 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
-public class GroupsCollection implements
- RestCollection<TopLevelResource, GroupResource>,
- AcceptsCreate<TopLevelResource>, NeedsParams {
+public class GroupsCollection
+ implements RestCollection<TopLevelResource, GroupResource>,
+ AcceptsCreate<TopLevelResource>,
+ NeedsParams {
private final DynamicMap<RestView<GroupResource>> views;
private final Provider<ListGroups> list;
private final Provider<QueryGroups> queryGroups;
@@ -53,7 +54,8 @@
private boolean hasQuery2;
@Inject
- GroupsCollection(DynamicMap<RestView<GroupResource>> views,
+ GroupsCollection(
+ DynamicMap<RestView<GroupResource>> views,
Provider<ListGroups> list,
Provider<QueryGroups> queryGroups,
CreateGroup.Factory createGroup,
@@ -70,11 +72,9 @@
}
@Override
- public void setParams(ListMultimap<String, String> params)
- throws BadRequestException {
+ public void setParams(ListMultimap<String, String> params) throws BadRequestException {
if (params.containsKey("query") && params.containsKey("query2")) {
- throw new BadRequestException(
- "\"query\" and \"query2\" options are mutually exclusive");
+ throw new BadRequestException("\"query\" and \"query2\" options are mutually exclusive");
}
// The --query2 option is defined in QueryGroups
@@ -82,8 +82,7 @@
}
@Override
- public RestView<TopLevelResource> list() throws ResourceNotFoundException,
- AuthException {
+ public RestView<TopLevelResource> list() throws ResourceNotFoundException, AuthException {
final CurrentUser user = self.get();
if (user instanceof AnonymousUser) {
throw new AuthException("Authentication required");
@@ -122,49 +121,40 @@
/**
* Parses a group ID from a request body and returns the group.
*
- * @param id ID of the group, can be a group UUID, a group name or a legacy
- * group ID
+ * @param id ID of the group, can be a group UUID, a group name or a legacy group ID
* @return the group
- * @throws UnprocessableEntityException thrown if the group ID cannot be
- * resolved or if the group is not visible to the calling user
+ * @throws UnprocessableEntityException thrown if the group ID cannot be resolved or if the group
+ * is not visible to the calling user
*/
- public GroupDescription.Basic parse(String id)
- throws UnprocessableEntityException {
+ public GroupDescription.Basic parse(String id) throws UnprocessableEntityException {
GroupDescription.Basic group = parseId(id);
if (group == null || !groupControlFactory.controlFor(group).isVisible()) {
- throw new UnprocessableEntityException(String.format(
- "Group Not Found: %s", id));
+ throw new UnprocessableEntityException(String.format("Group Not Found: %s", id));
}
return group;
}
/**
- * Parses a group ID from a request body and returns the group if it is a
- * Gerrit internal group.
+ * Parses a group ID from a request body and returns the group if it is a Gerrit internal group.
*
- * @param id ID of the group, can be a group UUID, a group name or a legacy
- * group ID
+ * @param id ID of the group, can be a group UUID, a group name or a legacy group ID
* @return the group
- * @throws UnprocessableEntityException thrown if the group ID cannot be
- * resolved, if the group is not visible to the calling user or if
- * it's an external group
+ * @throws UnprocessableEntityException thrown if the group ID cannot be resolved, if the group is
+ * not visible to the calling user or if it's an external group
*/
- public GroupDescription.Basic parseInternal(String id)
- throws UnprocessableEntityException {
+ public GroupDescription.Basic parseInternal(String id) throws UnprocessableEntityException {
GroupDescription.Basic group = parse(id);
if (GroupDescriptions.toAccountGroup(group) == null) {
- throw new UnprocessableEntityException(String.format(
- "External Group Not Allowed: %s", id));
+ throw new UnprocessableEntityException(String.format("External Group Not Allowed: %s", id));
}
return group;
}
/**
- * Parses a group ID and returns the group without making any permission
- * check whether the current user can see the group.
+ * Parses a group ID and returns the group without making any permission check whether the current
+ * user can see the group.
*
- * @param id ID of the group, can be a group UUID, a group name or a legacy
- * group ID
+ * @param id ID of the group, can be a group UUID, a group name or a legacy group ID
* @return the group, null if no group is found for the given group ID
*/
public GroupDescription.Basic parseId(String id) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/group/IncludedGroupResource.java b/gerrit-server/src/main/java/com/google/gerrit/server/group/IncludedGroupResource.java
index 7975f24..467de4c 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/group/IncludedGroupResource.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/group/IncludedGroupResource.java
@@ -25,8 +25,7 @@
private final GroupDescription.Basic member;
- public IncludedGroupResource(GroupResource group,
- GroupDescription.Basic member) {
+ public IncludedGroupResource(GroupResource group, GroupDescription.Basic member) {
super(group);
this.member = member;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/group/IncludedGroupsCollection.java b/gerrit-server/src/main/java/com/google/gerrit/server/group/IncludedGroupsCollection.java
index 8d0831d..865f8b5 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/group/IncludedGroupsCollection.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/group/IncludedGroupsCollection.java
@@ -34,9 +34,8 @@
import com.google.inject.Singleton;
@Singleton
-public class IncludedGroupsCollection implements
- ChildCollection<GroupResource, IncludedGroupResource>,
- AcceptsCreate<GroupResource> {
+public class IncludedGroupsCollection
+ implements ChildCollection<GroupResource, IncludedGroupResource>, AcceptsCreate<GroupResource> {
private final DynamicMap<RestView<IncludedGroupResource>> views;
private final ListIncludedGroups list;
private final GroupsCollection groupsCollection;
@@ -44,7 +43,8 @@
private final AddIncludedGroups put;
@Inject
- IncludedGroupsCollection(DynamicMap<RestView<IncludedGroupResource>> views,
+ IncludedGroupsCollection(
+ DynamicMap<RestView<IncludedGroupResource>> views,
ListIncludedGroups list,
GroupsCollection groupsCollection,
Provider<ReviewDb> dbProvider,
@@ -63,8 +63,7 @@
@Override
public IncludedGroupResource parse(GroupResource resource, IdString id)
- throws MethodNotAllowedException, AuthException,
- ResourceNotFoundException, OrmException {
+ throws MethodNotAllowedException, AuthException, ResourceNotFoundException, OrmException {
AccountGroup parent = resource.toAccountGroup();
if (parent == null) {
throw new MethodNotAllowedException();
@@ -72,19 +71,18 @@
GroupDescription.Basic member =
groupsCollection.parse(TopLevelResource.INSTANCE, id).getGroup();
- if (isMember(parent, member)
- && resource.getControl().canSeeGroup()) {
+ if (isMember(parent, member) && resource.getControl().canSeeGroup()) {
return new IncludedGroupResource(resource, member);
}
throw new ResourceNotFoundException(id);
}
- private boolean isMember(AccountGroup parent, GroupDescription.Basic member)
- throws OrmException {
- return dbProvider.get().accountGroupById().get(
- new AccountGroupById.Key(
- parent.getId(),
- member.getGroupUUID())) != null;
+ private boolean isMember(AccountGroup parent, GroupDescription.Basic member) throws OrmException {
+ return dbProvider
+ .get()
+ .accountGroupById()
+ .get(new AccountGroupById.Key(parent.getId(), member.getGroupUUID()))
+ != null;
}
@SuppressWarnings("unchecked")
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/group/Index.java b/gerrit-server/src/main/java/com/google/gerrit/server/group/Index.java
index 5a8978a..b7b98b2 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/group/Index.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/group/Index.java
@@ -24,13 +24,11 @@
import com.google.gerrit.server.group.Index.Input;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
import java.io.IOException;
@Singleton
public class Index implements RestModifyView<GroupResource, Input> {
- public static class Input {
- }
+ public static class Input {}
private final GroupCache groupCache;
@@ -48,8 +46,8 @@
AccountGroup group = GroupDescriptions.toAccountGroup(rsrc.getGroup());
if (group == null) {
- throw new UnprocessableEntityException(String
- .format("External Group Not Allowed: %s", rsrc.getGroupUUID().get()));
+ throw new UnprocessableEntityException(
+ String.format("External Group Not Allowed: %s", rsrc.getGroupUUID().get()));
}
// evicting the group from the cache, reindexes the group
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/group/ListGroups.java b/gerrit-server/src/main/java/com/google/gerrit/server/group/ListGroups.java
index 80a639b..9bf14e7 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/group/ListGroups.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/group/ListGroups.java
@@ -41,9 +41,6 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
-
-import org.kohsuke.args4j.Option;
-
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
@@ -56,6 +53,7 @@
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
+import org.kohsuke.args4j.Option;
/** List groups visible to the calling user. */
public class ListGroups implements RestReadView<TopLevelResource> {
@@ -72,8 +70,7 @@
private final GroupJson json;
private final GroupBackend groupBackend;
- private EnumSet<ListGroupsOption> options =
- EnumSet.noneOf(ListGroupsOption.class);
+ private EnumSet<ListGroupsOption> options = EnumSet.noneOf(ListGroupsOption.class);
private boolean visibleToAll;
private Account.Id user;
private boolean owned;
@@ -82,31 +79,42 @@
private String matchSubstring;
private String suggest;
- @Option(name = "--project", aliases = {"-p"},
- usage = "projects for which the groups should be listed")
+ @Option(
+ name = "--project",
+ aliases = {"-p"},
+ usage = "projects for which the groups should be listed"
+ )
public void addProject(ProjectControl project) {
projects.add(project);
}
- @Option(name = "--visible-to-all",
- usage = "to list only groups that are visible to all registered users")
+ @Option(
+ name = "--visible-to-all",
+ usage = "to list only groups that are visible to all registered users"
+ )
public void setVisibleToAll(boolean visibleToAll) {
this.visibleToAll = visibleToAll;
}
- @Option(name = "--user", aliases = {"-u"},
- usage = "user for which the groups should be listed")
+ @Option(
+ name = "--user",
+ aliases = {"-u"},
+ usage = "user for which the groups should be listed"
+ )
public void setUser(Account.Id user) {
this.user = user;
}
- @Option(name = "--owned", usage = "to list only groups that are owned by the"
- + " specified user or by the calling user if no user was specifed")
+ @Option(
+ name = "--owned",
+ usage =
+ "to list only groups that are owned by the"
+ + " specified user or by the calling user if no user was specifed"
+ )
public void setOwned(boolean owned) {
this.owned = owned;
}
-
/**
* Add a group to inspect.
*
@@ -114,37 +122,59 @@
* @deprecated use {@link #addGroup(AccountGroup.UUID)}.
*/
@Deprecated
- @Option(name = "--query", aliases = {"-q"},
- usage = "group to inspect (deprecated: use --group/-g instead)")
+ @Option(
+ name = "--query",
+ aliases = {"-q"},
+ usage = "group to inspect (deprecated: use --group/-g instead)"
+ )
void addGroup_Deprecated(AccountGroup.UUID uuid) {
addGroup(uuid);
}
- @Option(name = "--group", aliases = {"-g"}, usage = "group to inspect")
+ @Option(
+ name = "--group",
+ aliases = {"-g"},
+ usage = "group to inspect"
+ )
public void addGroup(AccountGroup.UUID uuid) {
groupsToInspect.add(uuid);
}
- @Option(name = "--limit", aliases = {"-n"}, metaVar = "CNT",
- usage = "maximum number of groups to list")
+ @Option(
+ name = "--limit",
+ aliases = {"-n"},
+ metaVar = "CNT",
+ usage = "maximum number of groups to list"
+ )
public void setLimit(int limit) {
this.limit = limit;
}
- @Option(name = "--start", aliases = {"-S"}, metaVar = "CNT",
- usage = "number of groups to skip")
+ @Option(
+ name = "--start",
+ aliases = {"-S"},
+ metaVar = "CNT",
+ usage = "number of groups to skip"
+ )
public void setStart(int start) {
this.start = start;
}
- @Option(name = "--match", aliases = {"-m"}, metaVar = "MATCH",
- usage = "match group substring")
+ @Option(
+ name = "--match",
+ aliases = {"-m"},
+ metaVar = "MATCH",
+ usage = "match group substring"
+ )
public void setMatchSubstring(String matchSubstring) {
this.matchSubstring = matchSubstring;
}
- @Option(name = "--suggest", aliases = {"-s"},
- usage = "to get a suggestion of groups")
+ @Option(
+ name = "--suggest",
+ aliases = {"-s"},
+ usage = "to get a suggestion of groups"
+ )
public void setSuggest(String suggest) {
this.suggest = suggest;
}
@@ -160,7 +190,8 @@
}
@Inject
- protected ListGroups(final GroupCache groupCache,
+ protected ListGroups(
+ final GroupCache groupCache,
final GroupControl.Factory groupControlFactory,
final GroupControl.GenericFactory genericGroupControlFactory,
final Provider<IdentifiedUser> identifiedUser,
@@ -195,9 +226,7 @@
throws OrmException, BadRequestException {
SortedMap<String, GroupInfo> output = new TreeMap<>();
for (GroupInfo info : get()) {
- output.put(MoreObjects.firstNonNull(
- info.name,
- "Group " + Url.decode(info.id)), info);
+ output.put(MoreObjects.firstNonNull(info.name, "Group " + Url.decode(info.id)), info);
info.name = null;
}
return output;
@@ -209,13 +238,11 @@
}
if (owned) {
- return getGroupsOwnedBy(
- user != null ? userFactory.create(user) : identifiedUser.get());
+ return getGroupsOwnedBy(user != null ? userFactory.create(user) : identifiedUser.get());
}
if (user != null) {
- return accountGetGroups.apply(
- new AccountResource(userFactory.create(user)));
+ return accountGetGroups.apply(new AccountResource(userFactory.create(user)));
}
return getAllGroups();
@@ -249,8 +276,7 @@
if (limit > 0 && ++found > limit) {
break;
}
- groupInfos.add(json.addOptions(options).format(
- GroupDescriptions.forAccountGroup(group)));
+ groupInfos.add(json.addOptions(options).format(GroupDescriptions.forAccountGroup(group)));
}
return groupInfos;
}
@@ -261,10 +287,11 @@
"You should only have no more than one --project and -n with --suggest");
}
- List<GroupReference> groupRefs = Lists.newArrayList(Iterables.limit(
- groupBackend.suggest(
- suggest, Iterables.getFirst(projects, null)),
- limit <= 0 ? 10 : Math.min(limit, 10)));
+ List<GroupReference> groupRefs =
+ Lists.newArrayList(
+ Iterables.limit(
+ groupBackend.suggest(suggest, Iterables.getFirst(projects, null)),
+ limit <= 0 ? 10 : Math.min(limit, 10)));
List<GroupInfo> groupInfos = Lists.newArrayListWithCapacity(groupRefs.size());
for (final GroupReference ref : groupRefs) {
@@ -304,16 +331,14 @@
return false;
}
- private List<GroupInfo> getGroupsOwnedBy(IdentifiedUser user)
- throws OrmException {
+ private List<GroupInfo> getGroupsOwnedBy(IdentifiedUser user) throws OrmException {
List<GroupInfo> groups = new ArrayList<>();
int found = 0;
int foundIndex = 0;
for (AccountGroup g : filterGroups(groupCache.all())) {
GroupControl ctl = groupControlFactory.controlFor(g);
try {
- if (genericGroupControlFactory.controlFor(user, g.getGroupUUID())
- .isOwner()) {
+ if (genericGroupControlFactory.controlFor(user, g.getGroupUUID()).isOwner()) {
if (foundIndex++ < start) {
continue;
}
@@ -331,11 +356,12 @@
private List<AccountGroup> filterGroups(Collection<AccountGroup> groups) {
List<AccountGroup> filteredGroups = new ArrayList<>(groups.size());
- boolean isAdmin =
- identifiedUser.get().getCapabilities().canAdministrateServer();
+ boolean isAdmin = identifiedUser.get().getCapabilities().canAdministrateServer();
for (AccountGroup group : groups) {
if (!Strings.isNullOrEmpty(matchSubstring)) {
- if (!group.getName().toLowerCase(Locale.US)
+ if (!group
+ .getName()
+ .toLowerCase(Locale.US)
.contains(matchSubstring.toLowerCase(Locale.US))) {
continue;
}
@@ -343,8 +369,7 @@
if (visibleToAll && !group.isVisibleToAll()) {
continue;
}
- if (!groupsToInspect.isEmpty()
- && !groupsToInspect.contains(group.getGroupUUID())) {
+ if (!groupsToInspect.isEmpty() && !groupsToInspect.contains(group.getGroupUUID())) {
continue;
}
if (!isAdmin) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/group/ListIncludedGroups.java b/gerrit-server/src/main/java/com/google/gerrit/server/group/ListIncludedGroups.java
index 803c498..b4cac87 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/group/ListIncludedGroups.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/group/ListIncludedGroups.java
@@ -27,13 +27,11 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
-import org.slf4j.Logger;
-
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
+import org.slf4j.Logger;
@Singleton
public class ListIncludedGroups implements RestReadView<GroupResource> {
@@ -44,47 +42,48 @@
private final GroupJson json;
@Inject
- ListIncludedGroups(GroupControl.Factory controlFactory,
- Provider<ReviewDb> dbProvider, GroupJson json) {
+ ListIncludedGroups(
+ GroupControl.Factory controlFactory, Provider<ReviewDb> dbProvider, GroupJson json) {
this.controlFactory = controlFactory;
this.dbProvider = dbProvider;
this.json = json;
}
@Override
- public List<GroupInfo> apply(GroupResource rsrc)
- throws MethodNotAllowedException, OrmException {
+ public List<GroupInfo> apply(GroupResource rsrc) throws MethodNotAllowedException, OrmException {
if (rsrc.toAccountGroup() == null) {
throw new MethodNotAllowedException();
}
boolean ownerOfParent = rsrc.getControl().isOwner();
List<GroupInfo> included = new ArrayList<>();
- for (AccountGroupById u : dbProvider.get()
- .accountGroupById()
- .byGroup(rsrc.toAccountGroup().getId())) {
+ for (AccountGroupById u :
+ dbProvider.get().accountGroupById().byGroup(rsrc.toAccountGroup().getId())) {
try {
GroupControl i = controlFactory.controlFor(u.getIncludeUUID());
if (ownerOfParent || i.isVisible()) {
included.add(json.format(i.getGroup()));
}
} catch (NoSuchGroupException notFound) {
- log.warn(String.format("Group %s no longer available, included into %s",
- u.getIncludeUUID(),
- rsrc.getGroup().getName()));
+ log.warn(
+ String.format(
+ "Group %s no longer available, included into %s",
+ u.getIncludeUUID(), rsrc.getGroup().getName()));
continue;
}
}
- Collections.sort(included, new Comparator<GroupInfo>() {
- @Override
- public int compare(GroupInfo a, GroupInfo b) {
- int cmp = nullToEmpty(a.name).compareTo(nullToEmpty(b.name));
- if (cmp != 0) {
- return cmp;
- }
- return nullToEmpty(a.id).compareTo(nullToEmpty(b.id));
- }
- });
+ Collections.sort(
+ included,
+ new Comparator<GroupInfo>() {
+ @Override
+ public int compare(GroupInfo a, GroupInfo b) {
+ int cmp = nullToEmpty(a.name).compareTo(nullToEmpty(b.name));
+ if (cmp != 0) {
+ return cmp;
+ }
+ return nullToEmpty(a.id).compareTo(nullToEmpty(b.id));
+ }
+ });
return included;
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/group/ListMembers.java b/gerrit-server/src/main/java/com/google/gerrit/server/group/ListMembers.java
index 98d18ca..8e2c925 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/group/ListMembers.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/group/ListMembers.java
@@ -30,14 +30,12 @@
import com.google.gerrit.server.api.accounts.AccountInfoComparator;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
-
-import org.kohsuke.args4j.Option;
-
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
+import org.kohsuke.args4j.Option;
public class ListMembers implements RestReadView<GroupResource> {
private final GroupCache groupCache;
@@ -48,7 +46,8 @@
private boolean recursive;
@Inject
- protected ListMembers(GroupCache groupCache,
+ protected ListMembers(
+ GroupCache groupCache,
GroupDetailFactory.Factory groupDetailFactory,
AccountLoader.Factory accountLoaderFactory) {
this.groupCache = groupCache;
@@ -71,13 +70,11 @@
return apply(resource.getGroupUUID());
}
- public List<AccountInfo> apply(AccountGroup group)
- throws OrmException {
+ public List<AccountInfo> apply(AccountGroup group) throws OrmException {
return apply(group.getGroupUUID());
}
- public List<AccountInfo> apply(AccountGroup.UUID groupId)
- throws OrmException {
+ public List<AccountInfo> apply(AccountGroup.UUID groupId) throws OrmException {
final Map<Account.Id, AccountInfo> members =
getMembers(groupId, new HashSet<AccountGroup.UUID>());
final List<AccountInfo> memberInfos = Lists.newArrayList(members.values());
@@ -86,8 +83,8 @@
}
private Map<Account.Id, AccountInfo> getMembers(
- final AccountGroup.UUID groupUUID,
- final HashSet<AccountGroup.UUID> seenGroups) throws OrmException {
+ final AccountGroup.UUID groupUUID, final HashSet<AccountGroup.UUID> seenGroups)
+ throws OrmException {
seenGroups.add(groupUUID);
final Map<Account.Id, AccountInfo> members = new HashMap<>();
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/group/MembersCollection.java b/gerrit-server/src/main/java/com/google/gerrit/server/group/MembersCollection.java
index fc69a1f..8f4d65e 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/group/MembersCollection.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/group/MembersCollection.java
@@ -34,9 +34,8 @@
import com.google.inject.Singleton;
@Singleton
-public class MembersCollection implements
- ChildCollection<GroupResource, MemberResource>,
- AcceptsCreate<GroupResource> {
+public class MembersCollection
+ implements ChildCollection<GroupResource, MemberResource>, AcceptsCreate<GroupResource> {
private final DynamicMap<RestView<MemberResource>> views;
private final Provider<ListMembers> list;
private final AccountsCollection accounts;
@@ -44,7 +43,8 @@
private final AddMembers put;
@Inject
- MembersCollection(DynamicMap<RestView<MemberResource>> views,
+ MembersCollection(
+ DynamicMap<RestView<MemberResource>> views,
Provider<ListMembers> list,
AccountsCollection accounts,
Provider<ReviewDb> db,
@@ -57,15 +57,13 @@
}
@Override
- public RestView<GroupResource> list() throws ResourceNotFoundException,
- AuthException {
+ public RestView<GroupResource> list() throws ResourceNotFoundException, AuthException {
return list.get();
}
@Override
public MemberResource parse(GroupResource parent, IdString id)
- throws MethodNotAllowedException, AuthException,
- ResourceNotFoundException, OrmException {
+ throws MethodNotAllowedException, AuthException, ResourceNotFoundException, OrmException {
if (parent.toAccountGroup() == null) {
throw new MethodNotAllowedException();
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/group/Module.java b/gerrit-server/src/main/java/com/google/gerrit/server/group/Module.java
index f6d0453..366cc4d 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/group/Module.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/group/Module.java
@@ -69,8 +69,6 @@
factory(CreateGroup.Factory.class);
- DynamicSet.bind(binder(), GroupMemberAuditListener.class).to(
- DbGroupMemberAuditListener.class);
-
+ DynamicSet.bind(binder(), GroupMemberAuditListener.class).to(DbGroupMemberAuditListener.class);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/group/PutDescription.java b/gerrit-server/src/main/java/com/google/gerrit/server/group/PutDescription.java
index 102e17c..b04da91 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/group/PutDescription.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/group/PutDescription.java
@@ -29,15 +29,13 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.io.IOException;
import java.util.Collections;
@Singleton
public class PutDescription implements RestModifyView<GroupResource, Input> {
public static class Input {
- @DefaultInput
- public String description;
+ @DefaultInput public String description;
}
private final GroupCache groupCache;
@@ -51,8 +49,8 @@
@Override
public Response<String> apply(GroupResource resource, Input input)
- throws AuthException, MethodNotAllowedException,
- ResourceNotFoundException, OrmException, IOException {
+ throws AuthException, MethodNotAllowedException, ResourceNotFoundException, OrmException,
+ IOException {
if (input == null) {
input = new Input(); // Delete would set description to null.
}
@@ -63,8 +61,7 @@
throw new AuthException("Not group owner");
}
- AccountGroup group = db.get().accountGroups().get(
- resource.toAccountGroup().getId());
+ AccountGroup group = db.get().accountGroups().get(resource.toAccountGroup().getId());
if (group == null) {
throw new ResourceNotFoundException();
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/group/PutName.java b/gerrit-server/src/main/java/com/google/gerrit/server/group/PutName.java
index cf6adf4e..dbbf0e38 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/group/PutName.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/group/PutName.java
@@ -35,7 +35,6 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.io.IOException;
import java.util.Collections;
import java.util.Date;
@@ -45,8 +44,7 @@
@Singleton
public class PutName implements RestModifyView<GroupResource, Input> {
public static class Input {
- @DefaultInput
- public String name;
+ @DefaultInput public String name;
}
private final Provider<ReviewDb> db;
@@ -56,7 +54,8 @@
private final Provider<IdentifiedUser> currentUser;
@Inject
- PutName(Provider<ReviewDb> db,
+ PutName(
+ Provider<ReviewDb> db,
GroupCache groupCache,
GroupDetailFactory.Factory groupDetailFactory,
RenameGroupOp.Factory renameGroupOpFactory,
@@ -71,8 +70,7 @@
@Override
public String apply(GroupResource rsrc, Input input)
throws MethodNotAllowedException, AuthException, BadRequestException,
- ResourceConflictException, OrmException, NoSuchGroupException,
- IOException {
+ ResourceConflictException, OrmException, NoSuchGroupException, IOException {
if (rsrc.toAccountGroup() == null) {
throw new MethodNotAllowedException();
} else if (!rsrc.getControl().isOwner()) {
@@ -93,8 +91,7 @@
}
private GroupDetail renameGroup(AccountGroup group, String newName)
- throws ResourceConflictException, OrmException,
- NoSuchGroupException, IOException {
+ throws ResourceConflictException, OrmException, NoSuchGroupException, IOException {
AccountGroup.Id groupId = group.getId();
AccountGroup.NameKey old = group.getNameKey();
AccountGroup.NameKey key = new AccountGroup.NameKey(newName);
@@ -113,8 +110,7 @@
// Otherwise, someone else has this identity.
//
- throw new ResourceConflictException("group with name " + newName
- + "already exists");
+ throw new ResourceConflictException("group with name " + newName + "already exists");
}
throw e;
}
@@ -129,10 +125,13 @@
groupCache.evict(group);
groupCache.evictAfterRename(old, key);
- renameGroupOpFactory.create(
- currentUser.get().newCommitterIdent(new Date(), TimeZone.getDefault()),
- group.getGroupUUID(),
- old.get(), newName).start(0, TimeUnit.MILLISECONDS);
+ renameGroupOpFactory
+ .create(
+ currentUser.get().newCommitterIdent(new Date(), TimeZone.getDefault()),
+ group.getGroupUUID(),
+ old.get(),
+ newName)
+ .start(0, TimeUnit.MILLISECONDS);
return groupDetailFactory.create(groupId).call();
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/group/PutOptions.java b/gerrit-server/src/main/java/com/google/gerrit/server/group/PutOptions.java
index 8af03c4..701d16f 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/group/PutOptions.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/group/PutOptions.java
@@ -27,13 +27,11 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.io.IOException;
import java.util.Collections;
@Singleton
-public class PutOptions
- implements RestModifyView<GroupResource, GroupOptionsInfo> {
+public class PutOptions implements RestModifyView<GroupResource, GroupOptionsInfo> {
private final GroupCache groupCache;
private final Provider<ReviewDb> db;
@@ -46,7 +44,7 @@
@Override
public GroupOptionsInfo apply(GroupResource resource, GroupOptionsInfo input)
throws MethodNotAllowedException, AuthException, BadRequestException,
- ResourceNotFoundException, OrmException, IOException {
+ ResourceNotFoundException, OrmException, IOException {
if (resource.toAccountGroup() == null) {
throw new MethodNotAllowedException();
} else if (!resource.getControl().isOwner()) {
@@ -60,8 +58,7 @@
input.visibleToAll = false;
}
- AccountGroup group = db.get().accountGroups().get(
- resource.toAccountGroup().getId());
+ AccountGroup group = db.get().accountGroups().get(resource.toAccountGroup().getId());
if (group == null) {
throw new ResourceNotFoundException();
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/group/PutOwner.java b/gerrit-server/src/main/java/com/google/gerrit/server/group/PutOwner.java
index 6654f5f..0c82b9d 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/group/PutOwner.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/group/PutOwner.java
@@ -32,15 +32,13 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.io.IOException;
import java.util.Collections;
@Singleton
public class PutOwner implements RestModifyView<GroupResource, Input> {
public static class Input {
- @DefaultInput
- public String owner;
+ @DefaultInput public String owner;
}
private final GroupsCollection groupsCollection;
@@ -49,8 +47,11 @@
private final GroupJson json;
@Inject
- PutOwner(GroupsCollection groupsCollection, GroupCache groupCache,
- Provider<ReviewDb> db, GroupJson json) {
+ PutOwner(
+ GroupsCollection groupsCollection,
+ GroupCache groupCache,
+ Provider<ReviewDb> db,
+ GroupJson json) {
this.groupsCollection = groupsCollection;
this.groupCache = groupCache;
this.db = db;
@@ -59,9 +60,8 @@
@Override
public GroupInfo apply(GroupResource resource, Input input)
- throws ResourceNotFoundException, MethodNotAllowedException,
- AuthException, BadRequestException, UnprocessableEntityException,
- OrmException, IOException {
+ throws ResourceNotFoundException, MethodNotAllowedException, AuthException,
+ BadRequestException, UnprocessableEntityException, OrmException, IOException {
AccountGroup group = resource.toAccountGroup();
if (group == null) {
throw new MethodNotAllowedException();
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/group/QueryGroups.java b/gerrit-server/src/main/java/com/google/gerrit/server/group/QueryGroups.java
index bbbfd7c..abf464e 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/group/QueryGroups.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/group/QueryGroups.java
@@ -32,12 +32,10 @@
import com.google.gerrit.server.query.group.GroupQueryProcessor;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
-
-import org.kohsuke.args4j.Option;
-
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
+import org.kohsuke.args4j.Option;
public class QueryGroups implements RestReadView<TopLevelResource> {
private final GroupIndexCollection indexes;
@@ -48,25 +46,36 @@
private String query;
private int limit;
private int start;
- private EnumSet<ListGroupsOption> options =
- EnumSet.noneOf(ListGroupsOption.class);
+ private EnumSet<ListGroupsOption> options = EnumSet.noneOf(ListGroupsOption.class);
// TODO(ekempin): --query in ListGroups is marked as deprecated, once it is
// removed we want to rename --query2 to --query here.
/** --query (-q) is already used by {@link ListGroups} */
- @Option(name = "--query2", aliases = {"-q2"}, usage = "group query")
+ @Option(
+ name = "--query2",
+ aliases = {"-q2"},
+ usage = "group query"
+ )
public void setQuery(String query) {
this.query = query;
}
- @Option(name = "--limit", aliases = {"-n"}, metaVar = "CNT",
- usage = "maximum number of groups to list")
+ @Option(
+ name = "--limit",
+ aliases = {"-n"},
+ metaVar = "CNT",
+ usage = "maximum number of groups to list"
+ )
public void setLimit(int limit) {
this.limit = limit;
}
- @Option(name = "--start", aliases = {"-S"}, metaVar = "CNT",
- usage = "number of groups to skip")
+ @Option(
+ name = "--start",
+ aliases = {"-S"},
+ metaVar = "CNT",
+ usage = "number of groups to skip"
+ )
public void setStart(int start) {
this.start = start;
}
@@ -82,7 +91,8 @@
}
@Inject
- protected QueryGroups(GroupIndexCollection indexes,
+ protected QueryGroups(
+ GroupIndexCollection indexes,
GroupQueryBuilder queryBuilder,
GroupQueryProcessor queryProcessor,
GroupJson json) {
@@ -113,12 +123,10 @@
}
try {
- QueryResult<AccountGroup> result =
- queryProcessor.query(queryBuilder.parse(query));
+ QueryResult<AccountGroup> result = queryProcessor.query(queryBuilder.parse(query));
List<AccountGroup> groups = result.entities();
- ArrayList<GroupInfo> groupInfos =
- Lists.newArrayListWithCapacity(groups.size());
+ ArrayList<GroupInfo> groupInfos = Lists.newArrayListWithCapacity(groups.size());
json.addOptions(options);
for (AccountGroup group : groups) {
groupInfos.add(json.format(GroupDescriptions.forAccountGroup(group)));
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/group/SystemGroupBackend.java b/gerrit-server/src/main/java/com/google/gerrit/server/group/SystemGroupBackend.java
index 244fac0..cbab0fc 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/group/SystemGroupBackend.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/group/SystemGroupBackend.java
@@ -35,9 +35,6 @@
import com.google.gerrit.server.project.ProjectControl;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.lib.Config;
-
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
@@ -48,6 +45,7 @@
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
+import org.eclipse.jgit.lib.Config;
@Singleton
public class SystemGroupBackend extends AbstractGroupBackend {
@@ -70,10 +68,7 @@
new AccountGroup.UUID(SYSTEM_GROUP_SCHEME + "Change-Owner");
private static final AccountGroup.UUID[] all = {
- ANONYMOUS_USERS,
- REGISTERED_USERS,
- PROJECT_OWNERS,
- CHANGE_OWNER,
+ ANONYMOUS_USERS, REGISTERED_USERS, PROJECT_OWNERS, CHANGE_OWNER,
};
public static boolean isSystemGroup(AccountGroup.UUID uuid) {
@@ -96,8 +91,7 @@
@VisibleForTesting
public SystemGroupBackend(@GerritServerConfig Config cfg) {
SortedMap<String, GroupReference> n = new TreeMap<>();
- ImmutableMap.Builder<AccountGroup.UUID, GroupReference> u =
- ImmutableMap.builder();
+ ImmutableMap.Builder<AccountGroup.UUID, GroupReference> u = ImmutableMap.builder();
ImmutableSet.Builder<String> reservedNamesBuilder = ImmutableSet.builder();
for (AccountGroup.UUID uuid : all) {
@@ -105,8 +99,8 @@
String defaultName = uuid.get().substring(c + 1).replace('-', ' ');
reservedNamesBuilder.add(defaultName);
String configuredName = cfg.getString("groups", uuid.get(), "name");
- GroupReference ref = new GroupReference(uuid,
- MoreObjects.firstNonNull(configuredName, defaultName));
+ GroupReference ref =
+ new GroupReference(uuid, MoreObjects.firstNonNull(configuredName, defaultName));
n.put(ref.getName().toLowerCase(Locale.US), ref);
u.put(ref.getUUID(), ref);
}
@@ -182,9 +176,7 @@
@Override
public GroupMembership membershipsOf(IdentifiedUser user) {
- return new ListGroupMembership(ImmutableSet.of(
- ANONYMOUS_USERS,
- REGISTERED_USERS));
+ return new ListGroupMembership(ImmutableSet.of(ANONYMOUS_USERS, REGISTERED_USERS));
}
public static class NameCheck implements StartupCheck {
@@ -192,8 +184,7 @@
private final GroupCache groupCache;
@Inject
- NameCheck(@GerritServerConfig Config cfg,
- GroupCache groupCache) {
+ NameCheck(@GerritServerConfig Config cfg, GroupCache groupCache) {
this.cfg = cfg;
this.groupCache = groupCache;
}
@@ -201,14 +192,12 @@
@Override
public void check() throws StartupException {
Map<AccountGroup.UUID, String> configuredNames = new HashMap<>();
- Map<String, AccountGroup.UUID> byLowerCaseConfiguredName =
- new HashMap<>();
+ Map<String, AccountGroup.UUID> byLowerCaseConfiguredName = new HashMap<>();
for (AccountGroup.UUID uuid : all) {
String configuredName = cfg.getString("groups", uuid.get(), "name");
if (configuredName != null) {
configuredNames.put(uuid, configuredName);
- byLowerCaseConfiguredName.put(configuredName.toLowerCase(Locale.US),
- uuid);
+ byLowerCaseConfiguredName.put(configuredName.toLowerCase(Locale.US), uuid);
}
}
if (configuredNames.isEmpty()) {
@@ -217,15 +206,18 @@
for (AccountGroup g : groupCache.all()) {
String name = g.getName().toLowerCase(Locale.US);
if (byLowerCaseConfiguredName.keySet().contains(name)) {
- AccountGroup.UUID uuidSystemGroup =
- byLowerCaseConfiguredName.get(name);
- throw new StartupException(String.format(
- "The configured name '%s' for system group '%s' is ambiguous"
- + " with the name '%s' of existing group '%s'."
- + " Please remove/change the value for groups.%s.name in"
- + " gerrit.config.",
- configuredNames.get(uuidSystemGroup), uuidSystemGroup.get(),
- g.getName(), g.getGroupUUID().get(), uuidSystemGroup.get()));
+ AccountGroup.UUID uuidSystemGroup = byLowerCaseConfiguredName.get(name);
+ throw new StartupException(
+ String.format(
+ "The configured name '%s' for system group '%s' is ambiguous"
+ + " with the name '%s' of existing group '%s'."
+ + " Please remove/change the value for groups.%s.name in"
+ + " gerrit.config.",
+ configuredNames.get(uuidSystemGroup),
+ uuidSystemGroup.get(),
+ g.getName(),
+ g.getGroupUUID().get(),
+ uuidSystemGroup.get()));
}
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/index/FieldDef.java b/gerrit-server/src/main/java/com/google/gerrit/server/index/FieldDef.java
index 92938cb..de654d5 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/index/FieldDef.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/index/FieldDef.java
@@ -23,16 +23,14 @@
import com.google.gerrit.server.config.TrackingFooters;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
-
import org.eclipse.jgit.lib.Config;
/**
* Definition of a field stored in the secondary index.
*
- * @param <I> input type from which documents are created and search results are
- * returned.
- * @param <T> type that should be extracted from the input object when converting
- * to an index document.
+ * @param <I> input type from which documents are created and search results are returned.
+ * @param <T> type that should be extracted from the input object when converting to an index
+ * document.
*/
public abstract class FieldDef<I, T> {
/** Definition of a single (non-repeatable) field. */
@@ -48,12 +46,11 @@
}
/** Definition of a repeatable field. */
- public abstract static class Repeatable<I, T>
- extends FieldDef<I, Iterable<T>> {
+ public abstract static class Repeatable<I, T> extends FieldDef<I, Iterable<T>> {
protected Repeatable(String name, FieldType<T> type, boolean stored) {
super(name, type, stored);
- Preconditions.checkArgument(type != FieldType.INTEGER_RANGE,
- "Range queries against repeated fields are unsupported");
+ Preconditions.checkArgument(
+ type != FieldType.INTEGER_RANGE, "Range queries against repeated fields are unsupported");
}
@Override
@@ -69,13 +66,10 @@
public final AllUsersName allUsers;
@Inject
- FillArgs(TrackingFooters trackingFooters,
- @GerritServerConfig Config cfg,
- AllUsersName allUsers) {
+ FillArgs(
+ TrackingFooters trackingFooters, @GerritServerConfig Config cfg, AllUsersName allUsers) {
this.trackingFooters = trackingFooters;
- this.allowsDrafts = cfg == null
- ? true
- : cfg.getBoolean("change", "allowDrafts", true);
+ this.allowsDrafts = cfg == null ? true : cfg.getBoolean("change", "allowDrafts", true);
this.allUsers = allUsers;
}
}
@@ -101,10 +95,7 @@
return name;
}
- /**
- * @return type of the field; for repeatable fields, the inner type, not the
- * iterable type.
- */
+ /** @return type of the field; for repeatable fields, the inner type, not the iterable type. */
public final FieldType<?> getType() {
return type;
}
@@ -118,10 +109,8 @@
* Get the field contents from the input object.
*
* @param input input object.
- * @param args arbitrary arguments needed to fill in indexable fields of the
- * input object.
+ * @param args arbitrary arguments needed to fill in indexable fields of the input object.
* @return the field value(s) to index.
- *
* @throws OrmException
*/
public abstract T get(I input, FillArgs args) throws OrmException;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/index/FieldType.java b/gerrit-server/src/main/java/com/google/gerrit/server/index/FieldType.java
index 89dc808..820b62a 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/index/FieldType.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/index/FieldType.java
@@ -16,40 +16,31 @@
import java.sql.Timestamp;
-
/** Document field types supported by the secondary index system. */
public class FieldType<T> {
/** A single integer-valued field. */
- public static final FieldType<Integer> INTEGER =
- new FieldType<>("INTEGER");
+ public static final FieldType<Integer> INTEGER = new FieldType<>("INTEGER");
/** A single-integer-valued field matched using range queries. */
- public static final FieldType<Integer> INTEGER_RANGE =
- new FieldType<>("INTEGER_RANGE");
+ public static final FieldType<Integer> INTEGER_RANGE = new FieldType<>("INTEGER_RANGE");
/** A single integer-valued field. */
- public static final FieldType<Long> LONG =
- new FieldType<>("LONG");
+ public static final FieldType<Long> LONG = new FieldType<>("LONG");
/** A single date/time-valued field. */
- public static final FieldType<Timestamp> TIMESTAMP =
- new FieldType<>("TIMESTAMP");
+ public static final FieldType<Timestamp> TIMESTAMP = new FieldType<>("TIMESTAMP");
/** A string field searched using exact-match semantics. */
- public static final FieldType<String> EXACT =
- new FieldType<>("EXACT");
+ public static final FieldType<String> EXACT = new FieldType<>("EXACT");
/** A string field searched using prefix. */
- public static final FieldType<String> PREFIX =
- new FieldType<>("PREFIX");
+ public static final FieldType<String> PREFIX = new FieldType<>("PREFIX");
/** A string field searched using fuzzy-match semantics. */
- public static final FieldType<String> FULL_TEXT =
- new FieldType<>("FULL_TEXT");
+ public static final FieldType<String> FULL_TEXT = new FieldType<>("FULL_TEXT");
/** A field that is only stored as raw bytes and cannot be queried. */
- public static final FieldType<byte[]> STORED_ONLY =
- new FieldType<>("STORED_ONLY");
+ public static final FieldType<byte[]> STORED_ONLY = new FieldType<>("STORED_ONLY");
private final String name;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/index/GerritIndexStatus.java b/gerrit-server/src/main/java/com/google/gerrit/server/index/GerritIndexStatus.java
index 5763185..d835227 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/index/GerritIndexStatus.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/index/GerritIndexStatus.java
@@ -17,24 +17,21 @@
import com.google.common.primitives.Ints;
import com.google.gerrit.server.config.SitePaths;
import com.google.gerrit.server.index.change.ChangeSchemaDefinitions;
-
+import java.io.IOException;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.storage.file.FileBasedConfig;
import org.eclipse.jgit.util.FS;
-import java.io.IOException;
-
public class GerritIndexStatus {
private static final String SECTION = "index";
private static final String KEY_READY = "ready";
private final FileBasedConfig cfg;
- public GerritIndexStatus(SitePaths sitePaths)
- throws ConfigInvalidException, IOException {
- cfg = new FileBasedConfig(
- sitePaths.index_dir.resolve("gerrit_index.config").toFile(),
- FS.detect());
+ public GerritIndexStatus(SitePaths sitePaths) throws ConfigInvalidException, IOException {
+ cfg =
+ new FileBasedConfig(
+ sitePaths.index_dir.resolve("gerrit_index.config").toFile(), FS.detect());
cfg.load();
convertLegacyConfig();
}
@@ -44,8 +41,7 @@
}
public boolean getReady(String indexName, int version) {
- return cfg.getBoolean(SECTION, indexDirName(indexName, version), KEY_READY,
- false);
+ return cfg.getBoolean(SECTION, indexDirName(indexName, version), KEY_READY, false);
}
public void save() throws IOException {
@@ -62,8 +58,7 @@
if (ready != null) {
dirty = false;
cfg.unset(SECTION, subsection, KEY_READY);
- cfg.setString(SECTION, indexDirName(ChangeSchemaDefinitions.NAME, v),
- KEY_READY, ready);
+ cfg.setString(SECTION, indexDirName(ChangeSchemaDefinitions.NAME, v), KEY_READY, ready);
}
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/index/Index.java b/gerrit-server/src/main/java/com/google/gerrit/server/index/Index.java
index 887715f..3be201a 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/index/Index.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/index/Index.java
@@ -18,20 +18,18 @@
import com.google.gerrit.server.query.Predicate;
import com.google.gerrit.server.query.QueryParseException;
import com.google.gwtorm.server.OrmException;
-
import java.io.IOException;
import java.util.List;
import java.util.Optional;
/**
* Secondary index implementation for arbitrary documents.
- * <p>
- * Documents are inserted into the index and are queried by converting special
- * {@link com.google.gerrit.server.query.Predicate} instances into index-aware
- * predicates that use the index search results as a source.
- * <p>
- * Implementations must be thread-safe and should batch inserts/updates where
- * appropriate.
+ *
+ * <p>Documents are inserted into the index and are queried by converting special {@link
+ * com.google.gerrit.server.query.Predicate} instances into index-aware predicates that use the
+ * index search results as a source.
+ *
+ * <p>Implementations must be thread-safe and should batch inserts/updates where appropriate.
*/
public interface Index<K, V> {
/** @return the schema version used by this index. */
@@ -45,14 +43,12 @@
/**
* Update a document in the index.
- * <p>
- * Semantically equivalent to deleting the document and reinserting it with
- * new field values. A document that does not already exist is created. Results
- * may not be immediately visible to searchers, but should be visible within a
- * reasonable amount of time.
+ *
+ * <p>Semantically equivalent to deleting the document and reinserting it with new field values. A
+ * document that does not already exist is created. Results may not be immediately visible to
+ * searchers, but should be visible within a reasonable amount of time.
*
* @param obj document object
- *
* @throws IOException
*/
void replace(V obj) throws IOException;
@@ -61,7 +57,6 @@
* Delete a document from the index by key.
*
* @param key document key
- *
* @throws IOException
*/
void delete(K key) throws IOException;
@@ -74,34 +69,28 @@
void deleteAll() throws IOException;
/**
- * Convert the given operator predicate into a source searching the index and
- * returning only the documents matching that predicate.
- * <p>
- * This method may be called multiple times for variations on the same
- * predicate or multiple predicate subtrees in the course of processing a
- * single query, so it should not have any side effects (e.g. starting a
- * search in the background).
+ * Convert the given operator predicate into a source searching the index and returning only the
+ * documents matching that predicate.
*
- * @param p the predicate to match. Must be a tree containing only AND, OR,
- * or NOT predicates as internal nodes, and {@link IndexPredicate}s as
- * leaves.
- * @param opts query options not implied by the predicate, such as start and
- * limit.
- * @return a source of documents matching the predicate, returned in a
- * defined order depending on the type of documents.
+ * <p>This method may be called multiple times for variations on the same predicate or multiple
+ * predicate subtrees in the course of processing a single query, so it should not have any side
+ * effects (e.g. starting a search in the background).
*
- * @throws QueryParseException if the predicate could not be converted to an
- * indexed data source.
+ * @param p the predicate to match. Must be a tree containing only AND, OR, or NOT predicates as
+ * internal nodes, and {@link IndexPredicate}s as leaves.
+ * @param opts query options not implied by the predicate, such as start and limit.
+ * @return a source of documents matching the predicate, returned in a defined order depending on
+ * the type of documents.
+ * @throws QueryParseException if the predicate could not be converted to an indexed data source.
*/
- DataSource<V> getSource(Predicate<V> p, QueryOptions opts)
- throws QueryParseException;
+ DataSource<V> getSource(Predicate<V> p, QueryOptions opts) throws QueryParseException;
/**
* Get a single document from the index.
*
* @param key document key.
- * @param opts query options. Options that do not make sense in the context of
- * a single document, such as start, will be ignored.
+ * @param opts query options. Options that do not make sense in the context of a single document,
+ * such as start, will be ignored.
* @return a single document if present.
* @throws IOException
*/
@@ -121,8 +110,7 @@
case 1:
return Optional.of(results.get(0));
default:
- throw new IOException("Multiple results found in index for key "
- + key + ": " + results);
+ throw new IOException("Multiple results found in index for key " + key + ": " + results);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/index/IndexCollection.java b/gerrit-server/src/main/java/com/google/gerrit/server/index/IndexCollection.java
index 61c4675..a887852 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/index/IndexCollection.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/index/IndexCollection.java
@@ -16,15 +16,13 @@
import com.google.common.collect.Lists;
import com.google.gerrit.extensions.events.LifecycleListener;
-
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicReference;
/** Dynamic pointers to the index versions used for searching and writing. */
-public abstract class IndexCollection<K, V, I extends Index<K, V>>
- implements LifecycleListener {
+public abstract class IndexCollection<K, V, I extends Index<K, V>> implements LifecycleListener {
private final CopyOnWriteArrayList<I> writeIndexes;
private final AtomicReference<I> searchIndex;
@@ -87,8 +85,7 @@
}
@Override
- public void start() {
- }
+ public void start() {}
@Override
public void stop() {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/index/IndexConfig.java b/gerrit-server/src/main/java/com/google/gerrit/server/index/IndexConfig.java
index 12eb347..a368190 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/index/IndexConfig.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/index/IndexConfig.java
@@ -17,15 +17,13 @@
import static com.google.common.base.Preconditions.checkArgument;
import com.google.auto.value.AutoValue;
-
import org.eclipse.jgit.lib.Config;
/**
* Implementation-specific configuration for secondary indexes.
- * <p>
- * Contains configuration that is tied to a specific index implementation but is
- * otherwise global, i.e. not tied to a specific {@link Index} and schema
- * version.
+ *
+ * <p>Contains configuration that is tied to a specific index implementation but is otherwise
+ * global, i.e. not tied to a specific {@link Index} and schema version.
*/
@AutoValue
public abstract class IndexConfig {
@@ -42,8 +40,7 @@
cfg.getInt("index", null, "maxTerms", 0));
}
- public static IndexConfig create(int maxLimit, int maxPages,
- int maxTerms) {
+ public static IndexConfig create(int maxLimit, int maxPages, int maxTerms) {
return new AutoValue_IndexConfig(
checkLimit(maxLimit, "maxLimit", Integer.MAX_VALUE),
checkLimit(maxPages, "maxPages", Integer.MAX_VALUE),
@@ -59,20 +56,19 @@
}
/**
- * @return maximum limit supported by the underlying index, or limited for
- * performance reasons.
+ * @return maximum limit supported by the underlying index, or limited for performance reasons.
*/
public abstract int maxLimit();
/**
- * @return maximum number of pages (limit / start) supported by the
- * underlying index, or limited for performance reasons.
+ * @return maximum number of pages (limit / start) supported by the underlying index, or limited
+ * for performance reasons.
*/
public abstract int maxPages();
/**
- * @return maximum number of total index query terms supported by the
- * underlying index, or limited for performance reasons.
+ * @return maximum number of total index query terms supported by the underlying index, or limited
+ * for performance reasons.
*/
public abstract int maxTerms();
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/index/IndexDefinition.java b/gerrit-server/src/main/java/com/google/gerrit/server/index/IndexDefinition.java
index 8787b2f..340e35e 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/index/IndexDefinition.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/index/IndexDefinition.java
@@ -19,11 +19,11 @@
/**
* Definition of an index over a Gerrit data type.
- * <p>
- * An <em>index</em> includes a set of schema definitions along with the
- * specific implementations used to query the secondary index implementation in
- * a running server. If you are just interested in the static definition of one
- * or more schemas, see the implementations of {@link SchemaDefinitions}.
+ *
+ * <p>An <em>index</em> includes a set of schema definitions along with the specific implementations
+ * used to query the secondary index implementation in a running server. If you are just interested
+ * in the static definition of one or more schemas, see the implementations of {@link
+ * SchemaDefinitions}.
*/
public abstract class IndexDefinition<K, V, I extends Index<K, V>> {
public interface IndexFactory<K, V, I extends Index<K, V>> {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/index/IndexExecutor.java b/gerrit-server/src/main/java/com/google/gerrit/server/index/IndexExecutor.java
index eb97fdc..f8145a4 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/index/IndexExecutor.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/index/IndexExecutor.java
@@ -19,13 +19,9 @@
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.gerrit.server.git.QueueProvider.QueueType;
import com.google.inject.BindingAnnotation;
-
import java.lang.annotation.Retention;
-/**
- * Marker on {@link ListeningExecutorService} used by secondary indexing
- * threads.
- */
+/** Marker on {@link ListeningExecutorService} used by secondary indexing threads. */
@Retention(RUNTIME)
@BindingAnnotation
public @interface IndexExecutor {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/index/IndexModule.java b/gerrit-server/src/main/java/com/google/gerrit/server/index/IndexModule.java
index 73812c6..a8b423a 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/index/IndexModule.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/index/IndexModule.java
@@ -47,33 +47,31 @@
import com.google.inject.Provides;
import com.google.inject.ProvisionException;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.lib.Config;
-
import java.util.Collection;
import java.util.Set;
+import org.eclipse.jgit.lib.Config;
/**
* Module for non-indexer-specific secondary index setup.
- * <p>
- * This module should not be used directly except by specific secondary indexer
- * implementations (e.g. Lucene).
+ *
+ * <p>This module should not be used directly except by specific secondary indexer implementations
+ * (e.g. Lucene).
*/
public class IndexModule extends LifecycleModule {
public enum IndexType {
- LUCENE, ELASTICSEARCH
+ LUCENE,
+ ELASTICSEARCH
}
public static final ImmutableCollection<SchemaDefinitions<?>> ALL_SCHEMA_DEFS =
- ImmutableList.<SchemaDefinitions<?>> of(
+ ImmutableList.<SchemaDefinitions<?>>of(
AccountSchemaDefinitions.INSTANCE,
ChangeSchemaDefinitions.INSTANCE,
GroupSchemaDefinitions.INSTANCE);
/** Type of secondary index. */
public static IndexType getIndexType(Injector injector) {
- Config cfg = injector.getInstance(
- Key.get(Config.class, GerritServerConfig.class));
+ Config cfg = injector.getInstance(Key.get(Config.class, GerritServerConfig.class));
return cfg.getEnum("index", null, "type", IndexType.LUCENE);
}
@@ -87,8 +85,8 @@
this.batchExecutor = null;
}
- public IndexModule(ListeningExecutorService interactiveExecutor,
- ListeningExecutorService batchExecutor) {
+ public IndexModule(
+ ListeningExecutorService interactiveExecutor, ListeningExecutorService batchExecutor) {
this.threads = -1;
this.interactiveExecutor = interactiveExecutor;
this.batchExecutor = batchExecutor;
@@ -114,32 +112,23 @@
@Provides
Collection<IndexDefinition<?, ?, ?>> getIndexDefinitions(
- AccountIndexDefinition accounts,
- ChangeIndexDefinition changes,
- GroupIndexDefinition groups) {
+ AccountIndexDefinition accounts, ChangeIndexDefinition changes, GroupIndexDefinition groups) {
Collection<IndexDefinition<?, ?, ?>> result =
- ImmutableList.<IndexDefinition<?, ?, ?>> of(
- accounts,
- groups,
- changes);
- Set<String> expected = FluentIterable.from(ALL_SCHEMA_DEFS)
- .transform(SchemaDefinitions::getName)
- .toSet();
- Set<String> actual = FluentIterable.from(result)
- .transform(IndexDefinition::getName)
- .toSet();
+ ImmutableList.<IndexDefinition<?, ?, ?>>of(accounts, groups, changes);
+ Set<String> expected =
+ FluentIterable.from(ALL_SCHEMA_DEFS).transform(SchemaDefinitions::getName).toSet();
+ Set<String> actual = FluentIterable.from(result).transform(IndexDefinition::getName).toSet();
if (!expected.equals(actual)) {
throw new ProvisionException(
- "need index definitions for all schemas: "
- + expected + " != " + actual);
+ "need index definitions for all schemas: " + expected + " != " + actual);
}
return result;
}
@Provides
@Singleton
- AccountIndexer getAccountIndexer(AccountIndexerImpl.Factory factory,
- AccountIndexCollection indexes) {
+ AccountIndexer getAccountIndexer(
+ AccountIndexerImpl.Factory factory, AccountIndexCollection indexes) {
return factory.create(indexes);
}
@@ -156,8 +145,7 @@
@Provides
@Singleton
- GroupIndexer getGroupIndexer(GroupIndexerImpl.Factory factory,
- GroupIndexCollection indexes) {
+ GroupIndexer getGroupIndexer(GroupIndexerImpl.Factory factory, GroupIndexCollection indexes) {
return factory.create(indexes);
}
@@ -165,8 +153,7 @@
@Singleton
@IndexExecutor(INTERACTIVE)
ListeningExecutorService getInteractiveIndexExecutor(
- @GerritServerConfig Config config,
- WorkQueue workQueue) {
+ @GerritServerConfig Config config, WorkQueue workQueue) {
if (interactiveExecutor != null) {
return interactiveExecutor;
}
@@ -177,16 +164,14 @@
if (threads <= 0) {
threads = Runtime.getRuntime().availableProcessors() / 2 + 1;
}
- return MoreExecutors.listeningDecorator(
- workQueue.createQueue(threads, "Index-Interactive"));
+ return MoreExecutors.listeningDecorator(workQueue.createQueue(threads, "Index-Interactive"));
}
@Provides
@Singleton
@IndexExecutor(BATCH)
ListeningExecutorService getBatchIndexExecutor(
- @GerritServerConfig Config config,
- WorkQueue workQueue) {
+ @GerritServerConfig Config config, WorkQueue workQueue) {
if (batchExecutor != null) {
return batchExecutor;
}
@@ -194,7 +179,6 @@
if (threads <= 0) {
threads = Runtime.getRuntime().availableProcessors();
}
- return MoreExecutors.listeningDecorator(
- workQueue.createQueue(threads, "Index-Batch"));
+ return MoreExecutors.listeningDecorator(workQueue.createQueue(threads, "Index-Batch"));
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/index/IndexRewriter.java b/gerrit-server/src/main/java/com/google/gerrit/server/index/IndexRewriter.java
index 276c52b..5c1d838 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/index/IndexRewriter.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/index/IndexRewriter.java
@@ -19,6 +19,5 @@
public interface IndexRewriter<T> {
- Predicate<T> rewrite(Predicate<T> in, QueryOptions opts)
- throws QueryParseException;
+ Predicate<T> rewrite(Predicate<T> in, QueryOptions opts) throws QueryParseException;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/index/IndexUtils.java b/gerrit-server/src/main/java/com/google/gerrit/server/index/IndexUtils.java
index eceec59..d01d1ce 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/index/IndexUtils.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/index/IndexUtils.java
@@ -24,19 +24,16 @@
import com.google.gerrit.server.config.SitePaths;
import com.google.gerrit.server.index.account.AccountField;
import com.google.gerrit.server.index.group.GroupField;
-
-import org.eclipse.jgit.errors.ConfigInvalidException;
-
import java.io.IOException;
import java.util.Map;
import java.util.Set;
+import org.eclipse.jgit.errors.ConfigInvalidException;
public final class IndexUtils {
- public static final Map<String, String> CUSTOM_CHAR_MAPPING =
- ImmutableMap.of("_", " ", ".", " ");
+ public static final Map<String, String> CUSTOM_CHAR_MAPPING = ImmutableMap.of("_", " ", ".", " ");
- public static void setReady(SitePaths sitePaths, String name, int version,
- boolean ready) throws IOException {
+ public static void setReady(SitePaths sitePaths, String name, int version, boolean ready)
+ throws IOException {
try {
GerritIndexStatus cfg = new GerritIndexStatus(sitePaths);
cfg.setReady(name, version, ready);
@@ -65,8 +62,7 @@
if (fs.contains(PROJECT.getName()) && fs.contains(LEGACY_ID.getName())) {
return fs;
}
- return Sets.union(fs,
- ImmutableSet.of(LEGACY_ID.getName(), PROJECT.getName()));
+ return Sets.union(fs, ImmutableSet.of(LEGACY_ID.getName(), PROJECT.getName()));
}
public static Set<String> groupFields(QueryOptions opts) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/index/IndexedQuery.java b/gerrit-server/src/main/java/com/google/gerrit/server/index/IndexedQuery.java
index 65097b4..b8f21f5 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/index/IndexedQuery.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/index/IndexedQuery.java
@@ -22,31 +22,29 @@
import com.google.gerrit.server.query.QueryParseException;
import com.google.gwtorm.server.OrmException;
import com.google.gwtorm.server.ResultSet;
-
import java.util.Collection;
import java.util.List;
/**
- * Wrapper combining an {@link IndexPredicate} together with a
- * {@link DataSource} that returns matching results from the index.
- * <p>
- * Appropriate to return as the rootmost predicate that can be processed using
- * the secondary index; such predicates must also implement {@link DataSource}
- * to be chosen by the query processor.
+ * Wrapper combining an {@link IndexPredicate} together with a {@link DataSource} that returns
+ * matching results from the index.
+ *
+ * <p>Appropriate to return as the rootmost predicate that can be processed using the secondary
+ * index; such predicates must also implement {@link DataSource} to be chosen by the query
+ * processor.
*
* @param <I> The type of the IDs by which the entities are stored in the index.
* @param <T> The type of the entities that are stored in the index.
*/
-public class IndexedQuery<I, T> extends Predicate<T>
- implements DataSource<T>, Paginated<T> {
+public class IndexedQuery<I, T> extends Predicate<T> implements DataSource<T>, Paginated<T> {
protected final Index<I, T> index;
private QueryOptions opts;
private final Predicate<T> pred;
protected DataSource<T> source;
- public IndexedQuery(Index<I, T> index, Predicate<T> pred,
- QueryOptions opts) throws QueryParseException {
+ public IndexedQuery(Index<I, T> index, Predicate<T> pred, QueryOptions opts)
+ throws QueryParseException {
this.index = index;
this.opts = opts;
this.pred = pred;
@@ -118,15 +116,11 @@
return false;
}
IndexedQuery<?, ?> o = (IndexedQuery<?, ?>) other;
- return pred.equals(o.pred)
- && opts.equals(o.opts);
+ return pred.equals(o.pred) && opts.equals(o.opts);
}
@Override
public String toString() {
- return MoreObjects.toStringHelper("index")
- .add("p", pred)
- .add("opts", opts)
- .toString();
+ return MoreObjects.toStringHelper("index").add("p", pred).add("opts", opts).toString();
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/index/IntegerRangePredicate.java b/gerrit-server/src/main/java/com/google/gerrit/server/index/IntegerRangePredicate.java
index e62a685..5832694 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/index/IntegerRangePredicate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/index/IntegerRangePredicate.java
@@ -22,8 +22,8 @@
public abstract class IntegerRangePredicate<T> extends IndexPredicate<T> {
private final Range range;
- protected IntegerRangePredicate(FieldDef<T, Integer> type,
- String value) throws QueryParseException {
+ protected IntegerRangePredicate(FieldDef<T, Integer> type, String value)
+ throws QueryParseException {
super(type, value);
range = RangeUtil.getRange(value, Integer.MIN_VALUE, Integer.MAX_VALUE);
if (range == null) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/index/OnlineReindexer.java b/gerrit-server/src/main/java/com/google/gerrit/server/index/OnlineReindexer.java
index 133d78b..e40015a 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/index/OnlineReindexer.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/index/OnlineReindexer.java
@@ -17,17 +17,14 @@
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.collect.Lists;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.io.IOException;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class OnlineReindexer<K, V, I extends Index<K, V>> {
- private static final Logger log = LoggerFactory
- .getLogger(OnlineReindexer.class);
+ private static final Logger log = LoggerFactory.getLogger(OnlineReindexer.class);
private final IndexCollection<K, V, I> indexes;
private final SiteIndexer<K, V, I> batchIndexer;
@@ -35,9 +32,7 @@
private I index;
private final AtomicBoolean running = new AtomicBoolean();
- public OnlineReindexer(
- IndexDefinition<K, V, I> def,
- int version) {
+ public OnlineReindexer(IndexDefinition<K, V, I> def, int version) {
this.indexes = def.getIndexCollection();
this.batchIndexer = def.getSiteIndexer();
this.version = version;
@@ -45,18 +40,18 @@
public void start() {
if (running.compareAndSet(false, true)) {
- Thread t = new Thread() {
- @Override
- public void run() {
- try {
- reindex();
- } finally {
- running.set(false);
- }
- }
- };
- t.setName(String.format("Reindex v%d-v%d",
- version(indexes.getSearchIndex()), version));
+ Thread t =
+ new Thread() {
+ @Override
+ public void run() {
+ try {
+ reindex();
+ } finally {
+ running.set(false);
+ }
+ }
+ };
+ t.setName(String.format("Reindex v%d-v%d", version(indexes.getSearchIndex()), version));
t.start();
}
}
@@ -74,15 +69,21 @@
}
private void reindex() {
- index = checkNotNull(indexes.getWriteIndex(version),
- "not an active write schema version: %s", version);
- log.info("Starting online reindex from schema version {} to {}",
- version(indexes.getSearchIndex()), version(index));
+ index =
+ checkNotNull(
+ indexes.getWriteIndex(version), "not an active write schema version: %s", version);
+ log.info(
+ "Starting online reindex from schema version {} to {}",
+ version(indexes.getSearchIndex()),
+ version(index));
SiteIndexer.Result result = batchIndexer.indexAll(index);
if (!result.success()) {
- log.error("Online reindex of schema version {} failed. Successfully"
- + " indexed {} changes, failed to index {} changes",
- version(index), result.doneCount(), result.failedCount());
+ log.error(
+ "Online reindex of schema version {} failed. Successfully"
+ + " indexed {} changes, failed to index {} changes",
+ version(index),
+ result.doneCount(),
+ result.failedCount());
return;
}
log.info("Reindex to version {} complete", version(index));
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/index/QueryOptions.java b/gerrit-server/src/main/java/com/google/gerrit/server/index/QueryOptions.java
index d0c2095..a26b0ac 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/index/QueryOptions.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/index/QueryOptions.java
@@ -19,17 +19,14 @@
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableSet;
import com.google.common.primitives.Ints;
-
import java.util.Set;
@AutoValue
public abstract class QueryOptions {
- public static QueryOptions create(IndexConfig config, int start, int limit,
- Set<String> fields) {
+ public static QueryOptions create(IndexConfig config, int start, int limit, Set<String> fields) {
checkArgument(start >= 0, "start must be nonnegative: %s", start);
checkArgument(limit > 0, "limit must be positive: %s", limit);
- return new AutoValue_QueryOptions(config, start, limit,
- ImmutableSet.copyOf(fields));
+ return new AutoValue_QueryOptions(config, start, limit, ImmutableSet.copyOf(fields));
}
public QueryOptions convertForBackend() {
@@ -42,8 +39,11 @@
}
public abstract IndexConfig config();
+
public abstract int start();
+
public abstract int limit();
+
public abstract ImmutableSet<String> fields();
public QueryOptions withLimit(int newLimit) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/index/Schema.java b/gerrit-server/src/main/java/com/google/gerrit/server/index/Schema.java
index faa6934..5e06242 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/index/Schema.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/index/Schema.java
@@ -24,15 +24,13 @@
import com.google.common.collect.ImmutableMap;
import com.google.gerrit.server.index.FieldDef.FillArgs;
import com.google.gwtorm.server.OrmException;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/** Specific version of a secondary index schema. */
public class Schema<T> {
@@ -81,10 +79,8 @@
}
}
- private static <T> FieldDef<T, ?> checkSame(FieldDef<T, ?> f1,
- FieldDef<T, ?> f2) {
- checkState(f1 == f2, "Mismatched %s fields: %s != %s",
- f1.getName(), f1, f2);
+ private static <T> FieldDef<T, ?> checkSame(FieldDef<T, ?> f1, FieldDef<T, ?> f2) {
+ checkState(f1 == f2, "Mismatched %s fields: %s != %s", f1.getName(), f1, f2);
return f1;
}
@@ -117,10 +113,10 @@
/**
* Get all fields in this schema.
- * <p>
- * This is primarily useful for iteration. Most callers should prefer one
- * of the helper methods {@link #getField(FieldDef, FieldDef...)} or {@link
- * #hasField(FieldDef)} to looking up fields by name
+ *
+ * <p>This is primarily useful for iteration. Most callers should prefer one of the helper methods
+ * {@link #getField(FieldDef, FieldDef...)} or {@link #hasField(FieldDef)} to looking up fields by
+ * name
*
* @return all fields in this schema indexed by name.
*/
@@ -128,10 +124,7 @@
return fields;
}
- /**
- * @return all fields in this schema where {@link FieldDef#isStored()} is
- * true.
- */
+ /** @return all fields in this schema where {@link FieldDef#isStored()} is true. */
public final ImmutableMap<String, FieldDef<T, ?>> getStoredFields() {
return storedFields;
}
@@ -141,12 +134,11 @@
*
* @param first the preferred field to look up.
* @param rest additional fields to look up.
- * @return the first field in the schema matching {@code first} or {@code
- * rest}, in order, or absent if no field matches.
+ * @return the first field in the schema matching {@code first} or {@code rest}, in order, or
+ * absent if no field matches.
*/
@SafeVarargs
- public final Optional<FieldDef<T, ?>> getField(FieldDef<T, ?> first,
- FieldDef<T, ?>... rest) {
+ public final Optional<FieldDef<T, ?>> getField(FieldDef<T, ?> first, FieldDef<T, ?>... rest) {
FieldDef<T, ?> field = fields.get(first.getName());
if (field != null) {
return Optional.of(checkSame(field, first));
@@ -177,44 +169,41 @@
/**
* Build all fields in the schema from an input object.
- * <p>
- * Null values are omitted, as are fields which cause errors, which are
- * logged.
+ *
+ * <p>Null values are omitted, as are fields which cause errors, which are logged.
*
* @param obj input object.
* @param fillArgs arguments for filling fields.
* @return all non-null field values from the object.
*/
- public final Iterable<Values<T>> buildFields(
- final T obj, final FillArgs fillArgs) {
+ public final Iterable<Values<T>> buildFields(final T obj, final FillArgs fillArgs) {
return FluentIterable.from(fields.values())
- .transform(new Function<FieldDef<T, ?>, Values<T>>() {
- @Override
- public Values<T> apply(FieldDef<T, ?> f) {
- Object v;
- try {
- v = f.get(obj, fillArgs);
- } catch (OrmException e) {
- log.error(String.format("error getting field %s of %s",
- f.getName(), obj), e);
- return null;
- }
- if (v == null) {
- return null;
- } else if (f.isRepeatable()) {
- return new Values<>(f, (Iterable<?>) v);
- } else {
- return new Values<>(f, Collections.singleton(v));
- }
- }
- }).filter(Predicates.notNull());
+ .transform(
+ new Function<FieldDef<T, ?>, Values<T>>() {
+ @Override
+ public Values<T> apply(FieldDef<T, ?> f) {
+ Object v;
+ try {
+ v = f.get(obj, fillArgs);
+ } catch (OrmException e) {
+ log.error(String.format("error getting field %s of %s", f.getName(), obj), e);
+ return null;
+ }
+ if (v == null) {
+ return null;
+ } else if (f.isRepeatable()) {
+ return new Values<>(f, (Iterable<?>) v);
+ } else {
+ return new Values<>(f, Collections.singleton(v));
+ }
+ }
+ })
+ .filter(Predicates.notNull());
}
@Override
public String toString() {
- return MoreObjects.toStringHelper(this)
- .addValue(fields.keySet())
- .toString();
+ return MoreObjects.toStringHelper(this).addValue(fields.keySet()).toString();
}
public void setVersion(int version) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/index/SchemaDefinitions.java b/gerrit-server/src/main/java/com/google/gerrit/server/index/SchemaDefinitions.java
index f9a799e..2bcf03a 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/index/SchemaDefinitions.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/index/SchemaDefinitions.java
@@ -21,12 +21,11 @@
/**
* Definitions of the various schema versions over a given Gerrit data type.
- * <p>
- * A <em>schema</em> is a description of the fields that are indexed over the
- * given data type. This class contains all the versions of a schema defined
- * over its data type, exposed as a map of version number to schema definition.
- * If you are interested in the classes responsible for backend-specific runtime
- * implementations, see the implementations of {@link IndexDefinition}.
+ *
+ * <p>A <em>schema</em> is a description of the fields that are indexed over the given data type.
+ * This class contains all the versions of a schema defined over its data type, exposed as a map of
+ * version number to schema definition. If you are interested in the classes responsible for
+ * backend-specific runtime implementations, see the implementations of {@link IndexDefinition}.
*/
public abstract class SchemaDefinitions<V> {
private final String name;
@@ -47,8 +46,7 @@
public final Schema<V> get(int version) {
Schema<V> schema = schemas.get(version);
- checkArgument(schema != null,
- "Unrecognized %s schema version: %s", name, version);
+ checkArgument(schema != null, "Unrecognized %s schema version: %s", name, version);
return schema;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/index/SchemaUtil.java b/gerrit-server/src/main/java/com/google/gerrit/server/index/SchemaUtil.java
index 28e43a7..ea33190 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/index/SchemaUtil.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/index/SchemaUtil.java
@@ -22,9 +22,6 @@
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.collect.Iterables;
-
-import org.eclipse.jgit.lib.PersonIdent;
-
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
@@ -35,6 +32,7 @@
import java.util.Locale;
import java.util.Map;
import java.util.Set;
+import org.eclipse.jgit.lib.PersonIdent;
public class SchemaUtil {
public static <V> ImmutableSortedMap<Integer, Schema<V>> schemasFromClass(
@@ -73,8 +71,7 @@
}
@SafeVarargs
- public static <V> Schema<V> schema(Schema<V> schema,
- FieldDef<V, ?>... moreFields) {
+ public static <V> Schema<V> schema(Schema<V> schema, FieldDef<V, ?>... moreFields) {
return new Schema<>(
new ImmutableList.Builder<FieldDef<V, ?>>()
.addAll(schema.getFields().values())
@@ -91,17 +88,14 @@
if (person == null) {
return ImmutableSet.of();
}
- return getNameParts(
- person.getName(),
- Collections.singleton(person.getEmailAddress()));
+ return getNameParts(person.getName(), Collections.singleton(person.getEmailAddress()));
}
public static Set<String> getNameParts(String name) {
return getNameParts(name, Collections.emptySet());
}
- public static Set<String> getNameParts(String name,
- Iterable<String> emails) {
+ public static Set<String> getNameParts(String name, Iterable<String> emails) {
Splitter at = Splitter.on('@');
Splitter s = Splitter.on(CharMatcher.anyOf("@.- /_")).omitEmptyStrings();
HashSet<String> parts = new HashSet<>();
@@ -120,6 +114,5 @@
return parts;
}
- private SchemaUtil() {
- }
+ private SchemaUtil() {}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/index/SingleVersionModule.java b/gerrit-server/src/main/java/com/google/gerrit/server/index/SingleVersionModule.java
index b86ec38..2df0b40 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/index/SingleVersionModule.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/index/SingleVersionModule.java
@@ -24,12 +24,10 @@
import com.google.inject.TypeLiteral;
import com.google.inject.name.Named;
import com.google.inject.name.Names;
-
-import org.eclipse.jgit.lib.Config;
-
import java.util.Collection;
import java.util.Map;
import java.util.Set;
+import org.eclipse.jgit.lib.Config;
@Singleton
public class SingleVersionModule extends LifecycleModule {
@@ -63,8 +61,7 @@
this.defs = defs;
this.singleVersions = singleVersions;
- disabled = ImmutableSet.copyOf(
- cfg.getStringList("index", null, "testDisable"));
+ disabled = ImmutableSet.copyOf(cfg.getStringList("index", null, "testDisable"));
}
@Override
@@ -74,8 +71,7 @@
}
}
- private <K, V, I extends Index<K, V>> void start(
- IndexDefinition<K, V, I> def) {
+ private <K, V, I extends Index<K, V>> void start(IndexDefinition<K, V, I> def) {
if (disabled.contains(def.getName())) {
return;
}
@@ -86,8 +82,8 @@
} else {
schema = def.getSchemas().get(v);
if (schema == null) {
- throw new ProvisionException(String.format(
- "Unrecognized %s schema version: %s", def.getName(), v));
+ throw new ProvisionException(
+ String.format("Unrecognized %s schema version: %s", def.getName(), v));
}
}
I index = def.getIndexFactory().create(schema);
@@ -100,4 +96,4 @@
// Do nothing; indexes are closed by IndexCollection.
}
}
-}
\ No newline at end of file
+}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/index/SiteIndexer.java b/gerrit-server/src/main/java/com/google/gerrit/server/index/SiteIndexer.java
index 8ee1ced..69e1cf1 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/index/SiteIndexer.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/index/SiteIndexer.java
@@ -19,17 +19,15 @@
import com.google.common.base.Stopwatch;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;
-
-import org.eclipse.jgit.lib.ProgressMonitor;
-import org.eclipse.jgit.util.io.NullOutputStream;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
+import org.eclipse.jgit.lib.ProgressMonitor;
+import org.eclipse.jgit.util.io.NullOutputStream;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public abstract class SiteIndexer<K, V, I extends Index<K, V>> {
private static final Logger log = LoggerFactory.getLogger(SiteIndexer.class);
@@ -66,8 +64,7 @@
protected int totalWork = -1;
protected OutputStream progressOut = NullOutputStream.INSTANCE;
- protected PrintWriter verboseWriter =
- new PrintWriter(NullOutputStream.INSTANCE);
+ protected PrintWriter verboseWriter = new PrintWriter(NullOutputStream.INSTANCE);
public void setTotalWork(int num) {
totalWork = num;
@@ -83,11 +80,10 @@
public abstract Result indexAll(I index);
- protected final void addErrorListener(ListenableFuture<?> future,
- String desc, ProgressMonitor progress, AtomicBoolean ok) {
+ protected final void addErrorListener(
+ ListenableFuture<?> future, String desc, ProgressMonitor progress, AtomicBoolean ok) {
future.addListener(
- new ErrorListener(future, desc, progress, ok),
- MoreExecutors.directExecutor());
+ new ErrorListener(future, desc, progress, ok), MoreExecutors.directExecutor());
}
private static class ErrorListener implements Runnable {
@@ -96,8 +92,8 @@
private final ProgressMonitor progress;
private final AtomicBoolean ok;
- private ErrorListener(ListenableFuture<?> future, String desc,
- ProgressMonitor progress, AtomicBoolean ok) {
+ private ErrorListener(
+ ListenableFuture<?> future, String desc, ProgressMonitor progress, AtomicBoolean ok) {
this.future = future;
this.desc = desc;
this.progress = progress;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/index/TimestampRangePredicate.java b/gerrit-server/src/main/java/com/google/gerrit/server/index/TimestampRangePredicate.java
index 1e2e80b..7e194b7 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/index/TimestampRangePredicate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/index/TimestampRangePredicate.java
@@ -16,7 +16,6 @@
import com.google.gerrit.server.query.QueryParseException;
import com.google.gwtjsonrpc.common.JavaSqlTimestampHelper;
-
import java.sql.Timestamp;
import java.util.Date;
@@ -31,11 +30,11 @@
}
}
- protected TimestampRangePredicate(FieldDef<I, Timestamp> def,
- String name, String value) {
+ protected TimestampRangePredicate(FieldDef<I, Timestamp> def, String name, String value) {
super(def, name, value);
}
public abstract Date getMinTimestamp();
+
public abstract Date getMaxTimestamp();
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/index/account/AccountField.java b/gerrit-server/src/main/java/com/google/gerrit/server/index/account/AccountField.java
index de5428f..b9d78e0 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/index/account/AccountField.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/index/account/AccountField.java
@@ -23,7 +23,6 @@
import com.google.gerrit.server.index.FieldDef;
import com.google.gerrit.server.index.FieldType;
import com.google.gerrit.server.index.SchemaUtil;
-
import java.sql.Timestamp;
import java.util.Collections;
import java.util.Locale;
@@ -32,8 +31,7 @@
/** Secondary index schemas for accounts. */
public class AccountField {
public static final FieldDef<AccountState, Integer> ID =
- new FieldDef.Single<AccountState, Integer>(
- "id", FieldType.INTEGER, true) {
+ new FieldDef.Single<AccountState, Integer>("id", FieldType.INTEGER, true) {
@Override
public Integer get(AccountState input, FillArgs args) {
return input.getAccount().getId().get();
@@ -41,27 +39,23 @@
};
public static final FieldDef<AccountState, Iterable<String>> EXTERNAL_ID =
- new FieldDef.Repeatable<AccountState, String>(
- "external_id", FieldType.EXACT, false) {
+ new FieldDef.Repeatable<AccountState, String>("external_id", FieldType.EXACT, false) {
@Override
public Iterable<String> get(AccountState input, FillArgs args) {
- return Iterables.transform(
- input.getExternalIds(), id -> id.getKey().get());
+ return Iterables.transform(input.getExternalIds(), id -> id.getKey().get());
}
};
/** Fuzzy prefix match on name and email parts. */
public static final FieldDef<AccountState, Iterable<String>> NAME_PART =
- new FieldDef.Repeatable<AccountState, String>(
- "name", FieldType.PREFIX, false) {
+ new FieldDef.Repeatable<AccountState, String>("name", FieldType.PREFIX, false) {
@Override
public Iterable<String> get(AccountState input, FillArgs args) {
String fullName = input.getAccount().getFullName();
- Set<String> parts = SchemaUtil.getNameParts(
- fullName,
- Iterables.transform(
- input.getExternalIds(),
- AccountExternalId::getEmailAddress));
+ Set<String> parts =
+ SchemaUtil.getNameParts(
+ fullName,
+ Iterables.transform(input.getExternalIds(), AccountExternalId::getEmailAddress));
// Additional values not currently added by getPersonParts.
// TODO(dborowitz): Move to getPersonParts and remove this hack.
@@ -73,8 +67,7 @@
};
public static final FieldDef<AccountState, String> FULL_NAME =
- new FieldDef.Single<AccountState, String>("full_name", FieldType.EXACT,
- false) {
+ new FieldDef.Single<AccountState, String>("full_name", FieldType.EXACT, false) {
@Override
public String get(AccountState input, FillArgs args) {
return input.getAccount().getFullName();
@@ -82,8 +75,7 @@
};
public static final FieldDef<AccountState, String> ACTIVE =
- new FieldDef.Single<AccountState, String>(
- "inactive", FieldType.EXACT, false) {
+ new FieldDef.Single<AccountState, String>("inactive", FieldType.EXACT, false) {
@Override
public String get(AccountState input, FillArgs args) {
return input.getAccount().isActive() ? "1" : "0";
@@ -91,23 +83,20 @@
};
public static final FieldDef<AccountState, Iterable<String>> EMAIL =
- new FieldDef.Repeatable<AccountState, String>(
- "email", FieldType.PREFIX, false) {
+ new FieldDef.Repeatable<AccountState, String>("email", FieldType.PREFIX, false) {
@Override
public Iterable<String> get(AccountState input, FillArgs args) {
return FluentIterable.from(input.getExternalIds())
- .transform(AccountExternalId::getEmailAddress)
- .append(
- Collections.singleton(input.getAccount().getPreferredEmail()))
- .filter(Predicates.notNull())
- .transform(String::toLowerCase)
- .toSet();
+ .transform(AccountExternalId::getEmailAddress)
+ .append(Collections.singleton(input.getAccount().getPreferredEmail()))
+ .filter(Predicates.notNull())
+ .transform(String::toLowerCase)
+ .toSet();
}
};
public static final FieldDef<AccountState, Timestamp> REGISTERED =
- new FieldDef.Single<AccountState, Timestamp>(
- "registered", FieldType.TIMESTAMP, false) {
+ new FieldDef.Single<AccountState, Timestamp>("registered", FieldType.TIMESTAMP, false) {
@Override
public Timestamp get(AccountState input, FillArgs args) {
return input.getAccount().getRegisteredOn();
@@ -115,8 +104,7 @@
};
public static final FieldDef<AccountState, String> USERNAME =
- new FieldDef.Single<AccountState, String>(
- "username", FieldType.EXACT, false) {
+ new FieldDef.Single<AccountState, String>("username", FieldType.EXACT, false) {
@Override
public String get(AccountState input, FillArgs args) {
return Strings.nullToEmpty(input.getUserName()).toLowerCase();
@@ -124,8 +112,7 @@
};
public static final FieldDef<AccountState, Iterable<String>> WATCHED_PROJECT =
- new FieldDef.Repeatable<AccountState, String>(
- "watchedproject", FieldType.EXACT, false) {
+ new FieldDef.Repeatable<AccountState, String>("watchedproject", FieldType.EXACT, false) {
@Override
public Iterable<String> get(AccountState input, FillArgs args) {
return FluentIterable.from(input.getProjectWatches().keySet())
@@ -134,6 +121,5 @@
}
};
- private AccountField() {
- }
+ private AccountField() {}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/index/account/AccountIndex.java b/gerrit-server/src/main/java/com/google/gerrit/server/index/account/AccountIndex.java
index 406982a..ffa94ec 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/index/account/AccountIndex.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/index/account/AccountIndex.java
@@ -22,9 +22,8 @@
import com.google.gerrit.server.query.account.AccountPredicates;
public interface AccountIndex extends Index<Account.Id, AccountState> {
- public interface Factory extends
- IndexDefinition.IndexFactory<Account.Id, AccountState, AccountIndex> {
- }
+ public interface Factory
+ extends IndexDefinition.IndexFactory<Account.Id, AccountState, AccountIndex> {}
@Override
default Predicate<AccountState> keyPredicate(Account.Id id) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/index/account/AccountIndexCollection.java b/gerrit-server/src/main/java/com/google/gerrit/server/index/account/AccountIndexCollection.java
index 6aa516c..2eb8235 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/index/account/AccountIndexCollection.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/index/account/AccountIndexCollection.java
@@ -22,10 +22,9 @@
import com.google.inject.Singleton;
@Singleton
-public class AccountIndexCollection extends
- IndexCollection<Account.Id, AccountState, AccountIndex> {
+public class AccountIndexCollection
+ extends IndexCollection<Account.Id, AccountState, AccountIndex> {
@Inject
@VisibleForTesting
- public AccountIndexCollection() {
- }
+ public AccountIndexCollection() {}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/index/account/AccountIndexDefinition.java b/gerrit-server/src/main/java/com/google/gerrit/server/index/account/AccountIndexDefinition.java
index 31a9250..72f23be 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/index/account/AccountIndexDefinition.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/index/account/AccountIndexDefinition.java
@@ -29,7 +29,10 @@
AccountIndexCollection indexCollection,
AccountIndex.Factory indexFactory,
@Nullable AllAccountsIndexer allAccountsIndexer) {
- super(AccountSchemaDefinitions.INSTANCE, indexCollection, indexFactory,
+ super(
+ AccountSchemaDefinitions.INSTANCE,
+ indexCollection,
+ indexFactory,
Providers.of(allAccountsIndexer));
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/index/account/AccountIndexRewriter.java b/gerrit-server/src/main/java/com/google/gerrit/server/index/account/AccountIndexRewriter.java
index 65e9b09..4fd7833 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/index/account/AccountIndexRewriter.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/index/account/AccountIndexRewriter.java
@@ -36,8 +36,8 @@
}
@Override
- public Predicate<AccountState> rewrite(Predicate<AccountState> in,
- QueryOptions opts) throws QueryParseException {
+ public Predicate<AccountState> rewrite(Predicate<AccountState> in, QueryOptions opts)
+ throws QueryParseException {
if (!AccountPredicates.hasActive(in)) {
in = Predicate.and(in, AccountPredicates.isActive());
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/index/account/AccountIndexer.java b/gerrit-server/src/main/java/com/google/gerrit/server/index/account/AccountIndexer.java
index 3203563..dd24714 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/index/account/AccountIndexer.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/index/account/AccountIndexer.java
@@ -15,7 +15,6 @@
package com.google.gerrit.server.index.account;
import com.google.gerrit.reviewdb.client.Account;
-
import java.io.IOException;
public interface AccountIndexer {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/index/account/AccountIndexerImpl.java b/gerrit-server/src/main/java/com/google/gerrit/server/index/account/AccountIndexerImpl.java
index d3bfeb8..027d4c3 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/index/account/AccountIndexerImpl.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/index/account/AccountIndexerImpl.java
@@ -22,7 +22,6 @@
import com.google.gerrit.server.index.Index;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
-
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
@@ -30,6 +29,7 @@
public class AccountIndexerImpl implements AccountIndexer {
public interface Factory {
AccountIndexerImpl create(AccountIndexCollection indexes);
+
AccountIndexerImpl create(@Nullable AccountIndex index);
}
@@ -38,16 +38,14 @@
private final AccountIndex index;
@AssistedInject
- AccountIndexerImpl(AccountCache byIdCache,
- @Assisted AccountIndexCollection indexes) {
+ AccountIndexerImpl(AccountCache byIdCache, @Assisted AccountIndexCollection indexes) {
this.byIdCache = byIdCache;
this.indexes = indexes;
this.index = null;
}
@AssistedInject
- AccountIndexerImpl(AccountCache byIdCache,
- @Assisted AccountIndex index) {
+ AccountIndexerImpl(AccountCache byIdCache, @Assisted AccountIndex index) {
this.byIdCache = byIdCache;
this.indexes = null;
this.index = index;
@@ -65,8 +63,6 @@
return indexes.getWriteIndexes();
}
- return index != null
- ? Collections.singleton(index)
- : ImmutableSet.<AccountIndex> of();
+ return index != null ? Collections.singleton(index) : ImmutableSet.<AccountIndex>of();
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/index/account/AccountSchemaDefinitions.java b/gerrit-server/src/main/java/com/google/gerrit/server/index/account/AccountSchemaDefinitions.java
index 05e49b9..011f1d1 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/index/account/AccountSchemaDefinitions.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/index/account/AccountSchemaDefinitions.java
@@ -22,27 +22,23 @@
public class AccountSchemaDefinitions extends SchemaDefinitions<AccountState> {
@Deprecated
- static final Schema<AccountState> V1 = schema(
- AccountField.ID,
- AccountField.ACTIVE,
- AccountField.EMAIL,
- AccountField.EXTERNAL_ID,
- AccountField.NAME_PART,
- AccountField.REGISTERED,
- AccountField.USERNAME);
+ static final Schema<AccountState> V1 =
+ schema(
+ AccountField.ID,
+ AccountField.ACTIVE,
+ AccountField.EMAIL,
+ AccountField.EXTERNAL_ID,
+ AccountField.NAME_PART,
+ AccountField.REGISTERED,
+ AccountField.USERNAME);
- @Deprecated
- static final Schema<AccountState> V2 =
- schema(V1, AccountField.WATCHED_PROJECT);
+ @Deprecated static final Schema<AccountState> V2 = schema(V1, AccountField.WATCHED_PROJECT);
- @Deprecated
- static final Schema<AccountState> V3 =
- schema(V2, AccountField.FULL_NAME);
+ @Deprecated static final Schema<AccountState> V3 = schema(V2, AccountField.FULL_NAME);
static final Schema<AccountState> V4 = schema(V3);
- public static final AccountSchemaDefinitions INSTANCE =
- new AccountSchemaDefinitions();
+ public static final AccountSchemaDefinitions INSTANCE = new AccountSchemaDefinitions();
private AccountSchemaDefinitions() {
super("accounts", AccountState.class);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/index/account/AllAccountsIndexer.java b/gerrit-server/src/main/java/com/google/gerrit/server/index/account/AllAccountsIndexer.java
index 14264af..1b84e8e 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/index/account/AllAccountsIndexer.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/index/account/AllAccountsIndexer.java
@@ -30,12 +30,6 @@
import com.google.gwtorm.server.SchemaFactory;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.lib.ProgressMonitor;
-import org.eclipse.jgit.lib.TextProgressMonitor;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
@@ -43,12 +37,14 @@
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
+import org.eclipse.jgit.lib.ProgressMonitor;
+import org.eclipse.jgit.lib.TextProgressMonitor;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
@Singleton
-public class AllAccountsIndexer
- extends SiteIndexer<Account.Id, AccountState, AccountIndex> {
- private static final Logger log =
- LoggerFactory.getLogger(AllAccountsIndexer.class);
+public class AllAccountsIndexer extends SiteIndexer<Account.Id, AccountState, AccountIndex> {
+ private static final Logger log = LoggerFactory.getLogger(AllAccountsIndexer.class);
private final SchemaFactory<ReviewDb> schemaFactory;
private final ListeningExecutorService executor;
@@ -66,8 +62,7 @@
@Override
public SiteIndexer.Result indexAll(final AccountIndex index) {
- ProgressMonitor progress =
- new TextProgressMonitor(new PrintWriter(progressOut));
+ ProgressMonitor progress = new TextProgressMonitor(new PrintWriter(progressOut));
progress.start(2);
Stopwatch sw = Stopwatch.createStarted();
List<Account.Id> ids;
@@ -80,8 +75,8 @@
return reindexAccounts(index, ids, progress);
}
- private SiteIndexer.Result reindexAccounts(final AccountIndex index,
- List<Account.Id> ids, ProgressMonitor progress) {
+ private SiteIndexer.Result reindexAccounts(
+ final AccountIndex index, List<Account.Id> ids, ProgressMonitor progress) {
progress.beginTask("Reindexing accounts", ids.size());
List<ListenableFuture<?>> futures = new ArrayList<>(ids.size());
AtomicBoolean ok = new AtomicBoolean(true);
@@ -90,22 +85,23 @@
Stopwatch sw = Stopwatch.createStarted();
for (final Account.Id id : ids) {
final String desc = "account " + id;
- ListenableFuture<?> future = executor.submit(
- new Callable<Void>() {
- @Override
- public Void call() throws Exception {
- try {
- accountCache.evict(id);
- index.replace(accountCache.get(id));
- verboseWriter.println("Reindexed " + desc);
- done.incrementAndGet();
- } catch (Exception e) {
- failed.incrementAndGet();
- throw e;
- }
- return null;
- }
- });
+ ListenableFuture<?> future =
+ executor.submit(
+ new Callable<Void>() {
+ @Override
+ public Void call() throws Exception {
+ try {
+ accountCache.evict(id);
+ index.replace(accountCache.get(id));
+ verboseWriter.println("Reindexed " + desc);
+ done.incrementAndGet();
+ } catch (Exception e) {
+ failed.incrementAndGet();
+ throw e;
+ }
+ return null;
+ }
+ });
addErrorListener(future, desc, progress, ok);
futures.add(future);
}
@@ -121,8 +117,7 @@
return new SiteIndexer.Result(sw, ok.get(), done.get(), failed.get());
}
- private List<Account.Id> collectAccounts(ProgressMonitor progress)
- throws OrmException {
+ private List<Account.Id> collectAccounts(ProgressMonitor progress) throws OrmException {
progress.beginTask("Collecting accounts", ProgressMonitor.UNKNOWN);
List<Account.Id> ids = new ArrayList<>();
try (ReviewDb db = schemaFactory.open()) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/index/account/IndexedAccountQuery.java b/gerrit-server/src/main/java/com/google/gerrit/server/index/account/IndexedAccountQuery.java
index 76103fc..8c29266 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/index/account/IndexedAccountQuery.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/index/account/IndexedAccountQuery.java
@@ -26,9 +26,9 @@
public class IndexedAccountQuery extends IndexedQuery<Account.Id, AccountState>
implements DataSource<AccountState> {
- public IndexedAccountQuery(Index<Account.Id, AccountState> index,
- Predicate<AccountState> pred, QueryOptions opts)
- throws QueryParseException {
+ public IndexedAccountQuery(
+ Index<Account.Id, AccountState> index, Predicate<AccountState> pred, QueryOptions opts)
+ throws QueryParseException {
super(index, pred, opts.convertForBackend());
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/index/change/AllChangesIndexer.java b/gerrit-server/src/main/java/com/google/gerrit/server/index/change/AllChangesIndexer.java
index 080aa5b..fd275b8 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/index/change/AllChangesIndexer.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/index/change/AllChangesIndexer.java
@@ -45,7 +45,20 @@
import com.google.gerrit.server.query.change.ChangeData;
import com.google.gwtorm.server.SchemaFactory;
import com.google.inject.Inject;
-
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.SortedSet;
+import java.util.TreeSet;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.atomic.AtomicBoolean;
import org.eclipse.jgit.diff.DiffEntry;
import org.eclipse.jgit.diff.DiffFormatter;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
@@ -66,25 +79,8 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.SortedSet;
-import java.util.TreeSet;
-import java.util.concurrent.Callable;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-public class AllChangesIndexer
- extends SiteIndexer<Change.Id, ChangeData, ChangeIndex> {
- private static final Logger log =
- LoggerFactory.getLogger(AllChangesIndexer.class);
+public class AllChangesIndexer extends SiteIndexer<Change.Id, ChangeData, ChangeIndex> {
+ private static final Logger log = LoggerFactory.getLogger(AllChangesIndexer.class);
private final SchemaFactory<ReviewDb> schemaFactory;
private final ChangeData.Factory changeDataFactory;
@@ -97,7 +93,8 @@
private final AutoMerger autoMerger;
@Inject
- AllChangesIndexer(SchemaFactory<ReviewDb> schemaFactory,
+ AllChangesIndexer(
+ SchemaFactory<ReviewDb> schemaFactory,
ChangeData.Factory changeDataFactory,
GitRepositoryManager repoManager,
@IndexExecutor(BATCH) ListeningExecutorService executor,
@@ -159,26 +156,31 @@
return indexAll(index, projects);
}
- public SiteIndexer.Result indexAll(ChangeIndex index,
- Iterable<ProjectHolder> projects) {
+ public SiteIndexer.Result indexAll(ChangeIndex index, Iterable<ProjectHolder> projects) {
Stopwatch sw = Stopwatch.createStarted();
- final MultiProgressMonitor mpm =
- new MultiProgressMonitor(progressOut, "Reindexing changes");
- final Task projTask = mpm.beginSubTask("projects",
- (projects instanceof Collection)
- ? ((Collection<?>) projects).size()
- : MultiProgressMonitor.UNKNOWN);
- final Task doneTask = mpm.beginSubTask(null,
- totalWork >= 0 ? totalWork : MultiProgressMonitor.UNKNOWN);
+ final MultiProgressMonitor mpm = new MultiProgressMonitor(progressOut, "Reindexing changes");
+ final Task projTask =
+ mpm.beginSubTask(
+ "projects",
+ (projects instanceof Collection)
+ ? ((Collection<?>) projects).size()
+ : MultiProgressMonitor.UNKNOWN);
+ final Task doneTask =
+ mpm.beginSubTask(null, totalWork >= 0 ? totalWork : MultiProgressMonitor.UNKNOWN);
final Task failedTask = mpm.beginSubTask("failed", MultiProgressMonitor.UNKNOWN);
final List<ListenableFuture<?>> futures = new ArrayList<>();
final AtomicBoolean ok = new AtomicBoolean(true);
for (final ProjectHolder project : projects) {
- ListenableFuture<?> future = executor.submit(reindexProject(
- indexerFactory.create(executor, index), project.name, doneTask,
- failedTask, verboseWriter));
+ ListenableFuture<?> future =
+ executor.submit(
+ reindexProject(
+ indexerFactory.create(executor, index),
+ project.name,
+ doneTask,
+ failedTask,
+ verboseWriter));
addErrorListener(future, "project " + project.name, projTask, ok);
futures.add(future);
}
@@ -204,15 +206,19 @@
int nTotal = nFailed + nDone;
double pctFailed = ((double) nFailed) / nTotal * 100;
if (pctFailed > 10) {
- log.error("Failed {}/{} changes ({}%); not marking new index as ready",
+ log.error(
+ "Failed {}/{} changes ({}%); not marking new index as ready",
nFailed, nTotal, Math.round(pctFailed));
ok.set(false);
}
return new Result(sw, ok.get(), nDone, nFailed);
}
- private Callable<Void> reindexProject(final ChangeIndexer indexer,
- final Project.NameKey project, final Task done, final Task failed,
+ private Callable<Void> reindexProject(
+ final ChangeIndexer indexer,
+ final Project.NameKey project,
+ final Task done,
+ final Task failed,
final PrintWriter verboseWriter) {
return new Callable<Void>() {
@Override
@@ -235,14 +241,9 @@
byId.put(r.getObjectId(), changeDataFactory.create(db, cn));
}
}
- new ProjectIndexer(indexer,
- mergeStrategy,
- autoMerger,
- byId,
- repo,
- done,
- failed,
- verboseWriter).call();
+ new ProjectIndexer(
+ indexer, mergeStrategy, autoMerger, byId, repo, done, failed, verboseWriter)
+ .call();
} catch (RepositoryNotFoundException rnfe) {
log.error(rnfe.getMessage());
}
@@ -266,7 +267,8 @@
private final PrintWriter verboseWriter;
private final Repository repo;
- private ProjectIndexer(ChangeIndexer indexer,
+ private ProjectIndexer(
+ ChangeIndexer indexer,
ThreeWayMergeStrategy mergeStrategy,
AutoMerger autoMerger,
ListMultimap<ObjectId, ChangeData> changesByCommitId,
@@ -315,8 +317,7 @@
return null;
}
- private void getPathsAndIndex(RevWalk walk, ObjectInserter ins, ObjectId b)
- throws Exception {
+ private void getPathsAndIndex(RevWalk walk, ObjectInserter ins, ObjectId b) throws Exception {
List<ChangeData> cds = Lists.newArrayList(byId.get(b));
try (DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE)) {
RevCommit bCommit = walk.parseCommit(b);
@@ -324,11 +325,10 @@
RevTree aTree = aFor(bCommit, walk, ins);
df.setRepository(repo);
if (!cds.isEmpty()) {
- List<String> paths = (aTree != null)
- ? getPaths(df.scan(aTree, bTree))
- : Collections.<String>emptyList();
+ List<String> paths =
+ (aTree != null) ? getPaths(df.scan(aTree, bTree)) : Collections.<String>emptyList();
Iterator<ChangeData> cdit = cds.iterator();
- for (ChangeData cd ; cdit.hasNext(); cdit.remove()) {
+ for (ChangeData cd; cdit.hasNext(); cdit.remove()) {
cd = cdit.next();
try {
cd.setCurrentFilePaths(paths);
@@ -361,8 +361,7 @@
return ImmutableList.copyOf(paths);
}
- private RevTree aFor(RevCommit b, RevWalk walk, ObjectInserter ins)
- throws IOException {
+ private RevTree aFor(RevCommit b, RevWalk walk, ObjectInserter ins) throws IOException {
switch (b.getParentCount()) {
case 0:
return walk.parseTree(emptyTree());
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/index/change/ChangeField.java b/gerrit-server/src/main/java/com/google/gerrit/server/index/change/ChangeField.java
index c943043..4747e1a 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/index/change/ChangeField.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/index/change/ChangeField.java
@@ -59,9 +59,6 @@
import com.google.gwtorm.protobuf.ProtobufCodec;
import com.google.gwtorm.server.OrmException;
import com.google.protobuf.CodedOutputStream;
-
-import org.eclipse.jgit.revwalk.FooterLine;
-
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.sql.Timestamp;
@@ -71,18 +68,17 @@
import java.util.List;
import java.util.Map;
import java.util.Set;
+import org.eclipse.jgit.revwalk.FooterLine;
/**
* Fields indexed on change documents.
- * <p>
- * Each field corresponds to both a field name supported by
- * {@link ChangeQueryBuilder} for querying that field, and a method on
- * {@link ChangeData} used for populating the corresponding document fields in
- * the secondary index.
- * <p>
- * Field names are all lowercase alphanumeric plus underscore; index
- * implementations may create unambiguous derived field names containing other
- * characters.
+ *
+ * <p>Each field corresponds to both a field name supported by {@link ChangeQueryBuilder} for
+ * querying that field, and a method on {@link ChangeData} used for populating the corresponding
+ * document fields in the secondary index.
+ *
+ * <p>Field names are all lowercase alphanumeric plus underscore; index implementations may create
+ * unambiguous derived field names containing other characters.
*/
public class ChangeField {
public static final int NO_ASSIGNEE = -1;
@@ -91,8 +87,7 @@
/** Legacy change ID. */
public static final FieldDef<ChangeData, Integer> LEGACY_ID =
- new FieldDef.Single<ChangeData, Integer>("legacy_id",
- FieldType.INTEGER, true) {
+ new FieldDef.Single<ChangeData, Integer>("legacy_id", FieldType.INTEGER, true) {
@Override
public Integer get(ChangeData input, FillArgs args) {
return input.getId().get();
@@ -101,11 +96,10 @@
/** Newer style Change-Id key. */
public static final FieldDef<ChangeData, String> ID =
- new FieldDef.Single<ChangeData, String>(ChangeQueryBuilder.FIELD_CHANGE_ID,
- FieldType.PREFIX, false) {
+ new FieldDef.Single<ChangeData, String>(
+ ChangeQueryBuilder.FIELD_CHANGE_ID, FieldType.PREFIX, false) {
@Override
- public String get(ChangeData input, FillArgs args)
- throws OrmException {
+ public String get(ChangeData input, FillArgs args) throws OrmException {
Change c = input.change();
if (c == null) {
return null;
@@ -116,11 +110,10 @@
/** Change status string, in the same format as {@code status:}. */
public static final FieldDef<ChangeData, String> STATUS =
- new FieldDef.Single<ChangeData, String>(ChangeQueryBuilder.FIELD_STATUS,
- FieldType.EXACT, false) {
+ new FieldDef.Single<ChangeData, String>(
+ ChangeQueryBuilder.FIELD_STATUS, FieldType.EXACT, false) {
@Override
- public String get(ChangeData input, FillArgs args)
- throws OrmException {
+ public String get(ChangeData input, FillArgs args) throws OrmException {
Change c = input.change();
if (c == null) {
return null;
@@ -134,8 +127,7 @@
new FieldDef.Single<ChangeData, String>(
ChangeQueryBuilder.FIELD_PROJECT, FieldType.EXACT, true) {
@Override
- public String get(ChangeData input, FillArgs args)
- throws OrmException {
+ public String get(ChangeData input, FillArgs args) throws OrmException {
Change c = input.change();
if (c == null) {
return null;
@@ -149,8 +141,7 @@
new FieldDef.Single<ChangeData, String>(
ChangeQueryBuilder.FIELD_PROJECTS, FieldType.PREFIX, false) {
@Override
- public String get(ChangeData input, FillArgs args)
- throws OrmException {
+ public String get(ChangeData input, FillArgs args) throws OrmException {
Change c = input.change();
if (c == null) {
return null;
@@ -164,8 +155,7 @@
new FieldDef.Single<ChangeData, String>(
ChangeQueryBuilder.FIELD_REF, FieldType.EXACT, false) {
@Override
- public String get(ChangeData input, FillArgs args)
- throws OrmException {
+ public String get(ChangeData input, FillArgs args) throws OrmException {
Change c = input.change();
if (c == null) {
return null;
@@ -176,22 +166,18 @@
/** Topic, a short annotation on the branch. */
public static final FieldDef<ChangeData, String> EXACT_TOPIC =
- new FieldDef.Single<ChangeData, String>(
- "topic4", FieldType.EXACT, false) {
+ new FieldDef.Single<ChangeData, String>("topic4", FieldType.EXACT, false) {
@Override
- public String get(ChangeData input, FillArgs args)
- throws OrmException {
+ public String get(ChangeData input, FillArgs args) throws OrmException {
return getTopic(input);
}
};
/** Topic, a short annotation on the branch. */
public static final FieldDef<ChangeData, String> FUZZY_TOPIC =
- new FieldDef.Single<ChangeData, String>(
- "topic5", FieldType.FULL_TEXT, false) {
+ new FieldDef.Single<ChangeData, String>("topic5", FieldType.FULL_TEXT, false) {
@Override
- public String get(ChangeData input, FillArgs args)
- throws OrmException {
+ public String get(ChangeData input, FillArgs args) throws OrmException {
return getTopic(input);
}
};
@@ -201,8 +187,7 @@
new FieldDef.Single<ChangeData, String>(
ChangeQueryBuilder.FIELD_SUBMISSIONID, FieldType.EXACT, false) {
@Override
- public String get(ChangeData input, FillArgs args)
- throws OrmException {
+ public String get(ChangeData input, FillArgs args) throws OrmException {
Change c = input.change();
if (c == null) {
return null;
@@ -213,11 +198,9 @@
/** Last update time since January 1, 1970. */
public static final FieldDef<ChangeData, Timestamp> UPDATED =
- new FieldDef.Single<ChangeData, Timestamp>(
- "updated2", FieldType.TIMESTAMP, true) {
+ new FieldDef.Single<ChangeData, Timestamp>("updated2", FieldType.TIMESTAMP, true) {
@Override
- public Timestamp get(ChangeData input, FillArgs args)
- throws OrmException {
+ public Timestamp get(ChangeData input, FillArgs args) throws OrmException {
Change c = input.change();
if (c == null) {
return null;
@@ -232,10 +215,8 @@
// Named for backwards compatibility.
ChangeQueryBuilder.FIELD_FILE, FieldType.EXACT, false) {
@Override
- public Iterable<String> get(ChangeData input, FillArgs args)
- throws OrmException {
- return firstNonNull(input.currentFilePaths(),
- ImmutableList.<String> of());
+ public Iterable<String> get(ChangeData input, FillArgs args) throws OrmException {
+ return firstNonNull(input.currentFilePaths(), ImmutableList.<String>of());
}
};
@@ -259,24 +240,17 @@
new FieldDef.Repeatable<ChangeData, String>(
ChangeQueryBuilder.FIELD_HASHTAG, FieldType.EXACT, false) {
@Override
- public Iterable<String> get(ChangeData input, FillArgs args)
- throws OrmException {
- return input.hashtags().stream()
- .map(String::toLowerCase)
- .collect(toSet());
+ public Iterable<String> get(ChangeData input, FillArgs args) throws OrmException {
+ return input.hashtags().stream().map(String::toLowerCase).collect(toSet());
}
};
/** Hashtags with original case. */
public static final FieldDef<ChangeData, Iterable<byte[]>> HASHTAG_CASE_AWARE =
- new FieldDef.Repeatable<ChangeData, byte[]>(
- "_hashtag", FieldType.STORED_ONLY, true) {
+ new FieldDef.Repeatable<ChangeData, byte[]>("_hashtag", FieldType.STORED_ONLY, true) {
@Override
- public Iterable<byte[]> get(ChangeData input, FillArgs args)
- throws OrmException {
- return input.hashtags().stream()
- .map(t -> t.getBytes(UTF_8))
- .collect(toSet());
+ public Iterable<byte[]> get(ChangeData input, FillArgs args) throws OrmException {
+ return input.hashtags().stream().map(t -> t.getBytes(UTF_8)).collect(toSet());
}
};
@@ -285,8 +259,7 @@
new FieldDef.Repeatable<ChangeData, String>(
ChangeQueryBuilder.FIELD_FILEPART, FieldType.EXACT, false) {
@Override
- public Iterable<String> get(ChangeData input, FillArgs args)
- throws OrmException {
+ public Iterable<String> get(ChangeData input, FillArgs args) throws OrmException {
return getFileParts(input);
}
};
@@ -296,8 +269,7 @@
new FieldDef.Single<ChangeData, Integer>(
ChangeQueryBuilder.FIELD_OWNER, FieldType.INTEGER, false) {
@Override
- public Integer get(ChangeData input, FillArgs args)
- throws OrmException {
+ public Integer get(ChangeData input, FillArgs args) throws OrmException {
Change c = input.change();
if (c == null) {
return null;
@@ -311,8 +283,7 @@
new FieldDef.Single<ChangeData, Integer>(
ChangeQueryBuilder.FIELD_ASSIGNEE, FieldType.INTEGER, false) {
@Override
- public Integer get(ChangeData input, FillArgs args)
- throws OrmException {
+ public Integer get(ChangeData input, FillArgs args) throws OrmException {
Account.Id id = input.change().getAssignee();
return id != null ? id.get() : NO_ASSIGNEE;
}
@@ -320,11 +291,9 @@
/** Reviewer(s) associated with the change. */
public static final FieldDef<ChangeData, Iterable<String>> REVIEWER =
- new FieldDef.Repeatable<ChangeData, String>(
- "reviewer2", FieldType.EXACT, true) {
+ new FieldDef.Repeatable<ChangeData, String>("reviewer2", FieldType.EXACT, true) {
@Override
- public Iterable<String> get(ChangeData input, FillArgs args)
- throws OrmException {
+ public Iterable<String> get(ChangeData input, FillArgs args) throws OrmException {
return getReviewerFieldValues(input.reviewers());
}
};
@@ -332,8 +301,8 @@
@VisibleForTesting
static List<String> getReviewerFieldValues(ReviewerSet reviewers) {
List<String> r = new ArrayList<>(reviewers.asTable().size() * 2);
- for (Table.Cell<ReviewerStateInternal, Account.Id, Timestamp> c
- : reviewers.asTable().cellSet()) {
+ for (Table.Cell<ReviewerStateInternal, Account.Id, Timestamp> c :
+ reviewers.asTable().cellSet()) {
String v = getReviewerFieldValue(c.getRowKey(), c.getColumnKey());
r.add(v);
r.add(v + ',' + c.getValue().getTime());
@@ -341,8 +310,7 @@
return r;
}
- public static String getReviewerFieldValue(ReviewerStateInternal state,
- Account.Id id) {
+ public static String getReviewerFieldValue(ReviewerStateInternal state, Account.Id id) {
return state.toString() + ',' + id;
}
@@ -371,8 +339,7 @@
new FieldDef.Repeatable<ChangeData, String>(
ChangeQueryBuilder.FIELD_COMMIT, FieldType.PREFIX, false) {
@Override
- public Iterable<String> get(ChangeData input, FillArgs args)
- throws OrmException {
+ public Iterable<String> get(ChangeData input, FillArgs args) throws OrmException {
return getRevisions(input);
}
};
@@ -382,8 +349,7 @@
new FieldDef.Repeatable<ChangeData, String>(
ChangeQueryBuilder.FIELD_EXACTCOMMIT, FieldType.EXACT, false) {
@Override
- public Iterable<String> get(ChangeData input, FillArgs args)
- throws OrmException {
+ public Iterable<String> get(ChangeData input, FillArgs args) throws OrmException {
return getRevisions(input);
}
};
@@ -403,15 +369,13 @@
new FieldDef.Repeatable<ChangeData, String>(
ChangeQueryBuilder.FIELD_TR, FieldType.EXACT, false) {
@Override
- public Iterable<String> get(ChangeData input, FillArgs args)
- throws OrmException {
+ public Iterable<String> get(ChangeData input, FillArgs args) throws OrmException {
try {
List<FooterLine> footers = input.commitFooters();
if (footers == null) {
return ImmutableSet.of();
}
- return Sets.newHashSet(
- args.trackingFooters.extract(footers).values());
+ return Sets.newHashSet(args.trackingFooters.extract(footers).values());
} catch (IOException e) {
throw new OrmException(e);
}
@@ -424,34 +388,29 @@
new FieldDef.Repeatable<ChangeData, String>(
ChangeQueryBuilder.FIELD_LABEL, FieldType.EXACT, false) {
@Override
- public Iterable<String> get(ChangeData input, FillArgs args)
- throws OrmException {
+ public Iterable<String> get(ChangeData input, FillArgs args) throws OrmException {
return getLabels(input, false);
}
};
/** List of labels on the current patch set including change owner votes. */
public static final FieldDef<ChangeData, Iterable<String>> LABEL2 =
- new FieldDef.Repeatable<ChangeData, String>(
- "label2", FieldType.EXACT, false) {
+ new FieldDef.Repeatable<ChangeData, String>("label2", FieldType.EXACT, false) {
@Override
- public Iterable<String> get(ChangeData input, FillArgs args)
- throws OrmException {
+ public Iterable<String> get(ChangeData input, FillArgs args) throws OrmException {
return getLabels(input, true);
}
};
- private static Iterable<String> getLabels(ChangeData input, boolean owners)
- throws OrmException {
+ private static Iterable<String> getLabels(ChangeData input, boolean owners) throws OrmException {
Set<String> allApprovals = new HashSet<>();
Set<String> distinctApprovals = new HashSet<>();
for (PatchSetApproval a : input.currentApprovals()) {
if (a.getValue() != 0 && !a.isLegacySubmit()) {
- allApprovals.add(formatLabel(a.getLabel(), a.getValue(),
- a.getAccountId()));
+ allApprovals.add(formatLabel(a.getLabel(), a.getValue(), a.getAccountId()));
if (owners && input.change().getOwner().equals(a.getAccountId())) {
- allApprovals.add(formatLabel(a.getLabel(), a.getValue(),
- ChangeQueryBuilder.OWNER_ACCOUNT_ID));
+ allApprovals.add(
+ formatLabel(a.getLabel(), a.getValue(), ChangeQueryBuilder.OWNER_ACCOUNT_ID));
}
distinctApprovals.add(formatLabel(a.getLabel(), a.getValue()));
}
@@ -477,44 +436,40 @@
}
/**
- * The exact email address, or any part of the author name or email address,
- * in the current patch set.
+ * The exact email address, or any part of the author name or email address, in the current patch
+ * set.
*/
public static final FieldDef<ChangeData, Iterable<String>> AUTHOR =
new FieldDef.Repeatable<ChangeData, String>(
ChangeQueryBuilder.FIELD_AUTHOR, FieldType.FULL_TEXT, false) {
@Override
- public Iterable<String> get(ChangeData input, FillArgs args)
- throws OrmException {
+ public Iterable<String> get(ChangeData input, FillArgs args) throws OrmException {
return getAuthorParts(input);
}
};
/**
- * The exact email address, or any part of the committer name or email address,
- * in the current patch set.
+ * The exact email address, or any part of the committer name or email address, in the current
+ * patch set.
*/
public static final FieldDef<ChangeData, Iterable<String>> COMMITTER =
new FieldDef.Repeatable<ChangeData, String>(
ChangeQueryBuilder.FIELD_COMMITTER, FieldType.FULL_TEXT, false) {
@Override
- public Iterable<String> get(ChangeData input, FillArgs args)
- throws OrmException {
+ public Iterable<String> get(ChangeData input, FillArgs args) throws OrmException {
return getCommitterParts(input);
}
};
public static class ChangeProtoField extends FieldDef.Single<ChangeData, byte[]> {
- public static final ProtobufCodec<Change> CODEC =
- CodecFactory.encoder(Change.class);
+ public static final ProtobufCodec<Change> CODEC = CodecFactory.encoder(Change.class);
private ChangeProtoField() {
super("_change", FieldType.STORED_ONLY, true);
}
@Override
- public byte[] get(ChangeData input, FieldDef.FillArgs args)
- throws OrmException {
+ public byte[] get(ChangeData input, FieldDef.FillArgs args) throws OrmException {
Change c = input.change();
if (c == null) {
return null;
@@ -526,8 +481,7 @@
/** Serialized change object, used for pre-populating results. */
public static final ChangeProtoField CHANGE = new ChangeProtoField();
- public static class PatchSetApprovalProtoField
- extends FieldDef.Repeatable<ChangeData, byte[]> {
+ public static class PatchSetApprovalProtoField extends FieldDef.Repeatable<ChangeData, byte[]> {
public static final ProtobufCodec<PatchSetApproval> CODEC =
CodecFactory.encoder(PatchSetApproval.class);
@@ -536,25 +490,22 @@
}
@Override
- public Iterable<byte[]> get(ChangeData input, FillArgs args)
- throws OrmException {
+ public Iterable<byte[]> get(ChangeData input, FillArgs args) throws OrmException {
return toProtos(CODEC, input.currentApprovals());
}
}
- /**
- * Serialized approvals for the current patch set, used for pre-populating
- * results.
- */
- public static final PatchSetApprovalProtoField APPROVAL =
- new PatchSetApprovalProtoField();
+ /** Serialized approvals for the current patch set, used for pre-populating results. */
+ public static final PatchSetApprovalProtoField APPROVAL = new PatchSetApprovalProtoField();
public static String formatLabel(String label, int value) {
return formatLabel(label, value, null);
}
public static String formatLabel(String label, int value, Account.Id accountId) {
- return label.toLowerCase() + (value >= 0 ? "+" : "") + value
+ return label.toLowerCase()
+ + (value >= 0 ? "+" : "")
+ + value
+ (accountId != null ? "," + formatAccount(accountId) : "");
}
@@ -567,8 +518,8 @@
/** Commit message of the current patch set. */
public static final FieldDef<ChangeData, String> COMMIT_MESSAGE =
- new FieldDef.Single<ChangeData, String>(ChangeQueryBuilder.FIELD_MESSAGE,
- FieldType.FULL_TEXT, false) {
+ new FieldDef.Single<ChangeData, String>(
+ ChangeQueryBuilder.FIELD_MESSAGE, FieldType.FULL_TEXT, false) {
@Override
public String get(ChangeData input, FillArgs args) throws OrmException {
try {
@@ -581,11 +532,10 @@
/** Summary or inline comment. */
public static final FieldDef<ChangeData, Iterable<String>> COMMENT =
- new FieldDef.Repeatable<ChangeData, String>(ChangeQueryBuilder.FIELD_COMMENT,
- FieldType.FULL_TEXT, false) {
+ new FieldDef.Repeatable<ChangeData, String>(
+ ChangeQueryBuilder.FIELD_COMMENT, FieldType.FULL_TEXT, false) {
@Override
- public Iterable<String> get(ChangeData input, FillArgs args)
- throws OrmException {
+ public Iterable<String> get(ChangeData input, FillArgs args) throws OrmException {
Set<String> r = new HashSet<>();
for (Comment c : input.publishedComments()) {
r.add(c.message);
@@ -602,8 +552,7 @@
new FieldDef.Single<ChangeData, String>(
ChangeQueryBuilder.FIELD_MERGEABLE, FieldType.EXACT, true) {
@Override
- public String get(ChangeData input, FillArgs args)
- throws OrmException {
+ public String get(ChangeData input, FillArgs args) throws OrmException {
Boolean m = input.isMergeable();
if (m == null) {
return null;
@@ -617,11 +566,8 @@
new FieldDef.Single<ChangeData, Integer>(
ChangeQueryBuilder.FIELD_ADDED, FieldType.INTEGER_RANGE, true) {
@Override
- public Integer get(ChangeData input, FillArgs args)
- throws OrmException {
- return input.changedLines().isPresent()
- ? input.changedLines().get().insertions
- : null;
+ public Integer get(ChangeData input, FillArgs args) throws OrmException {
+ return input.changedLines().isPresent() ? input.changedLines().get().insertions : null;
}
};
@@ -630,11 +576,8 @@
new FieldDef.Single<ChangeData, Integer>(
ChangeQueryBuilder.FIELD_DELETED, FieldType.INTEGER_RANGE, true) {
@Override
- public Integer get(ChangeData input, FillArgs args)
- throws OrmException {
- return input.changedLines().isPresent()
- ? input.changedLines().get().deletions
- : null;
+ public Integer get(ChangeData input, FillArgs args) throws OrmException {
+ return input.changedLines().isPresent() ? input.changedLines().get().deletions : null;
}
};
@@ -643,11 +586,8 @@
new FieldDef.Single<ChangeData, Integer>(
ChangeQueryBuilder.FIELD_DELTA, FieldType.INTEGER_RANGE, false) {
@Override
- public Integer get(ChangeData input, FillArgs args)
- throws OrmException {
- return input.changedLines()
- .map(c -> c.insertions + c.deletions)
- .orElse(null);
+ public Integer get(ChangeData input, FillArgs args) throws OrmException {
+ return input.changedLines().map(c -> c.insertions + c.deletions).orElse(null);
}
};
@@ -656,8 +596,7 @@
new FieldDef.Repeatable<ChangeData, Integer>(
ChangeQueryBuilder.FIELD_COMMENTBY, FieldType.INTEGER, false) {
@Override
- public Iterable<Integer> get(ChangeData input, FillArgs args)
- throws OrmException {
+ public Iterable<Integer> get(ChangeData input, FillArgs args) throws OrmException {
Set<Integer> r = new HashSet<>();
for (ChangeMessage m : input.messages()) {
if (m.getAuthor() != null) {
@@ -671,20 +610,16 @@
}
};
- /**
- * Star labels on this change in the format: <account-id>:<label>
- */
+ /** Star labels on this change in the format: <account-id>:<label> */
public static final FieldDef<ChangeData, Iterable<String>> STAR =
new FieldDef.Repeatable<ChangeData, String>(
ChangeQueryBuilder.FIELD_STAR, FieldType.EXACT, true) {
@Override
- public Iterable<String> get(ChangeData input, FillArgs args)
- throws OrmException {
+ public Iterable<String> get(ChangeData input, FillArgs args) throws OrmException {
return Iterables.transform(
input.stars().entries(),
(Map.Entry<Account.Id, String> e) -> {
- return StarredChangesUtil.StarField.create(
- e.getKey(), e.getValue()).toString();
+ return StarredChangesUtil.StarField.create(e.getKey(), e.getValue()).toString();
});
}
};
@@ -694,8 +629,7 @@
new FieldDef.Repeatable<ChangeData, Integer>(
ChangeQueryBuilder.FIELD_STARBY, FieldType.INTEGER, false) {
@Override
- public Iterable<Integer> get(ChangeData input, FillArgs args)
- throws OrmException {
+ public Iterable<Integer> get(ChangeData input, FillArgs args) throws OrmException {
return Iterables.transform(input.stars().keySet(), Account.Id::get);
}
};
@@ -705,8 +639,7 @@
new FieldDef.Repeatable<ChangeData, String>(
ChangeQueryBuilder.FIELD_GROUP, FieldType.EXACT, false) {
@Override
- public Iterable<String> get(ChangeData input, FillArgs args)
- throws OrmException {
+ public Iterable<String> get(ChangeData input, FillArgs args) throws OrmException {
Set<String> r = Sets.newHashSetWithExpectedSize(1);
for (PatchSet ps : input.patchSets()) {
r.addAll(ps.getGroups());
@@ -715,18 +648,15 @@
}
};
- public static class PatchSetProtoField
- extends FieldDef.Repeatable<ChangeData, byte[]> {
- public static final ProtobufCodec<PatchSet> CODEC =
- CodecFactory.encoder(PatchSet.class);
+ public static class PatchSetProtoField extends FieldDef.Repeatable<ChangeData, byte[]> {
+ public static final ProtobufCodec<PatchSet> CODEC = CodecFactory.encoder(PatchSet.class);
private PatchSetProtoField() {
super("_patch_set", FieldType.STORED_ONLY, true);
}
@Override
- public Iterable<byte[]> get(ChangeData input, FieldDef.FillArgs args)
- throws OrmException {
+ public Iterable<byte[]> get(ChangeData input, FieldDef.FillArgs args) throws OrmException {
return toProtos(CODEC, input.patchSets());
}
}
@@ -739,44 +669,36 @@
new FieldDef.Repeatable<ChangeData, Integer>(
ChangeQueryBuilder.FIELD_EDITBY, FieldType.INTEGER, false) {
@Override
- public Iterable<Integer> get(ChangeData input, FillArgs args)
- throws OrmException {
- return input.editsByUser().stream()
- .map(Account.Id::get)
- .collect(toSet());
+ public Iterable<Integer> get(ChangeData input, FillArgs args) throws OrmException {
+ return input.editsByUser().stream().map(Account.Id::get).collect(toSet());
}
};
-
/** Users who have draft comments on this change. */
public static final FieldDef<ChangeData, Iterable<Integer>> DRAFTBY =
new FieldDef.Repeatable<ChangeData, Integer>(
ChangeQueryBuilder.FIELD_DRAFTBY, FieldType.INTEGER, false) {
@Override
- public Iterable<Integer> get(ChangeData input, FillArgs args)
- throws OrmException {
- return input.draftsByUser().stream()
- .map(Account.Id::get)
- .collect(toSet());
+ public Iterable<Integer> get(ChangeData input, FillArgs args) throws OrmException {
+ return input.draftsByUser().stream().map(Account.Id::get).collect(toSet());
}
};
/**
* Users the change was reviewed by since the last author update.
- * <p>
- * A change is considered reviewed by a user if the latest update by that user
- * is newer than the latest update by the change author. Both top-level change
- * messages and new patch sets are considered to be updates.
- * <p>
- * If the latest update is by the change owner, then the special value {@link
- * #NOT_REVIEWED} is emitted.
+ *
+ * <p>A change is considered reviewed by a user if the latest update by that user is newer than
+ * the latest update by the change author. Both top-level change messages and new patch sets are
+ * considered to be updates.
+ *
+ * <p>If the latest update is by the change owner, then the special value {@link #NOT_REVIEWED} is
+ * emitted.
*/
public static final FieldDef<ChangeData, Iterable<Integer>> REVIEWEDBY =
new FieldDef.Repeatable<ChangeData, Integer>(
ChangeQueryBuilder.FIELD_REVIEWEDBY, FieldType.INTEGER, true) {
@Override
- public Iterable<Integer> get(ChangeData input, FillArgs args)
- throws OrmException {
+ public Iterable<Integer> get(ChangeData input, FillArgs args) throws OrmException {
Set<Account.Id> reviewedBy = input.reviewedBy();
if (reviewedBy.isEmpty()) {
return ImmutableSet.of(NOT_REVIEWED);
@@ -792,19 +714,16 @@
// Submit rule options in this class should never use fastEvalLabels. This
// slows down indexing slightly but produces correct search results.
public static final SubmitRuleOptions SUBMIT_RULE_OPTIONS_LENIENT =
- SubmitRuleOptions.defaults()
- .allowClosed(true)
- .allowDraft(true)
- .build();
+ SubmitRuleOptions.defaults().allowClosed(true).allowDraft(true).build();
public static final SubmitRuleOptions SUBMIT_RULE_OPTIONS_STRICT =
SubmitRuleOptions.defaults().build();
/**
* JSON type for storing SubmitRecords.
- * <p>
- * Stored fields need to use a stable format over a long period; this type
- * insulates the index from implementation changes in SubmitRecord itself.
+ *
+ * <p>Stored fields need to use a stable format over a long period; this type insulates the index
+ * from implementation changes in SubmitRecord itself.
*/
static class StoredSubmitRecord {
static class StoredLabel {
@@ -826,8 +745,7 @@
StoredLabel sl = new StoredLabel();
sl.label = label.label;
sl.status = label.status;
- sl.appliedBy =
- label.appliedBy != null ? label.appliedBy.get() : null;
+ sl.appliedBy = label.appliedBy != null ? label.appliedBy.get() : null;
this.labels.add(sl);
}
}
@@ -843,9 +761,7 @@
SubmitRecord.Label srl = new SubmitRecord.Label();
srl.label = label.label;
srl.status = label.status;
- srl.appliedBy = label.appliedBy != null
- ? new Account.Id(label.appliedBy)
- : null;
+ srl.appliedBy = label.appliedBy != null ? new Account.Id(label.appliedBy) : null;
rec.labels.add(srl);
}
}
@@ -854,36 +770,30 @@
}
public static final FieldDef<ChangeData, Iterable<String>> SUBMIT_RECORD =
- new FieldDef.Repeatable<ChangeData, String>(
- "submit_record", FieldType.EXACT, false) {
+ new FieldDef.Repeatable<ChangeData, String>("submit_record", FieldType.EXACT, false) {
@Override
- public Iterable<String> get(ChangeData input, FillArgs args)
- throws OrmException {
+ public Iterable<String> get(ChangeData input, FillArgs args) throws OrmException {
return formatSubmitRecordValues(input);
}
};
- public static final FieldDef<ChangeData, Iterable<byte[]>>
- STORED_SUBMIT_RECORD_STRICT =
- new FieldDef.Repeatable<ChangeData, byte[]>(
- "full_submit_record_strict", FieldType.STORED_ONLY, true) {
- @Override
- public Iterable<byte[]> get(ChangeData input, FillArgs args)
- throws OrmException {
- return storedSubmitRecords(input, SUBMIT_RULE_OPTIONS_STRICT);
- }
- };
+ public static final FieldDef<ChangeData, Iterable<byte[]>> STORED_SUBMIT_RECORD_STRICT =
+ new FieldDef.Repeatable<ChangeData, byte[]>(
+ "full_submit_record_strict", FieldType.STORED_ONLY, true) {
+ @Override
+ public Iterable<byte[]> get(ChangeData input, FillArgs args) throws OrmException {
+ return storedSubmitRecords(input, SUBMIT_RULE_OPTIONS_STRICT);
+ }
+ };
- public static final FieldDef<ChangeData, Iterable<byte[]>>
- STORED_SUBMIT_RECORD_LENIENT =
- new FieldDef.Repeatable<ChangeData, byte[]>(
- "full_submit_record_lenient", FieldType.STORED_ONLY, true) {
- @Override
- public Iterable<byte[]> get(ChangeData input, FillArgs args)
- throws OrmException {
- return storedSubmitRecords(input, SUBMIT_RULE_OPTIONS_LENIENT);
- }
- };
+ public static final FieldDef<ChangeData, Iterable<byte[]>> STORED_SUBMIT_RECORD_LENIENT =
+ new FieldDef.Repeatable<ChangeData, byte[]>(
+ "full_submit_record_lenient", FieldType.STORED_ONLY, true) {
+ @Override
+ public Iterable<byte[]> get(ChangeData input, FillArgs args) throws OrmException {
+ return storedSubmitRecords(input, SUBMIT_RULE_OPTIONS_LENIENT);
+ }
+ };
public static void parseSubmitRecords(
Collection<String> values, SubmitRuleOptions opts, ChangeData out) {
@@ -898,39 +808,34 @@
// Cache the fastEvalLabels variant as well so it can be used by
// ChangeJson.
- out.setSubmitRecords(
- opts.toBuilder().fastEvalLabels(true).build(),
- records);
+ out.setSubmitRecords(opts.toBuilder().fastEvalLabels(true).build(), records);
}
@VisibleForTesting
static List<SubmitRecord> parseSubmitRecords(Collection<String> values) {
- return values.stream()
+ return values
+ .stream()
.map(v -> GSON.fromJson(v, StoredSubmitRecord.class).toSubmitRecord())
.collect(toList());
}
@VisibleForTesting
static List<byte[]> storedSubmitRecords(List<SubmitRecord> records) {
- return Lists.transform(
- records, r -> GSON.toJson(new StoredSubmitRecord(r)).getBytes(UTF_8));
+ return Lists.transform(records, r -> GSON.toJson(new StoredSubmitRecord(r)).getBytes(UTF_8));
}
- private static Iterable<byte[]> storedSubmitRecords(
- ChangeData cd, SubmitRuleOptions opts) throws OrmException {
+ private static Iterable<byte[]> storedSubmitRecords(ChangeData cd, SubmitRuleOptions opts)
+ throws OrmException {
return storedSubmitRecords(cd.submitRecords(opts));
}
- public static List<String> formatSubmitRecordValues(ChangeData cd)
- throws OrmException {
+ public static List<String> formatSubmitRecordValues(ChangeData cd) throws OrmException {
return formatSubmitRecordValues(
- cd.submitRecords(SUBMIT_RULE_OPTIONS_STRICT),
- cd.change().getOwner());
+ cd.submitRecords(SUBMIT_RULE_OPTIONS_STRICT), cd.change().getOwner());
}
@VisibleForTesting
- static List<String> formatSubmitRecordValues(List<SubmitRecord> records,
- Account.Id changeOwner) {
+ static List<String> formatSubmitRecordValues(List<SubmitRecord> records, Account.Id changeOwner) {
List<String> result = new ArrayList<>();
for (SubmitRecord rec : records) {
result.add(rec.status.name());
@@ -953,37 +858,35 @@
}
/**
- * All values of all refs that were used in the course of indexing this
- * document.
- * <p>
- * Emitted as UTF-8 encoded strings of the form
- * {@code project:ref/name:[hex sha]}.
+ * All values of all refs that were used in the course of indexing this document.
+ *
+ * <p>Emitted as UTF-8 encoded strings of the form {@code project:ref/name:[hex sha]}.
*/
public static final FieldDef<ChangeData, Iterable<byte[]>> REF_STATE =
- new FieldDef.Repeatable<ChangeData, byte[]>(
- "ref_state", FieldType.STORED_ONLY, true) {
+ new FieldDef.Repeatable<ChangeData, byte[]>("ref_state", FieldType.STORED_ONLY, true) {
@Override
- public Iterable<byte[]> get(ChangeData input, FillArgs args)
- throws OrmException {
+ public Iterable<byte[]> get(ChangeData input, FillArgs args) throws OrmException {
List<byte[]> result = new ArrayList<>();
Project.NameKey project = input.change().getProject();
- input.editRefs().values().forEach(
- r -> result.add(RefState.of(r).toByteArray(project)));
- input.starRefs().values().forEach(
- r -> result.add(RefState.of(r.ref()).toByteArray(args.allUsers)));
+ input.editRefs().values().forEach(r -> result.add(RefState.of(r).toByteArray(project)));
+ input
+ .starRefs()
+ .values()
+ .forEach(r -> result.add(RefState.of(r.ref()).toByteArray(args.allUsers)));
if (PrimaryStorage.of(input.change()) == PrimaryStorage.NOTE_DB) {
ChangeNotes notes = input.notes();
- result.add(RefState.create(notes.getRefName(), notes.getMetaId())
- .toByteArray(project));
+ result.add(RefState.create(notes.getRefName(), notes.getMetaId()).toByteArray(project));
notes.getRobotComments(); // Force loading robot comments.
RobotCommentNotes robotNotes = notes.getRobotCommentNotes();
result.add(
RefState.create(robotNotes.getRefName(), robotNotes.getMetaId())
.toByteArray(project));
- input.draftRefs().values().forEach(
- r -> result.add(RefState.of(r).toByteArray(args.allUsers)));
+ input
+ .draftRefs()
+ .values()
+ .forEach(r -> result.add(RefState.of(r).toByteArray(args.allUsers)));
}
return result;
@@ -991,32 +894,29 @@
};
/**
- * All ref wildcard patterns that were used in the course of indexing this
- * document.
- * <p>
- * Emitted as UTF-8 encoded strings of the form {@code project:ref/name/*}.
- * See {@link RefStatePattern} for the pattern format.
+ * All ref wildcard patterns that were used in the course of indexing this document.
+ *
+ * <p>Emitted as UTF-8 encoded strings of the form {@code project:ref/name/*}. See {@link
+ * RefStatePattern} for the pattern format.
*/
- public static final FieldDef<ChangeData, Iterable<byte[]>>
- REF_STATE_PATTERN = new FieldDef.Repeatable<ChangeData, byte[]>(
+ public static final FieldDef<ChangeData, Iterable<byte[]>> REF_STATE_PATTERN =
+ new FieldDef.Repeatable<ChangeData, byte[]>(
"ref_state_pattern", FieldType.STORED_ONLY, true) {
@Override
- public Iterable<byte[]> get(ChangeData input, FillArgs args)
- throws OrmException {
+ public Iterable<byte[]> get(ChangeData input, FillArgs args) throws OrmException {
Change.Id id = input.getId();
Project.NameKey project = input.change().getProject();
List<byte[]> result = new ArrayList<>(3);
- result.add(RefStatePattern.create(
- RefNames.REFS_USERS + "*/" + RefNames.EDIT_PREFIX + id + "/*")
- .toByteArray(project));
result.add(
- RefStatePattern.create(
- RefNames.refsStarredChangesPrefix(id) + "*")
- .toByteArray(args.allUsers));
+ RefStatePattern.create(RefNames.REFS_USERS + "*/" + RefNames.EDIT_PREFIX + id + "/*")
+ .toByteArray(project));
+ result.add(
+ RefStatePattern.create(RefNames.refsStarredChangesPrefix(id) + "*")
+ .toByteArray(args.allUsers));
if (PrimaryStorage.of(input.change()) == PrimaryStorage.NOTE_DB) {
- result.add(RefStatePattern.create(
- RefNames.refsDraftCommentsPrefix(id) + "*")
- .toByteArray(args.allUsers));
+ result.add(
+ RefStatePattern.create(RefNames.refsDraftCommentsPrefix(id) + "*")
+ .toByteArray(args.allUsers));
}
return result;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/index/change/ChangeIndex.java b/gerrit-server/src/main/java/com/google/gerrit/server/index/change/ChangeIndex.java
index c56880f..27b0c26 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/index/change/ChangeIndex.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/index/change/ChangeIndex.java
@@ -22,9 +22,8 @@
import com.google.gerrit.server.query.change.LegacyChangeIdPredicate;
public interface ChangeIndex extends Index<Change.Id, ChangeData> {
- public interface Factory extends
- IndexDefinition.IndexFactory<Change.Id, ChangeData, ChangeIndex> {
- }
+ public interface Factory
+ extends IndexDefinition.IndexFactory<Change.Id, ChangeData, ChangeIndex> {}
@Override
default Predicate<ChangeData> keyPredicate(Change.Id id) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/index/change/ChangeIndexCollection.java b/gerrit-server/src/main/java/com/google/gerrit/server/index/change/ChangeIndexCollection.java
index dc1c4a5..f8acb74 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/index/change/ChangeIndexCollection.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/index/change/ChangeIndexCollection.java
@@ -22,10 +22,8 @@
import com.google.inject.Singleton;
@Singleton
-public class ChangeIndexCollection extends
- IndexCollection<Change.Id, ChangeData, ChangeIndex> {
+public class ChangeIndexCollection extends IndexCollection<Change.Id, ChangeData, ChangeIndex> {
@Inject
@VisibleForTesting
- public ChangeIndexCollection() {
- }
+ public ChangeIndexCollection() {}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/index/change/ChangeIndexDefinition.java b/gerrit-server/src/main/java/com/google/gerrit/server/index/change/ChangeIndexDefinition.java
index 2f1e4bb..4404298 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/index/change/ChangeIndexDefinition.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/index/change/ChangeIndexDefinition.java
@@ -21,15 +21,17 @@
import com.google.inject.Inject;
import com.google.inject.util.Providers;
-public class ChangeIndexDefinition
- extends IndexDefinition<Change.Id, ChangeData, ChangeIndex> {
+public class ChangeIndexDefinition extends IndexDefinition<Change.Id, ChangeData, ChangeIndex> {
@Inject
ChangeIndexDefinition(
ChangeIndexCollection indexCollection,
ChangeIndex.Factory indexFactory,
@Nullable AllChangesIndexer allChangesIndexer) {
- super(ChangeSchemaDefinitions.INSTANCE, indexCollection, indexFactory,
+ super(
+ ChangeSchemaDefinitions.INSTANCE,
+ indexCollection,
+ indexFactory,
Providers.of(allChangesIndexer));
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/index/change/ChangeIndexRewriter.java b/gerrit-server/src/main/java/com/google/gerrit/server/index/change/ChangeIndexRewriter.java
index 3523e5f..a9e1362 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/index/change/ChangeIndexRewriter.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/index/change/ChangeIndexRewriter.java
@@ -38,13 +38,11 @@
import com.google.gerrit.server.query.change.OrSource;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.util.MutableInteger;
-
import java.util.BitSet;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
+import org.eclipse.jgit.util.MutableInteger;
/** Rewriter that pushes boolean logic into the secondary index. */
@Singleton
@@ -73,9 +71,8 @@
* Get the set of statuses that changes matching the given predicate may have.
*
* @param in predicate
- * @return the maximal set of statuses that any changes matching the input
- * predicates may have, based on examining boolean and
- * {@link ChangeStatusPredicate}s.
+ * @return the maximal set of statuses that any changes matching the input predicates may have,
+ * based on examining boolean and {@link ChangeStatusPredicate}s.
*/
public static EnumSet<Change.Status> getPossibleStatus(Predicate<ChangeData> in) {
EnumSet<Change.Status> s = extractStatus(in);
@@ -129,15 +126,14 @@
private final IndexConfig config;
@Inject
- ChangeIndexRewriter(ChangeIndexCollection indexes,
- IndexConfig config) {
+ ChangeIndexRewriter(ChangeIndexCollection indexes, IndexConfig config) {
this.indexes = indexes;
this.config = config;
}
@Override
- public Predicate<ChangeData> rewrite(Predicate<ChangeData> in,
- QueryOptions opts) throws QueryParseException {
+ public Predicate<ChangeData> rewrite(Predicate<ChangeData> in, QueryOptions opts)
+ throws QueryParseException {
Predicate<ChangeData> s = rewriteImpl(in, opts);
if (!(s instanceof ChangeDataSource)) {
in = Predicate.and(open(), in);
@@ -149,8 +145,8 @@
return s;
}
- private Predicate<ChangeData> rewriteImpl(Predicate<ChangeData> in,
- QueryOptions opts) throws QueryParseException {
+ private Predicate<ChangeData> rewriteImpl(Predicate<ChangeData> in, QueryOptions opts)
+ throws QueryParseException {
ChangeIndex index = indexes.getSearchIndex();
MutableInteger leafTerms = new MutableInteger();
@@ -171,16 +167,15 @@
* @param index index whose schema determines which fields are indexed.
* @param opts other query options.
* @param leafTerms number of leaf index query terms encountered so far.
- * @return {@code null} if no part of this subtree can be queried in the
- * index directly. {@code in} if this subtree and all its children can be
- * queried directly in the index. Otherwise, a predicate that is
- * semantically equivalent, with some of its subtrees wrapped to query the
+ * @return {@code null} if no part of this subtree can be queried in the index directly. {@code
+ * in} if this subtree and all its children can be queried directly in the index. Otherwise, a
+ * predicate that is semantically equivalent, with some of its subtrees wrapped to query the
* index directly.
- * @throws QueryParseException if the underlying index implementation does not
- * support this predicate.
+ * @throws QueryParseException if the underlying index implementation does not support this
+ * predicate.
*/
- private Predicate<ChangeData> rewriteImpl(Predicate<ChangeData> in,
- ChangeIndex index, QueryOptions opts, MutableInteger leafTerms)
+ private Predicate<ChangeData> rewriteImpl(
+ Predicate<ChangeData> in, ChangeIndex index, QueryOptions opts, MutableInteger leafTerms)
throws QueryParseException {
if (isIndexPredicate(in, index)) {
if (++leafTerms.value > config.maxTerms()) {
@@ -226,8 +221,7 @@
return partitionChildren(in, newChildren, isIndexed, index, opts);
}
- private boolean isIndexPredicate(Predicate<ChangeData> in,
- ChangeIndex index) {
+ private boolean isIndexPredicate(Predicate<ChangeData> in, ChangeIndex index) {
if (!(in instanceof IndexPredicate)) {
return false;
}
@@ -240,21 +234,19 @@
List<Predicate<ChangeData>> newChildren,
BitSet isIndexed,
ChangeIndex index,
- QueryOptions opts) throws QueryParseException {
+ QueryOptions opts)
+ throws QueryParseException {
if (isIndexed.cardinality() == 1) {
int i = isIndexed.nextSetBit(0);
- newChildren.add(
- 0, new IndexedChangeQuery(index, newChildren.remove(i), opts));
+ newChildren.add(0, new IndexedChangeQuery(index, newChildren.remove(i), opts));
return copy(in, newChildren);
}
// Group all indexed predicates into a wrapped subtree.
- List<Predicate<ChangeData>> indexed =
- Lists.newArrayListWithCapacity(isIndexed.cardinality());
+ List<Predicate<ChangeData>> indexed = Lists.newArrayListWithCapacity(isIndexed.cardinality());
List<Predicate<ChangeData>> all =
- Lists.newArrayListWithCapacity(
- newChildren.size() - isIndexed.cardinality() + 1);
+ Lists.newArrayListWithCapacity(newChildren.size() - isIndexed.cardinality() + 1);
for (int i = 0; i < newChildren.size(); i++) {
Predicate<ChangeData> c = newChildren.get(i);
@@ -268,9 +260,7 @@
return copy(in, all);
}
- private Predicate<ChangeData> copy(
- Predicate<ChangeData> in,
- List<Predicate<ChangeData>> all) {
+ private Predicate<ChangeData> copy(Predicate<ChangeData> in, List<Predicate<ChangeData>> all) {
if (in instanceof AndPredicate) {
return new AndChangeSource(all);
} else if (in instanceof OrPredicate) {
@@ -280,9 +270,7 @@
}
private static boolean isRewritePossible(Predicate<ChangeData> p) {
- return p.getChildCount() > 0 && (
- p instanceof AndPredicate
- || p instanceof OrPredicate
- || p instanceof NotPredicate);
+ return p.getChildCount() > 0
+ && (p instanceof AndPredicate || p instanceof OrPredicate || p instanceof NotPredicate);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/index/change/ChangeIndexer.java b/gerrit-server/src/main/java/com/google/gerrit/server/index/change/ChangeIndexer.java
index f256707..a2f2e56 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/index/change/ChangeIndexer.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/index/change/ChangeIndexer.java
@@ -45,11 +45,6 @@
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
import com.google.inject.util.Providers;
-
-import org.eclipse.jgit.lib.Config;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
@@ -58,21 +53,23 @@
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicReference;
+import org.eclipse.jgit.lib.Config;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* Helper for (re)indexing a change document.
- * <p>
- * Indexing is run in the background, as it may require substantial work to
- * compute some of the fields and/or update the index.
+ *
+ * <p>Indexing is run in the background, as it may require substantial work to compute some of the
+ * fields and/or update the index.
*/
public class ChangeIndexer {
- private static final Logger log =
- LoggerFactory.getLogger(ChangeIndexer.class);
+ private static final Logger log = LoggerFactory.getLogger(ChangeIndexer.class);
public interface Factory {
ChangeIndexer create(ListeningExecutorService executor, ChangeIndex index);
- ChangeIndexer create(ListeningExecutorService executor,
- ChangeIndexCollection indexes);
+
+ ChangeIndexer create(ListeningExecutorService executor, ChangeIndexCollection indexes);
}
public static CheckedFuture<?, IOException> allAsList(
@@ -86,18 +83,17 @@
private static final Function<Exception, IOException> MAPPER =
new Function<Exception, IOException>() {
- @Override
- public IOException apply(Exception in) {
- if (in instanceof IOException) {
- return (IOException) in;
- } else if (in instanceof ExecutionException
- && in.getCause() instanceof IOException) {
- return (IOException) in.getCause();
- } else {
- return new IOException(in);
- }
- }
- };
+ @Override
+ public IOException apply(Exception in) {
+ if (in instanceof IOException) {
+ return (IOException) in;
+ } else if (in instanceof ExecutionException && in.getCause() instanceof IOException) {
+ return (IOException) in.getCause();
+ } else {
+ return new IOException(in);
+ }
+ }
+ };
private final ChangeIndexCollection indexes;
private final ChangeIndex index;
@@ -140,7 +136,8 @@
}
@AssistedInject
- ChangeIndexer(SchemaFactory<ReviewDb> schemaFactory,
+ ChangeIndexer(
+ SchemaFactory<ReviewDb> schemaFactory,
@GerritServerConfig Config cfg,
NotesMigration notesMigration,
ChangeNotes.Factory changeNotesFactory,
@@ -175,8 +172,7 @@
* @param id change to index.
* @return future for the indexing task.
*/
- public CheckedFuture<?, IOException> indexAsync(Project.NameKey project,
- Change.Id id) {
+ public CheckedFuture<?, IOException> indexAsync(Project.NameKey project, Change.Id id) {
return submit(new IndexTask(project, id));
}
@@ -186,8 +182,8 @@
* @param ids changes to index.
* @return future for completing indexing of all changes.
*/
- public CheckedFuture<?, IOException> indexAsync(Project.NameKey project,
- Collection<Change.Id> ids) {
+ public CheckedFuture<?, IOException> indexAsync(
+ Project.NameKey project, Collection<Change.Id> ids) {
List<ListenableFuture<?>> futures = new ArrayList<>(ids.size());
for (Change.Id id : ids) {
futures.add(indexAsync(project, id));
@@ -253,8 +249,7 @@
* @param db review database.
* @param change change to index.
*/
- public void index(ReviewDb db, Change change)
- throws IOException, OrmException {
+ public void index(ReviewDb db, Change change) throws IOException, OrmException {
index(newChangeData(db, change));
// See comment in #index(ChangeData).
reindexAfterIndexUpdate(change.getProject(), change.getId());
@@ -296,17 +291,15 @@
/**
* Asynchronously check if a change is stale, and reindex if it is.
- * <p>
- * Always run on the batch executor, even if this indexer instance is
- * configured to use a different executor.
+ *
+ * <p>Always run on the batch executor, even if this indexer instance is configured to use a
+ * different executor.
*
* @param project the project to which the change belongs.
* @param id ID of the change to index.
- * @return future for reindexing the change; returns true if the change was
- * stale.
+ * @return future for reindexing the change; returns true if the change was stale.
*/
- public CheckedFuture<Boolean, IOException> reindexIfStale(
- Project.NameKey project, Change.Id id) {
+ public CheckedFuture<Boolean, IOException> reindexIfStale(Project.NameKey project, Change.Id id) {
return submit(new ReindexIfStaleTask(project, id), batchExecutor);
}
@@ -325,19 +318,16 @@
}
private Collection<ChangeIndex> getWriteIndexes() {
- return indexes != null
- ? indexes.getWriteIndexes()
- : Collections.singleton(index);
+ return indexes != null ? indexes.getWriteIndexes() : Collections.singleton(index);
}
private <T> CheckedFuture<T, IOException> submit(Callable<T> task) {
return submit(task, executor);
}
- private static <T> CheckedFuture<T, IOException> submit(Callable<T> task,
- ListeningExecutorService executor) {
- return Futures.makeChecked(
- Futures.nonCancellationPropagating(executor.submit(task)), MAPPER);
+ private static <T> CheckedFuture<T, IOException> submit(
+ Callable<T> task, ListeningExecutorService executor) {
+ return Futures.makeChecked(Futures.nonCancellationPropagating(executor.submit(task)), MAPPER);
}
private abstract class AbstractIndexTask<T> implements Callable<T> {
@@ -357,35 +347,34 @@
@Override
public final T call() throws Exception {
try {
- final AtomicReference<Provider<ReviewDb>> dbRef =
- Atomics.newReference();
- RequestContext newCtx = new RequestContext() {
- @Override
- public Provider<ReviewDb> getReviewDbProvider() {
- Provider<ReviewDb> db = dbRef.get();
- if (db == null) {
- try {
- db = Providers.of(schemaFactory.open());
- } catch (OrmException e) {
- ProvisionException pe =
- new ProvisionException("error opening ReviewDb");
- pe.initCause(e);
- throw pe;
+ final AtomicReference<Provider<ReviewDb>> dbRef = Atomics.newReference();
+ RequestContext newCtx =
+ new RequestContext() {
+ @Override
+ public Provider<ReviewDb> getReviewDbProvider() {
+ Provider<ReviewDb> db = dbRef.get();
+ if (db == null) {
+ try {
+ db = Providers.of(schemaFactory.open());
+ } catch (OrmException e) {
+ ProvisionException pe = new ProvisionException("error opening ReviewDb");
+ pe.initCause(e);
+ throw pe;
+ }
+ dbRef.set(db);
+ }
+ return db;
}
- dbRef.set(db);
- }
- return db;
- }
- @Override
- public CurrentUser getUser() {
- throw new OutOfScopeException("No user during ChangeIndexer");
- }
- };
+ @Override
+ public CurrentUser getUser() {
+ throw new OutOfScopeException("No user during ChangeIndexer");
+ }
+ };
RequestContext oldCtx = context.setContext(newCtx);
try {
return callImpl(newCtx.getReviewDbProvider());
- } finally {
+ } finally {
context.setContext(oldCtx);
Provider<ReviewDb> db = dbRef.get();
if (db != null) {
@@ -463,24 +452,21 @@
// increases contention on the meta ref from a background indexing thread
// with little benefit. The next actual write to the entity may still incur a
// less-contentious rebuild.
- private ChangeData newChangeData(ReviewDb db, Change change)
- throws OrmException {
+ private ChangeData newChangeData(ReviewDb db, Change change) throws OrmException {
if (!notesMigration.readChanges()) {
- ChangeNotes notes = changeNotesFactory.createWithAutoRebuildingDisabled(
- change, null);
+ ChangeNotes notes = changeNotesFactory.createWithAutoRebuildingDisabled(change, null);
return changeDataFactory.create(db, notes);
}
return changeDataFactory.create(db, change);
}
- private ChangeData newChangeData(ReviewDb db, Project.NameKey project,
- Change.Id changeId) throws OrmException {
+ private ChangeData newChangeData(ReviewDb db, Project.NameKey project, Change.Id changeId)
+ throws OrmException {
if (!notesMigration.readChanges()) {
- ChangeNotes notes = changeNotesFactory.createWithAutoRebuildingDisabled(
- db, project, changeId);
+ ChangeNotes notes =
+ changeNotesFactory.createWithAutoRebuildingDisabled(db, project, changeId);
return changeDataFactory.create(db, notes);
}
return changeDataFactory.create(db, project, changeId);
}
-
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/index/change/ChangeSchemaDefinitions.java b/gerrit-server/src/main/java/com/google/gerrit/server/index/change/ChangeSchemaDefinitions.java
index b204d76..76a9bc9 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/index/change/ChangeSchemaDefinitions.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/index/change/ChangeSchemaDefinitions.java
@@ -22,75 +22,73 @@
public class ChangeSchemaDefinitions extends SchemaDefinitions<ChangeData> {
@Deprecated
- static final Schema<ChangeData> V32 = schema(
- ChangeField.LEGACY_ID,
- ChangeField.ID,
- ChangeField.STATUS,
- ChangeField.PROJECT,
- ChangeField.PROJECTS,
- ChangeField.REF,
- ChangeField.EXACT_TOPIC,
- ChangeField.FUZZY_TOPIC,
- ChangeField.UPDATED,
- ChangeField.FILE_PART,
- ChangeField.PATH,
- ChangeField.OWNER,
- ChangeField.COMMIT,
- ChangeField.TR,
- ChangeField.LABEL,
- ChangeField.COMMIT_MESSAGE,
- ChangeField.COMMENT,
- ChangeField.CHANGE,
- ChangeField.APPROVAL,
- ChangeField.MERGEABLE,
- ChangeField.ADDED,
- ChangeField.DELETED,
- ChangeField.DELTA,
- ChangeField.HASHTAG,
- ChangeField.COMMENTBY,
- ChangeField.PATCH_SET,
- ChangeField.GROUP,
- ChangeField.SUBMISSIONID,
- ChangeField.EDITBY,
- ChangeField.REVIEWEDBY,
- ChangeField.EXACT_COMMIT,
- ChangeField.AUTHOR,
- ChangeField.COMMITTER,
- ChangeField.DRAFTBY,
- ChangeField.HASHTAG_CASE_AWARE,
- ChangeField.STAR,
- ChangeField.STARBY,
- ChangeField.REVIEWER);
+ static final Schema<ChangeData> V32 =
+ schema(
+ ChangeField.LEGACY_ID,
+ ChangeField.ID,
+ ChangeField.STATUS,
+ ChangeField.PROJECT,
+ ChangeField.PROJECTS,
+ ChangeField.REF,
+ ChangeField.EXACT_TOPIC,
+ ChangeField.FUZZY_TOPIC,
+ ChangeField.UPDATED,
+ ChangeField.FILE_PART,
+ ChangeField.PATH,
+ ChangeField.OWNER,
+ ChangeField.COMMIT,
+ ChangeField.TR,
+ ChangeField.LABEL,
+ ChangeField.COMMIT_MESSAGE,
+ ChangeField.COMMENT,
+ ChangeField.CHANGE,
+ ChangeField.APPROVAL,
+ ChangeField.MERGEABLE,
+ ChangeField.ADDED,
+ ChangeField.DELETED,
+ ChangeField.DELTA,
+ ChangeField.HASHTAG,
+ ChangeField.COMMENTBY,
+ ChangeField.PATCH_SET,
+ ChangeField.GROUP,
+ ChangeField.SUBMISSIONID,
+ ChangeField.EDITBY,
+ ChangeField.REVIEWEDBY,
+ ChangeField.EXACT_COMMIT,
+ ChangeField.AUTHOR,
+ ChangeField.COMMITTER,
+ ChangeField.DRAFTBY,
+ ChangeField.HASHTAG_CASE_AWARE,
+ ChangeField.STAR,
+ ChangeField.STARBY,
+ ChangeField.REVIEWER);
+
+ @Deprecated static final Schema<ChangeData> V33 = schema(V32, ChangeField.ASSIGNEE);
@Deprecated
- static final Schema<ChangeData> V33 =
- schema(V32, ChangeField.ASSIGNEE);
-
- @Deprecated
- static final Schema<ChangeData> V34 = new Schema.Builder<ChangeData>()
- .add(V33)
- .remove(ChangeField.LABEL)
- .add(ChangeField.LABEL2)
- .build();
+ static final Schema<ChangeData> V34 =
+ new Schema.Builder<ChangeData>()
+ .add(V33)
+ .remove(ChangeField.LABEL)
+ .add(ChangeField.LABEL2)
+ .build();
@Deprecated
static final Schema<ChangeData> V35 =
- schema(V34,
+ schema(
+ V34,
ChangeField.SUBMIT_RECORD,
ChangeField.STORED_SUBMIT_RECORD_LENIENT,
ChangeField.STORED_SUBMIT_RECORD_STRICT);
@Deprecated
static final Schema<ChangeData> V36 =
- schema(V35,
- ChangeField.REF_STATE,
- ChangeField.REF_STATE_PATTERN);
+ schema(V35, ChangeField.REF_STATE, ChangeField.REF_STATE_PATTERN);
static final Schema<ChangeData> V37 = schema(V36);
public static final String NAME = "changes";
- public static final ChangeSchemaDefinitions INSTANCE =
- new ChangeSchemaDefinitions();
+ public static final ChangeSchemaDefinitions INSTANCE = new ChangeSchemaDefinitions();
private ChangeSchemaDefinitions() {
super(NAME, ChangeData.class);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/index/change/DummyChangeIndex.java b/gerrit-server/src/main/java/com/google/gerrit/server/index/change/DummyChangeIndex.java
index ff68106..6cbc1cb 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/index/change/DummyChangeIndex.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/index/change/DummyChangeIndex.java
@@ -20,7 +20,6 @@
import com.google.gerrit.server.query.Predicate;
import com.google.gerrit.server.query.change.ChangeData;
import com.google.gerrit.server.query.change.ChangeDataSource;
-
import java.io.IOException;
public class DummyChangeIndex implements ChangeIndex {
@@ -30,20 +29,16 @@
}
@Override
- public void close() {
- }
+ public void close() {}
@Override
- public void replace(ChangeData cd) throws IOException {
- }
+ public void replace(ChangeData cd) throws IOException {}
@Override
- public void delete(Change.Id id) throws IOException {
- }
+ public void delete(Change.Id id) throws IOException {}
@Override
- public void deleteAll() throws IOException {
- }
+ public void deleteAll() throws IOException {}
@Override
public ChangeDataSource getSource(Predicate<ChangeData> p, QueryOptions opts) {
@@ -51,8 +46,7 @@
}
@Override
- public void markReady(boolean ready) throws IOException {
- }
+ public void markReady(boolean ready) throws IOException {}
public int getMaxLimit() {
return Integer.MAX_VALUE;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/index/change/IndexedChangeQuery.java b/gerrit-server/src/main/java/com/google/gerrit/server/index/change/IndexedChangeQuery.java
index 3e0678d..ff35750 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/index/change/IndexedChangeQuery.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/index/change/IndexedChangeQuery.java
@@ -34,7 +34,6 @@
import com.google.gerrit.server.query.change.ChangeDataSource;
import com.google.gwtorm.server.OrmException;
import com.google.gwtorm.server.ResultSet;
-
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
@@ -43,25 +42,23 @@
import java.util.Set;
/**
- * Wrapper combining an {@link IndexPredicate} together with a
- * {@link ChangeDataSource} that returns matching results from the index.
- * <p>
- * Appropriate to return as the rootmost predicate that can be processed using
- * the secondary index; such predicates must also implement
- * {@link ChangeDataSource} to be chosen by the query processor.
+ * Wrapper combining an {@link IndexPredicate} together with a {@link ChangeDataSource} that returns
+ * matching results from the index.
+ *
+ * <p>Appropriate to return as the rootmost predicate that can be processed using the secondary
+ * index; such predicates must also implement {@link ChangeDataSource} to be chosen by the query
+ * processor.
*/
public class IndexedChangeQuery extends IndexedQuery<Change.Id, ChangeData>
implements ChangeDataSource, Matchable<ChangeData> {
public static QueryOptions oneResult() {
- return createOptions(IndexConfig.createDefault(), 0, 1,
- ImmutableSet.<String> of());
+ return createOptions(IndexConfig.createDefault(), 0, 1, ImmutableSet.<String>of());
}
- public static QueryOptions createOptions(IndexConfig config, int start,
- int limit, Set<String> fields) {
+ public static QueryOptions createOptions(
+ IndexConfig config, int start, int limit, Set<String> fields) {
// Always include project since it is needed to load the change from NoteDb.
- if (!fields.contains(CHANGE.getName())
- && !fields.contains(PROJECT.getName())) {
+ if (!fields.contains(CHANGE.getName()) && !fields.contains(PROJECT.getName())) {
fields = new HashSet<>(fields);
fields.add(PROJECT.getName());
}
@@ -71,14 +68,14 @@
@VisibleForTesting
static QueryOptions convertOptions(QueryOptions opts) {
opts = opts.convertForBackend();
- return IndexedChangeQuery.createOptions(opts.config(), opts.start(),
- opts.limit(), opts.fields());
+ return IndexedChangeQuery.createOptions(
+ opts.config(), opts.start(), opts.limit(), opts.fields());
}
private final Map<ChangeData, DataSource<ChangeData>> fromSource;
- public IndexedChangeQuery(ChangeIndex index, Predicate<ChangeData> pred,
- QueryOptions opts) throws QueryParseException {
+ public IndexedChangeQuery(ChangeIndex index, Predicate<ChangeData> pred, QueryOptions opts)
+ throws QueryParseException {
super(index, pred, convertOptions(opts));
this.fromSource = new HashMap<>();
}
@@ -92,11 +89,12 @@
@Override
public Iterator<ChangeData> iterator() {
return Iterables.transform(
- rs,
- cd -> {
- fromSource.put(cd, currSource);
- return cd;
- }).iterator();
+ rs,
+ cd -> {
+ fromSource.put(cd, currSource);
+ return cd;
+ })
+ .iterator();
}
@Override
@@ -122,8 +120,10 @@
}
Predicate<ChangeData> pred = getChild(0);
- checkState(pred.isMatchable(),
- "match invoked, but child predicate %s " + "doesn't implement %s", pred,
+ checkState(
+ pred.isMatchable(),
+ "match invoked, but child predicate %s " + "doesn't implement %s",
+ pred,
Matchable.class.getName());
return pred.asMatchable().match(cd);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/index/change/ReindexAfterUpdate.java b/gerrit-server/src/main/java/com/google/gerrit/server/index/change/ReindexAfterUpdate.java
index 47d120a..24cc537 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/index/change/ReindexAfterUpdate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/index/change/ReindexAfterUpdate.java
@@ -36,17 +36,14 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.io.IOException;
import java.util.List;
import java.util.concurrent.Callable;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class ReindexAfterUpdate implements GitReferenceUpdatedListener {
- private static final Logger log = LoggerFactory
- .getLogger(ReindexAfterUpdate.class);
+ private static final Logger log = LoggerFactory.getLogger(ReindexAfterUpdate.class);
private final OneOffRequestContext requestContext;
private final Provider<InternalChangeQuery> queryProvider;
@@ -127,14 +124,15 @@
if (ref.equals(RefNames.REFS_CONFIG)) {
return asChanges(queryProvider.get().byProjectOpen(project));
}
- return asChanges(queryProvider.get().byBranchNew(
- new Branch.NameKey(project, ref)));
+ return asChanges(queryProvider.get().byBranchNew(new Branch.NameKey(project, ref)));
}
@Override
public String toString() {
- return "Get changes to reindex caused by " + event.getRefName()
- + " update of project " + event.getProjectName();
+ return "Get changes to reindex caused by "
+ + event.getRefName()
+ + " update of project "
+ + event.getProjectName();
}
}
@@ -151,9 +149,10 @@
// Reload change, as some time may have passed since GetChanges.
ReviewDb db = ctx.getReviewDbProvider().get();
try {
- Change c = notesFactory
- .createChecked(db, new Project.NameKey(event.getProjectName()), id)
- .getChange();
+ Change c =
+ notesFactory
+ .createChecked(db, new Project.NameKey(event.getProjectName()), id)
+ .getChange();
indexerFactory.create(executor, indexes).index(db, c);
} catch (NoSuchChangeException e) {
indexerFactory.create(executor, indexes).delete(id);
@@ -163,8 +162,7 @@
@Override
public String toString() {
- return "Index change " + id.get() + " of project "
- + event.getProjectName();
+ return "Index change " + id.get() + " of project " + event.getProjectName();
}
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/index/change/StalenessChecker.java b/gerrit-server/src/main/java/com/google/gerrit/server/index/change/StalenessChecker.java
index 8194b6f..872dfaf 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/index/change/StalenessChecker.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/index/change/StalenessChecker.java
@@ -40,7 +40,12 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
+import java.io.IOException;
+import java.util.List;
+import java.util.Optional;
+import java.util.Set;
+import java.util.regex.Pattern;
+import java.util.stream.StreamSupport;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Ref;
@@ -48,22 +53,15 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.util.List;
-import java.util.Optional;
-import java.util.Set;
-import java.util.regex.Pattern;
-import java.util.stream.StreamSupport;
-
@Singleton
public class StalenessChecker {
- private static final Logger log =
- LoggerFactory.getLogger(StalenessChecker.class);
+ private static final Logger log = LoggerFactory.getLogger(StalenessChecker.class);
- public static final ImmutableSet<String> FIELDS = ImmutableSet.of(
- ChangeField.CHANGE.getName(),
- ChangeField.REF_STATE.getName(),
- ChangeField.REF_STATE_PATTERN.getName());
+ public static final ImmutableSet<String> FIELDS =
+ ImmutableSet.of(
+ ChangeField.CHANGE.getName(),
+ ChangeField.REF_STATE.getName(),
+ ChangeField.REF_STATE_PATTERN.getName());
private final ChangeIndexCollection indexes;
private final GitRepositoryManager repoManager;
@@ -92,15 +90,19 @@
return false; // Index version not new enough for this check.
}
- Optional<ChangeData> result = i.get(
- id, IndexedChangeQuery.createOptions(indexConfig, 0, 1, FIELDS));
+ Optional<ChangeData> result =
+ i.get(id, IndexedChangeQuery.createOptions(indexConfig, 0, 1, FIELDS));
if (!result.isPresent()) {
return true; // Not in index, but caller wants it to be.
}
ChangeData cd = result.get();
- return isStale(repoManager, id, cd.change(),
+ return isStale(
+ repoManager,
+ id,
+ cd.change(),
ChangeNotes.readOneReviewDbChange(db.get(), id),
- parseStates(cd), parsePatterns(cd));
+ parseStates(cd),
+ parsePatterns(cd));
}
public static boolean isStale(
@@ -115,12 +117,12 @@
}
@VisibleForTesting
- static boolean refsAreStale(GitRepositoryManager repoManager,
+ static boolean refsAreStale(
+ GitRepositoryManager repoManager,
Change.Id id,
SetMultimap<Project.NameKey, RefState> states,
ListMultimap<Project.NameKey, RefStatePattern> patterns) {
- Set<Project.NameKey> projects =
- Sets.union(states.keySet(), patterns.keySet());
+ Set<Project.NameKey> projects = Sets.union(states.keySet(), patterns.keySet());
for (Project.NameKey p : projects) {
if (refsAreStale(repoManager, id, p, states, patterns)) {
@@ -132,14 +134,15 @@
}
@VisibleForTesting
- static boolean reviewDbChangeIsStale(
- Change indexChange, @Nullable Change reviewDbChange) {
+ static boolean reviewDbChangeIsStale(Change indexChange, @Nullable Change reviewDbChange) {
if (reviewDbChange == null) {
return false; // Nothing the caller can do.
}
- checkArgument(indexChange.getId().equals(reviewDbChange.getId()),
+ checkArgument(
+ indexChange.getId().equals(reviewDbChange.getId()),
"mismatched change ID: %s != %s",
- indexChange.getId(), reviewDbChange.getId());
+ indexChange.getId(),
+ reviewDbChange.getId());
if (PrimaryStorage.of(reviewDbChange) != PrimaryStorage.REVIEW_DB) {
return false; // Not a ReviewDb change, don't check rowVersion.
}
@@ -150,8 +153,7 @@
return parseStates(cd.getRefStates());
}
- public static SetMultimap<Project.NameKey, RefState> parseStates(
- Iterable<byte[]> states) {
+ public static SetMultimap<Project.NameKey, RefState> parseStates(Iterable<byte[]> states) {
RefState.check(states != null, null);
SetMultimap<Project.NameKey, RefState> result =
MultimapBuilder.hashKeys().hashSetValues().build();
@@ -159,20 +161,13 @@
RefState.check(b != null, null);
String s = new String(b, UTF_8);
List<String> parts = Splitter.on(':').splitToList(s);
- RefState.check(
- parts.size() == 3
- && !parts.get(0).isEmpty()
- && !parts.get(1).isEmpty(),
- s);
- result.put(
- new Project.NameKey(parts.get(0)),
- RefState.create(parts.get(1), parts.get(2)));
+ RefState.check(parts.size() == 3 && !parts.get(0).isEmpty() && !parts.get(1).isEmpty(), s);
+ result.put(new Project.NameKey(parts.get(0)), RefState.create(parts.get(1), parts.get(2)));
}
return result;
}
- private ListMultimap<Project.NameKey, RefStatePattern> parsePatterns(
- ChangeData cd) {
+ private ListMultimap<Project.NameKey, RefStatePattern> parsePatterns(ChangeData cd) {
return parsePatterns(cd.getRefStatePatterns());
}
@@ -186,15 +181,15 @@
String s = new String(b, UTF_8);
List<String> parts = Splitter.on(':').splitToList(s);
RefStatePattern.check(parts.size() == 2, s);
- result.put(
- new Project.NameKey(parts.get(0)),
- RefStatePattern.create(parts.get(1)));
+ result.put(new Project.NameKey(parts.get(0)), RefStatePattern.create(parts.get(1)));
}
return result;
}
- private static boolean refsAreStale(GitRepositoryManager repoManager,
- Change.Id id, Project.NameKey project,
+ private static boolean refsAreStale(
+ GitRepositoryManager repoManager,
+ Change.Id id,
+ Project.NameKey project,
SetMultimap<Project.NameKey, RefState> allStates,
ListMultimap<Project.NameKey, RefStatePattern> allPatterns) {
try (Repository repo = repoManager.openRepository(project)) {
@@ -211,9 +206,7 @@
}
return false;
} catch (IOException e) {
- log.warn(
- String.format("error checking staleness of %s in %s", id, project),
- e);
+ log.warn(String.format("error checking staleness of %s in %s", id, project), e);
return true;
}
}
@@ -221,18 +214,15 @@
@AutoValue
public abstract static class RefState {
static RefState create(String ref, String sha) {
- return new AutoValue_StalenessChecker_RefState(
- ref, ObjectId.fromString(sha));
+ return new AutoValue_StalenessChecker_RefState(ref, ObjectId.fromString(sha));
}
static RefState create(String ref, @Nullable ObjectId id) {
- return new AutoValue_StalenessChecker_RefState(
- ref, firstNonNull(id, ObjectId.zeroId()));
+ return new AutoValue_StalenessChecker_RefState(ref, firstNonNull(id, ObjectId.zeroId()));
}
static RefState of(Ref ref) {
- return new AutoValue_StalenessChecker_RefState(
- ref.getName(), ref.getObjectId());
+ return new AutoValue_StalenessChecker_RefState(ref.getName(), ref.getObjectId());
}
byte[] toByteArray(Project.NameKey project) {
@@ -248,6 +238,7 @@
}
abstract String ref();
+
abstract ObjectId id();
private boolean match(Repository repo) throws IOException {
@@ -259,10 +250,10 @@
/**
* Pattern for matching refs.
- * <p>
- * Similar to '*' syntax for native Git refspecs, but slightly more powerful:
- * the pattern may contain arbitrarily many asterisks. There must be at least
- * one '*' and the first one must immediately follow a '/'.
+ *
+ * <p>Similar to '*' syntax for native Git refspecs, but slightly more powerful: the pattern may
+ * contain arbitrarily many asterisks. There must be at least one '*' and the first one must
+ * immediately follow a '/'.
*/
@AutoValue
public abstract static class RefStatePattern {
@@ -290,15 +281,16 @@
}
abstract String pattern();
+
abstract String prefix();
+
abstract Pattern regex();
boolean match(String refName) {
return regex().matcher(refName).find();
}
- private boolean match(Repository repo, Set<RefState> expected)
- throws IOException {
+ private boolean match(Repository repo, Set<RefState> expected) throws IOException {
for (Ref r : repo.getRefDatabase().getRefs(prefix()).values()) {
if (!match(r.getName())) {
continue;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/index/group/AllGroupsIndexer.java b/gerrit-server/src/main/java/com/google/gerrit/server/index/group/AllGroupsIndexer.java
index 18b6cc3..ec486b5 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/index/group/AllGroupsIndexer.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/index/group/AllGroupsIndexer.java
@@ -29,12 +29,6 @@
import com.google.gwtorm.server.SchemaFactory;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.lib.ProgressMonitor;
-import org.eclipse.jgit.lib.TextProgressMonitor;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
@@ -42,12 +36,14 @@
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
+import org.eclipse.jgit.lib.ProgressMonitor;
+import org.eclipse.jgit.lib.TextProgressMonitor;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
@Singleton
-public class AllGroupsIndexer
- extends SiteIndexer<AccountGroup.UUID, AccountGroup, GroupIndex> {
- private static final Logger log =
- LoggerFactory.getLogger(AllGroupsIndexer.class);
+public class AllGroupsIndexer extends SiteIndexer<AccountGroup.UUID, AccountGroup, GroupIndex> {
+ private static final Logger log = LoggerFactory.getLogger(AllGroupsIndexer.class);
private final SchemaFactory<ReviewDb> schemaFactory;
private final ListeningExecutorService executor;
@@ -65,8 +61,7 @@
@Override
public SiteIndexer.Result indexAll(GroupIndex index) {
- ProgressMonitor progress =
- new TextProgressMonitor(new PrintWriter(progressOut));
+ ProgressMonitor progress = new TextProgressMonitor(new PrintWriter(progressOut));
progress.start(2);
Stopwatch sw = Stopwatch.createStarted();
List<AccountGroup.UUID> uuids;
@@ -79,8 +74,8 @@
return reindexGroups(index, uuids, progress);
}
- private SiteIndexer.Result reindexGroups(GroupIndex index,
- List<AccountGroup.UUID> uuids, ProgressMonitor progress) {
+ private SiteIndexer.Result reindexGroups(
+ GroupIndex index, List<AccountGroup.UUID> uuids, ProgressMonitor progress) {
progress.beginTask("Reindexing groups", uuids.size());
List<ListenableFuture<?>> futures = new ArrayList<>(uuids.size());
AtomicBoolean ok = new AtomicBoolean(true);
@@ -89,25 +84,26 @@
Stopwatch sw = Stopwatch.createStarted();
for (final AccountGroup.UUID uuid : uuids) {
final String desc = "group " + uuid;
- ListenableFuture<?> future = executor.submit(
- new Callable<Void>() {
- @Override
- public Void call() throws Exception {
- try {
- AccountGroup oldGroup = groupCache.get(uuid);
- if (oldGroup != null) {
- groupCache.evict(oldGroup);
+ ListenableFuture<?> future =
+ executor.submit(
+ new Callable<Void>() {
+ @Override
+ public Void call() throws Exception {
+ try {
+ AccountGroup oldGroup = groupCache.get(uuid);
+ if (oldGroup != null) {
+ groupCache.evict(oldGroup);
+ }
+ index.replace(groupCache.get(uuid));
+ verboseWriter.println("Reindexed " + desc);
+ done.incrementAndGet();
+ } catch (Exception e) {
+ failed.incrementAndGet();
+ throw e;
+ }
+ return null;
}
- index.replace(groupCache.get(uuid));
- verboseWriter.println("Reindexed " + desc);
- done.incrementAndGet();
- } catch (Exception e) {
- failed.incrementAndGet();
- throw e;
- }
- return null;
- }
- });
+ });
addErrorListener(future, desc, progress, ok);
futures.add(future);
}
@@ -123,8 +119,7 @@
return new SiteIndexer.Result(sw, ok.get(), done.get(), failed.get());
}
- private List<AccountGroup.UUID> collectGroups(ProgressMonitor progress)
- throws OrmException {
+ private List<AccountGroup.UUID> collectGroups(ProgressMonitor progress) throws OrmException {
progress.beginTask("Collecting groups", ProgressMonitor.UNKNOWN);
List<AccountGroup.UUID> uuids = new ArrayList<>();
try (ReviewDb db = schemaFactory.open()) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/index/group/GroupField.java b/gerrit-server/src/main/java/com/google/gerrit/server/index/group/GroupField.java
index 6c0ab86..cc07dfd 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/index/group/GroupField.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/index/group/GroupField.java
@@ -24,8 +24,7 @@
public class GroupField {
/** Legacy group ID. */
public static final FieldDef<AccountGroup, Integer> ID =
- new FieldDef.Single<AccountGroup, Integer>(
- "id", FieldType.INTEGER, false) {
+ new FieldDef.Single<AccountGroup, Integer>("id", FieldType.INTEGER, false) {
@Override
public Integer get(AccountGroup input, FillArgs args) {
return input.getId().get();
@@ -34,8 +33,7 @@
/** Group UUID. */
public static final FieldDef<AccountGroup, String> UUID =
- new FieldDef.Single<AccountGroup, String>(
- "uuid", FieldType.EXACT, true) {
+ new FieldDef.Single<AccountGroup, String>("uuid", FieldType.EXACT, true) {
@Override
public String get(AccountGroup input, FillArgs args) {
return input.getGroupUUID().get();
@@ -44,8 +42,7 @@
/** Group owner UUID. */
public static final FieldDef<AccountGroup, String> OWNER_UUID =
- new FieldDef.Single<AccountGroup, String>(
- "owner_uuid", FieldType.EXACT, false) {
+ new FieldDef.Single<AccountGroup, String>("owner_uuid", FieldType.EXACT, false) {
@Override
public String get(AccountGroup input, FillArgs args) {
return input.getOwnerGroupUUID().get();
@@ -54,8 +51,7 @@
/** Group name. */
public static final FieldDef<AccountGroup, String> NAME =
- new FieldDef.Single<AccountGroup, String>(
- "name", FieldType.EXACT, false) {
+ new FieldDef.Single<AccountGroup, String>("name", FieldType.EXACT, false) {
@Override
public String get(AccountGroup input, FillArgs args) {
return input.getName();
@@ -64,8 +60,7 @@
/** Prefix match on group name parts. */
public static final FieldDef<AccountGroup, Iterable<String>> NAME_PART =
- new FieldDef.Repeatable<AccountGroup, String>(
- "name_part", FieldType.PREFIX, false) {
+ new FieldDef.Repeatable<AccountGroup, String>("name_part", FieldType.PREFIX, false) {
@Override
public Iterable<String> get(AccountGroup input, FillArgs args) {
return SchemaUtil.getNameParts(input.getName());
@@ -74,8 +69,7 @@
/** Group description. */
public static final FieldDef<AccountGroup, String> DESCRIPTION =
- new FieldDef.Single<AccountGroup, String>(
- "description", FieldType.FULL_TEXT, false) {
+ new FieldDef.Single<AccountGroup, String>("description", FieldType.FULL_TEXT, false) {
@Override
public String get(AccountGroup input, FillArgs args) {
return input.getDescription();
@@ -84,11 +78,9 @@
/** Whether the group is visible to all users. */
public static final FieldDef<AccountGroup, String> IS_VISIBLE_TO_ALL =
- new FieldDef.Single<AccountGroup, String>(
- "is_visible_to_all", FieldType.EXACT, false) {
+ new FieldDef.Single<AccountGroup, String>("is_visible_to_all", FieldType.EXACT, false) {
@Override
- public String get(AccountGroup input, FillArgs args)
- throws OrmException {
+ public String get(AccountGroup input, FillArgs args) throws OrmException {
return input.isVisibleToAll() ? "1" : "0";
}
};
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/index/group/GroupIndex.java b/gerrit-server/src/main/java/com/google/gerrit/server/index/group/GroupIndex.java
index 773da67..48480f8 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/index/group/GroupIndex.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/index/group/GroupIndex.java
@@ -21,9 +21,8 @@
import com.google.gerrit.server.query.group.GroupPredicates;
public interface GroupIndex extends Index<AccountGroup.UUID, AccountGroup> {
- public interface Factory extends
- IndexDefinition.IndexFactory<AccountGroup.UUID, AccountGroup, GroupIndex> {
- }
+ public interface Factory
+ extends IndexDefinition.IndexFactory<AccountGroup.UUID, AccountGroup, GroupIndex> {}
@Override
default Predicate<AccountGroup> keyPredicate(AccountGroup.UUID uuid) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/index/group/GroupIndexCollection.java b/gerrit-server/src/main/java/com/google/gerrit/server/index/group/GroupIndexCollection.java
index f8ca15d..2f0d8e0 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/index/group/GroupIndexCollection.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/index/group/GroupIndexCollection.java
@@ -25,6 +25,5 @@
extends IndexCollection<AccountGroup.UUID, AccountGroup, GroupIndex> {
@Inject
@VisibleForTesting
- public GroupIndexCollection() {
- }
+ public GroupIndexCollection() {}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/index/group/GroupIndexDefinition.java b/gerrit-server/src/main/java/com/google/gerrit/server/index/group/GroupIndexDefinition.java
index 0f89e73..0dbea79 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/index/group/GroupIndexDefinition.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/index/group/GroupIndexDefinition.java
@@ -24,10 +24,14 @@
extends IndexDefinition<AccountGroup.UUID, AccountGroup, GroupIndex> {
@Inject
- GroupIndexDefinition(GroupIndexCollection indexCollection,
+ GroupIndexDefinition(
+ GroupIndexCollection indexCollection,
GroupIndex.Factory indexFactory,
@Nullable AllGroupsIndexer allGroupsIndexer) {
- super(GroupSchemaDefinitions.INSTANCE, indexCollection, indexFactory,
+ super(
+ GroupSchemaDefinitions.INSTANCE,
+ indexCollection,
+ indexFactory,
Providers.of(allGroupsIndexer));
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/index/group/GroupIndexRewriter.java b/gerrit-server/src/main/java/com/google/gerrit/server/index/group/GroupIndexRewriter.java
index e64631e..82f55ed 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/index/group/GroupIndexRewriter.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/index/group/GroupIndexRewriter.java
@@ -34,8 +34,8 @@
}
@Override
- public Predicate<AccountGroup> rewrite(Predicate<AccountGroup> in,
- QueryOptions opts) throws QueryParseException {
+ public Predicate<AccountGroup> rewrite(Predicate<AccountGroup> in, QueryOptions opts)
+ throws QueryParseException {
GroupIndex index = indexes.getSearchIndex();
checkNotNull(index, "no active search index configured for groups");
return new IndexedGroupQuery(index, in, opts);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/index/group/GroupIndexer.java b/gerrit-server/src/main/java/com/google/gerrit/server/index/group/GroupIndexer.java
index 6606f8e..0925cf4 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/index/group/GroupIndexer.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/index/group/GroupIndexer.java
@@ -15,7 +15,6 @@
package com.google.gerrit.server.index.group;
import com.google.gerrit.reviewdb.client.AccountGroup;
-
import java.io.IOException;
public interface GroupIndexer {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/index/group/GroupIndexerImpl.java b/gerrit-server/src/main/java/com/google/gerrit/server/index/group/GroupIndexerImpl.java
index dc2e81a..f740f58 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/index/group/GroupIndexerImpl.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/index/group/GroupIndexerImpl.java
@@ -21,7 +21,6 @@
import com.google.gerrit.server.index.Index;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
-
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
@@ -29,6 +28,7 @@
public class GroupIndexerImpl implements GroupIndexer {
public interface Factory {
GroupIndexerImpl create(GroupIndexCollection indexes);
+
GroupIndexerImpl create(@Nullable GroupIndex index);
}
@@ -37,16 +37,14 @@
private final GroupIndex index;
@AssistedInject
- GroupIndexerImpl(GroupCache groupCache,
- @Assisted GroupIndexCollection indexes) {
+ GroupIndexerImpl(GroupCache groupCache, @Assisted GroupIndexCollection indexes) {
this.groupCache = groupCache;
this.indexes = indexes;
this.index = null;
}
@AssistedInject
- GroupIndexerImpl(GroupCache groupCache,
- @Assisted GroupIndex index) {
+ GroupIndexerImpl(GroupCache groupCache, @Assisted GroupIndex index) {
this.groupCache = groupCache;
this.indexes = null;
this.index = index;
@@ -64,8 +62,6 @@
return indexes.getWriteIndexes();
}
- return index != null
- ? Collections.singleton(index)
- : ImmutableSet.of();
+ return index != null ? Collections.singleton(index) : ImmutableSet.of();
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/index/group/GroupSchemaDefinitions.java b/gerrit-server/src/main/java/com/google/gerrit/server/index/group/GroupSchemaDefinitions.java
index 42062cd..6ba46cb 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/index/group/GroupSchemaDefinitions.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/index/group/GroupSchemaDefinitions.java
@@ -22,19 +22,19 @@
public class GroupSchemaDefinitions extends SchemaDefinitions<AccountGroup> {
@Deprecated
- static final Schema<AccountGroup> V1 = schema(
- GroupField.ID,
- GroupField.UUID,
- GroupField.OWNER_UUID,
- GroupField.NAME,
- GroupField.NAME_PART,
- GroupField.DESCRIPTION,
- GroupField.IS_VISIBLE_TO_ALL);
+ static final Schema<AccountGroup> V1 =
+ schema(
+ GroupField.ID,
+ GroupField.UUID,
+ GroupField.OWNER_UUID,
+ GroupField.NAME,
+ GroupField.NAME_PART,
+ GroupField.DESCRIPTION,
+ GroupField.IS_VISIBLE_TO_ALL);
static final Schema<AccountGroup> V2 = schema(V1);
- public static final GroupSchemaDefinitions INSTANCE =
- new GroupSchemaDefinitions();
+ public static final GroupSchemaDefinitions INSTANCE = new GroupSchemaDefinitions();
private GroupSchemaDefinitions() {
super("groups", AccountGroup.class);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/index/group/IndexedGroupQuery.java b/gerrit-server/src/main/java/com/google/gerrit/server/index/group/IndexedGroupQuery.java
index 9ee9b78..1ea4478 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/index/group/IndexedGroupQuery.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/index/group/IndexedGroupQuery.java
@@ -22,13 +22,12 @@
import com.google.gerrit.server.query.Predicate;
import com.google.gerrit.server.query.QueryParseException;
-public class IndexedGroupQuery
- extends IndexedQuery<AccountGroup.UUID, AccountGroup>
+public class IndexedGroupQuery extends IndexedQuery<AccountGroup.UUID, AccountGroup>
implements DataSource<AccountGroup> {
- public IndexedGroupQuery(Index<AccountGroup.UUID, AccountGroup> index,
- Predicate<AccountGroup> pred, QueryOptions opts)
- throws QueryParseException {
+ public IndexedGroupQuery(
+ Index<AccountGroup.UUID, AccountGroup> index, Predicate<AccountGroup> pred, QueryOptions opts)
+ throws QueryParseException {
super(index, pred, opts.convertForBackend());
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/ioutil/BasicSerialization.java b/gerrit-server/src/main/java/com/google/gerrit/server/ioutil/BasicSerialization.java
index 989b270..5f77877 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/ioutil/BasicSerialization.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/ioutil/BasicSerialization.java
@@ -32,13 +32,11 @@
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.gerrit.reviewdb.client.CodedEnum;
-
-import org.eclipse.jgit.util.IO;
-
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
+import org.eclipse.jgit.util.IO;
public class BasicSerialization {
private static final byte[] NO_BYTES = {};
@@ -59,8 +57,7 @@
}
/** Write a fixed-width 64 bit integer in network byte order (big-endian). */
- public static void writeFixInt64(final OutputStream output, final long val)
- throws IOException {
+ public static void writeFixInt64(final OutputStream output, final long val) throws IOException {
writeFixInt32(output, (int) (val >>> 32));
writeFixInt32(output, (int) (val & 0xFFFFFFFFL));
}
@@ -75,8 +72,7 @@
}
/** Write a fixed-width 32 bit integer in network byte order (big-endian). */
- public static void writeFixInt32(final OutputStream output, final int val)
- throws IOException {
+ public static void writeFixInt32(final OutputStream output, final int val) throws IOException {
output.write((val >>> 24) & 0xFF);
output.write((val >>> 16) & 0xFF);
output.write((val >>> 8) & 0xFF);
@@ -98,8 +94,7 @@
}
/** Write a varint; value is treated as an unsigned value. */
- public static void writeVarInt32(final OutputStream output, int value)
- throws IOException {
+ public static void writeVarInt32(final OutputStream output, int value) throws IOException {
while (true) {
if ((value & ~0x7F) == 0) {
output.write(value);
@@ -122,14 +117,14 @@
}
/** Write a byte array prefixed by its length in a varint. */
- public static void writeBytes(final OutputStream output, final byte[] data)
- throws IOException {
+ public static void writeBytes(final OutputStream output, final byte[] data) throws IOException {
writeBytes(output, data, 0, data.length);
}
/** Write a byte array prefixed by its length in a varint. */
- public static void writeBytes(final OutputStream output, final byte[] data,
- final int offset, final int len) throws IOException {
+ public static void writeBytes(
+ final OutputStream output, final byte[] data, final int offset, final int len)
+ throws IOException {
writeVarInt32(output, len);
output.write(data, offset, len);
}
@@ -144,8 +139,7 @@
}
/** Write a UTF-8 string, prefixed by its byte length in a varint. */
- public static void writeString(final OutputStream output, final String s)
- throws IOException {
+ public static void writeString(final OutputStream output, final String s) throws IOException {
if (s == null) {
writeVarInt32(output, 0);
} else {
@@ -154,8 +148,8 @@
}
/** Read an enum whose code is stored as a varint. */
- public static <T extends CodedEnum> T readEnum(final InputStream input,
- final T[] all) throws IOException {
+ public static <T extends CodedEnum> T readEnum(final InputStream input, final T[] all)
+ throws IOException {
final int val = readVarInt32(input);
for (T t : all) {
if (t.getCode() == val) {
@@ -166,11 +160,10 @@
}
/** Write an enum whose code is stored as a varint. */
- public static <T extends CodedEnum> void writeEnum(final OutputStream output,
- final T e) throws IOException {
+ public static <T extends CodedEnum> void writeEnum(final OutputStream output, final T e)
+ throws IOException {
writeVarInt32(output, e.getCode());
}
- private BasicSerialization() {
- }
+ private BasicSerialization() {}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/ioutil/ColumnFormatter.java b/gerrit-server/src/main/java/com/google/gerrit/server/ioutil/ColumnFormatter.java
index a73f1cb..c96e808 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/ioutil/ColumnFormatter.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/ioutil/ColumnFormatter.java
@@ -15,14 +15,12 @@
package com.google.gerrit.server.ioutil;
import com.google.gerrit.server.StringUtil;
-
import java.io.PrintWriter;
/**
- * Simple output formatter for column-oriented data, writing its output to
- * a {@link java.io.PrintWriter} object. Handles escaping of the column
- * data so that the resulting output is unambiguous and reasonably safe and
- * machine parsable.
+ * Simple output formatter for column-oriented data, writing its output to a {@link
+ * java.io.PrintWriter} object. Handles escaping of the column data so that the resulting output is
+ * unambiguous and reasonably safe and machine parsable.
*/
public class ColumnFormatter {
private char columnSeparator;
@@ -31,11 +29,9 @@
/**
* @param out The writer to which output should be sent.
- * @param columnSeparator A character that should serve as the separator
- * token between columns of output. As only non-printable characters
- * in the column text are ever escaped, the column separator must be
- * a non-printable character if the output needs to be unambiguously
- * parsed.
+ * @param columnSeparator A character that should serve as the separator token between columns of
+ * output. As only non-printable characters in the column text are ever escaped, the column
+ * separator must be a non-printable character if the output needs to be unambiguously parsed.
*/
public ColumnFormatter(final PrintWriter out, final char columnSeparator) {
this.out = out;
@@ -44,8 +40,8 @@
}
/**
- * Adds a text string as a new column in the current line of output,
- * taking care of escaping as necessary.
+ * Adds a text string as a new column in the current line of output, taking care of escaping as
+ * necessary.
*
* @param content the string to add.
*/
@@ -58,8 +54,7 @@
}
/**
- * Finishes the output by flushing the current line and takes care of any
- * other cleanup action.
+ * Finishes the output by flushing the current line and takes care of any other cleanup action.
*/
public void finish() {
nextLine();
@@ -67,11 +62,10 @@
}
/**
- * Flushes the current line of output and makes the formatter ready to
- * start receiving new column data for a new line (or end-of-file).
- * If the current line is empty nothing is done, i.e. consecutive calls
- * to this method without intervening calls to {@link #addColumn} will
- * be squashed.
+ * Flushes the current line of output and makes the formatter ready to start receiving new column
+ * data for a new line (or end-of-file). If the current line is empty nothing is done, i.e.
+ * consecutive calls to this method without intervening calls to {@link #addColumn} will be
+ * squashed.
*/
public void nextLine() {
if (!firstColumn) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/mail/Address.java b/gerrit-server/src/main/java/com/google/gerrit/server/mail/Address.java
index 2088261..f3b08fb 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/mail/Address.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/mail/Address.java
@@ -32,8 +32,7 @@
if (name.endsWith("\"")) {
nameEnd--;
}
- return new Address(name.length() > 0 ?
- name.substring(nameStart, nameEnd): null, email);
+ return new Address(name.length() > 0 ? name.substring(nameStart, nameEnd) : null, email);
}
if (lt < 0 && gt < 0 && 0 < at && at < in.length() - 1) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/mail/EmailSettings.java b/gerrit-server/src/main/java/com/google/gerrit/server/mail/EmailSettings.java
index b719193..6bdb076 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/mail/EmailSettings.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/mail/EmailSettings.java
@@ -18,10 +18,8 @@
import com.google.gerrit.server.mail.receive.Protocol;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.lib.Config;
-
import java.util.concurrent.TimeUnit;
+import org.eclipse.jgit.lib.Config;
@Singleton
public class EmailSettings {
@@ -52,10 +50,13 @@
port = cfg.getInt(RECEIVE_EMAL, "port", 0);
username = cfg.getString(RECEIVE_EMAL, null, "username");
password = cfg.getString(RECEIVE_EMAL, null, "password");
- encryption =
- cfg.getEnum(RECEIVE_EMAL, null, "encryption", Encryption.NONE);
- fetchInterval = cfg.getTimeUnit(RECEIVE_EMAL, null, "fetchInterval",
- TimeUnit.MILLISECONDS.convert(60, TimeUnit.SECONDS),
- TimeUnit.MILLISECONDS);
+ encryption = cfg.getEnum(RECEIVE_EMAL, null, "encryption", Encryption.NONE);
+ fetchInterval =
+ cfg.getTimeUnit(
+ RECEIVE_EMAL,
+ null,
+ "fetchInterval",
+ TimeUnit.MILLISECONDS.convert(60, TimeUnit.SECONDS),
+ TimeUnit.MILLISECONDS);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/mail/EmailTokenVerifier.java b/gerrit-server/src/main/java/com/google/gerrit/server/mail/EmailTokenVerifier.java
index 488711a..5b5f33d 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/mail/EmailTokenVerifier.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/mail/EmailTokenVerifier.java
@@ -25,14 +25,14 @@
*
* @param accountId the caller that wants to add an email to their account.
* @param emailAddress the address to add.
- * @return an unforgeable string to email to {@code emailAddress}. Presenting
- * the string provides proof the user has the ability to read messages
- * sent to that address. Must not be null.
+ * @return an unforgeable string to email to {@code emailAddress}. Presenting the string provides
+ * proof the user has the ability to read messages sent to that address. Must not be null.
*/
String encode(Account.Id accountId, String emailAddress);
/**
* Decode a token previously created.
+ *
* @param tokenString the string created by encode. Never null.
* @return a pair of account id and email address.
* @throws InvalidTokenException the token is invalid, expired, malformed, etc.
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/mail/Encryption.java b/gerrit-server/src/main/java/com/google/gerrit/server/mail/Encryption.java
index a557532..99c3022 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/mail/Encryption.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/mail/Encryption.java
@@ -15,5 +15,7 @@
package com.google.gerrit.server.mail;
public enum Encryption {
- NONE, SSL, TLS
+ NONE,
+ SSL,
+ TLS
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/mail/MailFilter.java b/gerrit-server/src/main/java/com/google/gerrit/server/mail/MailFilter.java
index 31c6641..d50064d 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/mail/MailFilter.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/mail/MailFilter.java
@@ -19,8 +19,8 @@
/**
* Listener to filter incoming email.
- * <p>
- * Invoked by Gerrit for each incoming email.
+ *
+ * <p>Invoked by Gerrit for each incoming email.
*/
@ExtensionPoint
public interface MailFilter {
@@ -28,8 +28,7 @@
* Determine if Gerrit should discard or further process the message.
*
* @param message MailMessage parsed by Gerrit.
- * @return {@code true}, if Gerrit should process the message, {@code false}
- * otherwise.
+ * @return {@code true}, if Gerrit should process the message, {@code false} otherwise.
*/
boolean shouldProcessMessage(MailMessage message);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/mail/MailUtil.java b/gerrit-server/src/main/java/com/google/gerrit/server/mail/MailUtil.java
index ca8d101..b6d7fa8 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/mail/MailUtil.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/mail/MailUtil.java
@@ -24,34 +24,34 @@
import com.google.gerrit.server.ReviewerSet;
import com.google.gerrit.server.account.AccountResolver;
import com.google.gwtorm.server.OrmException;
-
-import org.eclipse.jgit.revwalk.FooterKey;
-import org.eclipse.jgit.revwalk.FooterLine;
-
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
+import org.eclipse.jgit.revwalk.FooterKey;
+import org.eclipse.jgit.revwalk.FooterLine;
public class MailUtil {
public static DateTimeFormatter rfcDateformatter =
DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss ZZZ");
public static MailRecipients getRecipientsFromFooters(
- ReviewDb db, AccountResolver accountResolver, boolean draftPatchSet,
- List<FooterLine> footerLines) throws OrmException {
+ ReviewDb db,
+ AccountResolver accountResolver,
+ boolean draftPatchSet,
+ List<FooterLine> footerLines)
+ throws OrmException {
MailRecipients recipients = new MailRecipients();
if (!draftPatchSet) {
for (FooterLine footerLine : footerLines) {
try {
if (isReviewer(footerLine)) {
- recipients.reviewers.add(toAccountId(db, accountResolver, footerLine
- .getValue().trim()));
+ recipients.reviewers.add(
+ toAccountId(db, accountResolver, footerLine.getValue().trim()));
} else if (footerLine.matches(FooterKey.CC)) {
- recipients.cc.add(toAccountId(db, accountResolver, footerLine
- .getValue().trim()));
+ recipients.cc.add(toAccountId(db, accountResolver, footerLine.getValue().trim()));
}
} catch (NoSuchAccountException e) {
continue;
@@ -61,21 +61,19 @@
return recipients;
}
- public static MailRecipients getRecipientsFromReviewers(
- ReviewerSet reviewers) {
+ public static MailRecipients getRecipientsFromReviewers(ReviewerSet reviewers) {
MailRecipients recipients = new MailRecipients();
recipients.reviewers.addAll(reviewers.byState(REVIEWER));
recipients.cc.addAll(reviewers.byState(CC));
return recipients;
}
- private static Account.Id toAccountId(ReviewDb db,
- AccountResolver accountResolver, String nameOrEmail)
+ private static Account.Id toAccountId(
+ ReviewDb db, AccountResolver accountResolver, String nameOrEmail)
throws OrmException, NoSuchAccountException {
Account a = accountResolver.findByNameOrEmail(db, nameOrEmail);
if (a == null) {
- throw new NoSuchAccountException("\"" + nameOrEmail
- + "\" is not registered");
+ throw new NoSuchAccountException("\"" + nameOrEmail + "\" is not registered");
}
return a.getId();
}
@@ -96,8 +94,7 @@
this.cc = new HashSet<>();
}
- public MailRecipients(final Set<Account.Id> reviewers,
- final Set<Account.Id> cc) {
+ public MailRecipients(final Set<Account.Id> reviewers, final Set<Account.Id> cc) {
this.reviewers = new HashSet<>(reviewers);
this.cc = new HashSet<>(cc);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/mail/SignedTokenEmailTokenVerifier.java b/gerrit-server/src/main/java/com/google/gerrit/server/mail/SignedTokenEmailTokenVerifier.java
index 3dd98ea..aaf3243 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/mail/SignedTokenEmailTokenVerifier.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/mail/SignedTokenEmailTokenVerifier.java
@@ -25,11 +25,9 @@
import com.google.inject.AbstractModule;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.util.Base64;
-
import java.util.regex.Matcher;
import java.util.regex.Pattern;
+import org.eclipse.jgit.util.Base64;
/** Verifies the token sent by {@link RegisterNewEmailSender}. */
@Singleton
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/mail/receive/HtmlParser.java b/gerrit-server/src/main/java/com/google/gerrit/server/mail/receive/HtmlParser.java
index 6b81d35..20e163e 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/mail/receive/HtmlParser.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/mail/receive/HtmlParser.java
@@ -18,14 +18,12 @@
import com.google.common.collect.Iterators;
import com.google.common.collect.PeekingIterator;
import com.google.gerrit.reviewdb.client.Comment;
-
-import org.jsoup.Jsoup;
-import org.jsoup.nodes.Document;
-import org.jsoup.nodes.Element;
-
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
+import org.jsoup.Jsoup;
+import org.jsoup.nodes.Document;
+import org.jsoup.nodes.Element;
/** HTMLParser provides parsing functionality for html email. */
public class HtmlParser {
@@ -33,16 +31,14 @@
* Parses comments from html email.
*
* @param email MailMessage as received from the email service.
- * @param comments A specific set of comments as sent out in the original
- * notification email. Comments are expected to be in the same
- * order as they were sent out to in the email
- * @param changeUrl Canonical change URL that points to the change on this
- * Gerrit instance.
- * Example: https://go-review.googlesource.com/#/c/91570
+ * @param comments A specific set of comments as sent out in the original notification email.
+ * Comments are expected to be in the same order as they were sent out to in the email
+ * @param changeUrl Canonical change URL that points to the change on this Gerrit instance.
+ * Example: https://go-review.googlesource.com/#/c/91570
* @return List of MailComments parsed from the html part of the email.
*/
- public static List<MailComment> parse(MailMessage email,
- Collection<Comment> comments, String changeUrl) {
+ public static List<MailComment> parse(
+ MailMessage email, Collection<Comment> comments, String changeUrl) {
// TODO(hiesel) Add support for Gmail Mobile
// TODO(hiesel) Add tests for other popular email clients
@@ -53,17 +49,14 @@
// Gerrit as these are generally more reliable then the text captions.
List<MailComment> parsedComments = new ArrayList<>();
Document d = Jsoup.parse(email.htmlContent());
- PeekingIterator<Comment> iter =
- Iterators.peekingIterator(comments.iterator());
+ PeekingIterator<Comment> iter = Iterators.peekingIterator(comments.iterator());
String lastEncounteredFileName = null;
Comment lastEncounteredComment = null;
for (Element e : d.body().getAllElements()) {
String elementName = e.tagName();
- boolean isInBlockQuote = e.parents().stream()
- .filter(p -> p.tagName().equals("blockquote"))
- .findAny()
- .isPresent();
+ boolean isInBlockQuote =
+ e.parents().stream().filter(p -> p.tagName().equals("blockquote")).findAny().isPresent();
if (elementName.equals("a")) {
String href = e.attr("href");
@@ -74,8 +67,8 @@
}
Comment perspectiveComment = iter.peek();
if (href.equals(ParserUtil.filePath(changeUrl, perspectiveComment))) {
- if (lastEncounteredFileName == null || !lastEncounteredFileName
- .equals(perspectiveComment.key.filename)) {
+ if (lastEncounteredFileName == null
+ || !lastEncounteredFileName.equals(perspectiveComment.key.filename)) {
// Not a file-level comment, but users could have typed a comment
// right after this file annotation to create a new file-level
// comment. If this file has a file-level comment, we have already
@@ -88,34 +81,34 @@
lastEncounteredComment = perspectiveComment;
iter.next();
}
- } else if (ParserUtil.isCommentUrl(href, changeUrl,
- perspectiveComment)) {
+ } else if (ParserUtil.isCommentUrl(href, changeUrl, perspectiveComment)) {
// This is a regular inline comment
lastEncounteredComment = perspectiveComment;
iter.next();
}
- } else if (!isInBlockQuote && elementName.equals("div") &&
- !e.className().startsWith("gmail")) {
+ } else if (!isInBlockQuote
+ && elementName.equals("div")
+ && !e.className().startsWith("gmail")) {
// This is a comment typed by the user
String content = e.ownText().trim();
if (!Strings.isNullOrEmpty(content)) {
- if (lastEncounteredComment == null &&
- lastEncounteredFileName == null) {
+ if (lastEncounteredComment == null && lastEncounteredFileName == null) {
// Remove quotation line, email signature and
// "Sent from my xyz device"
content = ParserUtil.trimQuotationLine(content);
// TODO(hiesel) Add more sanitizer
if (!Strings.isNullOrEmpty(content)) {
- parsedComments.add(new MailComment(content, null, null,
- MailComment.CommentType.CHANGE_MESSAGE));
+ parsedComments.add(
+ new MailComment(content, null, null, MailComment.CommentType.CHANGE_MESSAGE));
}
} else if (lastEncounteredComment == null) {
- parsedComments.add(new MailComment(content, lastEncounteredFileName,
- null, MailComment.CommentType.FILE_COMMENT));
+ parsedComments.add(
+ new MailComment(
+ content, lastEncounteredFileName, null, MailComment.CommentType.FILE_COMMENT));
} else {
- parsedComments.add(new MailComment(content, null,
- lastEncounteredComment,
- MailComment.CommentType.INLINE_COMMENT));
+ parsedComments.add(
+ new MailComment(
+ content, null, lastEncounteredComment, MailComment.CommentType.INLINE_COMMENT));
}
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/mail/receive/ImapMailReceiver.java b/gerrit-server/src/main/java/com/google/gerrit/server/mail/receive/ImapMailReceiver.java
index ce2a834..3362897 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/mail/receive/ImapMailReceiver.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/mail/receive/ImapMailReceiver.java
@@ -19,32 +19,28 @@
import com.google.gerrit.server.mail.Encryption;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
import org.apache.commons.net.imap.IMAPClient;
import org.apache.commons.net.imap.IMAPSClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-
@Singleton
public class ImapMailReceiver extends MailReceiver {
- private static final Logger log =
- LoggerFactory.getLogger(ImapMailReceiver.class);
+ private static final Logger log = LoggerFactory.getLogger(ImapMailReceiver.class);
private static final String INBOX_FOLDER = "INBOX";
@Inject
- ImapMailReceiver(EmailSettings mailSettings,
- MailProcessor mailProcessor,
- WorkQueue workQueue) {
+ ImapMailReceiver(EmailSettings mailSettings, MailProcessor mailProcessor, WorkQueue workQueue) {
super(mailSettings, mailProcessor, workQueue);
}
/**
- * handleEmails will open a connection to the mail server, remove emails
- * where deletion is pending, read new email and close the connection.
+ * handleEmails will open a connection to the mail server, remove emails where deletion is
+ * pending, read new email and close the connection.
+ *
* @param async Determines if processing messages should happen asynchronous.
*/
@Override
@@ -68,7 +64,7 @@
return;
}
try {
- if (!imap.select(INBOX_FOLDER)){
+ if (!imap.select(INBOX_FOLDER)) {
log.error("Could not select IMAP folder " + INBOX_FOLDER);
return;
}
@@ -102,7 +98,7 @@
// checked, that the fetch returned true (OK), so we safely ignore
// those two lines.
StringBuilder b = new StringBuilder(2 * (rawMessage.length - 2));
- for(int j = 1; j < rawMessage.length - 1; j++) {
+ for (int j = 1; j < rawMessage.length - 1; j++) {
if (j > 1) {
b.append("\n");
}
@@ -115,8 +111,7 @@
if (imap.store(i + ":" + i, "+FLAGS", "(\\Deleted)")) {
pendingDeletion.remove(mailMessage.id());
} else {
- log.error("Could not mark mail message as deleted: " +
- mailMessage.id());
+ log.error("Could not mark mail message as deleted: " + mailMessage.id());
}
} else {
mailMessages.add(mailMessage);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/mail/receive/MailComment.java b/gerrit-server/src/main/java/com/google/gerrit/server/mail/receive/MailComment.java
index 4144cfc..8afbe81 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/mail/receive/MailComment.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/mail/receive/MailComment.java
@@ -29,10 +29,9 @@
String fileName;
String message;
- public MailComment() { }
+ public MailComment() {}
- public MailComment(String message, String fileName, Comment inReplyTo,
- CommentType type) {
+ public MailComment(String message, String fileName, Comment inReplyTo, CommentType type) {
this.message = message;
this.fileName = fileName;
this.inReplyTo = inReplyTo;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/mail/receive/MailMessage.java b/gerrit-server/src/main/java/com/google/gerrit/server/mail/receive/MailMessage.java
index 27d3052..dcac25c 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/mail/receive/MailMessage.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/mail/receive/MailMessage.java
@@ -18,18 +18,16 @@
import com.google.common.collect.ImmutableList;
import com.google.gerrit.common.Nullable;
import com.google.gerrit.server.mail.Address;
-
import org.joda.time.DateTime;
/**
- * MailMessage is a simplified representation of an RFC 2045-2047 mime email
- * message used for representing received emails inside Gerrit. It is populated
- * by the MailParser after MailReceiver has received a message. Transformations
- * done by the parser include stitching mime parts together, transforming all
- * content to UTF-16 and removing attachments.
+ * MailMessage is a simplified representation of an RFC 2045-2047 mime email message used for
+ * representing received emails inside Gerrit. It is populated by the MailParser after MailReceiver
+ * has received a message. Transformations done by the parser include stitching mime parts together,
+ * transforming all content to UTF-16 and removing attachments.
*
- * A valid MailMessage contains at least the following fields: id, from, to,
- * subject and dateReceived.
+ * <p>A valid MailMessage contains at least the following fields: id, from, to, subject and
+ * dateReceived.
*/
@AutoValue
public abstract class MailMessage {
@@ -37,20 +35,26 @@
public abstract String id();
// Envelop Information
public abstract Address from();
+
public abstract ImmutableList<Address> to();
+
public abstract ImmutableList<Address> cc();
// Metadata
public abstract DateTime dateReceived();
+
public abstract ImmutableList<String> additionalHeaders();
// Content
public abstract String subject();
+
@Nullable
public abstract String textContent();
+
@Nullable
public abstract String htmlContent();
// Raw content as received over the wire
@Nullable
public abstract ImmutableList<Integer> rawContent();
+
@Nullable
public abstract String rawContentUTF();
@@ -63,7 +67,9 @@
@AutoValue.Builder
public abstract static class Builder {
public abstract Builder id(String val);
+
public abstract Builder from(Address val);
+
public abstract ImmutableList.Builder<Address> toBuilder();
public Builder addTo(Address val) {
@@ -79,6 +85,7 @@
}
public abstract Builder dateReceived(DateTime val);
+
public abstract ImmutableList.Builder<String> additionalHeadersBuilder();
public Builder addAdditionalHeader(String val) {
@@ -87,9 +94,13 @@
}
public abstract Builder subject(String val);
+
public abstract Builder textContent(String val);
+
public abstract Builder htmlContent(String val);
+
public abstract Builder rawContent(ImmutableList<Integer> val);
+
public abstract Builder rawContentUTF(String val);
public abstract MailMessage build();
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/mail/receive/MailMetadata.java b/gerrit-server/src/main/java/com/google/gerrit/server/mail/receive/MailMetadata.java
index c353e54..f85291c 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/mail/receive/MailMetadata.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/mail/receive/MailMetadata.java
@@ -15,7 +15,6 @@
package com.google.gerrit.server.mail.receive;
import com.google.common.base.MoreObjects;
-
import java.sql.Timestamp;
/** MailMetadata represents metadata parsed from inbound email. */
@@ -26,10 +25,12 @@
public Timestamp timestamp;
public String messageType; // we expect comment here
-
public boolean hasRequiredFields() {
- return changeId != null && patchSet != null && author != null &&
- timestamp != null && messageType != null;
+ return changeId != null
+ && patchSet != null
+ && author != null
+ && timestamp != null
+ && messageType != null;
}
@Override
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/mail/receive/MailProcessor.java b/gerrit-server/src/main/java/com/google/gerrit/server/mail/receive/MailProcessor.java
index eb084ca..08bd0ba 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/mail/receive/MailProcessor.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/mail/receive/MailProcessor.java
@@ -46,21 +46,18 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
@Singleton
public class MailProcessor {
- private static final Logger log =
- LoggerFactory.getLogger(MailProcessor.class.getName());
+ private static final Logger log = LoggerFactory.getLogger(MailProcessor.class.getName());
private final AccountByEmailCache accountByEmailCache;
private final BatchUpdate.Factory buf;
@@ -75,7 +72,8 @@
private final Provider<String> canonicalUrl;
@Inject
- public MailProcessor(AccountByEmailCache accountByEmailCache,
+ public MailProcessor(
+ AccountByEmailCache accountByEmailCache,
BatchUpdate.Factory buf,
ChangeMessagesUtil changeMessagesUtil,
CommentsUtil commentsUtil,
@@ -101,57 +99,68 @@
/**
* Parse comments from MailMessage and persist them on the change.
+ *
* @param message MailMessage to process.
* @throws OrmException
*/
public void process(MailMessage message) throws OrmException {
for (DynamicMap.Entry<MailFilter> filter : mailFilters) {
if (!filter.getProvider().get().shouldProcessMessage(message)) {
- log.warn("Mail: Message " + message.id() + " filtered by plugin " +
- filter.getPluginName() + " " + filter.getExportName() +
- ". Will delete message.");
+ log.warn(
+ "Mail: Message "
+ + message.id()
+ + " filtered by plugin "
+ + filter.getPluginName()
+ + " "
+ + filter.getExportName()
+ + ". Will delete message.");
return;
}
}
MailMetadata metadata = MetadataParser.parse(message);
if (!metadata.hasRequiredFields()) {
- log.error("Mail: Message " + message.id() +
- " is missing required metadata, have " + metadata +
- ". Will delete message.");
+ log.error(
+ "Mail: Message "
+ + message.id()
+ + " is missing required metadata, have "
+ + metadata
+ + ". Will delete message.");
return;
}
Set<Account.Id> accounts = accountByEmailCache.get(metadata.author);
if (accounts.size() != 1) {
- log.error("Mail: Address " + metadata.author +
- " could not be matched to a unique account. It was matched to " +
- accounts + ". Will delete message.");
+ log.error(
+ "Mail: Address "
+ + metadata.author
+ + " could not be matched to a unique account. It was matched to "
+ + accounts
+ + ". Will delete message.");
return;
}
Account.Id account = accounts.iterator().next();
if (!reviewDb.get().accounts().get(account).isActive()) {
- log.warn("Mail: Account " + account +
- " is inactive. Will delete message.");
+ log.warn("Mail: Account " + account + " is inactive. Will delete message.");
return;
}
try (ManualRequestContext ctx = oneOffRequestContext.openAs(account)) {
- ChangeData cd = queryProvider.get().setLimit(1)
- .byKey(Change.Key.parse(metadata.changeId)).get(0);
+ ChangeData cd =
+ queryProvider.get().setLimit(1).byKey(Change.Key.parse(metadata.changeId)).get(0);
if (existingMessageIds(cd).contains(message.id())) {
- log.info("Mail: Message " + message.id() +
- " was already processed. Will delete message.");
+ log.info("Mail: Message " + message.id() + " was already processed. Will delete message.");
return;
}
// Get all comments; filter and sort them to get the original list of
// comments from the outbound email.
// TODO(hiesel) Also filter by original comment author.
- Collection<Comment> comments = cd.publishedComments().stream()
- .filter(c -> (c.writtenOn.getTime() / 1000) ==
- (metadata.timestamp.getTime() / 1000))
- .sorted(CommentsUtil.COMMENT_ORDER)
- .collect(Collectors.toList());
+ Collection<Comment> comments =
+ cd.publishedComments()
+ .stream()
+ .filter(c -> (c.writtenOn.getTime() / 1000) == (metadata.timestamp.getTime() / 1000))
+ .sorted(CommentsUtil.COMMENT_ORDER)
+ .collect(Collectors.toList());
Project.NameKey project = cd.project();
String changeUrl = canonicalUrl.get() + "#/c/" + cd.getId().get();
@@ -163,15 +172,13 @@
}
if (parsedComments.isEmpty()) {
- log.warn("Mail: Could not parse any comments from " + message.id() +
- ". Will delete message.");
+ log.warn(
+ "Mail: Could not parse any comments from " + message.id() + ". Will delete message.");
return;
}
- Op o = new Op(new PatchSet.Id(cd.getId(), metadata.patchSet),
- parsedComments, message.id());
- BatchUpdate batchUpdate = buf.create(cd.db(), project, ctx.getUser(),
- TimeUtil.nowTs());
+ Op o = new Op(new PatchSet.Id(cd.getId(), metadata.patchSet), parsedComments, message.id());
+ BatchUpdate batchUpdate = buf.create(cd.db(), project, ctx.getUser(), TimeUtil.nowTs());
batchUpdate.addOp(cd.getId(), o);
try {
batchUpdate.execute();
@@ -186,24 +193,22 @@
private final List<MailComment> parsedComments;
private final String tag;
- private Op(PatchSet.Id psId, List<MailComment> parsedComments,
- String messageId) {
+ private Op(PatchSet.Id psId, List<MailComment> parsedComments, String messageId) {
this.psId = psId;
this.parsedComments = parsedComments;
this.tag = "mailMessageId=" + messageId;
}
@Override
- public boolean updateChange(ChangeContext ctx) throws OrmException,
- UnprocessableEntityException {
+ public boolean updateChange(ChangeContext ctx)
+ throws OrmException, UnprocessableEntityException {
PatchSet ps = psUtil.get(ctx.getDb(), ctx.getNotes(), psId);
if (ps == null) {
throw new OrmException("patch set not found: " + psId);
}
String changeMsg = "Patch Set " + psId.get() + ":";
- if (parsedComments.get(0).type ==
- MailComment.CommentType.CHANGE_MESSAGE) {
+ if (parsedComments.get(0).type == MailComment.CommentType.CHANGE_MESSAGE) {
if (parsedComments.size() > 1) {
changeMsg += "\n" + numComments(parsedComments.size() - 1);
}
@@ -213,8 +218,7 @@
}
ChangeMessage msg = ChangeMessagesUtil.newMessage(ctx, changeMsg, tag);
- changeMessagesUtil.addChangeMessage(ctx.getDb(),
- ctx.getUpdate(psId), msg);
+ changeMessagesUtil.addChangeMessage(ctx.getDb(), ctx.getUpdate(psId), msg);
List<Comment> comments = new ArrayList<>();
for (MailComment c : parsedComments) {
@@ -229,9 +233,11 @@
Side side;
if (c.inReplyTo != null) {
fileName = c.inReplyTo.key.filename;
- psForComment = psUtil.get(ctx.getDb(), ctx.getNotes(),
- new PatchSet.Id(ctx.getChange().getId(),
- c.inReplyTo.key.patchSetId));
+ psForComment =
+ psUtil.get(
+ ctx.getDb(),
+ ctx.getNotes(),
+ new PatchSet.Id(ctx.getChange().getId(), c.inReplyTo.key.patchSetId));
side = Side.fromShort(c.inReplyTo.side);
} else {
fileName = c.fileName;
@@ -239,9 +245,15 @@
side = Side.REVISION;
}
- Comment comment = commentsUtil.newComment(ctx, fileName,
- psForComment.getId(), (short) side.ordinal(), c.message,
- false, null);
+ Comment comment =
+ commentsUtil.newComment(
+ ctx,
+ fileName,
+ psForComment.getId(),
+ (short) side.ordinal(),
+ c.message,
+ false,
+ null);
comment.tag = tag;
if (c.inReplyTo != null) {
comment.parentUuid = c.inReplyTo.key.uuid;
@@ -249,12 +261,13 @@
comment.range = c.inReplyTo.range;
comment.unresolved = c.inReplyTo.unresolved;
}
- CommentsUtil.setCommentRevId(comment, patchListCache,
- ctx.getChange(), psForComment);
+ CommentsUtil.setCommentRevId(comment, patchListCache, ctx.getChange(), psForComment);
comments.add(comment);
}
- commentsUtil.putComments(ctx.getDb(),
- ctx.getUpdate(ctx.getChange().currentPatchSetId()), Status.PUBLISHED,
+ commentsUtil.putComments(
+ ctx.getDb(),
+ ctx.getUpdate(ctx.getChange().currentPatchSetId()),
+ Status.PUBLISHED,
comments);
return true;
@@ -271,18 +284,24 @@
private Set<String> existingMessageIds(ChangeData cd) throws OrmException {
Set<String> existingMessageIds = new HashSet<>();
- cd.messages().stream().forEach(m -> {
- String messageId = CommentsUtil.extractMessageId(m.getTag());
- if (messageId != null) {
- existingMessageIds.add(messageId);
- }
- });
- cd.publishedComments().stream().forEach(c -> {
- String messageId = CommentsUtil.extractMessageId(c.tag);
- if (messageId != null) {
- existingMessageIds.add(messageId);
- }
- });
+ cd.messages()
+ .stream()
+ .forEach(
+ m -> {
+ String messageId = CommentsUtil.extractMessageId(m.getTag());
+ if (messageId != null) {
+ existingMessageIds.add(messageId);
+ }
+ });
+ cd.publishedComments()
+ .stream()
+ .forEach(
+ c -> {
+ String messageId = CommentsUtil.extractMessageId(c.tag);
+ if (messageId != null) {
+ existingMessageIds.add(messageId);
+ }
+ });
return existingMessageIds;
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/mail/receive/MailReceiver.java b/gerrit-server/src/main/java/com/google/gerrit/server/mail/receive/MailReceiver.java
index 24f4f48..1cabe16 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/mail/receive/MailReceiver.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/mail/receive/MailReceiver.java
@@ -21,10 +21,6 @@
import com.google.gerrit.server.mail.EmailSettings;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
@@ -32,11 +28,12 @@
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Callable;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/** MailReceiver implements base functionality for receiving emails. */
public abstract class MailReceiver implements LifecycleListener {
- private static final Logger log =
- LoggerFactory.getLogger(MailReceiver.class.getName());
+ private static final Logger log = LoggerFactory.getLogger(MailReceiver.class.getName());
protected EmailSettings mailSettings;
protected Set<String> pendingDeletion;
@@ -71,8 +68,7 @@
}
}
- MailReceiver(EmailSettings mailSettings, MailProcessor mailProcessor,
- WorkQueue workQueue) {
+ MailReceiver(EmailSettings mailSettings, MailProcessor mailProcessor, WorkQueue workQueue) {
this.mailSettings = mailSettings;
this.mailProcessor = mailProcessor;
this.workQueue = workQueue;
@@ -86,12 +82,15 @@
} else {
timer.cancel();
}
- timer.scheduleAtFixedRate(new TimerTask() {
- @Override
- public void run() {
- MailReceiver.this.handleEmails(true);
- }
- }, 0L, mailSettings.fetchInterval);
+ timer.scheduleAtFixedRate(
+ new TimerTask() {
+ @Override
+ public void run() {
+ MailReceiver.this.handleEmails(true);
+ }
+ },
+ 0L,
+ mailSettings.fetchInterval);
}
@Override
@@ -102,9 +101,10 @@
}
/**
- * requestDeletion will enqueue an email for deletion and delete it the
- * next time we connect to the email server. This does not guarantee deletion
- * as the Gerrit instance might fail before we connect to the email server.
+ * requestDeletion will enqueue an email for deletion and delete it the next time we connect to
+ * the email server. This does not guarantee deletion as the Gerrit instance might fail before we
+ * connect to the email server.
+ *
* @param messageId
*/
public void requestDeletion(String messageId) {
@@ -112,27 +112,27 @@
}
/**
- * handleEmails will open a connection to the mail server, remove emails
- * where deletion is pending, read new email and close the connection.
+ * handleEmails will open a connection to the mail server, remove emails where deletion is
+ * pending, read new email and close the connection.
+ *
* @param async Determines if processing messages should happen asynchronous.
*/
@VisibleForTesting
public abstract void handleEmails(boolean async);
- protected void dispatchMailProcessor(List<MailMessage> messages,
- boolean async) {
+ protected void dispatchMailProcessor(List<MailMessage> messages, boolean async) {
for (MailMessage m : messages) {
if (async) {
- Callable<?> task = () -> {
- try {
- mailProcessor.process(m);
- requestDeletion(m.id());
- } catch (OrmException e) {
- log.error("Mail: Can't process message " + m.id() +
- " . Won't delete.", e);
- }
- return null;
- };
+ Callable<?> task =
+ () -> {
+ try {
+ mailProcessor.process(m);
+ requestDeletion(m.id());
+ } catch (OrmException e) {
+ log.error("Mail: Can't process message " + m.id() + " . Won't delete.", e);
+ }
+ return null;
+ };
workQueue.getDefaultQueue().submit(task);
} else {
// Synchronous processing is used only in tests.
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/mail/receive/MetadataParser.java b/gerrit-server/src/main/java/com/google/gerrit/server/mail/receive/MetadataParser.java
index 1a3b14d..c812568 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/mail/receive/MetadataParser.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/mail/receive/MetadataParser.java
@@ -21,7 +21,6 @@
import com.google.common.primitives.Ints;
import com.google.gerrit.server.mail.MailUtil;
import com.google.gerrit.server.mail.MetadataName;
-
import java.sql.Timestamp;
import java.time.Instant;
@@ -35,23 +34,17 @@
// Check email headers for X-Gerrit-<Name>
for (String header : m.additionalHeaders()) {
if (header.startsWith(toHeaderWithDelimiter(MetadataName.CHANGE_ID))) {
- metadata.changeId = header
- .substring(toHeaderWithDelimiter(MetadataName.CHANGE_ID).length());
- } else if (header.startsWith(
- toHeaderWithDelimiter(MetadataName.PATCH_SET))) {
- String ps = header.substring(
- toHeaderWithDelimiter(MetadataName.PATCH_SET).length());
+ metadata.changeId =
+ header.substring(toHeaderWithDelimiter(MetadataName.CHANGE_ID).length());
+ } else if (header.startsWith(toHeaderWithDelimiter(MetadataName.PATCH_SET))) {
+ String ps = header.substring(toHeaderWithDelimiter(MetadataName.PATCH_SET).length());
metadata.patchSet = Ints.tryParse(ps);
- } else if (header.startsWith(
- toHeaderWithDelimiter(MetadataName.TIMESTAMP))) {
- String ts = header.substring(
- toHeaderWithDelimiter(MetadataName.TIMESTAMP).length());
- metadata.timestamp = Timestamp.from(
- MailUtil.rfcDateformatter.parse(ts, Instant::from));
- } else if (header.startsWith(
- toHeaderWithDelimiter(MetadataName.MESSAGE_TYPE))) {
- metadata.messageType = header.substring(
- toHeaderWithDelimiter(MetadataName.MESSAGE_TYPE).length());
+ } else if (header.startsWith(toHeaderWithDelimiter(MetadataName.TIMESTAMP))) {
+ String ts = header.substring(toHeaderWithDelimiter(MetadataName.TIMESTAMP).length());
+ metadata.timestamp = Timestamp.from(MailUtil.rfcDateformatter.parse(ts, Instant::from));
+ } else if (header.startsWith(toHeaderWithDelimiter(MetadataName.MESSAGE_TYPE))) {
+ metadata.messageType =
+ header.substring(toHeaderWithDelimiter(MetadataName.MESSAGE_TYPE).length());
}
}
if (metadata.hasRequiredFields()) {
@@ -83,22 +76,16 @@
private static void extractFooters(String[] lines, MailMetadata metadata) {
for (String line : lines) {
if (metadata.changeId == null && line.contains(MetadataName.CHANGE_ID)) {
- metadata.changeId =
- extractFooter(toFooterWithDelimiter(MetadataName.CHANGE_ID), line);
- } else if (metadata.patchSet == null &&
- line.contains(MetadataName.PATCH_SET)) {
- metadata.patchSet = Ints.tryParse(
- extractFooter(toFooterWithDelimiter(MetadataName.PATCH_SET), line));
- } else if (metadata.timestamp == null &&
- line.contains(MetadataName.TIMESTAMP)) {
- String ts =
- extractFooter(toFooterWithDelimiter(MetadataName.TIMESTAMP), line);
- metadata.timestamp = Timestamp.from(
- MailUtil.rfcDateformatter.parse(ts, Instant::from));
- } else if (metadata.messageType == null &&
- line.contains(MetadataName.MESSAGE_TYPE)) {
- metadata.messageType = extractFooter(
- toFooterWithDelimiter(MetadataName.MESSAGE_TYPE), line);
+ metadata.changeId = extractFooter(toFooterWithDelimiter(MetadataName.CHANGE_ID), line);
+ } else if (metadata.patchSet == null && line.contains(MetadataName.PATCH_SET)) {
+ metadata.patchSet =
+ Ints.tryParse(extractFooter(toFooterWithDelimiter(MetadataName.PATCH_SET), line));
+ } else if (metadata.timestamp == null && line.contains(MetadataName.TIMESTAMP)) {
+ String ts = extractFooter(toFooterWithDelimiter(MetadataName.TIMESTAMP), line);
+ metadata.timestamp = Timestamp.from(MailUtil.rfcDateformatter.parse(ts, Instant::from));
+ } else if (metadata.messageType == null && line.contains(MetadataName.MESSAGE_TYPE)) {
+ metadata.messageType =
+ extractFooter(toFooterWithDelimiter(MetadataName.MESSAGE_TYPE), line);
}
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/mail/receive/ParserUtil.java b/gerrit-server/src/main/java/com/google/gerrit/server/mail/receive/ParserUtil.java
index dbdea22..72eb18a 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/mail/receive/ParserUtil.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/mail/receive/ParserUtil.java
@@ -15,17 +15,18 @@
package com.google.gerrit.server.mail.receive;
import com.google.gerrit.reviewdb.client.Comment;
-
import java.util.regex.Pattern;
public class ParserUtil {
- private static final Pattern SIMPLE_EMAIL_PATTERN = Pattern.compile(
- "[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+"
- + "(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})");
+ private static final Pattern SIMPLE_EMAIL_PATTERN =
+ Pattern.compile(
+ "[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+"
+ + "(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})");
/**
- * Trims the quotation line that email clients add
- * Example: On Sun, Nov 20, 2016 at 10:33 PM, <gerrit@hiesel.it> wrote:
+ * Trims the quotation line that email clients add Example: On Sun, Nov 20, 2016 at 10:33 PM,
+ * <gerrit@hiesel.it> wrote:
+ *
* @param comment Comment parsed from an email.
* @return Trimmed comment.
*/
@@ -44,14 +45,14 @@
if (c >= '0' && c <= '9') {
numConsecutiveDigits++;
} else if (numConsecutiveDigits > 0) {
- maxConsecutiveDigits = Integer.max(maxConsecutiveDigits,
- numConsecutiveDigits);
+ maxConsecutiveDigits = Integer.max(maxConsecutiveDigits, numConsecutiveDigits);
numConsecutiveDigits = 0;
numDigitGroups++;
}
}
- if (numDigitGroups < 4 || maxConsecutiveDigits > 4 ||
- !SIMPLE_EMAIL_PATTERN.matcher(line).find()) {
+ if (numDigitGroups < 4
+ || maxConsecutiveDigits > 4
+ || !SIMPLE_EMAIL_PATTERN.matcher(line).find()) {
b.append(line);
}
}
@@ -59,15 +60,13 @@
}
/** Check if string is an inline comment url on a patch set or the base */
- public static boolean isCommentUrl(String str, String changeUrl,
- Comment comment) {
- return str.equals(filePath(changeUrl, comment) + "@" + comment.lineNbr) ||
- str.equals(filePath(changeUrl, comment) + "@a" + comment.lineNbr);
+ public static boolean isCommentUrl(String str, String changeUrl, Comment comment) {
+ return str.equals(filePath(changeUrl, comment) + "@" + comment.lineNbr)
+ || str.equals(filePath(changeUrl, comment) + "@a" + comment.lineNbr);
}
/** Generate the fully qualified filepath */
public static String filePath(String changeUrl, Comment comment) {
- return changeUrl + "/" + comment.key.patchSetId + "/" +
- comment.key.filename;
+ return changeUrl + "/" + comment.key.patchSetId + "/" + comment.key.filename;
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/mail/receive/Pop3MailReceiver.java b/gerrit-server/src/main/java/com/google/gerrit/server/mail/receive/Pop3MailReceiver.java
index d1498fd..3bf452f 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/mail/receive/Pop3MailReceiver.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/mail/receive/Pop3MailReceiver.java
@@ -20,33 +20,29 @@
import com.google.gerrit.server.mail.Encryption;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
import org.apache.commons.net.pop3.POP3Client;
import org.apache.commons.net.pop3.POP3MessageInfo;
import org.apache.commons.net.pop3.POP3SClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-
@Singleton
public class Pop3MailReceiver extends MailReceiver {
- private static final Logger log =
- LoggerFactory.getLogger(Pop3MailReceiver.class);
+ private static final Logger log = LoggerFactory.getLogger(Pop3MailReceiver.class);
@Inject
- Pop3MailReceiver(EmailSettings mailSettings,
- MailProcessor mailProcessor,
- WorkQueue workQueue) {
+ Pop3MailReceiver(EmailSettings mailSettings, MailProcessor mailProcessor, WorkQueue workQueue) {
super(mailSettings, mailProcessor, workQueue);
}
/**
- * handleEmails will open a connection to the mail server, remove emails
- * where deletion is pending, read new email and close the connection.
+ * handleEmails will open a connection to the mail server, remove emails where deletion is
+ * pending, read new email and close the connection.
+ *
* @param async Determines if processing messages should happen asynchronous.
*/
@Override
@@ -69,8 +65,7 @@
try {
try {
if (!pop3.login(mailSettings.username, mailSettings.password)) {
- log.error("Could not login to POP3 email server."
- + " Check username and password");
+ log.error("Could not login to POP3 email server." + " Check username and password");
return;
}
try {
@@ -87,12 +82,10 @@
// Message was deleted
continue;
}
- try (BufferedReader reader =
- (BufferedReader) pop3.retrieveMessage(msginfo.number)) {
+ try (BufferedReader reader = (BufferedReader) pop3.retrieveMessage(msginfo.number)) {
if (reader == null) {
log.error(
- "Could not retrieve POP3 message header for message {}",
- msginfo.identifier);
+ "Could not retrieve POP3 message header for message {}", msginfo.identifier);
return;
}
int[] message = fetchMessage(reader);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/mail/receive/Protocol.java b/gerrit-server/src/main/java/com/google/gerrit/server/mail/receive/Protocol.java
index e8311f1..cbd40ed 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/mail/receive/Protocol.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/mail/receive/Protocol.java
@@ -15,5 +15,7 @@
package com.google.gerrit.server.mail.receive;
public enum Protocol {
- NONE, POP3, IMAP
+ NONE,
+ POP3,
+ IMAP
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/mail/receive/RawMailParser.java b/gerrit-server/src/main/java/com/google/gerrit/server/mail/receive/RawMailParser.java
index 52dc3ce..e2f05dc 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/mail/receive/RawMailParser.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/mail/receive/RawMailParser.java
@@ -22,7 +22,9 @@
import com.google.common.io.CharStreams;
import com.google.common.primitives.Ints;
import com.google.gerrit.server.mail.Address;
-
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStreamReader;
import org.apache.james.mime4j.MimeException;
import org.apache.james.mime4j.dom.Entity;
import org.apache.james.mime4j.dom.Message;
@@ -33,21 +35,17 @@
import org.apache.james.mime4j.message.DefaultMessageBuilder;
import org.joda.time.DateTime;
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStreamReader;
-
/**
- * RawMailParser parses raw email content received through POP3 or IMAP into
- * an internal {@link MailMessage}.
+ * RawMailParser parses raw email content received through POP3 or IMAP into an internal {@link
+ * MailMessage}.
*/
public class RawMailParser {
private static final ImmutableSet<String> MAIN_HEADERS =
- ImmutableSet.of("to", "from", "cc", "date", "message-id",
- "subject", "content-type");
+ ImmutableSet.of("to", "from", "cc", "date", "message-id", "subject", "content-type");
/**
* Parses a MailMessage from a string.
+ *
* @param raw String as received over the wire
* @return Parsed MailMessage
* @throws MailParsingException
@@ -58,8 +56,7 @@
Message mimeMessage;
try {
MessageBuilder builder = new DefaultMessageBuilder();
- mimeMessage =
- builder.parseMessage(new ByteArrayInputStream(raw.getBytes(UTF_8)));
+ mimeMessage = builder.parseMessage(new ByteArrayInputStream(raw.getBytes(UTF_8)));
} catch (IOException | MimeException e) {
throw new MailParsingException("Can't parse email", e);
}
@@ -85,10 +82,12 @@
}
// Add additional headers
- mimeMessage.getHeader().getFields().stream()
+ mimeMessage
+ .getHeader()
+ .getFields()
+ .stream()
.filter(f -> !MAIN_HEADERS.contains(f.getName().toLowerCase()))
- .forEach(f -> messageBuilder.addAdditionalHeader(
- f.getName() + ": " + f.getBody()));
+ .forEach(f -> messageBuilder.addAdditionalHeader(f.getName() + ": " + f.getBody()));
// Add text and html body parts
StringBuilder textBuilder = new StringBuilder();
@@ -107,19 +106,18 @@
// required attributes are missing, so that the caller doesn't fall over.
return messageBuilder.build();
} catch (IllegalStateException e) {
- throw new MailParsingException(
- "Missing required attributes after email was parsed", e);
+ throw new MailParsingException("Missing required attributes after email was parsed", e);
}
}
/**
- * Parses a MailMessage from an array of characters. Note that the character
- * array is int-typed. This method is only used by POP3, which specifies that
- * all transferred characters are US-ASCII (RFC 6856). When reading the input
- * in Java, io.Reader yields ints. These can be safely converted to chars
- * as all US-ASCII characters fit in a char. If emails contain non-ASCII
- * characters, such as UTF runes, these will be encoded in ASCII using either
- * Base64 or quoted-printable encoding.
+ * Parses a MailMessage from an array of characters. Note that the character array is int-typed.
+ * This method is only used by POP3, which specifies that all transferred characters are US-ASCII
+ * (RFC 6856). When reading the input in Java, io.Reader yields ints. These can be safely
+ * converted to chars as all US-ASCII characters fit in a char. If emails contain non-ASCII
+ * characters, such as UTF runes, these will be encoded in ASCII using either Base64 or
+ * quoted-printable encoding.
+ *
* @param chars Array as received over the wire
* @return Parsed MailMessage
* @throws MailParsingException
@@ -136,20 +134,19 @@
}
/**
- * Traverses a mime tree and parses out text and html parts. All other parts
- * will be dropped.
+ * Traverses a mime tree and parses out text and html parts. All other parts will be dropped.
+ *
* @param part MimePart to parse
* @param textBuilder StringBuilder to append all plaintext parts
* @param htmlBuilder StringBuilder to append all html parts
* @throws IOException
*/
- private static void handleMimePart(Entity part, StringBuilder textBuilder,
- StringBuilder htmlBuilder) throws IOException {
- if (isPlainOrHtml(part.getMimeType()) &&
- !isAttachment(part.getDispositionType())) {
+ private static void handleMimePart(
+ Entity part, StringBuilder textBuilder, StringBuilder htmlBuilder) throws IOException {
+ if (isPlainOrHtml(part.getMimeType()) && !isAttachment(part.getDispositionType())) {
TextBody tb = (TextBody) part.getBody();
- String result = CharStreams.toString(new InputStreamReader(
- tb.getInputStream(), tb.getMimeCharset()));
+ String result =
+ CharStreams.toString(new InputStreamReader(tb.getInputStream(), tb.getMimeCharset()));
if (part.getMimeType().equals("text/plain")) {
textBuilder.append(result);
} else if (part.getMimeType().equals("text/html")) {
@@ -168,8 +165,7 @@
}
private static boolean isMixedOrAlternative(String mimeType) {
- return mimeType.equals("multipart/alternative") ||
- mimeType.equals("multipart/mixed");
+ return mimeType.equals("multipart/alternative") || mimeType.equals("multipart/mixed");
}
private static boolean isAttachment(String dispositionType) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/mail/receive/TextParser.java b/gerrit-server/src/main/java/com/google/gerrit/server/mail/receive/TextParser.java
index 8b28df5..a752e89 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/mail/receive/TextParser.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/mail/receive/TextParser.java
@@ -17,23 +17,20 @@
import com.google.common.collect.Iterators;
import com.google.common.collect.PeekingIterator;
import com.google.gerrit.reviewdb.client.Comment;
-
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
-/** TextParser provides parsing functionality for plaintext email. */
+/** TextParser provides parsing functionality for plaintext email. */
public class TextParser {
/**
* Parses comments from plaintext email.
*
* @param email MailMessage as received from the email service.
- * @param comments Comments previously persisted on the change that caused the
- * original notification email to be sent out. Ordering must
- * be the same as in the outbound email
- * @param changeUrl Canonical change url that points to the change on this
- * Gerrit instance.
- * Example: https://go-review.googlesource.com/#/c/91570
+ * @param comments Comments previously persisted on the change that caused the original
+ * notification email to be sent out. Ordering must be the same as in the outbound email
+ * @param changeUrl Canonical change url that points to the change on this Gerrit instance.
+ * Example: https://go-review.googlesource.com/#/c/91570
* @return List of MailComments parsed from the plaintext part of the email.
*/
public static List<MailComment> parse(
@@ -56,13 +53,11 @@
// > A comment typed in the email directly
String singleQuotePattern = "\n> ";
String doubleQuotePattern = "\n>> ";
- if (countOccurrences(body, doubleQuotePattern) >
- countOccurrences(body, singleQuotePattern)) {
+ if (countOccurrences(body, doubleQuotePattern) > countOccurrences(body, singleQuotePattern)) {
body = body.replace(doubleQuotePattern, singleQuotePattern);
}
- PeekingIterator<Comment> iter =
- Iterators.peekingIterator(comments.iterator());
+ PeekingIterator<Comment> iter = Iterators.peekingIterator(comments.iterator());
String[] lines = body.split("\n");
MailComment currentComment = null;
@@ -83,9 +78,8 @@
}
Comment perspectiveComment = iter.peek();
if (line.equals(ParserUtil.filePath(changeUrl, perspectiveComment))) {
- if (lastEncounteredFileName == null ||
- !lastEncounteredFileName
- .equals(perspectiveComment.key.filename)) {
+ if (lastEncounteredFileName == null
+ || !lastEncounteredFileName.equals(perspectiveComment.key.filename)) {
// This is the annotation of a file
lastEncounteredFileName = perspectiveComment.key.filename;
lastEncounteredComment = null;
@@ -94,8 +88,7 @@
lastEncounteredComment = perspectiveComment;
iter.next();
}
- } else if (ParserUtil.isCommentUrl(line, changeUrl,
- perspectiveComment)) {
+ } else if (ParserUtil.isCommentUrl(line, changeUrl, perspectiveComment)) {
lastEncounteredComment = perspectiveComment;
iter.next();
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/AbandonedSender.java b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/AbandonedSender.java
index 8ddfe5c..ca762c9 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/AbandonedSender.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/AbandonedSender.java
@@ -24,16 +24,14 @@
/** Send notice about a change being abandoned by its owner. */
public class AbandonedSender extends ReplyToChangeSender {
- public interface Factory extends
- ReplyToChangeSender.Factory<AbandonedSender> {
+ public interface Factory extends ReplyToChangeSender.Factory<AbandonedSender> {
@Override
AbandonedSender create(Project.NameKey project, Change.Id change);
}
@Inject
- public AbandonedSender(EmailArguments ea,
- @Assisted Project.NameKey project,
- @Assisted Change.Id id)
+ public AbandonedSender(
+ EmailArguments ea, @Assisted Project.NameKey project, @Assisted Change.Id id)
throws OrmException {
super(ea, "abandon", ChangeEmail.newChangeData(ea, project, id));
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/AddKeySender.java b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/AddKeySender.java
index 47068eb..0c09639 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/AddKeySender.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/AddKeySender.java
@@ -22,7 +22,6 @@
import com.google.gerrit.server.mail.Address;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
-
import java.util.List;
public class AddKeySender extends OutgoingEmail {
@@ -38,7 +37,8 @@
private final List<String> gpgKeys;
@AssistedInject
- public AddKeySender(EmailArguments ea,
+ public AddKeySender(
+ EmailArguments ea,
IdentifiedUser callingUser,
@Assisted IdentifiedUser user,
@Assisted AccountSshKey sshKey) {
@@ -50,7 +50,8 @@
}
@AssistedInject
- public AddKeySender(EmailArguments ea,
+ public AddKeySender(
+ EmailArguments ea,
IdentifiedUser callingUser,
@Assisted IdentifiedUser user,
@Assisted List<String> gpgKeys) {
@@ -64,8 +65,7 @@
@Override
protected void init() throws EmailException {
super.init();
- setHeader("Subject",
- String.format("[Gerrit Code Review] New %s Keys Added", getKeyType()));
+ setHeader("Subject", String.format("[Gerrit Code Review] New %s Keys Added", getKeyType()));
add(RecipientType.TO, new Address(getEmail()));
}
@@ -75,9 +75,8 @@
* Don't send an email if no keys are added, or an admin is adding a key to
* a user.
*/
- return (sshKey != null || gpgKeys.size() > 0) &&
- (user.equals(callingUser) ||
- !callingUser.getCapabilities().canAdministrateServer());
+ return (sshKey != null || gpgKeys.size() > 0)
+ && (user.equals(callingUser) || !callingUser.getCapabilities().canAdministrateServer());
}
@Override
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/AddReviewerSender.java b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/AddReviewerSender.java
index 67577de..cb70106 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/AddReviewerSender.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/AddReviewerSender.java
@@ -28,9 +28,8 @@
}
@Inject
- public AddReviewerSender(EmailArguments ea,
- @Assisted Project.NameKey project,
- @Assisted Change.Id id)
+ public AddReviewerSender(
+ EmailArguments ea, @Assisted Project.NameKey project, @Assisted Change.Id id)
throws OrmException {
super(ea, newChangeData(ea, project, id));
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/ChangeEmail.java b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/ChangeEmail.java
index e867caf..769cb09 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/ChangeEmail.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/ChangeEmail.java
@@ -39,15 +39,6 @@
import com.google.gerrit.server.project.ProjectState;
import com.google.gerrit.server.query.change.ChangeData;
import com.google.gwtorm.server.OrmException;
-
-import org.eclipse.jgit.diff.DiffFormatter;
-import org.eclipse.jgit.internal.JGitText;
-import org.eclipse.jgit.lib.Repository;
-import org.eclipse.jgit.util.RawParseUtils;
-import org.eclipse.jgit.util.TemporaryBuffer;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.io.IOException;
import java.sql.Timestamp;
import java.text.MessageFormat;
@@ -59,13 +50,20 @@
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
+import org.eclipse.jgit.diff.DiffFormatter;
+import org.eclipse.jgit.internal.JGitText;
+import org.eclipse.jgit.lib.Repository;
+import org.eclipse.jgit.util.RawParseUtils;
+import org.eclipse.jgit.util.TemporaryBuffer;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/** Sends an email to one or more interested parties. */
public abstract class ChangeEmail extends NotificationEmail {
private static final Logger log = LoggerFactory.getLogger(ChangeEmail.class);
- protected static ChangeData newChangeData(EmailArguments ea,
- Project.NameKey project, Change.Id id) {
+ protected static ChangeData newChangeData(
+ EmailArguments ea, Project.NameKey project, Change.Id id) {
return ea.changeDataFactory.create(ea.db.get(), project, id);
}
@@ -80,8 +78,7 @@
protected Set<Account.Id> authors;
protected boolean emailOnlyAuthors;
- protected ChangeEmail(EmailArguments ea, String mc, ChangeData cd)
- throws OrmException {
+ protected ChangeEmail(EmailArguments ea, String mc, ChangeData cd) throws OrmException {
super(ea, mc, cd.change().getDest());
changeData = cd;
change = cd.change();
@@ -93,7 +90,7 @@
super.setFrom(id);
/** Is the from user in an email squelching group? */
- final IdentifiedUser user = args.identifiedUserFactory.create(id);
+ final IdentifiedUser user = args.identifiedUserFactory.create(id);
emailOnlyAuthors = !user.getCapabilities().canEmailReviewers();
}
@@ -135,8 +132,7 @@
*
* @throws EmailException if an error occurred.
*/
- protected void formatFooter() throws EmailException {
- }
+ protected void formatFooter() throws EmailException {}
/** Setup the message headers and envelope (TO, CC, BCC). */
@Override
@@ -159,8 +155,8 @@
setHeader("X-Gerrit-PatchSet", patchSet.getPatchSetId() + "");
if (patchSetInfo == null) {
try {
- patchSetInfo = args.patchSetInfoFactory.get(
- args.db.get(), changeData.notes(), patchSet.getId());
+ patchSetInfo =
+ args.patchSetInfoFactory.get(args.db.get(), changeData.notes(), patchSet.getId());
} catch (PatchSetInfoNotAvailableException | OrmException err) {
patchSetInfo = null;
}
@@ -187,7 +183,8 @@
}
private void setCommitIdHeader() {
- if (patchSet != null && patchSet.getRevision() != null
+ if (patchSet != null
+ && patchSet.getRevision() != null
&& patchSet.getRevision().get() != null
&& patchSet.getRevision().get().length() > 0) {
setHeader("X-Gerrit-Commit", patchSet.getRevision().get());
@@ -210,8 +207,7 @@
}
public String getChangeMessageThreadId() throws EmailException {
- return velocify("<gerrit.${change.createdOn.time}.$change.key.get()" +
- "@$email.gerritHost>");
+ return velocify("<gerrit.${change.createdOn.time}.$change.key.get()" + "@$email.gerritHost>");
}
/** Format the sender's "cover letter", {@link #getCoverLetter()}. */
@@ -254,16 +250,22 @@
if (Patch.isMagic(p.getNewName())) {
continue;
}
- detail.append(p.getChangeType().getCode())
- .append(" ").append(p.getNewName()).append("\n");
+ detail
+ .append(p.getChangeType().getCode())
+ .append(" ")
+ .append(p.getNewName())
+ .append("\n");
}
- detail.append(MessageFormat.format("" //
- + "{0,choice,0#0 files|1#1 file|1<{0} files} changed, " //
- + "{1,choice,0#0 insertions|1#1 insertion|1<{1} insertions}(+), " //
- + "{2,choice,0#0 deletions|1#1 deletion|1<{2} deletions}(-)" //
- + "\n", patchList.getPatches().size() - 1, //
- patchList.getInsertions(), //
- patchList.getDeletions()));
+ detail.append(
+ MessageFormat.format(
+ "" //
+ + "{0,choice,0#0 files|1#1 file|1<{0} files} changed, " //
+ + "{1,choice,0#0 insertions|1#1 insertion|1<{1} insertions}(+), " //
+ + "{2,choice,0#0 deletions|1#1 deletion|1<{2} deletions}(-)" //
+ + "\n",
+ patchList.getPatches().size() - 1, //
+ patchList.getInsertions(), //
+ patchList.getDeletions()));
detail.append("\n");
}
return detail.toString();
@@ -291,7 +293,7 @@
final ProjectState r;
r = args.projectCache.get(change.getProject());
- return r != null ? r.getOwners() : Collections.<AccountGroup.UUID> emptySet();
+ return r != null ? r.getOwners() : Collections.<AccountGroup.UUID>emptySet();
}
/** TO or CC all vested parties (change owner, patch set uploader, author). */
@@ -313,8 +315,7 @@
//
ListMultimap<Account.Id, String> stars =
args.starredChangesUtil.byChangeFromIndex(change.getId());
- for (Map.Entry<Account.Id, Collection<String>> e :
- stars.asMap().entrySet()) {
+ for (Map.Entry<Account.Id, Collection<String>> e : stars.asMap().entrySet()) {
if (e.getValue().contains(StarredChangesUtil.DEFAULT_LABEL)) {
super.add(RecipientType.BCC, e.getKey());
}
@@ -339,15 +340,13 @@
return new Watchers();
}
- ProjectWatch watch = new ProjectWatch(
- args, branch.getParentKey(), projectState, changeData);
+ ProjectWatch watch = new ProjectWatch(args, branch.getParentKey(), projectState, changeData);
return watch.getWatchers(type);
}
/** Any user who has published comments on this change. */
protected void ccAllApprovals() {
- if (!NotifyHandling.ALL.equals(notify)
- && !NotifyHandling.OWNER_REVIEWERS.equals(notify)) {
+ if (!NotifyHandling.ALL.equals(notify) && !NotifyHandling.OWNER_REVIEWERS.equals(notify)) {
return;
}
@@ -362,14 +361,12 @@
/** Users who have non-zero approval codes on the change. */
protected void ccExistingReviewers() {
- if (!NotifyHandling.ALL.equals(notify)
- && !NotifyHandling.OWNER_REVIEWERS.equals(notify)) {
+ if (!NotifyHandling.ALL.equals(notify) && !NotifyHandling.OWNER_REVIEWERS.equals(notify)) {
return;
}
try {
- for (Account.Id id : changeData.reviewers()
- .byState(ReviewerStateInternal.REVIEWER)) {
+ for (Account.Id id : changeData.reviewers().byState(ReviewerStateInternal.REVIEWER)) {
add(RecipientType.CC, id);
}
} catch (OrmException err) {
@@ -379,7 +376,7 @@
@Override
protected void add(final RecipientType rt, final Account.Id to) {
- if (! emailOnlyAuthors || authors.contains(to)) {
+ if (!emailOnlyAuthors || authors.contains(to)) {
super.add(rt, to);
}
}
@@ -387,8 +384,10 @@
@Override
protected boolean isVisibleTo(final Account.Id to) throws OrmException {
return projectState == null
- || projectState.controlFor(args.identifiedUserFactory.create(to))
- .controlFor(args.db.get(), change).isVisible(args.db.get());
+ || projectState
+ .controlFor(args.identifiedUserFactory.create(to))
+ .controlFor(args.db.get(), change)
+ .isVisible(args.db.get());
}
/** Find all users who are authors of any part of this change. */
@@ -471,8 +470,7 @@
footers.add("Gerrit-MessageType: " + messageClass);
footers.add("Gerrit-Change-Id: " + change.getKey().get());
- footers.add("Gerrit-Change-Number: " +
- Integer.toString(change.getChangeId()));
+ footers.add("Gerrit-Change-Number: " + Integer.toString(change.getChangeId()));
footers.add("Gerrit-PatchSet: " + patchSet.getPatchSetId());
footers.add("Gerrit-Owner: " + getNameEmailFor(change.getOwner()));
for (String reviewer : getEmailsByState(ReviewerStateInternal.REVIEWER)) {
@@ -517,8 +515,7 @@
}
int maxSize = args.settings.maximumDiffSize;
- TemporaryBuffer.Heap buf =
- new TemporaryBuffer.Heap(Math.min(HEAP_EST_SIZE, maxSize), maxSize);
+ TemporaryBuffer.Heap buf = new TemporaryBuffer.Heap(Math.min(HEAP_EST_SIZE, maxSize), maxSize);
try (DiffFormatter fmt = new DiffFormatter(buf)) {
try (Repository git = args.server.openRepository(change.getProject())) {
try {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/CommentFormatter.java b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/CommentFormatter.java
index 722fe1f..74d1480 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/CommentFormatter.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/CommentFormatter.java
@@ -17,7 +17,6 @@
import static com.google.common.base.Strings.isNullOrEmpty;
import com.google.gerrit.common.Nullable;
-
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@@ -38,12 +37,11 @@
}
/**
- * Take a string of comment text that was written using the wiki-Like format
- * and emit a list of blocks that can be rendered to block-level HTML. This
- * method does not escape HTML.
+ * Take a string of comment text that was written using the wiki-Like format and emit a list of
+ * blocks that can be rendered to block-level HTML. This method does not escape HTML.
*
- * Adapted from the {@code wikify} method found in:
- * com.google.gwtexpui.safehtml.client.SafeHtml
+ * <p>Adapted from the {@code wikify} method found in:
+ * com.google.gwtexpui.safehtml.client.SafeHtml
*
* @param source The raw, unescaped comment in the Gerrit wiki-like format.
* @return List of block objects, each with unescaped comment content.
@@ -69,30 +67,25 @@
}
/**
- * Take a block of comment text that contains a list and potentially
- * paragraphs (but does not contain blank lines), generate appropriate block
- * elements and append them to the output list.
+ * Take a block of comment text that contains a list and potentially paragraphs (but does not
+ * contain blank lines), generate appropriate block elements and append them to the output list.
*
- * In simple cases, this will generate a single list block. For example, on
- * the following input.
+ * <p>In simple cases, this will generate a single list block. For example, on the following
+ * input.
*
- * * Item one.
- * * Item two.
- * * item three.
+ * <p>* Item one. * Item two. * item three.
*
- * However, if the list is adjacent to a paragraph, it will need to also
- * generate that paragraph. Consider the following input.
+ * <p>However, if the list is adjacent to a paragraph, it will need to also generate that
+ * paragraph. Consider the following input.
*
- * A bit of text describing the context of the list:
- * * List item one.
- * * List item two.
- * * Et cetera.
+ * <p>A bit of text describing the context of the list: * List item one. * List item two. * Et
+ * cetera.
*
- * In this case, {@code makeList} generates a paragraph block object
- * containing the non-bullet-prefixed text, followed by a list block.
+ * <p>In this case, {@code makeList} generates a paragraph block object containing the
+ * non-bullet-prefixed text, followed by a list block.
*
- * Adapted from the {@code wikifyList} method found in:
- * com.google.gwtexpui.safehtml.client.SafeHtml
+ * <p>Adapted from the {@code wikifyList} method found in:
+ * com.google.gwtexpui.safehtml.client.SafeHtml
*
* @param p The block containing the list (as well as potential paragraphs).
* @param out The list of blocks to append to.
@@ -179,12 +172,10 @@
}
private static boolean isPreFormat(String p) {
- return p.startsWith(" ") || p.startsWith("\t")
- || p.contains("\n ") || p.contains("\n\t");
+ return p.startsWith(" ") || p.startsWith("\t") || p.contains("\n ") || p.contains("\n\t");
}
private static boolean isList(String p) {
- return p.startsWith("- ") || p.startsWith("* ")
- || p.contains("\n- ") || p.contains("\n* ");
+ return p.startsWith("- ") || p.startsWith("* ") || p.contains("\n- ") || p.contains("\n* ");
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/CommentSender.java b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/CommentSender.java
index acb98cf..1ebda4b 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/CommentSender.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/CommentSender.java
@@ -36,11 +36,6 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
-
-import org.eclipse.jgit.lib.Repository;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.io.IOException;
import java.time.ZoneId;
import java.time.ZonedDateTime;
@@ -54,12 +49,13 @@
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
+import org.eclipse.jgit.lib.Repository;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
-/** Send comments, after the author of them hit used Publish Comments in the UI.
- */
+/** Send comments, after the author of them hit used Publish Comments in the UI. */
public class CommentSender extends ReplyToChangeSender {
- private static final Logger log = LoggerFactory
- .getLogger(CommentSender.class);
+ private static final Logger log = LoggerFactory.getLogger(CommentSender.class);
public interface Factory {
CommentSender create(Project.NameKey project, Change.Id id);
@@ -71,9 +67,7 @@
public PatchFile fileData;
public List<Comment> comments = new ArrayList<>();
- /**
- * @return a web link to the given patch set and file.
- */
+ /** @return a web link to the given patch set and file. */
public String getLink() {
String url = getGerritUrl();
if (url == null) {
@@ -81,16 +75,18 @@
}
return new StringBuilder()
- .append(url)
- .append("#/c/").append(change.getId())
- .append('/').append(patchSetId)
- .append('/').append(KeyUtil.encode(filename))
- .toString();
+ .append(url)
+ .append("#/c/")
+ .append(change.getId())
+ .append('/')
+ .append(patchSetId)
+ .append('/')
+ .append(KeyUtil.encode(filename))
+ .toString();
}
/**
- * @return A title for the group, i.e. "Commit Message", "Merge List", or
- * "File [[filename]]".
+ * @return A title for the group, i.e. "Commit Message", "Merge List", or "File [[filename]]".
*/
public String getTitle() {
if (Patch.COMMIT_MSG.equals(filename)) {
@@ -109,10 +105,12 @@
private final CommentsUtil commentsUtil;
@Inject
- public CommentSender(EmailArguments ea,
+ public CommentSender(
+ EmailArguments ea,
CommentsUtil commentsUtil,
@Assisted Project.NameKey project,
- @Assisted Change.Id id) throws OrmException {
+ @Assisted Change.Id id)
+ throws OrmException {
super(ea, "comment", newChangeData(ea, project, id));
this.commentsUtil = commentsUtil;
}
@@ -129,11 +127,11 @@
changeData.setCurrentFilePaths(Ordering.natural().sortedCopy(paths));
}
- public void setPatchSetComment(String comment) {
+ public void setPatchSetComment(String comment) {
this.patchSetComment = comment;
}
- public void setLabels(List<LabelVote> labels) {
+ public void setLabels(List<LabelVote> labels) {
this.labels = labels;
}
@@ -170,28 +168,19 @@
}
}
- /**
- * No longer used outside Velocity. Remove this method when VTL support is
- * removed.
- */
+ /** No longer used outside Velocity. Remove this method when VTL support is removed. */
@Deprecated
public boolean hasInlineComments() {
return !inlineComments.isEmpty();
}
- /**
- * No longer used outside Velocity. Remove this method when VTL support is
- * removed.
- */
+ /** No longer used outside Velocity. Remove this method when VTL support is removed. */
@Deprecated
public String getInlineComments() {
return getInlineComments(1);
}
- /**
- * No longer used outside Velocity. Remove this method when VTL support is
- * removed.
- */
+ /** No longer used outside Velocity. Remove this method when VTL support is removed. */
@Deprecated
public String getInlineComments(int lines) {
try (Repository repo = getRepository()) {
@@ -212,11 +201,10 @@
}
/**
- * @return a list of FileCommentGroup objects representing the inline comments
- * grouped by the file.
+ * @return a list of FileCommentGroup objects representing the inline comments grouped by the
+ * file.
*/
- private List<CommentSender.FileCommentGroup> getGroupedInlineComments(
- Repository repo) {
+ private List<CommentSender.FileCommentGroup> getGroupedInlineComments(Repository repo) {
List<CommentSender.FileCommentGroup> groups = new ArrayList<>();
// Get the patch list:
PatchList patchList = null;
@@ -242,14 +230,15 @@
groups.add(currentGroup);
if (patchList != null) {
try {
- currentGroup.fileData =
- new PatchFile(repo, patchList, c.key.filename);
+ currentGroup.fileData = new PatchFile(repo, patchList, c.key.filename);
} catch (IOException e) {
- log.warn(String.format(
- "Cannot load %s from %s in %s",
- c.key.filename,
- patchList.getNewId().name(),
- projectState.getProject().getName()), e);
+ log.warn(
+ String.format(
+ "Cannot load %s from %s in %s",
+ c.key.filename,
+ patchList.getNewId().name(),
+ projectState.getProject().getName()),
+ e);
currentGroup.fileData = null;
}
}
@@ -260,25 +249,21 @@
}
}
- Collections.sort(groups,
- Comparator.comparing(g -> g.filename, FilenameComparator.INSTANCE));
+ Collections.sort(groups, Comparator.comparing(g -> g.filename, FilenameComparator.INSTANCE));
return groups;
}
- /**
- * No longer used except for Velocity. Remove this method when VTL support is
- * removed.
- */
+ /** No longer used except for Velocity. Remove this method when VTL support is removed. */
@Deprecated
- private void appendComment(StringBuilder out, int contextLines,
- PatchFile currentFileData, Comment comment) {
+ private void appendComment(
+ StringBuilder out, int contextLines, PatchFile currentFileData, Comment comment) {
if (comment instanceof RobotComment) {
RobotComment robotComment = (RobotComment) comment;
out.append("Robot Comment from ")
- .append(robotComment.robotId)
- .append(" (run ID ")
- .append(robotComment.robotRunId)
- .append("):\n");
+ .append(robotComment.robotId)
+ .append(" (run ID ")
+ .append(robotComment.robotRunId)
+ .append("):\n");
}
if (comment.range != null) {
appendRangedComment(out, currentFileData, comment);
@@ -287,20 +272,14 @@
}
}
- /**
- * No longer used except for Velocity. Remove this method when VTL support is
- * removed.
- */
+ /** No longer used except for Velocity. Remove this method when VTL support is removed. */
@Deprecated
- private void appendRangedComment(StringBuilder out, PatchFile fileData,
- Comment comment) {
+ private void appendRangedComment(StringBuilder out, PatchFile fileData, Comment comment) {
String prefix = getCommentLinePrefix(comment);
String emptyPrefix = Strings.padStart(": ", prefix.length(), ' ');
boolean firstLine = true;
for (String line : getLinesByRange(comment.range, fileData, comment.side)) {
- out.append(firstLine ? prefix : emptyPrefix)
- .append(line)
- .append('\n');
+ out.append(firstLine ? prefix : emptyPrefix).append(line).append('\n');
firstLine = false;
}
appendQuotedParent(out, comment);
@@ -308,8 +287,7 @@
}
private String getCommentLinePrefix(Comment comment) {
- int lineNbr = comment.range == null ?
- comment.lineNbr : comment.range.startLine;
+ int lineNbr = comment.range == null ? comment.lineNbr : comment.range.startLine;
StringBuilder sb = new StringBuilder();
sb.append("PS").append(comment.key.patchSetId);
if (lineNbr != 0) {
@@ -320,19 +298,15 @@
}
/**
- * @return the lines of file content in fileData that are encompassed by range
- * on the given side.
+ * @return the lines of file content in fileData that are encompassed by range on the given side.
*/
- private List<String> getLinesByRange(Comment.Range range,
- PatchFile fileData, short side) {
+ private List<String> getLinesByRange(Comment.Range range, PatchFile fileData, short side) {
List<String> lines = new ArrayList<>();
for (int n = range.startLine; n <= range.endLine; n++) {
String s = getLine(fileData, side, n);
if (n == range.startLine && n == range.endLine) {
- s = s.substring(
- Math.min(range.startChar, s.length()),
- Math.min(range.endChar, s.length()));
+ s = s.substring(Math.min(range.startChar, s.length()), Math.min(range.endChar, s.length()));
} else if (n == range.startLine) {
s = s.substring(Math.min(range.startChar, s.length()));
} else if (n == range.endLine) {
@@ -343,13 +317,10 @@
return lines;
}
- /**
- * No longer used except for Velocity. Remove this method when VTL support is
- * removed.
- */
+ /** No longer used except for Velocity. Remove this method when VTL support is removed. */
@Deprecated
- private void appendLineComment(StringBuilder out, int contextLines,
- PatchFile currentFileData, Comment comment) {
+ private void appendLineComment(
+ StringBuilder out, int contextLines, PatchFile currentFileData, Comment comment) {
short side = comment.side;
int lineNbr = comment.lineNbr;
@@ -360,12 +331,10 @@
maxLines = currentFileData.getLineCount(side);
} catch (IOException err) {
// The file could not be read, leave the max as is.
- log.warn(String.format("Failed to read file %s on side %d",
- comment.key.filename, side), err);
+ log.warn(String.format("Failed to read file %s on side %d", comment.key.filename, side), err);
} catch (NoSuchEntityException err) {
// The file could not be read, leave the max as is.
- log.warn(String.format("Side %d of file %s didn't exist",
- side, comment.key.filename), err);
+ log.warn(String.format("Side %d of file %s didn't exist", side, comment.key.filename), err);
}
int startLine = Math.max(1, lineNbr - contextLines + 1);
@@ -382,65 +351,51 @@
}
}
- /**
- * No longer used except for Velocity. Remove this method when VTL support is
- * removed.
- */
+ /** No longer used except for Velocity. Remove this method when VTL support is removed. */
@Deprecated
- private void appendFileLine(StringBuilder cmts, PatchFile fileData,
- short side, int line) {
+ private void appendFileLine(StringBuilder cmts, PatchFile fileData, short side, int line) {
String lineStr = getLine(fileData, side, line);
- cmts.append("Line ")
- .append(line)
- .append(": ")
- .append(lineStr)
- .append("\n");
+ cmts.append("Line ").append(line).append(": ").append(lineStr).append("\n");
}
- /**
- * No longer used except for Velocity. Remove this method when VTL support is
- * removed.
- */
+ /** No longer used except for Velocity. Remove this method when VTL support is removed. */
@Deprecated
private void appendQuotedParent(StringBuilder out, Comment child) {
Optional<Comment> parent = getParent(child);
if (parent.isPresent()) {
- out.append("> ")
- .append(getShortenedCommentMessage(parent.get()))
- .append('\n');
+ out.append("> ").append(getShortenedCommentMessage(parent.get())).append('\n');
}
}
/**
* Get the parent comment of a given comment.
+ *
* @param child the comment with a potential parent comment.
- * @return an optional comment that will be present if the given comment has
- * a parent, and is empty if it does not.
+ * @return an optional comment that will be present if the given comment has a parent, and is
+ * empty if it does not.
*/
private Optional<Comment> getParent(Comment child) {
if (child.parentUuid == null) {
return Optional.empty();
}
- Comment.Key key = new Comment.Key(child.parentUuid, child.key.filename,
- child.key.patchSetId);
+ Comment.Key key = new Comment.Key(child.parentUuid, child.key.filename, child.key.patchSetId);
try {
return commentsUtil.get(args.db.get(), changeData.notes(), key);
} catch (OrmException e) {
- log.warn("Could not find the parent of this comment: "
- + child.toString());
+ log.warn("Could not find the parent of this comment: " + child.toString());
return Optional.empty();
}
}
/**
* Retrieve the file lines referred to by a comment.
- * @param comment The comment that refers to some file contents. The comment
- * may be a line comment or a ranged comment.
+ *
+ * @param comment The comment that refers to some file contents. The comment may be a line comment
+ * or a ranged comment.
* @param fileData The file on which the comment appears.
- * @return file contents referred to by the comment. If the comment is a line
- * comment, the result will be a list of one string. Otherwise it will be
- * a list of one or more strings.
+ * @return file contents referred to by the comment. If the comment is a line comment, the result
+ * will be a list of one string. Otherwise it will be a list of one or more strings.
*/
private List<String> getLinesOfComment(Comment comment, PatchFile fileData) {
List<String> lines = new ArrayList<>();
@@ -457,8 +412,8 @@
}
/**
- * @return a shortened version of the given comment's message. Will be
- * shortened to 75 characters or the first line, whichever is shorter.
+ * @return a shortened version of the given comment's message. Will be shortened to 75 characters
+ * or the first line, whichever is shorter.
*/
private String getShortenedCommentMessage(Comment comment) {
String msg = comment.message.trim();
@@ -473,15 +428,13 @@
}
/**
- * @return grouped inline comment data mapped to data structures that are
- * suitable for passing into Soy.
+ * @return grouped inline comment data mapped to data structures that are suitable for passing
+ * into Soy.
*/
- private List<Map<String, Object>> getCommentGroupsTemplateData(
- Repository repo) {
+ private List<Map<String, Object>> getCommentGroupsTemplateData(Repository repo) {
List<Map<String, Object>> commentGroups = new ArrayList<>();
- for (
- CommentSender.FileCommentGroup group : getGroupedInlineComments(repo)) {
+ for (CommentSender.FileCommentGroup group : getGroupedInlineComments(repo)) {
Map<String, Object> groupData = new HashMap<>();
groupData.put("link", group.getLink());
groupData.put("title", group.getTitle());
@@ -492,15 +445,13 @@
Map<String, Object> commentData = new HashMap<>();
commentData.put("lines", getLinesOfComment(comment, group.fileData));
commentData.put("message", comment.message.trim());
- List<CommentFormatter.Block> blocks =
- CommentFormatter.parse(comment.message);
+ List<CommentFormatter.Block> blocks = CommentFormatter.parse(comment.message);
commentData.put("messageBlocks", commentBlocksToSoyData(blocks));
// Set the prefix.
String prefix = getCommentLinePrefix(comment);
commentData.put("linePrefix", prefix);
- commentData.put("linePrefixEmpty",
- Strings.padStart(": ", prefix.length(), ' '));
+ commentData.put("linePrefixEmpty", Strings.padStart(": ", prefix.length(), ' '));
// Set line numbers.
int startLine;
@@ -537,8 +488,7 @@
// Set parent comment info.
Optional<Comment> parent = getParent(comment);
if (parent.isPresent()) {
- commentData.put("parentMessage",
- getShortenedCommentMessage(parent.get()));
+ commentData.put("parentMessage", getShortenedCommentMessage(parent.get()));
}
}
@@ -551,31 +501,32 @@
return commentGroups;
}
- private List<Map<String, Object>> commentBlocksToSoyData(
- List<CommentFormatter.Block> blocks) {
- return blocks.stream()
- .map(b -> {
- Map<String, Object> map = new HashMap<>();
- switch (b.type) {
- case PARAGRAPH:
- map.put("type", "paragraph");
- map.put("text", b.text);
- break;
- case PRE_FORMATTED:
- map.put("type", "pre");
- map.put("text", b.text);
- break;
- case QUOTE:
- map.put("type", "quote");
- map.put("quotedBlocks", commentBlocksToSoyData(b.quotedBlocks));
- break;
- case LIST:
- map.put("type", "list");
- map.put("items", b.items);
- break;
- }
- return map;
- })
+ private List<Map<String, Object>> commentBlocksToSoyData(List<CommentFormatter.Block> blocks) {
+ return blocks
+ .stream()
+ .map(
+ b -> {
+ Map<String, Object> map = new HashMap<>();
+ switch (b.type) {
+ case PARAGRAPH:
+ map.put("type", "paragraph");
+ map.put("text", b.text);
+ break;
+ case PRE_FORMATTED:
+ map.put("type", "pre");
+ map.put("text", b.text);
+ break;
+ case QUOTE:
+ map.put("type", "quote");
+ map.put("quotedBlocks", commentBlocksToSoyData(b.quotedBlocks));
+ break;
+ case LIST:
+ map.put("type", "list");
+ map.put("items", b.items);
+ break;
+ }
+ return map;
+ })
.collect(Collectors.toList());
}
@@ -606,13 +557,13 @@
hasComments = !files.isEmpty();
}
- soyContext.put("patchSetCommentBlocks",
- commentBlocksToSoyData(CommentFormatter.parse(patchSetComment)));
+ soyContext.put(
+ "patchSetCommentBlocks", commentBlocksToSoyData(CommentFormatter.parse(patchSetComment)));
soyContext.put("labels", getLabelVoteSoyData(labels));
soyContext.put("commentCount", inlineComments.size());
soyContext.put("commentTimestamp", getCommentTimestamp());
- soyContext.put("coverLetterBlocks",
- commentBlocksToSoyData(CommentFormatter.parse(getCoverLetter())));
+ soyContext.put(
+ "coverLetterBlocks", commentBlocksToSoyData(CommentFormatter.parse(getCoverLetter())));
footers.add("Gerrit-Comment-Date: " + getCommentTimestamp());
footers.add("Gerrit-HasComments: " + (hasComments ? "Yes" : "No"));
@@ -628,8 +579,7 @@
} catch (IndexOutOfBoundsException err) {
// Default to the empty string if the given line number does not appear
// in the file.
- log.debug(String.format("Failed to get line number of file on side %d",
- side), err);
+ log.debug(String.format("Failed to get line number of file on side %d", side), err);
return "";
} catch (NoSuchEntityException err) {
// Default to the empty string if the side cannot be found.
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/CreateChangeSender.java b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/CreateChangeSender.java
index 51f8cef..332320e 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/CreateChangeSender.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/CreateChangeSender.java
@@ -25,23 +25,20 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** Notify interested parties of a brand new change. */
public class CreateChangeSender extends NewChangeSender {
- private static final Logger log =
- LoggerFactory.getLogger(CreateChangeSender.class);
+ private static final Logger log = LoggerFactory.getLogger(CreateChangeSender.class);
public interface Factory {
CreateChangeSender create(Project.NameKey project, Change.Id id);
}
@Inject
- public CreateChangeSender(EmailArguments ea,
- @Assisted Project.NameKey project,
- @Assisted Change.Id id)
+ public CreateChangeSender(
+ EmailArguments ea, @Assisted Project.NameKey project, @Assisted Change.Id id)
throws OrmException {
super(ea, newChangeData(ea, project, id));
}
@@ -54,10 +51,8 @@
try {
// Try to mark interested owners with TO and CC or BCC line.
Watchers matching = getWatchers(NotifyType.NEW_CHANGES);
- for (Account.Id user : Iterables.concat(
- matching.to.accounts,
- matching.cc.accounts,
- matching.bcc.accounts)) {
+ for (Account.Id user :
+ Iterables.concat(matching.to.accounts, matching.cc.accounts, matching.bcc.accounts)) {
if (isOwnerOfProjectOrBranch(user)) {
add(RecipientType.TO, user);
}
@@ -80,8 +75,9 @@
private boolean isOwnerOfProjectOrBranch(Account.Id user) {
return projectState != null
- && projectState.controlFor(args.identifiedUserFactory.create(user))
- .controlForRef(change.getDest())
- .isOwner();
+ && projectState
+ .controlFor(args.identifiedUserFactory.create(user))
+ .controlForRef(change.getDest())
+ .isOwner();
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/DeleteReviewerSender.java b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/DeleteReviewerSender.java
index dafa786..f46eab6 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/DeleteReviewerSender.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/DeleteReviewerSender.java
@@ -23,28 +23,24 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
-
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
-/** Let users know that a reviewer and possibly her review have
- * been removed. */
+/** Let users know that a reviewer and possibly her review have been removed. */
public class DeleteReviewerSender extends ReplyToChangeSender {
private final Set<Account.Id> reviewers = new HashSet<>();
- public interface Factory extends
- ReplyToChangeSender.Factory<DeleteReviewerSender> {
+ public interface Factory extends ReplyToChangeSender.Factory<DeleteReviewerSender> {
@Override
DeleteReviewerSender create(Project.NameKey project, Change.Id change);
}
@Inject
- public DeleteReviewerSender(EmailArguments ea,
- @Assisted Project.NameKey project,
- @Assisted Change.Id id)
+ public DeleteReviewerSender(
+ EmailArguments ea, @Assisted Project.NameKey project, @Assisted Change.Id id)
throws OrmException {
super(ea, "deleteReviewer", newChangeData(ea, project, id));
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/DeleteVoteSender.java b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/DeleteVoteSender.java
index a9e8cc4..13ee4ac 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/DeleteVoteSender.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/DeleteVoteSender.java
@@ -24,16 +24,14 @@
/** Send notice about a vote that was removed from a change. */
public class DeleteVoteSender extends ReplyToChangeSender {
- public interface Factory extends
- ReplyToChangeSender.Factory<DeleteVoteSender> {
+ public interface Factory extends ReplyToChangeSender.Factory<DeleteVoteSender> {
@Override
DeleteVoteSender create(Project.NameKey project, Change.Id change);
}
@Inject
- protected DeleteVoteSender(EmailArguments ea,
- @Assisted Project.NameKey project,
- @Assisted Change.Id id)
+ protected DeleteVoteSender(
+ EmailArguments ea, @Assisted Project.NameKey project, @Assisted Change.Id id)
throws OrmException {
super(ea, "deleteVote", newChangeData(ea, project, id));
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/EmailArguments.java b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/EmailArguments.java
index c870474..9306c7a 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/EmailArguments.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/EmailArguments.java
@@ -45,12 +45,10 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.template.soy.tofu.SoyTofu;
-
+import java.util.List;
import org.apache.velocity.runtime.RuntimeInstance;
import org.eclipse.jgit.lib.PersonIdent;
-import java.util.List;
-
public class EmailArguments {
final GitRepositoryManager server;
final ProjectCache projectCache;
@@ -84,13 +82,17 @@
final Provider<InternalAccountQuery> accountQueryProvider;
@Inject
- EmailArguments(GitRepositoryManager server, ProjectCache projectCache,
- GroupBackend groupBackend, GroupIncludeCache groupIncludes,
+ EmailArguments(
+ GitRepositoryManager server,
+ ProjectCache projectCache,
+ GroupBackend groupBackend,
+ GroupIncludeCache groupIncludes,
AccountCache accountCache,
PatchListCache patchListCache,
ApprovalsUtil approvalsUtil,
FromAddressGenerator fromAddressGenerator,
- EmailSender emailSender, PatchSetInfoFactory patchSetInfoFactory,
+ EmailSender emailSender,
+ PatchSetInfoFactory patchSetInfoFactory,
GenericFactory identifiedUserFactory,
CapabilityControl.Factory capabilityControlFactory,
ChangeNotes.Factory changeNotesFactory,
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/EmailHeader.java b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/EmailHeader.java
index 43d365c..e2b5894 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/EmailHeader.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/EmailHeader.java
@@ -18,7 +18,6 @@
import com.google.common.base.MoreObjects;
import com.google.gerrit.server.mail.Address;
-
import java.io.IOException;
import java.io.Writer;
import java.text.SimpleDateFormat;
@@ -66,8 +65,7 @@
@Override
public boolean equals(Object o) {
- return (o instanceof String)
- && Objects.equals(value, ((String) o).value);
+ return (o instanceof String) && Objects.equals(value, ((String) o).value);
}
@Override
@@ -96,9 +94,7 @@
case '_':
return false;
default:
- if (('a' <= cp && cp <= 'z')
- || ('A' <= cp && cp <= 'Z')
- || ('0' <= cp && cp <= '9')) {
+ if (('a' <= cp && cp <= 'z') || ('A' <= cp && cp <= 'Z') || ('0' <= cp && cp <= '9')) {
return false;
}
return true;
@@ -116,7 +112,7 @@
} else if (needsQuotedPrintableWithinPhrase(cp)) {
byte[] buf = new java.lang.String(Character.toChars(cp)).getBytes(UTF_8);
- for (byte b: buf) {
+ for (byte b : buf) {
r.append('=');
r.append(Integer.toHexString((b >>> 4) & 0x0f).toUpperCase());
r.append(Integer.toHexString(b & 0x0f).toUpperCase());
@@ -162,8 +158,7 @@
@Override
public boolean equals(Object o) {
- return (o instanceof Date)
- && Objects.equals(value, ((Date) o).value);
+ return (o instanceof Date) && Objects.equals(value, ((Date) o).value);
}
@Override
@@ -175,8 +170,7 @@
public static class AddressList extends EmailHeader {
private final List<Address> list = new ArrayList<>();
- public AddressList() {
- }
+ public AddressList() {}
public AddressList(Address addr) {
add(addr);
@@ -191,7 +185,7 @@
}
void remove(java.lang.String email) {
- for (Iterator<Address> i = list.iterator(); i.hasNext();) {
+ for (Iterator<Address> i = list.iterator(); i.hasNext(); ) {
if (i.next().getEmail().equals(email)) {
i.remove();
}
@@ -234,8 +228,7 @@
@Override
public boolean equals(Object o) {
- return (o instanceof AddressList)
- && Objects.equals(list, ((AddressList) o).list);
+ return (o instanceof AddressList) && Objects.equals(list, ((AddressList) o).list);
}
@Override
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/EmailSender.java b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/EmailSender.java
index 0bfb6f2..23fa1fe 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/EmailSender.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/EmailSender.java
@@ -17,7 +17,6 @@
import com.google.gerrit.common.Nullable;
import com.google.gerrit.common.errors.EmailException;
import com.google.gerrit.server.mail.Address;
-
import java.util.Collection;
import java.util.Map;
@@ -34,44 +33,44 @@
boolean canEmail(String address);
/**
- * Sends an email message. Messages always contain a text body, but messages
- * can optionally include an additional HTML body. If both body types are
- * present, {@code send} should construct a {@code multipart/alternative}
- * message with an appropriately-selected boundary.
+ * Sends an email message. Messages always contain a text body, but messages can optionally
+ * include an additional HTML body. If both body types are present, {@code send} should construct
+ * a {@code multipart/alternative} message with an appropriately-selected boundary.
*
* @param from who the message is from.
- * @param rcpt one or more address where the message will be delivered to.
- * This list overrides any To or CC headers in {@code headers}.
+ * @param rcpt one or more address where the message will be delivered to. This list overrides any
+ * To or CC headers in {@code headers}.
* @param headers message headers.
- * @param textBody text to appear in the {@code text/plain} body of the
- * message.
- * @param htmlBody optional HTML code to appear in the {@code text/html} body
- * of the message.
+ * @param textBody text to appear in the {@code text/plain} body of the message.
+ * @param htmlBody optional HTML code to appear in the {@code text/html} body of the message.
* @throws EmailException the message cannot be sent.
*/
- default void send(Address from, Collection<Address> rcpt,
- Map<String, EmailHeader> headers, String textBody,
- @Nullable String htmlBody) throws EmailException {
+ default void send(
+ Address from,
+ Collection<Address> rcpt,
+ Map<String, EmailHeader> headers,
+ String textBody,
+ @Nullable String htmlBody)
+ throws EmailException {
send(from, rcpt, headers, textBody);
}
/**
* Sends an email message with a text body only (i.e. not HTML or multipart).
*
- * Authors of new implementations of this interface should not use this method
- * to send a message because this method does not accept the HTML body.
- * Instead, authors should use the above signature of {@code send}.
+ * <p>Authors of new implementations of this interface should not use this method to send a
+ * message because this method does not accept the HTML body. Instead, authors should use the
+ * above signature of {@code send}.
*
- * This version of the method is preserved for support of legacy
- * implementations.
+ * <p>This version of the method is preserved for support of legacy implementations.
*
* @param from who the message is from.
- * @param rcpt one or more address where the message will be delivered to.
- * This list overrides any To or CC headers in {@code headers}.
+ * @param rcpt one or more address where the message will be delivered to. This list overrides any
+ * To or CC headers in {@code headers}.
* @param headers message headers.
* @param body text to appear in the body of the message.
* @throws EmailException the message cannot be sent.
*/
- void send(Address from, Collection<Address> rcpt,
- Map<String, EmailHeader> headers, String body) throws EmailException;
+ void send(Address from, Collection<Address> rcpt, Map<String, EmailHeader> headers, String body)
+ throws EmailException;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/FromAddressGeneratorProvider.java b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/FromAddressGeneratorProvider.java
index 3326b38..db52626 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/FromAddressGeneratorProvider.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/FromAddressGeneratorProvider.java
@@ -27,23 +27,21 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.regex.Pattern;
import org.apache.commons.codec.binary.Base64;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.lib.PersonIdent;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
-import java.util.regex.Pattern;
-
/** Creates a {@link FromAddressGenerator} from the {@link GerritServerConfig} */
@Singleton
-public class FromAddressGeneratorProvider implements
- Provider<FromAddressGenerator> {
+public class FromAddressGeneratorProvider implements Provider<FromAddressGenerator> {
private final FromAddressGenerator generator;
@Inject
- FromAddressGeneratorProvider(@GerritServerConfig final Config cfg,
+ FromAddressGeneratorProvider(
+ @GerritServerConfig final Config cfg,
@AnonymousCowardName final String anonymousCowardName,
@GerritPersonIdent final PersonIdent myIdent,
final AccountCache accountCache) {
@@ -54,15 +52,13 @@
if (from == null || "MIXED".equalsIgnoreCase(from)) {
ParameterizedString name = new ParameterizedString("${user} (Code Review)");
generator =
- new PatternGen(srvAddr, accountCache, anonymousCowardName, name,
- srvAddr.getEmail());
+ new PatternGen(srvAddr, accountCache, anonymousCowardName, name, srvAddr.getEmail());
} else if ("USER".equalsIgnoreCase(from)) {
String[] domains = cfg.getStringList("sendemail", null, "allowedDomain");
Pattern domainPattern = MailUtil.glob(domains);
- ParameterizedString namePattern =
- new ParameterizedString("${user} (Code Review)");
- generator = new UserGen(accountCache, domainPattern, anonymousCowardName,
- namePattern, srvAddr);
+ ParameterizedString namePattern = new ParameterizedString("${user} (Code Review)");
+ generator =
+ new UserGen(accountCache, domainPattern, anonymousCowardName, namePattern, srvAddr);
} else if ("SERVER".equalsIgnoreCase(from)) {
generator = new ServerGen(srvAddr);
} else {
@@ -72,9 +68,7 @@
if (name == null || name.getParameterNames().isEmpty()) {
generator = new ServerGen(a);
} else {
- generator =
- new PatternGen(srvAddr, accountCache, anonymousCowardName, name,
- a.getEmail());
+ generator = new PatternGen(srvAddr, accountCache, anonymousCowardName, name, a.getEmail());
}
}
}
@@ -99,16 +93,18 @@
* From address generator for USER mode
*
* @param accountCache get user account from id
- * @param domainPattern allowed user domain pattern that Gerrit can send as
- * the user
+ * @param domainPattern allowed user domain pattern that Gerrit can send as the user
* @param anonymousCowardName name used when user's full name is missing
- * @param nameRewriteTmpl name template used for rewriting the sender's name
- * when Gerrit can not send as the user
- * @param serverAddress serverAddress.name is used when fromId is null and
- * serverAddress.email is used when Gerrit can not send as the user
+ * @param nameRewriteTmpl name template used for rewriting the sender's name when Gerrit can not
+ * send as the user
+ * @param serverAddress serverAddress.name is used when fromId is null and serverAddress.email
+ * is used when Gerrit can not send as the user
*/
- UserGen(AccountCache accountCache, Pattern domainPattern,
- String anonymousCowardName, ParameterizedString nameRewriteTmpl,
+ UserGen(
+ AccountCache accountCache,
+ Pattern domainPattern,
+ String anonymousCowardName,
+ ParameterizedString nameRewriteTmpl,
Address serverAddress) {
this.accountCache = accountCache;
this.domainPattern = domainPattern;
@@ -142,13 +138,11 @@
}
String senderEmail;
- ParameterizedString senderEmailPattern =
- new ParameterizedString(serverAddress.getEmail());
+ ParameterizedString senderEmailPattern = new ParameterizedString(serverAddress.getEmail());
if (senderEmailPattern.getParameterNames().isEmpty()) {
senderEmail = senderEmailPattern.getRawPattern();
} else {
- senderEmail = senderEmailPattern.replace("userHash", hashOf(senderName))
- .toString();
+ senderEmail = senderEmailPattern.replace("userHash", hashOf(senderName)).toString();
}
return new Address(senderName, senderEmail);
}
@@ -190,9 +184,12 @@
private final String anonymousCowardName;
private final ParameterizedString namePattern;
- PatternGen(final Address serverAddress, final AccountCache accountCache,
+ PatternGen(
+ final Address serverAddress,
+ final AccountCache accountCache,
final String anonymousCowardName,
- final ParameterizedString namePattern, final String senderEmail) {
+ final ParameterizedString namePattern,
+ final String senderEmail) {
this.senderEmailPattern = new ParameterizedString(senderEmail);
this.serverAddress = serverAddress;
this.accountCache = accountCache;
@@ -225,9 +222,7 @@
if (senderEmailPattern.getParameterNames().isEmpty()) {
senderEmail = senderEmailPattern.getRawPattern();
} else {
- senderEmail = senderEmailPattern
- .replace("userHash", hashOf(senderName))
- .toString();
+ senderEmail = senderEmailPattern.replace("userHash", hashOf(senderName)).toString();
}
return new Address(senderName, senderEmail);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/MailSoyTofuProvider.java b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/MailSoyTofuProvider.java
index c3cc701..b267275 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/MailSoyTofuProvider.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/MailSoyTofuProvider.java
@@ -24,7 +24,6 @@
import com.google.template.soy.SoyFileSet;
import com.google.template.soy.shared.SoyAstCache;
import com.google.template.soy.tofu.SoyTofu;
-
import java.io.IOException;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
@@ -75,8 +74,7 @@
private final SoyAstCache cache;
@Inject
- MailSoyTofuProvider(SitePaths site,
- SoyAstCache cache) {
+ MailSoyTofuProvider(SitePaths site, SoyAstCache cache) {
this.site = site;
this.cache = cache;
}
@@ -91,8 +89,7 @@
return builder.build().compileToTofu();
}
- private void addTemplate(SoyFileSet.Builder builder, String name)
- throws ProvisionException {
+ private void addTemplate(SoyFileSet.Builder builder, String name) throws ProvisionException {
// Load as a file in the mail templates directory if present.
Path tmpl = site.mail_dir.resolve(name);
if (Files.isRegularFile(tmpl)) {
@@ -102,8 +99,8 @@
try (Reader r = Files.newBufferedReader(tmpl, StandardCharsets.UTF_8)) {
content = CharStreams.toString(r);
} catch (IOException err) {
- throw new ProvisionException("Failed to read template file " +
- tmpl.toAbsolutePath().toString(), err);
+ throw new ProvisionException(
+ "Failed to read template file " + tmpl.toAbsolutePath().toString(), err);
}
builder.add(content, tmpl.toAbsolutePath().toString());
return;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/MailTemplates.java b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/MailTemplates.java
index b92567f..71f5246 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/MailTemplates.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/MailTemplates.java
@@ -17,7 +17,6 @@
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import com.google.inject.BindingAnnotation;
-
import java.lang.annotation.Retention;
@Retention(RUNTIME)
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/MergedSender.java b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/MergedSender.java
index 38a2d5b..0460a70 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/MergedSender.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/MergedSender.java
@@ -38,9 +38,7 @@
private final LabelTypes labelTypes;
@Inject
- public MergedSender(EmailArguments ea,
- @Assisted Project.NameKey project,
- @Assisted Change.Id id)
+ public MergedSender(EmailArguments ea, @Assisted Project.NameKey project, @Assisted Change.Id id)
throws OrmException {
super(ea, "merged", newChangeData(ea, project, id));
labelTypes = changeData.changeControl().getLabelTypes();
@@ -69,8 +67,9 @@
try {
Table<Account.Id, String, PatchSetApproval> pos = HashBasedTable.create();
Table<Account.Id, String, PatchSetApproval> neg = HashBasedTable.create();
- for (PatchSetApproval ca : args.approvalsUtil.byPatchSet(
- args.db.get(), changeData.changeControl(), patchSet.getId())) {
+ for (PatchSetApproval ca :
+ args.approvalsUtil.byPatchSet(
+ args.db.get(), changeData.changeControl(), patchSet.getId())) {
LabelType lt = labelTypes.byLabel(ca.getLabelId());
if (lt == null) {
continue;
@@ -89,8 +88,7 @@
return "";
}
- private String format(String type,
- Table<Account.Id, String, PatchSetApproval> approvals) {
+ private String format(String type, Table<Account.Id, String, PatchSetApproval> approvals) {
StringBuilder txt = new StringBuilder();
if (approvals.isEmpty()) {
return "";
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/NewChangeSender.java b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/NewChangeSender.java
index b4d6d01..f1a9ad8 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/NewChangeSender.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/NewChangeSender.java
@@ -19,7 +19,6 @@
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.server.query.change.ChangeData;
import com.google.gwtorm.server.OrmException;
-
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
@@ -31,8 +30,7 @@
private final Set<Account.Id> reviewers = new HashSet<>();
private final Set<Account.Id> extraCC = new HashSet<>();
- protected NewChangeSender(EmailArguments ea, ChangeData cd)
- throws OrmException {
+ protected NewChangeSender(EmailArguments ea, ChangeData cd) throws OrmException {
super(ea, "newchange", cd);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/NotificationEmail.java b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/NotificationEmail.java
index 7d10a3f..b63694c 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/NotificationEmail.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/NotificationEmail.java
@@ -23,24 +23,18 @@
import com.google.gerrit.server.mail.Address;
import com.google.gerrit.server.mail.send.ProjectWatch.Watchers;
import com.google.gwtorm.server.OrmException;
-
+import java.util.HashMap;
+import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * Common class for notifications that are related to a project and branch
- */
+/** Common class for notifications that are related to a project and branch */
public abstract class NotificationEmail extends OutgoingEmail {
- private static final Logger log =
- LoggerFactory.getLogger(NotificationEmail.class);
+ private static final Logger log = LoggerFactory.getLogger(NotificationEmail.class);
protected Branch.NameKey branch;
- protected NotificationEmail(EmailArguments ea,
- String mc, Branch.NameKey branch) {
+ protected NotificationEmail(EmailArguments ea, String mc, Branch.NameKey branch) {
super(ea, mc);
this.branch = branch;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/OutgoingEmail.java b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/OutgoingEmail.java
index b8358c5..d0f9efe 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/OutgoingEmail.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/OutgoingEmail.java
@@ -34,17 +34,6 @@
import com.google.gerrit.server.validators.ValidationException;
import com.google.gwtorm.server.OrmException;
import com.google.template.soy.data.SanitizedContent;
-
-import org.apache.commons.lang.StringUtils;
-import org.apache.velocity.Template;
-import org.apache.velocity.VelocityContext;
-import org.apache.velocity.context.InternalContextAdapterImpl;
-import org.apache.velocity.runtime.RuntimeInstance;
-import org.apache.velocity.runtime.parser.node.SimpleNode;
-import org.eclipse.jgit.util.SystemReader;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.io.StringReader;
import java.io.StringWriter;
import java.net.MalformedURLException;
@@ -61,6 +50,15 @@
import java.util.List;
import java.util.Map;
import java.util.Set;
+import org.apache.commons.lang.StringUtils;
+import org.apache.velocity.Template;
+import org.apache.velocity.VelocityContext;
+import org.apache.velocity.context.InternalContextAdapterImpl;
+import org.apache.velocity.runtime.RuntimeInstance;
+import org.apache.velocity.runtime.parser.node.SimpleNode;
+import org.eclipse.jgit.util.SystemReader;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/** Sends an email to one or more interested parties. */
public abstract class OutgoingEmail {
@@ -76,8 +74,7 @@
private Address smtpFromAddress;
private StringBuilder textBody;
private StringBuilder htmlBody;
- private ListMultimap<RecipientType, Account.Id> accountsToNotify =
- ImmutableListMultimap.of();
+ private ListMultimap<RecipientType, Account.Id> accountsToNotify = ImmutableListMultimap.of();
protected VelocityContext velocityContext;
protected Map<String, Object> soyContext;
protected Map<String, Object> soyContextEmailData;
@@ -100,8 +97,7 @@
this.notify = checkNotNull(notify);
}
- public void setAccountsToNotify(
- ListMultimap<RecipientType, Account.Id> accountsToNotify) {
+ public void setAccountsToNotify(ListMultimap<RecipientType, Account.Id> accountsToNotify) {
this.accountsToNotify = checkNotNull(accountsToNotify);
}
@@ -135,15 +131,13 @@
final Account fromUser = args.accountCache.get(fromId).getAccount();
GeneralPreferencesInfo senderPrefs = fromUser.getGeneralPreferencesInfo();
- if (senderPrefs != null
- && senderPrefs.getEmailStrategy() == CC_ON_OWN_COMMENTS) {
+ if (senderPrefs != null && senderPrefs.getEmailStrategy() == CC_ON_OWN_COMMENTS) {
// If we are impersonating a user, make sure they receive a CC of
// this message so they can always review and audit what we sent
// on their behalf to others.
//
add(RecipientType.CC, fromId);
- } else if (!accountsToNotify.containsValue(fromId)
- && rcptTo.remove(fromId)) {
+ } else if (!accountsToNotify.containsValue(fromId) && rcptTo.remove(fromId)) {
// If they don't want a copy, but we queued one up anyway,
// drop them from the recipient lists.
//
@@ -186,8 +180,7 @@
}
}
- args.emailSender.send(va.smtpFromAddress, va.smtpRcptTo, va.headers,
- va.body, va.htmlBody);
+ args.emailSender.send(va.smtpFromAddress, va.smtpRcptTo, va.headers, va.body, va.htmlBody);
}
}
@@ -241,8 +234,7 @@
final String email = account.getPreferredEmail();
StringBuilder f = new StringBuilder();
- if ((name != null && !name.isEmpty())
- || (email != null && !email.isEmpty())) {
+ if ((name != null && !name.isEmpty()) || (email != null && !email.isEmpty())) {
f.append("From");
if (name != null && !name.isEmpty()) {
f.append(" ").append(name);
@@ -286,8 +278,7 @@
}
/** Set a header in the outgoing message using a template. */
- protected void setVHeader(final String name, final String value) throws
- EmailException {
+ protected void setVHeader(final String name, final String value) throws EmailException {
setHeader(name, velocify(value));
}
@@ -332,8 +323,8 @@
}
/**
- * Gets the human readable name and email for an account;
- * if neither are available, returns the Anonymous Coward name.
+ * Gets the human readable name and email for an account; if neither are available, returns the
+ * Anonymous Coward name.
*
* @param accountId user to fetch.
* @return name/email of account, or Anonymous Coward if unset.
@@ -357,9 +348,8 @@
}
/**
- * Gets the human readable name and email for an account;
- * if both are unavailable, returns the username. If no
- * username is set, this function returns null.
+ * Gets the human readable name and email for an account; if both are unavailable, returns the
+ * username. If no username is set, this function returns null.
*
* @param accountId user to fetch.
* @return name/email of account, username, or null if unset.
@@ -397,7 +387,8 @@
}
if ((accountsToNotify == null || accountsToNotify.isEmpty())
- && smtpRcptTo.size() == 1 && rcptTo.size() == 1
+ && smtpRcptTo.size() == 1
+ && rcptTo.size() == 1
&& rcptTo.contains(fromId)) {
// If the only recipient is also the sender, don't bother.
//
@@ -546,10 +537,8 @@
}
/**
- * Evaluate the named template according to the following priority:
- * 1) Velocity file override, OR...
- * 2) Soy file override, OR...
- * 3) Soy resource.
+ * Evaluate the named template according to the following priority: 1) Velocity file override,
+ * OR... 2) Soy file override, OR... 3) Soy resource.
*/
protected String textTemplate(String name) throws EmailException {
String velocityName = name + ".vm";
@@ -584,15 +573,14 @@
protected void removeUser(Account user) {
String fromEmail = user.getPreferredEmail();
- for (Iterator<Address> j = smtpRcptTo.iterator(); j.hasNext();) {
+ for (Iterator<Address> j = smtpRcptTo.iterator(); j.hasNext(); ) {
if (j.next().getEmail().equals(fromEmail)) {
j.remove();
}
}
for (Map.Entry<String, EmailHeader> entry : headers.entrySet()) {
// Don't remove fromEmail from the "From" header though!
- if (entry.getValue() instanceof AddressList
- && !entry.getKey().equals("From")) {
+ if (entry.getValue() instanceof AddressList && !entry.getKey().equals("From")) {
((AddressList) entry.getValue()).remove(fromEmail);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/OutgoingEmailValidator.java b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/OutgoingEmailValidator.java
index 1e92c83..2d9db1d 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/OutgoingEmailValidator.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/OutgoingEmailValidator.java
@@ -21,7 +21,7 @@
public class OutgoingEmailValidator {
static {
- DomainValidator.updateTLDOverride(GENERIC_PLUS, new String[]{"local"});
+ DomainValidator.updateTLDOverride(GENERIC_PLUS, new String[] {"local"});
}
public static boolean isValid(String addr) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/ProjectWatch.java b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/ProjectWatch.java
index 2269b66..3eb6f05 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/ProjectWatch.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/ProjectWatch.java
@@ -37,15 +37,13 @@
import com.google.gerrit.server.query.change.ChangeQueryBuilder;
import com.google.gerrit.server.query.change.SingleGroupUser;
import com.google.gwtorm.server.OrmException;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class ProjectWatch {
private static final Logger log = LoggerFactory.getLogger(ProjectWatch.class);
@@ -55,8 +53,11 @@
protected final Project.NameKey project;
protected final ChangeData changeData;
- public ProjectWatch(EmailArguments args, Project.NameKey project,
- ProjectState projectState, ChangeData changeData) {
+ public ProjectWatch(
+ EmailArguments args,
+ Project.NameKey project,
+ ProjectState projectState,
+ ChangeData changeData) {
this.args = args;
this.project = project;
this.projectState = projectState;
@@ -68,23 +69,19 @@
Watchers matching = new Watchers();
Set<Account.Id> projectWatchers = new HashSet<>();
- for (AccountState a : args.accountQueryProvider.get()
- .byWatchedProject(project)) {
+ for (AccountState a : args.accountQueryProvider.get().byWatchedProject(project)) {
Account.Id accountId = a.getAccount().getId();
- for (Map.Entry<ProjectWatchKey, Set<NotifyType>> e :
- a.getProjectWatches().entrySet()) {
+ for (Map.Entry<ProjectWatchKey, Set<NotifyType>> e : a.getProjectWatches().entrySet()) {
if (project.equals(e.getKey().project())
- && add(matching, accountId, e.getKey(), e.getValue(), type)) {
+ && add(matching, accountId, e.getKey(), e.getValue(), type)) {
// We only want to prevent matching All-Projects if this filter hits
projectWatchers.add(accountId);
}
}
}
- for (AccountState a : args.accountQueryProvider.get()
- .byWatchedProject(args.allProjectsName)) {
- for (Map.Entry<ProjectWatchKey, Set<NotifyType>> e :
- a.getProjectWatches().entrySet()) {
+ for (AccountState a : args.accountQueryProvider.get().byWatchedProject(args.allProjectsName)) {
+ for (Map.Entry<ProjectWatchKey, Set<NotifyType>> e : a.getProjectWatches().entrySet()) {
if (args.allProjectsName.equals(e.getKey().project())) {
Account.Id accountId = a.getAccount().getId();
if (!projectWatchers.contains(accountId)) {
@@ -100,9 +97,12 @@
try {
add(matching, nc);
} catch (QueryParseException e) {
- log.warn("Project {} has invalid notify {} filter \"{}\": {}",
- state.getProject().getName(), nc.getName(),
- nc.getFilter(), e.getMessage());
+ log.warn(
+ "Project {} has invalid notify {} filter \"{}\": {}",
+ state.getProject().getName(),
+ nc.getName(),
+ nc.getFilter(),
+ e.getMessage());
}
}
}
@@ -116,6 +116,7 @@
protected final Set<Account.Id> accounts = new HashSet<>();
protected final Set<Address> emails = new HashSet<>();
}
+
protected final List to = new List();
protected final List cc = new List();
protected final List bcc = new List();
@@ -133,11 +134,9 @@
}
}
- private void add(Watchers matching, NotifyConfig nc)
- throws OrmException, QueryParseException {
+ private void add(Watchers matching, NotifyConfig nc) throws OrmException, QueryParseException {
for (GroupReference ref : nc.getGroups()) {
- CurrentUser user = new SingleGroupUser(args.capabilityControlFactory,
- ref.getUUID());
+ CurrentUser user = new SingleGroupUser(args.capabilityControlFactory, ref.getUUID());
if (filterMatch(user, nc.getFilter())) {
deliverToMembers(matching.list(nc.getHeader()), ref.getUUID());
}
@@ -150,9 +149,8 @@
}
}
- private void deliverToMembers(
- Watchers.List matching,
- AccountGroup.UUID startUUID) throws OrmException {
+ private void deliverToMembers(Watchers.List matching, AccountGroup.UUID startUUID)
+ throws OrmException {
ReviewDb db = args.db.get();
Set<AccountGroup.UUID> seen = new HashSet<>();
List<AccountGroup.UUID> q = new ArrayList<>();
@@ -186,8 +184,12 @@
}
}
- private boolean add(Watchers matching, Account.Id accountId,
- ProjectWatchKey key, Set<NotifyType> watchedTypes, NotifyType type)
+ private boolean add(
+ Watchers matching,
+ Account.Id accountId,
+ ProjectWatchKey key,
+ Set<NotifyType> watchedTypes,
+ NotifyType type)
throws OrmException {
IdentifiedUser user = args.identifiedUserFactory.create(accountId);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/RegisterNewEmailSender.java b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/RegisterNewEmailSender.java
index b665690..c667026 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/RegisterNewEmailSender.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/RegisterNewEmailSender.java
@@ -35,7 +35,8 @@
private String emailToken;
@Inject
- public RegisterNewEmailSender(EmailArguments ea,
+ public RegisterNewEmailSender(
+ EmailArguments ea,
EmailTokenVerifier etv,
IdentifiedUser callingUser,
@Assisted final String address) {
@@ -63,8 +64,7 @@
public String getEmailRegistrationToken() {
if (emailToken == null) {
- emailToken = checkNotNull(
- tokenVerifier.encode(user.getAccountId(), addr), "token");
+ emailToken = checkNotNull(tokenVerifier.encode(user.getAccountId(), addr), "token");
}
return emailToken;
}
@@ -76,8 +76,7 @@
@Override
protected void setupSoyContext() {
super.setupSoyContext();
- soyContextEmailData
- .put("emailRegistrationToken", getEmailRegistrationToken());
+ soyContextEmailData.put("emailRegistrationToken", getEmailRegistrationToken());
soyContextEmailData.put("userNameEmail", getUserNameEmail());
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/ReplacePatchSetSender.java b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/ReplacePatchSetSender.java
index d5ba4a8..1d670da 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/ReplacePatchSetSender.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/ReplacePatchSetSender.java
@@ -23,7 +23,6 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
-
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
@@ -40,9 +39,8 @@
private final Set<Account.Id> extraCC = new HashSet<>();
@Inject
- public ReplacePatchSetSender(EmailArguments ea,
- @Assisted Project.NameKey project,
- @Assisted Change.Id id)
+ public ReplacePatchSetSender(
+ EmailArguments ea, @Assisted Project.NameKey project, @Assisted Change.Id id)
throws OrmException {
super(ea, "newpatchset", newChangeData(ea, project, id));
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/ReplyToChangeSender.java b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/ReplyToChangeSender.java
index a6e2fa7..61e9d1d 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/ReplyToChangeSender.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/ReplyToChangeSender.java
@@ -27,8 +27,7 @@
T create(Project.NameKey project, Change.Id id);
}
- protected ReplyToChangeSender(EmailArguments ea, String mc, ChangeData cd)
- throws OrmException {
+ protected ReplyToChangeSender(EmailArguments ea, String mc, ChangeData cd) throws OrmException {
super(ea, mc, cd);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/RestoredSender.java b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/RestoredSender.java
index fe37984..7456d06 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/RestoredSender.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/RestoredSender.java
@@ -24,16 +24,14 @@
/** Send notice about a change being restored by its owner. */
public class RestoredSender extends ReplyToChangeSender {
- public interface Factory extends
- ReplyToChangeSender.Factory<RestoredSender> {
+ public interface Factory extends ReplyToChangeSender.Factory<RestoredSender> {
@Override
RestoredSender create(Project.NameKey project, Change.Id id);
}
@Inject
- public RestoredSender(EmailArguments ea,
- @Assisted Project.NameKey project,
- @Assisted Change.Id id)
+ public RestoredSender(
+ EmailArguments ea, @Assisted Project.NameKey project, @Assisted Change.Id id)
throws OrmException {
super(ea, "restore", ChangeEmail.newChangeData(ea, project, id));
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/RevertedSender.java b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/RevertedSender.java
index bad72ab..e590d94 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/RevertedSender.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/RevertedSender.java
@@ -29,9 +29,8 @@
}
@Inject
- public RevertedSender(EmailArguments ea,
- @Assisted Project.NameKey project,
- @Assisted Change.Id id)
+ public RevertedSender(
+ EmailArguments ea, @Assisted Project.NameKey project, @Assisted Change.Id id)
throws OrmException {
super(ea, "revert", ChangeEmail.newChangeData(ea, project, id));
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/SetAssigneeSender.java b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/SetAssigneeSender.java
index 11d9a6e..9708b1b 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/SetAssigneeSender.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/SetAssigneeSender.java
@@ -25,14 +25,14 @@
public class SetAssigneeSender extends ChangeEmail {
public interface Factory {
- SetAssigneeSender create(Project.NameKey project, Change.Id id,
- Account.Id assignee);
+ SetAssigneeSender create(Project.NameKey project, Change.Id id, Account.Id assignee);
}
private final Account.Id assignee;
@Inject
- public SetAssigneeSender(EmailArguments ea,
+ public SetAssigneeSender(
+ EmailArguments ea,
@Assisted Project.NameKey project,
@Assisted Change.Id id,
@Assisted Account.Id assignee)
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/SmtpEmailSender.java b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/SmtpEmailSender.java
index d5622bf..841c995 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/SmtpEmailSender.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/SmtpEmailSender.java
@@ -29,12 +29,6 @@
import com.google.inject.AbstractModule;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
-import org.apache.commons.net.smtp.AuthSMTPClient;
-import org.apache.commons.net.smtp.SMTPClient;
-import org.apache.commons.net.smtp.SMTPReply;
-import org.eclipse.jgit.lib.Config;
-
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.Writer;
@@ -48,6 +42,10 @@
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
+import org.apache.commons.net.smtp.AuthSMTPClient;
+import org.apache.commons.net.smtp.SMTPClient;
+import org.apache.commons.net.smtp.SMTPReply;
+import org.eclipse.jgit.lib.Config;
/** Sends email via a nearby SMTP server. */
@Singleton
@@ -79,17 +77,21 @@
SmtpEmailSender(@GerritServerConfig final Config cfg) {
enabled = cfg.getBoolean("sendemail", null, "enable", true);
connectTimeout =
- Ints.checkedCast(ConfigUtil.getTimeUnit(cfg, "sendemail", null,
- "connectTimeout", DEFAULT_CONNECT_TIMEOUT, TimeUnit.MILLISECONDS));
-
+ Ints.checkedCast(
+ ConfigUtil.getTimeUnit(
+ cfg,
+ "sendemail",
+ null,
+ "connectTimeout",
+ DEFAULT_CONNECT_TIMEOUT,
+ TimeUnit.MILLISECONDS));
smtpHost = cfg.getString("sendemail", null, "smtpserver");
if (smtpHost == null) {
smtpHost = "127.0.0.1";
}
- smtpEncryption =
- cfg.getEnum("sendemail", null, "smtpencryption", Encryption.NONE);
+ smtpEncryption = cfg.getEnum("sendemail", null, "smtpencryption", Encryption.NONE);
sslVerify = cfg.getBoolean("sendemail", null, "sslverify", true);
final int defaultPort;
@@ -146,22 +148,28 @@
}
@Override
- public void send(final Address from, Collection<Address> rcpt,
- final Map<String, EmailHeader> callerHeaders, String body)
+ public void send(
+ final Address from,
+ Collection<Address> rcpt,
+ final Map<String, EmailHeader> callerHeaders,
+ String body)
throws EmailException {
send(from, rcpt, callerHeaders, body, null);
}
@Override
- public void send(final Address from, Collection<Address> rcpt,
- final Map<String, EmailHeader> callerHeaders, String textBody,
- @Nullable String htmlBody) throws EmailException {
+ public void send(
+ final Address from,
+ Collection<Address> rcpt,
+ final Map<String, EmailHeader> callerHeaders,
+ String textBody,
+ @Nullable String htmlBody)
+ throws EmailException {
if (!isEnabled()) {
throw new EmailException("Sending email is disabled");
}
- final Map<String, EmailHeader> hdrs =
- new LinkedHashMap<>(callerHeaders);
+ final Map<String, EmailHeader> hdrs = new LinkedHashMap<>(callerHeaders);
setMissingHeader(hdrs, "MIME-Version", "1.0");
setMissingHeader(hdrs, "Content-Transfer-Encoding", "8bit");
setMissingHeader(hdrs, "Content-Disposition", "inline");
@@ -170,10 +178,9 @@
setMissingHeader(hdrs, "Importance", importance);
}
if (expiryDays > 0) {
- Date expiry = new Date(TimeUtil.nowMs() +
- expiryDays * 24 * 60 * 60 * 1000L );
- setMissingHeader(hdrs, "Expiry-Date",
- new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z").format(expiry));
+ Date expiry = new Date(TimeUtil.nowMs() + expiryDays * 24 * 60 * 60 * 1000L);
+ setMissingHeader(
+ hdrs, "Expiry-Date", new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z").format(expiry));
}
String encodedBody;
@@ -182,9 +189,10 @@
encodedBody = textBody;
} else {
String boundary = generateMultipartBoundary(textBody, htmlBody);
- setMissingHeader(hdrs, "Content-Type", "multipart/alternative; "
- + "boundary=\"" + boundary + "\"; "
- + "charset=UTF-8");
+ setMissingHeader(
+ hdrs,
+ "Content-Type",
+ "multipart/alternative; " + "boundary=\"" + boundary + "\"; " + "charset=UTF-8");
encodedBody = buildMultipartBody(boundary, textBody, htmlBody);
}
@@ -193,8 +201,8 @@
final SMTPClient client = open();
try {
if (!client.setSender(from.getEmail())) {
- throw new EmailException("Server " + smtpHost
- + " rejected from address " + from.getEmail());
+ throw new EmailException(
+ "Server " + smtpHost + " rejected from address " + from.getEmail());
}
/* Do not prevent the email from being sent to "good" users simply
@@ -207,9 +215,13 @@
for (Address addr : rcpt) {
if (!client.addRecipient(addr.getEmail())) {
String error = client.getReplyString();
- rejected.append("Server ").append(smtpHost)
- .append(" rejected recipient ").append(addr)
- .append(": ").append(error);
+ rejected
+ .append("Server ")
+ .append(smtpHost)
+ .append(" rejected recipient ")
+ .append(addr)
+ .append(": ")
+ .append(error);
}
}
@@ -219,8 +231,12 @@
* information. That piece of the puzzle is vital if zero recipients
* are accepted and the server consequently rejects the DATA command.
*/
- throw new EmailException(rejected + "Server " + smtpHost
- + " rejected DATA command: " + client.getReplyString());
+ throw new EmailException(
+ rejected
+ + "Server "
+ + smtpHost
+ + " rejected DATA command: "
+ + client.getReplyString());
}
try (Writer w = new BufferedWriter(messageDataWriter)) {
for (Map.Entry<String, EmailHeader> h : hdrs.entrySet()) {
@@ -238,8 +254,8 @@
}
if (!client.completePendingCommand()) {
- throw new EmailException("Server " + smtpHost
- + " rejected message body: " + client.getReplyString());
+ throw new EmailException(
+ "Server " + smtpHost + " rejected message body: " + client.getReplyString());
}
client.logout();
@@ -254,8 +270,8 @@
}
}
- public static String generateMultipartBoundary(String textBody,
- String htmlBody) throws EmailException {
+ public static String generateMultipartBoundary(String textBody, String htmlBody)
+ throws EmailException {
byte[] bytes = new byte[8];
ThreadLocalRandom rng = ThreadLocalRandom.current();
@@ -276,29 +292,36 @@
throw new EmailException("Gave up generating unique MIME boundary");
}
- protected String buildMultipartBody(String boundary, String textPart,
- String htmlPart) {
+ protected String buildMultipartBody(String boundary, String textPart, String htmlPart) {
return
- // Output the text part:
- "--" + boundary + "\r\n"
+ // Output the text part:
+ "--"
+ + boundary
+ + "\r\n"
+ "Content-Type: text/plain; charset=UTF-8\r\n"
+ "Content-Transfer-Encoding: 8bit\r\n"
+ "\r\n"
- + textPart + "\r\n"
+ + textPart
+ + "\r\n"
// Output the HTML part:
- + "--" + boundary + "\r\n"
+ + "--"
+ + boundary
+ + "\r\n"
+ "Content-Type: text/html; charset=UTF-8\r\n"
+ "Content-Transfer-Encoding: 8bit\r\n"
+ "\r\n"
- + htmlPart + "\r\n"
+ + htmlPart
+ + "\r\n"
// Output the closing boundary.
- + "--" + boundary + "--\r\n";
+ + "--"
+ + boundary
+ + "--\r\n";
}
- private void setMissingHeader(final Map<String, EmailHeader> hdrs,
- final String name, final String value) {
+ private void setMissingHeader(
+ final Map<String, EmailHeader> hdrs, final String name, final String value) {
if (!hdrs.containsKey(name) || hdrs.get(name).isEmpty()) {
hdrs.put(name, new EmailHeader.String(value));
}
@@ -318,12 +341,10 @@
String replyString = client.getReplyString();
if (!SMTPReply.isPositiveCompletion(replyCode)) {
throw new EmailException(
- String.format("SMTP server rejected connection: %d: %s",
- replyCode, replyString));
+ String.format("SMTP server rejected connection: %d: %s", replyCode, replyString));
}
if (!client.login()) {
- throw new EmailException(
- "SMTP server rejected HELO/EHLO greeting: " + replyString);
+ throw new EmailException("SMTP server rejected HELO/EHLO greeting: " + replyString);
}
if (smtpEncryption == Encryption.TLS) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/VelocityRuntimeProvider.java b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/VelocityRuntimeProvider.java
index 03d4f7a..3e17778 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/VelocityRuntimeProvider.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/mail/send/VelocityRuntimeProvider.java
@@ -19,7 +19,8 @@
import com.google.inject.Provider;
import com.google.inject.ProvisionException;
import com.google.inject.Singleton;
-
+import java.nio.file.Files;
+import java.util.Properties;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.RuntimeInstance;
import org.apache.velocity.runtime.RuntimeServices;
@@ -27,9 +28,6 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.nio.file.Files;
-import java.util.Properties;
-
/** Configures Velocity template engine for sending email. */
@Singleton
public class VelocityRuntimeProvider implements Provider<RuntimeInstance> {
@@ -47,16 +45,14 @@
Properties p = new Properties();
p.setProperty(RuntimeConstants.VM_PERM_INLINE_LOCAL, "true");
- p.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS,
- Slf4jLogChute.class.getName());
+ p.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, Slf4jLogChute.class.getName());
p.setProperty(RuntimeConstants.RUNTIME_REFERENCES_STRICT, "true");
p.setProperty("runtime.log.logsystem.log4j.category", "velocity");
if (Files.isDirectory(site.mail_dir)) {
p.setProperty(rl, "file, class");
p.setProperty("file." + rl + ".class", pkg + ".FileResourceLoader");
- p.setProperty("file." + rl + ".path",
- site.mail_dir.toAbsolutePath().toString());
+ p.setProperty("file." + rl + ".path", site.mail_dir.toAbsolutePath().toString());
p.setProperty("class." + rl + ".class", pkg + ".ClasspathResourceLoader");
} else {
p.setProperty(rl, "class");
@@ -77,8 +73,7 @@
private static final Logger log = LoggerFactory.getLogger("velocity");
@Override
- public void init(RuntimeServices rs) {
- }
+ public void init(RuntimeServices rs) {}
@Override
public boolean isLevelEnabled(int level) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/mime/DefaultFileExtensionRegistry.java b/gerrit-server/src/main/java/com/google/gerrit/server/mime/DefaultFileExtensionRegistry.java
index 8c6bb3e..7f0661c 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/mime/DefaultFileExtensionRegistry.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/mime/DefaultFileExtensionRegistry.java
@@ -15,15 +15,10 @@
package com.google.gerrit.server.mime;
import com.google.common.collect.ImmutableMap;
-
import eu.medsea.mimeutil.MimeException;
import eu.medsea.mimeutil.MimeType;
import eu.medsea.mimeutil.MimeUtil;
import eu.medsea.mimeutil.detector.MimeDetector;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
@@ -32,6 +27,8 @@
import java.util.Collections;
import java.util.Map;
import java.util.Properties;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/** Loads mime types from {@code mime-types.properties} at specificity of 2. */
public class DefaultFileExtensionRegistry extends MimeDetector {
@@ -40,8 +37,8 @@
static {
Properties prop = new Properties();
- try (InputStream in = DefaultFileExtensionRegistry.class
- .getResourceAsStream("mime-types.properties")) {
+ try (InputStream in =
+ DefaultFileExtensionRegistry.class.getResourceAsStream("mime-types.properties")) {
prop.load(in);
} catch (IOException e) {
log.warn("Cannot load mime-types.properties", e);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/mime/FileTypeRegistry.java b/gerrit-server/src/main/java/com/google/gerrit/server/mime/FileTypeRegistry.java
index a231693..e9e3c71 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/mime/FileTypeRegistry.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/mime/FileTypeRegistry.java
@@ -21,15 +21,14 @@
/**
* Get the most specific MIME type available for a file.
*
- * @param path name of the file. The base name (component after the last '/')
- * may be used to help determine the MIME type, such as by examining
- * the extension (portion after the last '.' if present).
- * @param content the complete file content. If non-null the content may be
- * used to guess the MIME type by examining the beginning for common
- * file headers.
- * @return the MIME type for this content. If the MIME type is not recognized
- * or cannot be determined, {@link MimeUtil2#UNKNOWN_MIME_TYPE} which
- * is an alias for {@code application/octet-stream}.
+ * @param path name of the file. The base name (component after the last '/') may be used to help
+ * determine the MIME type, such as by examining the extension (portion after the last '.' if
+ * present).
+ * @param content the complete file content. If non-null the content may be used to guess the MIME
+ * type by examining the beginning for common file headers.
+ * @return the MIME type for this content. If the MIME type is not recognized or cannot be
+ * determined, {@link MimeUtil2#UNKNOWN_MIME_TYPE} which is an alias for {@code
+ * application/octet-stream}.
*/
MimeType getMimeType(String path, byte[] content);
@@ -37,11 +36,9 @@
* Is this content type safe to transmit to a browser directly?
*
* @param type the MIME type of the file content.
- * @return true if the Gerrit administrator wants to permit this content to be
- * served as-is; false if the administrator does not trust this
- * content type and wants it to be protected (typically by wrapping
- * the data in a ZIP archive).
+ * @return true if the Gerrit administrator wants to permit this content to be served as-is; false
+ * if the administrator does not trust this content type and wants it to be protected
+ * (typically by wrapping the data in a ZIP archive).
*/
boolean isSafeInline(MimeType type);
-
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/mime/MimeUtil2Module.java b/gerrit-server/src/main/java/com/google/gerrit/server/mime/MimeUtil2Module.java
index 61b01af8..387482a 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/mime/MimeUtil2Module.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/mime/MimeUtil2Module.java
@@ -18,15 +18,13 @@
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.Singleton;
-
import eu.medsea.mimeutil.MimeUtil2;
import eu.medsea.mimeutil.detector.ExtensionMimeDetector;
import eu.medsea.mimeutil.detector.MagicMimeMimeDetector;
public class MimeUtil2Module extends AbstractModule {
@Override
- protected void configure() {
- }
+ protected void configure() {}
@Provides
@Singleton
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/mime/MimeUtilFileTypeRegistry.java b/gerrit-server/src/main/java/com/google/gerrit/server/mime/MimeUtilFileTypeRegistry.java
index 2387200..859363c 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/mime/MimeUtilFileTypeRegistry.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/mime/MimeUtilFileTypeRegistry.java
@@ -17,15 +17,9 @@
import com.google.gerrit.server.config.GerritServerConfig;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
import eu.medsea.mimeutil.MimeException;
import eu.medsea.mimeutil.MimeType;
import eu.medsea.mimeutil.MimeUtil2;
-
-import org.eclipse.jgit.lib.Config;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
@@ -33,13 +27,15 @@
import java.util.HashSet;
import java.util.List;
import java.util.Set;
+import org.eclipse.jgit.lib.Config;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
@Singleton
public class MimeUtilFileTypeRegistry implements FileTypeRegistry {
private static final String KEY_SAFE = "safe";
private static final String SECTION_MIMETYPE = "mimetype";
- private static final Logger log =
- LoggerFactory.getLogger(MimeUtilFileTypeRegistry.class);
+ private static final Logger log = LoggerFactory.getLogger(MimeUtilFileTypeRegistry.class);
private final Config cfg;
private final MimeUtil2 mimeUtil;
@@ -53,9 +49,8 @@
/**
* Get specificity of mime types with generic types forced to low values
*
- * "application/octet-stream" is forced to -1.
- * "text/plain" is forced to 0.
- * All other mime types return the specificity reported by mimeType itself.
+ * <p>"application/octet-stream" is forced to -1. "text/plain" is forced to 0. All other mime
+ * types return the specificity reported by mimeType itself.
*
* @param mimeType The mimeType to get the corrected specificity for.
* @return The corrected specificity.
@@ -103,12 +98,14 @@
}
final List<MimeType> types = new ArrayList<>(mimeTypes);
- Collections.sort(types, new Comparator<MimeType>() {
- @Override
- public int compare(MimeType a, MimeType b) {
- return getCorrectedMimeSpecificity(b) - getCorrectedMimeSpecificity(a);
- }
- });
+ Collections.sort(
+ types,
+ new Comparator<MimeType>() {
+ @Override
+ public int compare(MimeType a, MimeType b) {
+ return getCorrectedMimeSpecificity(b) - getCorrectedMimeSpecificity(a);
+ }
+ });
return types.get(0);
}
@@ -135,7 +132,6 @@
if (mimeTypes.isEmpty()) {
return true;
}
- return mimeTypes.size() == 1
- && mimeTypes.contains(MimeUtil2.UNKNOWN_MIME_TYPE);
+ return mimeTypes.size() == 1 && mimeTypes.contains(MimeUtil2.UNKNOWN_MIME_TYPE);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/AbstractChangeNotes.java b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/AbstractChangeNotes.java
index c58d3fe..4cb570a 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/AbstractChangeNotes.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/AbstractChangeNotes.java
@@ -34,15 +34,13 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
+import java.io.IOException;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
-import java.io.IOException;
-
-/** View of contents at a single ref related to some change. **/
+/** View of contents at a single ref related to some change. * */
public abstract class AbstractChangeNotes<T> {
@VisibleForTesting
@Singleton
@@ -91,16 +89,18 @@
} else if (id != null) {
id = id.copy();
}
- return new AutoValue_AbstractChangeNotes_LoadHandle(
- checkNotNull(walk), id);
+ return new AutoValue_AbstractChangeNotes_LoadHandle(checkNotNull(walk), id);
}
public static LoadHandle missing() {
return new AutoValue_AbstractChangeNotes_LoadHandle(null, null);
}
- @Nullable public abstract ChangeNotesRevWalk walk();
- @Nullable public abstract ObjectId id();
+ @Nullable
+ public abstract ChangeNotesRevWalk walk();
+
+ @Nullable
+ public abstract ObjectId id();
@Override
public void close() {
@@ -118,13 +118,12 @@
private ObjectId revision;
private boolean loaded;
- AbstractChangeNotes(Args args, Change.Id changeId,
- @Nullable PrimaryStorage primaryStorage, boolean autoRebuild) {
+ AbstractChangeNotes(
+ Args args, Change.Id changeId, @Nullable PrimaryStorage primaryStorage, boolean autoRebuild) {
this.args = checkNotNull(args);
this.changeId = checkNotNull(changeId);
this.primaryStorage = primaryStorage;
- this.autoRebuild = primaryStorage == PrimaryStorage.REVIEW_DB
- && autoRebuild;
+ this.autoRebuild = primaryStorage == PrimaryStorage.REVIEW_DB && autoRebuild;
}
public Change.Id getChangeId() {
@@ -177,18 +176,15 @@
/**
* Open a handle for reading this entity from a repository.
- * <p>
- * Implementations may override this method to provide auto-rebuilding
- * behavior.
+ *
+ * <p>Implementations may override this method to provide auto-rebuilding behavior.
*
* @param repo open repository.
* @return handle for reading the entity.
- *
* @throws NoSuchChangeException change does not exist.
* @throws IOException a repo-level error occurred.
*/
- protected LoadHandle openHandle(Repository repo)
- throws NoSuchChangeException, IOException {
+ protected LoadHandle openHandle(Repository repo) throws NoSuchChangeException, IOException {
return openHandle(repo, readRef(repo));
}
@@ -219,8 +215,8 @@
protected abstract void loadDefaults();
/**
- * @return the NameKey for the project where the notes should be stored,
- * which is not necessarily the same as the change's project.
+ * @return the NameKey for the project where the notes should be stored, which is not necessarily
+ * the same as the change's project.
*/
public abstract Project.NameKey getProjectName();
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/AbstractChangeUpdate.java b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/AbstractChangeUpdate.java
index fa23b80..8df9bd6 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/AbstractChangeUpdate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/AbstractChangeUpdate.java
@@ -28,7 +28,8 @@
import com.google.gerrit.server.InternalUser;
import com.google.gerrit.server.project.ChangeControl;
import com.google.gwtorm.server.OrmException;
-
+import java.io.IOException;
+import java.util.Date;
import org.eclipse.jgit.lib.CommitBuilder;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.ObjectId;
@@ -37,9 +38,6 @@
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;
-import java.io.IOException;
-import java.util.Date;
-
/** A single delta related to a specific patch-set of a change. */
public abstract class AbstractChangeUpdate {
protected final NotesMigration migration;
@@ -72,10 +70,8 @@
this.change = notes.getChange();
this.accountId = accountId(ctl.getUser());
Account.Id realAccountId = accountId(ctl.getUser().getRealUser());
- this.realAccountId =
- realAccountId != null ? realAccountId : accountId;
- this.authorIdent =
- ident(noteUtil, serverIdent, anonymousCowardName, ctl.getUser(), when);
+ this.realAccountId = realAccountId != null ? realAccountId : accountId;
+ this.authorIdent = ident(noteUtil, serverIdent, anonymousCowardName, ctl.getUser(), when);
this.when = when;
}
@@ -91,8 +87,7 @@
PersonIdent authorIdent,
Date when) {
checkArgument(
- (notes != null && change == null)
- || (notes == null && change != null),
+ (notes != null && change == null) || (notes == null && change != null),
"exactly one of notes or change required");
this.migration = migration;
this.noteUtil = noteUtil;
@@ -109,7 +104,8 @@
private static void checkUserType(CurrentUser user) {
checkArgument(
(user instanceof IdentifiedUser) || (user instanceof InternalUser),
- "user must be IdentifiedUser or InternalUser: %s", user);
+ "user must be IdentifiedUser or InternalUser: %s",
+ user);
}
private static Account.Id accountId(CurrentUser u) {
@@ -117,13 +113,16 @@
return (u instanceof IdentifiedUser) ? u.getAccountId() : null;
}
- private static PersonIdent ident(ChangeNoteUtil noteUtil,
- PersonIdent serverIdent, String anonymousCowardName, CurrentUser u,
+ private static PersonIdent ident(
+ ChangeNoteUtil noteUtil,
+ PersonIdent serverIdent,
+ String anonymousCowardName,
+ CurrentUser u,
Date when) {
checkUserType(u);
if (u instanceof IdentifiedUser) {
- return noteUtil.newIdent(u.asIdentifiedUser().getAccount(), when,
- serverIdent, anonymousCowardName);
+ return noteUtil.newIdent(
+ u.asIdentifiedUser().getAccount(), when, serverIdent, anonymousCowardName);
} else if (u instanceof InternalUser) {
return serverIdent;
}
@@ -157,9 +156,11 @@
}
public Account.Id getAccountId() {
- checkState(accountId != null,
+ checkState(
+ accountId != null,
"author identity for %s is not from an IdentifiedUser: %s",
- getClass().getSimpleName(), authorIdent.toExternalString());
+ getClass().getSimpleName(),
+ authorIdent.toExternalString());
return accountId;
}
@@ -175,8 +176,8 @@
public abstract boolean isEmpty();
/**
- * @return the NameKey for the project where the update will be stored,
- * which is not necessarily the same as the change's project.
+ * @return the NameKey for the project where the update will be stored, which is not necessarily
+ * the same as the change's project.
*/
protected abstract Project.NameKey getProjectName();
@@ -188,9 +189,9 @@
* @param rw walk for reading back any objects needed for the update.
* @param ins inserter to write to; callers should not flush.
* @param curr the current tip of the branch prior to this update.
- * @return commit ID produced by inserting this update's commit, or null if
- * this update is a no-op and should be skipped. The zero ID is a valid
- * return value, and indicates the ref should be deleted.
+ * @return commit ID produced by inserting this update's commit, or null if this update is a no-op
+ * and should be skipped. The zero ID is a valid return value, and indicates the ref should be
+ * deleted.
* @throws OrmException if a Gerrit-level error occurred.
* @throws IOException if a lower-level error occurred.
*/
@@ -236,18 +237,17 @@
* Create a commit containing the contents of this update.
*
* @param ins inserter to write to; callers should not flush.
- * @return a new commit builder representing this commit, or null to indicate
- * the meta ref should be deleted as a result of this update. The parent,
- * author, and committer fields in the return value are always
- * overwritten. The tree ID may be unset by this method, which indicates
- * to the caller that it should be copied from the parent commit. To
- * indicate that this update is a no-op (but this could not be determined
- * by {@link #isEmpty()}), return the sentinel {@link #NO_OP_UPDATE}.
+ * @return a new commit builder representing this commit, or null to indicate the meta ref should
+ * be deleted as a result of this update. The parent, author, and committer fields in the
+ * return value are always overwritten. The tree ID may be unset by this method, which
+ * indicates to the caller that it should be copied from the parent commit. To indicate that
+ * this update is a no-op (but this could not be determined by {@link #isEmpty()}), return the
+ * sentinel {@link #NO_OP_UPDATE}.
* @throws OrmException if a Gerrit-level error occurred.
* @throws IOException if a lower-level error occurred.
*/
- protected abstract CommitBuilder applyImpl(RevWalk rw, ObjectInserter ins,
- ObjectId curr) throws OrmException, IOException;
+ protected abstract CommitBuilder applyImpl(RevWalk rw, ObjectInserter ins, ObjectId curr)
+ throws OrmException, IOException;
protected static final CommitBuilder NO_OP_UPDATE = new CommitBuilder();
@@ -267,13 +267,16 @@
checkArgument(c.revId != null, "RevId required for comment: %s", c);
checkArgument(
c.author.getId().equals(getAccountId()),
- "The author for the following comment does not match the author of"
- + " this %s (%s): %s",
- getClass().getSimpleName(), getAccountId(), c);
+ "The author for the following comment does not match the author of" + " this %s (%s): %s",
+ getClass().getSimpleName(),
+ getAccountId(),
+ c);
checkArgument(
c.getRealAuthor().getId().equals(realAccountId),
"The real author for the following comment does not match the real"
+ " author of this %s (%s): %s",
- getClass().getSimpleName(), realAccountId, c);
+ getClass().getSimpleName(),
+ realAccountId,
+ c);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/ChangeBundle.java b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/ChangeBundle.java
index a107bda..eaa0335 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/ChangeBundle.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/ChangeBundle.java
@@ -55,7 +55,6 @@
import com.google.gerrit.server.notedb.rebuild.ChangeRebuilderImpl;
import com.google.gwtorm.client.Column;
import com.google.gwtorm.server.OrmException;
-
import java.lang.reflect.Field;
import java.sql.Timestamp;
import java.util.ArrayList;
@@ -73,26 +72,31 @@
/**
* A bundle of all entities rooted at a single {@link Change} entity.
- * <p>
- * See the {@link Change} Javadoc for a depiction of this tree. Bundles may be
- * compared using {@link #differencesFrom(ChangeBundle)}, which normalizes out
- * the minor implementation differences between ReviewDb and NoteDb.
+ *
+ * <p>See the {@link Change} Javadoc for a depiction of this tree. Bundles may be compared using
+ * {@link #differencesFrom(ChangeBundle)}, which normalizes out the minor implementation differences
+ * between ReviewDb and NoteDb.
*/
public class ChangeBundle {
public enum Source {
- REVIEW_DB, NOTE_DB;
+ REVIEW_DB,
+ NOTE_DB;
}
- public static ChangeBundle fromNotes(CommentsUtil commentsUtil,
- ChangeNotes notes) throws OrmException {
+ public static ChangeBundle fromNotes(CommentsUtil commentsUtil, ChangeNotes notes)
+ throws OrmException {
return new ChangeBundle(
notes.getChange(),
notes.getChangeMessages(),
notes.getPatchSets().values(),
notes.getApprovals().values(),
- Iterables.concat(CommentsUtil.toPatchLineComments(notes.getChangeId(),
- PatchLineComment.Status.DRAFT, commentsUtil.draftByChange(null, notes)),
- CommentsUtil.toPatchLineComments(notes.getChangeId(),
+ Iterables.concat(
+ CommentsUtil.toPatchLineComments(
+ notes.getChangeId(),
+ PatchLineComment.Status.DRAFT,
+ commentsUtil.draftByChange(null, notes)),
+ CommentsUtil.toPatchLineComments(
+ notes.getChangeId(),
PatchLineComment.Status.PUBLISHED,
commentsUtil.publishedByChange(null, notes))),
notes.getReviewers(),
@@ -101,16 +105,17 @@
private static Map<ChangeMessage.Key, ChangeMessage> changeMessageMap(
Iterable<ChangeMessage> in) {
- Map<ChangeMessage.Key, ChangeMessage> out = new TreeMap<>(
- new Comparator<ChangeMessage.Key>() {
- @Override
- public int compare(ChangeMessage.Key a, ChangeMessage.Key b) {
- return ComparisonChain.start()
- .compare(a.getParentKey().get(), b.getParentKey().get())
- .compare(a.get(), b.get())
- .result();
- }
- });
+ Map<ChangeMessage.Key, ChangeMessage> out =
+ new TreeMap<>(
+ new Comparator<ChangeMessage.Key>() {
+ @Override
+ public int compare(ChangeMessage.Key a, ChangeMessage.Key b) {
+ return ComparisonChain.start()
+ .compare(a.getParentKey().get(), b.getParentKey().get())
+ .compare(a.get(), b.get())
+ .result();
+ }
+ });
for (ChangeMessage cm : in) {
out.put(cm.getKey(), cm);
}
@@ -121,15 +126,13 @@
// this comparator sorts first on timestamp, then on every other field.
private static final Ordering<ChangeMessage> CHANGE_MESSAGE_ORDER =
new Ordering<ChangeMessage>() {
- final Ordering<Comparable<?>> nullsFirst =
- Ordering.natural().nullsFirst();
+ final Ordering<Comparable<?>> nullsFirst = Ordering.natural().nullsFirst();
@Override
public int compare(ChangeMessage a, ChangeMessage b) {
return ComparisonChain.start()
.compare(a.getWrittenOn(), b.getWrittenOn())
- .compare(a.getKey().getParentKey().get(),
- b.getKey().getParentKey().get())
+ .compare(a.getKey().getParentKey().get(), b.getKey().getParentKey().get())
.compare(psId(a), psId(b), nullsFirst)
.compare(a.getAuthor(), b.getAuthor(), intKeyOrdering())
.compare(a.getMessage(), b.getMessage(), nullsFirst)
@@ -141,57 +144,59 @@
}
};
- private static ImmutableList<ChangeMessage> changeMessageList(
- Iterable<ChangeMessage> in) {
+ private static ImmutableList<ChangeMessage> changeMessageList(Iterable<ChangeMessage> in) {
return CHANGE_MESSAGE_ORDER.immutableSortedCopy(in);
}
private static TreeMap<PatchSet.Id, PatchSet> patchSetMap(Iterable<PatchSet> in) {
- TreeMap<PatchSet.Id, PatchSet> out = new TreeMap<>(
- new Comparator<PatchSet.Id>() {
- @Override
- public int compare(PatchSet.Id a, PatchSet.Id b) {
- return patchSetIdChain(a, b).result();
- }
- });
+ TreeMap<PatchSet.Id, PatchSet> out =
+ new TreeMap<>(
+ new Comparator<PatchSet.Id>() {
+ @Override
+ public int compare(PatchSet.Id a, PatchSet.Id b) {
+ return patchSetIdChain(a, b).result();
+ }
+ });
for (PatchSet ps : in) {
out.put(ps.getId(), ps);
}
return out;
}
- private static Map<PatchSetApproval.Key, PatchSetApproval>
- patchSetApprovalMap(Iterable<PatchSetApproval> in) {
- Map<PatchSetApproval.Key, PatchSetApproval> out = new TreeMap<>(
- new Comparator<PatchSetApproval.Key>() {
- @Override
- public int compare(PatchSetApproval.Key a, PatchSetApproval.Key b) {
- return patchSetIdChain(a.getParentKey(), b.getParentKey())
- .compare(a.getAccountId().get(), b.getAccountId().get())
- .compare(a.getLabelId(), b.getLabelId())
- .result();
- }
- });
+ private static Map<PatchSetApproval.Key, PatchSetApproval> patchSetApprovalMap(
+ Iterable<PatchSetApproval> in) {
+ Map<PatchSetApproval.Key, PatchSetApproval> out =
+ new TreeMap<>(
+ new Comparator<PatchSetApproval.Key>() {
+ @Override
+ public int compare(PatchSetApproval.Key a, PatchSetApproval.Key b) {
+ return patchSetIdChain(a.getParentKey(), b.getParentKey())
+ .compare(a.getAccountId().get(), b.getAccountId().get())
+ .compare(a.getLabelId(), b.getLabelId())
+ .result();
+ }
+ });
for (PatchSetApproval psa : in) {
out.put(psa.getKey(), psa);
}
return out;
}
- private static Map<PatchLineComment.Key, PatchLineComment>
- patchLineCommentMap(Iterable<PatchLineComment> in) {
- Map<PatchLineComment.Key, PatchLineComment> out = new TreeMap<>(
- new Comparator<PatchLineComment.Key>() {
- @Override
- public int compare(PatchLineComment.Key a, PatchLineComment.Key b) {
- Patch.Key pka = a.getParentKey();
- Patch.Key pkb = b.getParentKey();
- return patchSetIdChain(pka.getParentKey(), pkb.getParentKey())
- .compare(pka.get(), pkb.get())
- .compare(a.get(), b.get())
- .result();
- }
- });
+ private static Map<PatchLineComment.Key, PatchLineComment> patchLineCommentMap(
+ Iterable<PatchLineComment> in) {
+ Map<PatchLineComment.Key, PatchLineComment> out =
+ new TreeMap<>(
+ new Comparator<PatchLineComment.Key>() {
+ @Override
+ public int compare(PatchLineComment.Key a, PatchLineComment.Key b) {
+ Patch.Key pka = a.getParentKey();
+ Patch.Key pkb = b.getParentKey();
+ return patchSetIdChain(pka.getParentKey(), pkb.getParentKey())
+ .compare(pka.get(), pkb.get())
+ .compare(a.get(), b.get())
+ .result();
+ }
+ });
for (PatchLineComment plc : in) {
out.put(plc.getKey(), plc);
}
@@ -213,9 +218,12 @@
}
}
Set<Integer> expectedIds = Sets.newTreeSet(Arrays.asList(expected));
- checkState(ids.equals(expectedIds),
+ checkState(
+ ids.equals(expectedIds),
"Unexpected column set for %s: %s != %s",
- clazz.getSimpleName(), ids, expectedIds);
+ clazz.getSimpleName(),
+ ids,
+ expectedIds);
}
static {
@@ -223,8 +231,7 @@
// last time this file was updated.
checkColumns(Change.Id.class, 1);
- checkColumns(Change.class,
- 1, 2, 3, 4, 5, 7, 8, 10, 12, 13, 14, 17, 18, 19, 101);
+ checkColumns(Change.class, 1, 2, 3, 4, 5, 7, 8, 10, 12, 13, 14, 17, 18, 19, 101);
checkColumns(ChangeMessage.Key.class, 1, 2);
checkColumns(ChangeMessage.class, 1, 2, 3, 4, 5, 6, 7);
checkColumns(PatchSet.Id.class, 1, 2);
@@ -238,10 +245,8 @@
private final Change change;
private final ImmutableList<ChangeMessage> changeMessages;
private final ImmutableSortedMap<PatchSet.Id, PatchSet> patchSets;
- private final ImmutableMap<PatchSetApproval.Key, PatchSetApproval>
- patchSetApprovals;
- private final ImmutableMap<PatchLineComment.Key, PatchLineComment>
- patchLineComments;
+ private final ImmutableMap<PatchSetApproval.Key, PatchSetApproval> patchSetApprovals;
+ private final ImmutableMap<PatchLineComment.Key, PatchLineComment> patchLineComments;
private final ReviewerSet reviewers;
private final Source source;
@@ -256,10 +261,8 @@
this.change = checkNotNull(change);
this.changeMessages = changeMessageList(changeMessages);
this.patchSets = ImmutableSortedMap.copyOfSorted(patchSetMap(patchSets));
- this.patchSetApprovals =
- ImmutableMap.copyOf(patchSetApprovalMap(patchSetApprovals));
- this.patchLineComments =
- ImmutableMap.copyOf(patchLineCommentMap(patchLineComments));
+ this.patchSetApprovals = ImmutableMap.copyOf(patchSetApprovalMap(patchSetApprovals));
+ this.patchLineComments = ImmutableMap.copyOf(patchLineCommentMap(patchLineComments));
this.reviewers = checkNotNull(reviewers);
this.source = checkNotNull(source);
@@ -273,8 +276,7 @@
checkArgument(k.getParentKey().getParentKey().equals(change.getId()));
}
for (PatchLineComment.Key k : this.patchLineComments.keySet()) {
- checkArgument(k.getParentKey().getParentKey().getParentKey()
- .equals(change.getId()));
+ checkArgument(k.getParentKey().getParentKey().getParentKey().equals(change.getId()));
}
}
@@ -345,23 +347,16 @@
return firstNonNull(ts, change.getLastUpdatedOn());
}
- private Map<PatchSetApproval.Key, PatchSetApproval>
- filterPatchSetApprovals() {
- return limitToValidPatchSets(
- patchSetApprovals, PatchSetApproval.Key::getParentKey);
+ private Map<PatchSetApproval.Key, PatchSetApproval> filterPatchSetApprovals() {
+ return limitToValidPatchSets(patchSetApprovals, PatchSetApproval.Key::getParentKey);
}
- private Map<PatchLineComment.Key, PatchLineComment>
- filterPatchLineComments() {
- return limitToValidPatchSets(
- patchLineComments,
- k -> k.getParentKey().getParentKey());
+ private Map<PatchLineComment.Key, PatchLineComment> filterPatchLineComments() {
+ return limitToValidPatchSets(patchLineComments, k -> k.getParentKey().getParentKey());
}
- private <K, V> Map<K, V> limitToValidPatchSets(Map<K, V> in,
- Function<K, PatchSet.Id> func) {
- return Maps.filterKeys(
- in, Predicates.compose(validPatchSetPredicate(), func));
+ private <K, V> Map<K, V> limitToValidPatchSets(Map<K, V> in, Function<K, PatchSet.Id> func) {
+ return Maps.filterKeys(in, Predicates.compose(validPatchSetPredicate(), func));
}
private Predicate<PatchSet.Id> validPatchSetPredicate() {
@@ -370,7 +365,9 @@
private Collection<ChangeMessage> filterChangeMessages() {
final Predicate<PatchSet.Id> validPatchSet = validPatchSetPredicate();
- return Collections2.filter(changeMessages, m -> {
+ return Collections2.filter(
+ changeMessages,
+ m -> {
PatchSet.Id psId = m.getPatchSetId();
if (psId == null) {
return true;
@@ -379,8 +376,7 @@
});
}
- private static void diffChanges(List<String> diffs, ChangeBundle bundleA,
- ChangeBundle bundleB) {
+ private static void diffChanges(List<String> diffs, ChangeBundle bundleA, ChangeBundle bundleB) {
Change a = bundleA.change;
Change b = bundleB.change;
String desc = a.getId().equals(b.getId()) ? describe(a.getId()) : "Changes";
@@ -435,35 +431,33 @@
//
// Use max timestamp of all ReviewDb entities when comparing with NoteDb.
if (bundleA.source == REVIEW_DB && bundleB.source == NOTE_DB) {
- excludeCreatedOn = !timestampsDiffer(
- bundleA, bundleA.getFirstPatchSetTime(), bundleB, b.getCreatedOn());
+ excludeCreatedOn =
+ !timestampsDiffer(bundleA, bundleA.getFirstPatchSetTime(), bundleB, b.getCreatedOn());
aSubj = cleanReviewDbSubject(aSubj);
- excludeCurrentPatchSetId =
- !bundleA.validPatchSetPredicate().apply(a.currentPatchSetId());
+ excludeCurrentPatchSetId = !bundleA.validPatchSetPredicate().apply(a.currentPatchSetId());
excludeSubject = bSubj.startsWith(aSubj) || excludeCurrentPatchSetId;
excludeOrigSubj = true;
String aTopic = trimLeadingOrNull(a.getTopic());
- excludeTopic = Objects.equals(aTopic, b.getTopic())
- || "".equals(aTopic) && b.getTopic() == null;
+ excludeTopic =
+ Objects.equals(aTopic, b.getTopic()) || "".equals(aTopic) && b.getTopic() == null;
aUpdated = bundleA.getLatestTimestamp();
} else if (bundleA.source == NOTE_DB && bundleB.source == REVIEW_DB) {
- excludeCreatedOn = !timestampsDiffer(
- bundleA, a.getCreatedOn(), bundleB, bundleB.getFirstPatchSetTime());
+ excludeCreatedOn =
+ !timestampsDiffer(bundleA, a.getCreatedOn(), bundleB, bundleB.getFirstPatchSetTime());
bSubj = cleanReviewDbSubject(bSubj);
- excludeCurrentPatchSetId =
- !bundleB.validPatchSetPredicate().apply(b.currentPatchSetId());
+ excludeCurrentPatchSetId = !bundleB.validPatchSetPredicate().apply(b.currentPatchSetId());
excludeSubject = aSubj.startsWith(bSubj) || excludeCurrentPatchSetId;
excludeOrigSubj = true;
String bTopic = trimLeadingOrNull(b.getTopic());
- excludeTopic = Objects.equals(bTopic, a.getTopic())
- || a.getTopic() == null && "".equals(bTopic);
+ excludeTopic =
+ Objects.equals(bTopic, a.getTopic()) || a.getTopic() == null && "".equals(bTopic);
bUpdated = bundleB.getLatestTimestamp();
}
String subjectField = "subject";
String updatedField = "lastUpdatedOn";
- List<String> exclude = Lists.newArrayList(
- subjectField, updatedField, "noteDbState", "rowVersion");
+ List<String> exclude =
+ Lists.newArrayList(subjectField, updatedField, "noteDbState", "rowVersion");
if (excludeCreatedOn) {
exclude.add("createdOn");
}
@@ -476,16 +470,14 @@
if (excludeTopic) {
exclude.add("topic");
}
- diffColumnsExcluding(diffs, Change.class, desc, bundleA, a, bundleB, b,
- exclude);
+ diffColumnsExcluding(diffs, Change.class, desc, bundleA, a, bundleB, b, exclude);
// Allow last updated timestamps to either be exactly equal (within slop),
// or the NoteDb timestamp to be equal to the latest entity timestamp in the
// whole ReviewDb bundle (within slop).
- if (timestampsDiffer(bundleA, a.getLastUpdatedOn(),
- bundleB, b.getLastUpdatedOn())) {
- diffTimestamps(diffs, desc, bundleA, aUpdated, bundleB, bUpdated,
- "effective last updated time");
+ if (timestampsDiffer(bundleA, a.getLastUpdatedOn(), bundleB, b.getLastUpdatedOn())) {
+ diffTimestamps(
+ diffs, desc, bundleA, aUpdated, bundleB, bUpdated, "effective last updated time");
}
if (!excludeSubject) {
diffValues(diffs, desc, aSubj, bSubj, subjectField);
@@ -514,22 +506,24 @@
/**
* Set of fields that must always exactly match between ReviewDb and NoteDb.
- * <p>
- * Used to limit the worst-case quadratic search when pairing off matching
- * messages below.
+ *
+ * <p>Used to limit the worst-case quadratic search when pairing off matching messages below.
*/
@AutoValue
abstract static class ChangeMessageCandidate {
static ChangeMessageCandidate create(ChangeMessage cm) {
return new AutoValue_ChangeBundle_ChangeMessageCandidate(
- cm.getAuthor(),
- cm.getMessage(),
- cm.getTag());
+ cm.getAuthor(), cm.getMessage(), cm.getTag());
}
- @Nullable abstract Account.Id author();
- @Nullable abstract String message();
- @Nullable abstract String tag();
+ @Nullable
+ abstract Account.Id author();
+
+ @Nullable
+ abstract String message();
+
+ @Nullable
+ abstract String tag();
// Exclude:
// - patch set, which may be null on ReviewDb side but not NoteDb
@@ -537,14 +531,12 @@
// - writtenOn, which is fuzzy
}
- private static void diffChangeMessages(List<String> diffs,
- ChangeBundle bundleA, ChangeBundle bundleB) {
+ private static void diffChangeMessages(
+ List<String> diffs, ChangeBundle bundleA, ChangeBundle bundleB) {
if (bundleA.source == REVIEW_DB && bundleB.source == REVIEW_DB) {
// Both came from ReviewDb: check all fields exactly.
- Map<ChangeMessage.Key, ChangeMessage> as =
- changeMessageMap(bundleA.filterChangeMessages());
- Map<ChangeMessage.Key, ChangeMessage> bs =
- changeMessageMap(bundleB.filterChangeMessages());
+ Map<ChangeMessage.Key, ChangeMessage> as = changeMessageMap(bundleA.filterChangeMessages());
+ Map<ChangeMessage.Key, ChangeMessage> bs = changeMessageMap(bundleB.filterChangeMessages());
for (ChangeMessage.Key k : diffKeySets(diffs, as, bs)) {
ChangeMessage a = as.get(k);
@@ -562,17 +554,16 @@
// but easy to reason about.
List<ChangeMessage> as = new LinkedList<>(bundleA.filterChangeMessages());
- ListMultimap<ChangeMessageCandidate, ChangeMessage> bs =
- LinkedListMultimap.create();
+ ListMultimap<ChangeMessageCandidate, ChangeMessage> bs = LinkedListMultimap.create();
for (ChangeMessage b : bundleB.filterChangeMessages()) {
bs.put(ChangeMessageCandidate.create(b), b);
}
Iterator<ChangeMessage> ait = as.iterator();
- A: while (ait.hasNext()) {
+ A:
+ while (ait.hasNext()) {
ChangeMessage a = ait.next();
- Iterator<ChangeMessage> bit =
- bs.get(ChangeMessageCandidate.create(a)).iterator();
+ Iterator<ChangeMessage> bit = bs.get(ChangeMessageCandidate.create(a)).iterator();
while (bit.hasNext()) {
ChangeMessage b = bit.next();
if (changeMessagesMatch(bundleA, a, bundleB, b)) {
@@ -586,8 +577,8 @@
if (as.isEmpty() && bs.isEmpty()) {
return;
}
- StringBuilder sb = new StringBuilder("ChangeMessages differ for Change.Id ")
- .append(id).append('\n');
+ StringBuilder sb =
+ new StringBuilder("ChangeMessages differ for Change.Id ").append(id).append('\n');
if (!as.isEmpty()) {
sb.append("Only in A:");
for (ChangeMessage cm : as) {
@@ -607,8 +598,7 @@
}
private static boolean changeMessagesMatch(
- ChangeBundle bundleA, ChangeMessage a,
- ChangeBundle bundleB, ChangeMessage b) {
+ ChangeBundle bundleA, ChangeMessage a, ChangeBundle bundleB, ChangeMessage b) {
List<String> tempDiffs = new ArrayList<>();
String temp = "temp";
@@ -622,12 +612,18 @@
boolean excludeWrittenOn = false;
if (bundleA.source == REVIEW_DB && bundleB.source == NOTE_DB) {
excludePatchSet = a.getPatchSetId() == null;
- excludeWrittenOn = psa != null && psb != null
- && ta.before(psa.getCreatedOn()) && tb.equals(psb.getCreatedOn());
+ excludeWrittenOn =
+ psa != null
+ && psb != null
+ && ta.before(psa.getCreatedOn())
+ && tb.equals(psb.getCreatedOn());
} else if (bundleA.source == NOTE_DB && bundleB.source == REVIEW_DB) {
excludePatchSet = b.getPatchSetId() == null;
- excludeWrittenOn = psa != null && psb != null
- && tb.before(psb.getCreatedOn()) && ta.equals(psa.getCreatedOn());
+ excludeWrittenOn =
+ psa != null
+ && psb != null
+ && tb.before(psb.getCreatedOn())
+ && ta.equals(psa.getCreatedOn());
}
List<String> exclude = Lists.newArrayList("key");
@@ -638,13 +634,12 @@
exclude.add("writtenOn");
}
- diffColumnsExcluding(
- tempDiffs, ChangeMessage.class, temp, bundleA, a, bundleB, b, exclude);
+ diffColumnsExcluding(tempDiffs, ChangeMessage.class, temp, bundleA, a, bundleB, b, exclude);
return tempDiffs.isEmpty();
}
- private static void diffPatchSets(List<String> diffs, ChangeBundle bundleA,
- ChangeBundle bundleB) {
+ private static void diffPatchSets(
+ List<String> diffs, ChangeBundle bundleA, ChangeBundle bundleB) {
Map<PatchSet.Id, PatchSet> as = bundleA.patchSets;
Map<PatchSet.Id, PatchSet> bs = bundleB.patchSets;
for (PatchSet.Id id : diffKeySets(diffs, as, bs)) {
@@ -652,8 +647,7 @@
PatchSet b = bs.get(id);
String desc = describe(id);
String pushCertField = "pushCertificate";
- diffColumnsExcluding(diffs, PatchSet.class, desc, bundleA, a, bundleB, b,
- pushCertField);
+ diffColumnsExcluding(diffs, PatchSet.class, desc, bundleA, a, bundleB, b, pushCertField);
diffValues(diffs, desc, trimPushCert(a), trimPushCert(b), pushCertField);
}
}
@@ -665,12 +659,10 @@
return CharMatcher.is('\n').trimTrailingFrom(ps.getPushCertificate());
}
- private static void diffPatchSetApprovals(List<String> diffs,
- ChangeBundle bundleA, ChangeBundle bundleB) {
- Map<PatchSetApproval.Key, PatchSetApproval> as =
- bundleA.filterPatchSetApprovals();
- Map<PatchSetApproval.Key, PatchSetApproval> bs =
- bundleB.filterPatchSetApprovals();
+ private static void diffPatchSetApprovals(
+ List<String> diffs, ChangeBundle bundleA, ChangeBundle bundleB) {
+ Map<PatchSetApproval.Key, PatchSetApproval> as = bundleA.filterPatchSetApprovals();
+ Map<PatchSetApproval.Key, PatchSetApproval> bs = bundleB.filterPatchSetApprovals();
for (PatchSetApproval.Key k : diffKeySets(diffs, as, bs)) {
PatchSetApproval a = as.get(k);
PatchSetApproval b = bs.get(k);
@@ -692,33 +684,28 @@
if (bundleA.source == REVIEW_DB && bundleB.source == NOTE_DB) {
excludeGranted =
(ta.before(psa.getCreatedOn()) && tb.equals(psb.getCreatedOn()))
- || ta.compareTo(tb) < 0;
+ || ta.compareTo(tb) < 0;
} else if (bundleA.source == NOTE_DB && bundleB.source == REVIEW_DB) {
excludeGranted =
- tb.before(psb.getCreatedOn()) && ta.equals(psa.getCreatedOn())
- || tb.compareTo(ta) < 0;
+ tb.before(psb.getCreatedOn()) && ta.equals(psa.getCreatedOn()) || tb.compareTo(ta) < 0;
}
if (excludeGranted) {
exclude.add("granted");
}
- diffColumnsExcluding(
- diffs, PatchSetApproval.class, desc, bundleA, a, bundleB, b, exclude);
+ diffColumnsExcluding(diffs, PatchSetApproval.class, desc, bundleA, a, bundleB, b, exclude);
}
}
- private static void diffReviewers(List<String> diffs,
- ChangeBundle bundleA, ChangeBundle bundleB) {
- diffSets(
- diffs, bundleA.reviewers.all(), bundleB.reviewers.all(), "reviewer");
+ private static void diffReviewers(
+ List<String> diffs, ChangeBundle bundleA, ChangeBundle bundleB) {
+ diffSets(diffs, bundleA.reviewers.all(), bundleB.reviewers.all(), "reviewer");
}
- private static void diffPatchLineComments(List<String> diffs,
- ChangeBundle bundleA, ChangeBundle bundleB) {
- Map<PatchLineComment.Key, PatchLineComment> as =
- bundleA.filterPatchLineComments();
- Map<PatchLineComment.Key, PatchLineComment> bs =
- bundleB.filterPatchLineComments();
+ private static void diffPatchLineComments(
+ List<String> diffs, ChangeBundle bundleA, ChangeBundle bundleB) {
+ Map<PatchLineComment.Key, PatchLineComment> as = bundleA.filterPatchLineComments();
+ Map<PatchLineComment.Key, PatchLineComment> bs = bundleB.filterPatchLineComments();
for (PatchLineComment.Key k : diffKeySets(diffs, as, bs)) {
PatchLineComment a = as.get(k);
PatchLineComment b = bs.get(k);
@@ -727,18 +714,15 @@
}
}
- private static <T> Set<T> diffKeySets(List<String> diffs, Map<T, ?> a,
- Map<T, ?> b) {
+ private static <T> Set<T> diffKeySets(List<String> diffs, Map<T, ?> a, Map<T, ?> b) {
if (a.isEmpty() && b.isEmpty()) {
return a.keySet();
}
- String clazz =
- keyClass((!a.isEmpty() ? a.keySet() : b.keySet()).iterator().next());
+ String clazz = keyClass((!a.isEmpty() ? a.keySet() : b.keySet()).iterator().next());
return diffSets(diffs, a.keySet(), b.keySet(), clazz);
}
- private static <T> Set<T> diffSets(List<String> diffs, Set<T> as,
- Set<T> bs, String desc) {
+ private static <T> Set<T> diffSets(List<String> diffs, Set<T> as, Set<T> bs, String desc) {
if (as.isEmpty() && bs.isEmpty()) {
return as;
}
@@ -748,26 +732,42 @@
if (aNotB.isEmpty() && bNotA.isEmpty()) {
return as;
}
- diffs.add(desc + " sets differ: " + aNotB + " only in A; "
- + bNotA + " only in B");
+ diffs.add(desc + " sets differ: " + aNotB + " only in A; " + bNotA + " only in B");
return Sets.intersection(as, bs);
}
- private static <T> void diffColumns(List<String> diffs, Class<T> clazz,
- String desc, ChangeBundle bundleA, T a, ChangeBundle bundleB, T b) {
+ private static <T> void diffColumns(
+ List<String> diffs,
+ Class<T> clazz,
+ String desc,
+ ChangeBundle bundleA,
+ T a,
+ ChangeBundle bundleB,
+ T b) {
diffColumnsExcluding(diffs, clazz, desc, bundleA, a, bundleB, b);
}
- private static <T> void diffColumnsExcluding(List<String> diffs,
- Class<T> clazz, String desc, ChangeBundle bundleA, T a,
- ChangeBundle bundleB, T b, String... exclude) {
- diffColumnsExcluding(diffs, clazz, desc, bundleA, a, bundleB, b,
- Arrays.asList(exclude));
+ private static <T> void diffColumnsExcluding(
+ List<String> diffs,
+ Class<T> clazz,
+ String desc,
+ ChangeBundle bundleA,
+ T a,
+ ChangeBundle bundleB,
+ T b,
+ String... exclude) {
+ diffColumnsExcluding(diffs, clazz, desc, bundleA, a, bundleB, b, Arrays.asList(exclude));
}
- private static <T> void diffColumnsExcluding(List<String> diffs,
- Class<T> clazz, String desc, ChangeBundle bundleA, T a,
- ChangeBundle bundleB, T b, Iterable<String> exclude) {
+ private static <T> void diffColumnsExcluding(
+ List<String> diffs,
+ Class<T> clazz,
+ String desc,
+ ChangeBundle bundleA,
+ T a,
+ ChangeBundle bundleB,
+ T b,
+ Iterable<String> exclude) {
Set<String> toExclude = Sets.newLinkedHashSet(exclude);
for (Field f : clazz.getDeclaredFields()) {
Column col = f.getAnnotation(Column.class);
@@ -787,13 +787,20 @@
throw new IllegalArgumentException(e);
}
}
- checkArgument(toExclude.isEmpty(),
+ checkArgument(
+ toExclude.isEmpty(),
"requested columns to exclude not present in %s: %s",
- clazz.getSimpleName(), toExclude);
+ clazz.getSimpleName(),
+ toExclude);
}
- private static void diffTimestamps(List<String> diffs, String desc,
- ChangeBundle bundleA, Object a, ChangeBundle bundleB, Object b,
+ private static void diffTimestamps(
+ List<String> diffs,
+ String desc,
+ ChangeBundle bundleA,
+ Object a,
+ ChangeBundle bundleB,
+ Object b,
String field) {
checkArgument(a.getClass() == b.getClass());
Class<?> clazz = a.getClass();
@@ -806,50 +813,53 @@
f.setAccessible(true);
ta = (Timestamp) f.get(a);
tb = (Timestamp) f.get(b);
- } catch (IllegalAccessException | NoSuchFieldException
- | SecurityException e) {
+ } catch (IllegalAccessException | NoSuchFieldException | SecurityException e) {
throw new IllegalArgumentException(e);
}
diffTimestamps(diffs, desc, bundleA, ta, bundleB, tb, field);
}
- private static void diffTimestamps(List<String> diffs, String desc,
- ChangeBundle bundleA, Timestamp ta, ChangeBundle bundleB, Timestamp tb,
+ private static void diffTimestamps(
+ List<String> diffs,
+ String desc,
+ ChangeBundle bundleA,
+ Timestamp ta,
+ ChangeBundle bundleB,
+ Timestamp tb,
String fieldDesc) {
if (bundleA.source == bundleB.source || ta == null || tb == null) {
diffValues(diffs, desc, ta, tb, fieldDesc);
} else if (bundleA.source == NOTE_DB) {
- diffTimestamps(
- diffs, desc,
- bundleA.getChange(), ta,
- bundleB.getChange(), tb,
- fieldDesc);
+ diffTimestamps(diffs, desc, bundleA.getChange(), ta, bundleB.getChange(), tb, fieldDesc);
} else {
- diffTimestamps(
- diffs, desc,
- bundleB.getChange(), tb,
- bundleA.getChange(), ta,
- fieldDesc);
+ diffTimestamps(diffs, desc, bundleB.getChange(), tb, bundleA.getChange(), ta, fieldDesc);
}
}
- private static boolean timestampsDiffer(ChangeBundle bundleA, Timestamp ta,
- ChangeBundle bundleB, Timestamp tb) {
+ private static boolean timestampsDiffer(
+ ChangeBundle bundleA, Timestamp ta, ChangeBundle bundleB, Timestamp tb) {
List<String> tempDiffs = new ArrayList<>(1);
diffTimestamps(tempDiffs, "temp", bundleA, ta, bundleB, tb, "temp");
return !tempDiffs.isEmpty();
}
- private static void diffTimestamps(List<String> diffs, String desc,
- Change changeFromNoteDb, Timestamp tsFromNoteDb,
- Change changeFromReviewDb, Timestamp tsFromReviewDb,
+ private static void diffTimestamps(
+ List<String> diffs,
+ String desc,
+ Change changeFromNoteDb,
+ Timestamp tsFromNoteDb,
+ Change changeFromReviewDb,
+ Timestamp tsFromReviewDb,
String field) {
// Because ChangeRebuilder may batch events together that are several
// seconds apart, the timestamp in NoteDb may actually be several seconds
// *earlier* than the timestamp in ReviewDb that it was converted from.
- checkArgument(tsFromNoteDb.equals(roundToSecond(tsFromNoteDb)),
+ checkArgument(
+ tsFromNoteDb.equals(roundToSecond(tsFromNoteDb)),
"%s from NoteDb has non-rounded %s timestamp: %s",
- desc, field, tsFromNoteDb);
+ desc,
+ field,
+ tsFromNoteDb);
if (tsFromReviewDb.before(changeFromReviewDb.getCreatedOn())
&& tsFromNoteDb.equals(changeFromNoteDb.getCreatedOn())) {
@@ -859,21 +869,26 @@
return;
}
-
long delta = tsFromReviewDb.getTime() - tsFromNoteDb.getTime();
long max = ChangeRebuilderImpl.MAX_WINDOW_MS;
if (delta < 0 || delta > max) {
diffs.add(
- field + " differs for " + desc + " in NoteDb vs. ReviewDb:"
- + " {" + tsFromNoteDb + "} != {" + tsFromReviewDb + "}");
+ field
+ + " differs for "
+ + desc
+ + " in NoteDb vs. ReviewDb:"
+ + " {"
+ + tsFromNoteDb
+ + "} != {"
+ + tsFromReviewDb
+ + "}");
}
}
- private static void diffValues(List<String> diffs, String desc, Object va,
- Object vb, String name) {
+ private static void diffValues(
+ List<String> diffs, String desc, Object va, Object vb, String name) {
if (!Objects.equals(va, vb)) {
- diffs.add(
- name + " differs for " + desc + ": {" + va + "} != {" + vb + "}");
+ diffs.add(name + " differs for " + desc + ": {" + va + "} != {" + vb + "}");
}
}
@@ -884,8 +899,7 @@
private static String keyClass(Object obj) {
Class<?> clazz = obj.getClass();
String name = clazz.getSimpleName();
- checkArgument(name.endsWith("Key") || name.endsWith("Id"),
- "not an Id/Key class: %s", name);
+ checkArgument(name.endsWith("Key") || name.endsWith("Id"), "not an Id/Key class: %s", name);
if (name.equals("Key") || name.equals("Id")) {
return clazz.getEnclosingClass().getSimpleName() + "." + name;
} else if (name.startsWith("AutoValue_")) {
@@ -896,11 +910,21 @@
@Override
public String toString() {
- return getClass().getSimpleName() + "{id=" + change.getId()
- + ", ChangeMessage[" + changeMessages.size() + "]"
- + ", PatchSet[" + patchSets.size() + "]"
- + ", PatchSetApproval[" + patchSetApprovals.size() + "]"
- + ", PatchLineComment[" + patchLineComments.size() + "]"
+ return getClass().getSimpleName()
+ + "{id="
+ + change.getId()
+ + ", ChangeMessage["
+ + changeMessages.size()
+ + "]"
+ + ", PatchSet["
+ + patchSets.size()
+ + "]"
+ + ", PatchSetApproval["
+ + patchSetApprovals.size()
+ + "]"
+ + ", PatchLineComment["
+ + patchLineComments.size()
+ + "]"
+ "}";
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/ChangeDraftUpdate.java b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/ChangeDraftUpdate.java
index 57d5dce..74ffb96 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/ChangeDraftUpdate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/ChangeDraftUpdate.java
@@ -32,15 +32,6 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
-
-import org.eclipse.jgit.errors.ConfigInvalidException;
-import org.eclipse.jgit.lib.CommitBuilder;
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.lib.ObjectInserter;
-import org.eclipse.jgit.lib.PersonIdent;
-import org.eclipse.jgit.notes.NoteMap;
-import org.eclipse.jgit.revwalk.RevWalk;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
@@ -49,15 +40,21 @@
import java.util.List;
import java.util.Map;
import java.util.Set;
+import org.eclipse.jgit.errors.ConfigInvalidException;
+import org.eclipse.jgit.lib.CommitBuilder;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.lib.ObjectInserter;
+import org.eclipse.jgit.lib.PersonIdent;
+import org.eclipse.jgit.notes.NoteMap;
+import org.eclipse.jgit.revwalk.RevWalk;
/**
* A single delta to apply atomically to a change.
- * <p>
- * This delta contains only draft comments on a single patch set of a change by
- * a single author. This delta will become a single commit in the All-Users
- * repository.
- * <p>
- * This class is not thread safe.
+ *
+ * <p>This delta contains only draft comments on a single patch set of a change by a single author.
+ * This delta will become a single commit in the All-Users repository.
+ *
+ * <p>This class is not thread safe.
*/
public class ChangeDraftUpdate extends AbstractChangeUpdate {
public interface Factory {
@@ -79,6 +76,7 @@
@AutoValue
abstract static class Key {
abstract String revId();
+
abstract Comment.Key key();
}
@@ -103,8 +101,17 @@
@Assisted("real") Account.Id realAccountId,
@Assisted PersonIdent authorIdent,
@Assisted Date when) {
- super(migration, noteUtil, serverIdent, anonymousCowardName, notes, null,
- accountId, realAccountId, authorIdent, when);
+ super(
+ migration,
+ noteUtil,
+ serverIdent,
+ anonymousCowardName,
+ notes,
+ null,
+ accountId,
+ realAccountId,
+ authorIdent,
+ when);
this.draftsProject = allUsers;
}
@@ -120,8 +127,17 @@
@Assisted("real") Account.Id realAccountId,
@Assisted PersonIdent authorIdent,
@Assisted Date when) {
- super(migration, noteUtil, serverIdent, anonymousCowardName, null, change,
- accountId, realAccountId, authorIdent, when);
+ super(
+ migration,
+ noteUtil,
+ serverIdent,
+ anonymousCowardName,
+ null,
+ change,
+ accountId,
+ realAccountId,
+ authorIdent,
+ when);
this.draftsProject = allUsers;
}
@@ -139,12 +155,11 @@
delete.add(new AutoValue_ChangeDraftUpdate_Key(revId, key));
}
- private CommitBuilder storeCommentsInNotes(RevWalk rw, ObjectInserter ins,
- ObjectId curr, CommitBuilder cb)
+ private CommitBuilder storeCommentsInNotes(
+ RevWalk rw, ObjectInserter ins, ObjectId curr, CommitBuilder cb)
throws ConfigInvalidException, OrmException, IOException {
RevisionNoteMap<ChangeRevisionNote> rnm = getRevisionNoteMap(rw, curr);
- Set<RevId> updatedRevs =
- Sets.newHashSetWithExpectedSize(rnm.revisionNotes.size());
+ Set<RevId> updatedRevs = Sets.newHashSetWithExpectedSize(rnm.revisionNotes.size());
RevisionNoteBuilder.Cache cache = new RevisionNoteBuilder.Cache(rnm);
for (Comment c : put) {
@@ -193,21 +208,18 @@
return cb;
}
- private RevisionNoteMap<ChangeRevisionNote> getRevisionNoteMap(RevWalk rw,
- ObjectId curr) throws ConfigInvalidException, OrmException, IOException {
+ private RevisionNoteMap<ChangeRevisionNote> getRevisionNoteMap(RevWalk rw, ObjectId curr)
+ throws ConfigInvalidException, OrmException, IOException {
if (migration.readChanges()) {
// If reading from changes is enabled, then the old DraftCommentNotes
// already parsed the revision notes. We can reuse them as long as the ref
// hasn't advanced.
ChangeNotes changeNotes = getNotes();
if (changeNotes != null) {
- DraftCommentNotes draftNotes =
- changeNotes.load().getDraftCommentNotes();
+ DraftCommentNotes draftNotes = changeNotes.load().getDraftCommentNotes();
if (draftNotes != null) {
- ObjectId idFromNotes =
- firstNonNull(draftNotes.getRevision(), ObjectId.zeroId());
- RevisionNoteMap<ChangeRevisionNote> rnm =
- draftNotes.getRevisionNoteMap();
+ ObjectId idFromNotes = firstNonNull(draftNotes.getRevision(), ObjectId.zeroId());
+ RevisionNoteMap<ChangeRevisionNote> rnm = draftNotes.getRevisionNoteMap();
if (idFromNotes.equals(curr) && rnm != null) {
return rnm;
}
@@ -223,15 +235,12 @@
// Even though reading from changes might not be enabled, we need to
// parse any existing revision notes so we can merge them.
return RevisionNoteMap.parse(
- noteUtil, getId(),
- rw.getObjectReader(),
- noteMap,
- PatchLineComment.Status.DRAFT);
+ noteUtil, getId(), rw.getObjectReader(), noteMap, PatchLineComment.Status.DRAFT);
}
@Override
- protected CommitBuilder applyImpl(RevWalk rw, ObjectInserter ins,
- ObjectId curr) throws OrmException, IOException {
+ protected CommitBuilder applyImpl(RevWalk rw, ObjectInserter ins, ObjectId curr)
+ throws OrmException, IOException {
CommitBuilder cb = new CommitBuilder();
cb.setMessage("Update draft comments");
try {
@@ -253,7 +262,6 @@
@Override
public boolean isEmpty() {
- return delete.isEmpty()
- && put.isEmpty();
+ return delete.isEmpty() && put.isEmpty();
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/ChangeNoteUtil.java b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/ChangeNoteUtil.java
index d47e462..425575e 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/ChangeNoteUtil.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/ChangeNoteUtil.java
@@ -37,18 +37,6 @@
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.inject.Inject;
-
-import org.eclipse.jgit.errors.ConfigInvalidException;
-import org.eclipse.jgit.lib.Config;
-import org.eclipse.jgit.lib.PersonIdent;
-import org.eclipse.jgit.revwalk.FooterKey;
-import org.eclipse.jgit.util.GitDateFormatter;
-import org.eclipse.jgit.util.GitDateFormatter.Format;
-import org.eclipse.jgit.util.GitDateParser;
-import org.eclipse.jgit.util.MutableInteger;
-import org.eclipse.jgit.util.QuotedString;
-import org.eclipse.jgit.util.RawParseUtils;
-
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
@@ -61,6 +49,16 @@
import java.util.List;
import java.util.Locale;
import java.util.Set;
+import org.eclipse.jgit.errors.ConfigInvalidException;
+import org.eclipse.jgit.lib.Config;
+import org.eclipse.jgit.lib.PersonIdent;
+import org.eclipse.jgit.revwalk.FooterKey;
+import org.eclipse.jgit.util.GitDateFormatter;
+import org.eclipse.jgit.util.GitDateFormatter.Format;
+import org.eclipse.jgit.util.GitDateParser;
+import org.eclipse.jgit.util.MutableInteger;
+import org.eclipse.jgit.util.QuotedString;
+import org.eclipse.jgit.util.RawParseUtils;
public class ChangeNoteUtil {
public static final FooterKey FOOTER_ASSIGNEE = new FooterKey("Assignee");
@@ -77,10 +75,8 @@
public static final FooterKey FOOTER_REAL_USER = new FooterKey("Real-user");
public static final FooterKey FOOTER_STATUS = new FooterKey("Status");
public static final FooterKey FOOTER_SUBJECT = new FooterKey("Subject");
- public static final FooterKey FOOTER_SUBMISSION_ID =
- new FooterKey("Submission-id");
- public static final FooterKey FOOTER_SUBMITTED_WITH =
- new FooterKey("Submitted-with");
+ public static final FooterKey FOOTER_SUBMISSION_ID = new FooterKey("Submission-id");
+ public static final FooterKey FOOTER_SUBMITTED_WITH = new FooterKey("Submitted-with");
public static final FooterKey FOOTER_TOPIC = new FooterKey("Topic");
public static final FooterKey FOOTER_TAG = new FooterKey("Tag");
@@ -113,7 +109,8 @@
private final boolean writeJson;
@Inject
- public ChangeNoteUtil(AccountCache accountCache,
+ public ChangeNoteUtil(
+ AccountCache accountCache,
@GerritPersonIdent PersonIdent serverIdent,
@AnonymousCowardName String anonymousCowardName,
@GerritServerId String serverId,
@@ -126,12 +123,13 @@
}
@VisibleForTesting
- public PersonIdent newIdent(Account author, Date when,
- PersonIdent serverIdent, String anonymousCowardName) {
+ public PersonIdent newIdent(
+ Account author, Date when, PersonIdent serverIdent, String anonymousCowardName) {
return new PersonIdent(
author.getName(anonymousCowardName),
author.getId().get() + "@" + serverId,
- when, serverIdent.getTimeZone());
+ when,
+ serverIdent.getTimeZone());
}
public boolean getWriteJson() {
@@ -159,8 +157,7 @@
}
}
}
- throw parseException(changeId, "invalid identity, expected <id>@%s: %s",
- serverId, email);
+ throw parseException(changeId, "invalid identity, expected <id>@%s: %s", serverId, email);
}
private static boolean match(byte[] note, MutableInteger p, byte[] expected) {
@@ -168,8 +165,8 @@
return m == p.value + expected.length;
}
- public List<Comment> parseNote(byte[] note, MutableInteger p,
- Change.Id changeId) throws ConfigInvalidException {
+ public List<Comment> parseNote(byte[] note, MutableInteger p, Change.Id changeId)
+ throws ConfigInvalidException {
if (p.value >= note.length) {
return ImmutableList.of();
}
@@ -201,30 +198,32 @@
parentNumber = parseParentNumber(note, p, changeId);
}
} else if (psId == null) {
- throw parseException(changeId, "missing %s or %s header",
- PATCH_SET, BASE_PATCH_SET);
+ throw parseException(changeId, "missing %s or %s header", PATCH_SET, BASE_PATCH_SET);
}
- Comment c = parseComment(
- note, p, fileName, psId, revId, isForBase, parentNumber);
+ Comment c = parseComment(note, p, fileName, psId, revId, isForBase, parentNumber);
fileName = c.key.filename;
if (!seen.add(c.key)) {
- throw parseException(
- changeId, "multiple comments for %s in note", c.key);
+ throw parseException(changeId, "multiple comments for %s in note", c.key);
}
result.add(c);
}
return result;
}
- private Comment parseComment(byte[] note, MutableInteger curr,
- String currentFileName, PatchSet.Id psId, RevId revId, boolean isForBase,
- Integer parentNumber) throws ConfigInvalidException {
+ private Comment parseComment(
+ byte[] note,
+ MutableInteger curr,
+ String currentFileName,
+ PatchSet.Id psId,
+ RevId revId,
+ boolean isForBase,
+ Integer parentNumber)
+ throws ConfigInvalidException {
Change.Id changeId = psId.getParentKey();
// Check if there is a new file.
- boolean newFile =
- (RawParseUtils.match(note, curr.value, FILE.getBytes(UTF_8))) != -1;
+ boolean newFile = (RawParseUtils.match(note, curr.value, FILE.getBytes(UTF_8))) != -1;
if (newFile) {
// If so, parse the new file name.
currentFileName = parseFilename(note, curr, changeId);
@@ -240,31 +239,27 @@
Timestamp commentTime = parseTimestamp(note, curr, changeId);
Account.Id aId = parseAuthor(note, curr, changeId, AUTHOR);
boolean hasRealAuthor =
- (RawParseUtils.match(note, curr.value, REAL_AUTHOR.getBytes(UTF_8)))
- != -1;
+ (RawParseUtils.match(note, curr.value, REAL_AUTHOR.getBytes(UTF_8))) != -1;
Account.Id raId = null;
if (hasRealAuthor) {
raId = parseAuthor(note, curr, changeId, REAL_AUTHOR);
}
- boolean hasParent =
- (RawParseUtils.match(note, curr.value, PARENT.getBytes(UTF_8))) != -1;
+ boolean hasParent = (RawParseUtils.match(note, curr.value, PARENT.getBytes(UTF_8))) != -1;
String parentUUID = null;
boolean unresolved = false;
if (hasParent) {
parentUUID = parseStringField(note, curr, changeId, PARENT);
}
boolean hasUnresolved =
- (RawParseUtils.match(note, curr.value,
- UNRESOLVED.getBytes(UTF_8))) != -1;
+ (RawParseUtils.match(note, curr.value, UNRESOLVED.getBytes(UTF_8))) != -1;
if (hasUnresolved) {
unresolved = parseBooleanField(note, curr, changeId, UNRESOLVED);
}
String uuid = parseStringField(note, curr, changeId, UUID);
- boolean hasTag =
- (RawParseUtils.match(note, curr.value, TAG.getBytes(UTF_8))) != -1;
+ boolean hasTag = (RawParseUtils.match(note, curr.value, TAG.getBytes(UTF_8))) != -1;
String tag = null;
if (hasTag) {
tag = parseStringField(note, curr, changeId, TAG);
@@ -272,20 +267,18 @@
int commentLength = parseCommentLength(note, curr, changeId);
- String message = RawParseUtils.decode(
- UTF_8, note, curr.value, curr.value + commentLength);
+ String message = RawParseUtils.decode(UTF_8, note, curr.value, curr.value + commentLength);
checkResult(message, "message contents", changeId);
- Comment c = new Comment(
- new Comment.Key(uuid, currentFileName, psId.get()),
- aId,
- commentTime,
- isForBase
- ? (short) (parentNumber == null ? 0 : -parentNumber)
- : (short) 1,
- message,
- serverId,
- unresolved);
+ Comment c =
+ new Comment(
+ new Comment.Key(uuid, currentFileName, psId.get()),
+ aId,
+ commentTime,
+ isForBase ? (short) (parentNumber == null ? 0 : -parentNumber) : (short) 1,
+ message,
+ serverId,
+ unresolved);
c.lineNbr = range.getEndLine();
c.parentUuid = parentUUID;
c.tag = tag;
@@ -303,8 +296,9 @@
return c;
}
- private static String parseStringField(byte[] note, MutableInteger curr,
- Change.Id changeId, String fieldName) throws ConfigInvalidException {
+ private static String parseStringField(
+ byte[] note, MutableInteger curr, Change.Id changeId, String fieldName)
+ throws ConfigInvalidException {
int endOfLine = RawParseUtils.nextLF(note, curr.value);
checkHeaderLineFormat(note, curr, fieldName, changeId);
int startOfField = RawParseUtils.endOfFooterLineKey(note, curr.value) + 2;
@@ -313,11 +307,10 @@
}
/**
- * @return a comment range. If the comment range line in the note only has
- * one number, we return a CommentRange with that one number as the end
- * line and the other fields as -1. If the comment range line in the note
- * contains a whole comment range, then we return a CommentRange with all
- * fields set. If the line is not correctly formatted, return null.
+ * @return a comment range. If the comment range line in the note only has one number, we return a
+ * CommentRange with that one number as the end line and the other fields as -1. If the
+ * comment range line in the note contains a whole comment range, then we return a
+ * CommentRange with all fields set. If the line is not correctly formatted, return null.
*/
private static CommentRange parseCommentRange(byte[] note, MutableInteger ptr) {
CommentRange range = new CommentRange(-1, -1, -1, -1);
@@ -372,14 +365,13 @@
return range;
}
- private static PatchSet.Id parsePsId(byte[] note, MutableInteger curr,
- Change.Id changeId, String fieldName) throws ConfigInvalidException {
+ private static PatchSet.Id parsePsId(
+ byte[] note, MutableInteger curr, Change.Id changeId, String fieldName)
+ throws ConfigInvalidException {
checkHeaderLineFormat(note, curr, fieldName, changeId);
- int startOfPsId =
- RawParseUtils.endOfFooterLineKey(note, curr.value) + 1;
+ int startOfPsId = RawParseUtils.endOfFooterLineKey(note, curr.value) + 1;
MutableInteger i = new MutableInteger();
- int patchSetId =
- RawParseUtils.parseBase10(note, startOfPsId, i);
+ int patchSetId = RawParseUtils.parseBase10(note, startOfPsId, i);
int endOfLine = RawParseUtils.nextLF(note, curr.value);
if (i.value != endOfLine - 1) {
throw parseException(changeId, "could not parse %s", fieldName);
@@ -389,8 +381,8 @@
return new PatchSet.Id(changeId, patchSetId);
}
- private static Integer parseParentNumber(byte[] note, MutableInteger curr,
- Change.Id changeId) throws ConfigInvalidException {
+ private static Integer parseParentNumber(byte[] note, MutableInteger curr, Change.Id changeId)
+ throws ConfigInvalidException {
checkHeaderLineFormat(note, curr, PARENT_NUMBER, changeId);
int start = RawParseUtils.endOfFooterLineKey(note, curr.value) + 1;
@@ -403,14 +395,12 @@
checkResult(parentNumber, "parent number", changeId);
curr.value = endOfLine;
return Integer.valueOf(parentNumber);
-
}
- private static String parseFilename(byte[] note, MutableInteger curr,
- Change.Id changeId) throws ConfigInvalidException {
+ private static String parseFilename(byte[] note, MutableInteger curr, Change.Id changeId)
+ throws ConfigInvalidException {
checkHeaderLineFormat(note, curr, FILE, changeId);
- int startOfFileName =
- RawParseUtils.endOfFooterLineKey(note, curr.value) + 2;
+ int startOfFileName = RawParseUtils.endOfFooterLineKey(note, curr.value) + 2;
int endOfLine = RawParseUtils.nextLF(note, curr.value);
curr.value = endOfLine;
curr.value = RawParseUtils.nextLF(note, curr.value);
@@ -418,15 +408,13 @@
RawParseUtils.decode(UTF_8, note, startOfFileName, endOfLine - 1));
}
- private static Timestamp parseTimestamp(byte[] note, MutableInteger curr,
- Change.Id changeId) throws ConfigInvalidException {
+ private static Timestamp parseTimestamp(byte[] note, MutableInteger curr, Change.Id changeId)
+ throws ConfigInvalidException {
int endOfLine = RawParseUtils.nextLF(note, curr.value);
Timestamp commentTime;
- String dateString =
- RawParseUtils.decode(UTF_8, note, curr.value, endOfLine - 1);
+ String dateString = RawParseUtils.decode(UTF_8, note, curr.value, endOfLine - 1);
try {
- commentTime = new Timestamp(
- GitDateParser.parse(dateString, null, Locale.US).getTime());
+ commentTime = new Timestamp(GitDateParser.parse(dateString, null, Locale.US).getTime());
} catch (ParseException e) {
throw new ConfigInvalidException("could not parse comment timestamp", e);
}
@@ -434,27 +422,24 @@
return checkResult(commentTime, "comment timestamp", changeId);
}
- private Account.Id parseAuthor(byte[] note, MutableInteger curr,
- Change.Id changeId, String fieldName) throws ConfigInvalidException {
+ private Account.Id parseAuthor(
+ byte[] note, MutableInteger curr, Change.Id changeId, String fieldName)
+ throws ConfigInvalidException {
checkHeaderLineFormat(note, curr, fieldName, changeId);
- int startOfAccountId =
- RawParseUtils.endOfFooterLineKey(note, curr.value) + 2;
- PersonIdent ident =
- RawParseUtils.parsePersonIdent(note, startOfAccountId);
+ int startOfAccountId = RawParseUtils.endOfFooterLineKey(note, curr.value) + 2;
+ PersonIdent ident = RawParseUtils.parsePersonIdent(note, startOfAccountId);
Account.Id aId = parseIdent(ident, changeId);
curr.value = RawParseUtils.nextLF(note, curr.value);
return checkResult(aId, fieldName, changeId);
}
- private static int parseCommentLength(byte[] note, MutableInteger curr,
- Change.Id changeId) throws ConfigInvalidException {
+ private static int parseCommentLength(byte[] note, MutableInteger curr, Change.Id changeId)
+ throws ConfigInvalidException {
checkHeaderLineFormat(note, curr, LENGTH, changeId);
- int startOfLength =
- RawParseUtils.endOfFooterLineKey(note, curr.value) + 1;
+ int startOfLength = RawParseUtils.endOfFooterLineKey(note, curr.value) + 1;
MutableInteger i = new MutableInteger();
i.value = startOfLength;
- int commentLength =
- RawParseUtils.parseBase10(note, startOfLength, i);
+ int commentLength = RawParseUtils.parseBase10(note, startOfLength, i);
if (i.value == startOfLength) {
throw parseException(changeId, "could not parse %s", LENGTH);
}
@@ -466,19 +451,20 @@
return checkResult(commentLength, "comment length", changeId);
}
- private boolean parseBooleanField(byte[] note, MutableInteger curr,
- Change.Id changeId, String fieldName) throws ConfigInvalidException {
+ private boolean parseBooleanField(
+ byte[] note, MutableInteger curr, Change.Id changeId, String fieldName)
+ throws ConfigInvalidException {
String str = parseStringField(note, curr, changeId, fieldName);
if ("true".equalsIgnoreCase(str)) {
return true;
} else if ("false".equalsIgnoreCase(str)) {
return false;
- }
- throw parseException(changeId, "invalid boolean for %s: %s", fieldName, str);
+ }
+ throw parseException(changeId, "invalid boolean for %s: %s", fieldName, str);
}
- private static <T> T checkResult(T o, String fieldName,
- Change.Id changeId) throws ConfigInvalidException {
+ private static <T> T checkResult(T o, String fieldName, Change.Id changeId)
+ throws ConfigInvalidException {
if (o == null) {
throw parseException(changeId, "could not parse %s", fieldName);
}
@@ -493,18 +479,17 @@
return i;
}
- private void appendHeaderField(PrintWriter writer,
- String field, String value) {
+ private void appendHeaderField(PrintWriter writer, String field, String value) {
writer.print(field);
writer.print(": ");
writer.print(value);
writer.print('\n');
}
- private static void checkHeaderLineFormat(byte[] note, MutableInteger curr,
- String fieldName, Change.Id changeId) throws ConfigInvalidException {
- boolean correct =
- RawParseUtils.match(note, curr.value, fieldName.getBytes(UTF_8)) != -1;
+ private static void checkHeaderLineFormat(
+ byte[] note, MutableInteger curr, String fieldName, Change.Id changeId)
+ throws ConfigInvalidException {
+ boolean correct = RawParseUtils.match(note, curr.value, fieldName.getBytes(UTF_8)) != -1;
int p = curr.value + fieldName.length();
correct &= (p < note.length && note[p] == ':');
p++;
@@ -515,18 +500,16 @@
}
/**
- * Build a note that contains the metadata for and the contents of all of the
- * comments in the given comments.
+ * Build a note that contains the metadata for and the contents of all of the comments in the
+ * given comments.
*
- * @param comments Comments to be written to the output stream, keyed by patch
- * set ID; multiple patch sets are allowed since base revisions may be
- * shared across patch sets. All of the comments must share the same
- * RevId, and all the comments for a given patch set must have the same
- * side.
+ * @param comments Comments to be written to the output stream, keyed by patch set ID; multiple
+ * patch sets are allowed since base revisions may be shared across patch sets. All of the
+ * comments must share the same RevId, and all the comments for a given patch set must have
+ * the same side.
* @param out output stream to write to.
*/
- void buildNote(ListMultimap<Integer, Comment> comments,
- OutputStream out) {
+ void buildNote(ListMultimap<Integer, Comment> comments, OutputStream out) {
if (comments.isEmpty()) {
return;
}
@@ -544,10 +527,7 @@
Comment first = psComments.get(0);
short side = first.side;
- appendHeaderField(writer, side <= 0
- ? BASE_PATCH_SET
- : PATCH_SET,
- Integer.toString(psId));
+ appendHeaderField(writer, side <= 0 ? BASE_PATCH_SET : PATCH_SET, Integer.toString(psId));
if (side < 0) {
appendHeaderField(writer, PARENT_NUMBER, Integer.toString(-side));
}
@@ -555,14 +535,20 @@
String currentFilename = null;
for (Comment c : psComments) {
- checkArgument(revId.equals(c.revId),
+ checkArgument(
+ revId.equals(c.revId),
"All comments being added must have all the same RevId. The "
- + "comment below does not have the same RevId as the others "
- + "(%s).\n%s", revId, c);
- checkArgument(side == c.side,
+ + "comment below does not have the same RevId as the others "
+ + "(%s).\n%s",
+ revId,
+ c);
+ checkArgument(
+ side == c.side,
"All comments being added must all have the same side. The "
- + "comment below does not have the same side as the others "
- + "(%s).\n%s", side, c);
+ + "comment below does not have the same side as the others "
+ + "(%s).\n%s",
+ side,
+ c);
String commentFilename = QuotedString.GIT_PATH.quote(c.key.filename);
if (!commentFilename.equals(currentFilename)) {
@@ -617,18 +603,15 @@
}
byte[] messageBytes = c.message.getBytes(UTF_8);
- appendHeaderField(writer, LENGTH,
- Integer.toString(messageBytes.length));
+ appendHeaderField(writer, LENGTH, Integer.toString(messageBytes.length));
writer.print(c.message);
writer.print("\n\n");
}
- private void appendIdent(PrintWriter writer, String header, Account.Id id,
- Timestamp ts) {
- PersonIdent ident = newIdent(
- accountCache.get(id).getAccount(),
- ts, serverIdent, anonymousCowardName);
+ private void appendIdent(PrintWriter writer, String header, Account.Id id, Timestamp ts) {
+ PersonIdent ident =
+ newIdent(accountCache.get(id).getAccount(), ts, serverIdent, anonymousCowardName);
StringBuilder name = new StringBuilder();
PersonIdent.appendSanitized(name, ident.getName());
name.append(" <");
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/ChangeNotes.java b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/ChangeNotes.java
index ee9f4f7..b15874d 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/ChangeNotes.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/ChangeNotes.java
@@ -62,14 +62,6 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.errors.ConfigInvalidException;
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.lib.Ref;
-import org.eclipse.jgit.lib.Repository;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
@@ -79,6 +71,12 @@
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.function.Predicate;
+import org.eclipse.jgit.errors.ConfigInvalidException;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.lib.Ref;
+import org.eclipse.jgit.lib.Repository;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/** View of a single {@link Change} based on the log of its notes branch. */
public class ChangeNotes extends AbstractChangeNotes<ChangeNotes> {
@@ -90,14 +88,12 @@
public static final Ordering<ChangeMessage> MESSAGE_BY_TIME =
Ordering.from(comparing(ChangeMessage::getWrittenOn));
- public static ConfigInvalidException parseException(Change.Id changeId,
- String fmt, Object... args) {
- return new ConfigInvalidException("Change " + changeId + ": "
- + String.format(fmt, args));
+ public static ConfigInvalidException parseException(
+ Change.Id changeId, String fmt, Object... args) {
+ return new ConfigInvalidException("Change " + changeId + ": " + String.format(fmt, args));
}
- public static Change readOneReviewDbChange(ReviewDb db, Change.Id id)
- throws OrmException {
+ public static Change readOneReviewDbChange(ReviewDb db, Change.Id id) throws OrmException {
return ReviewDbUtil.unwrapDb(db).changes().get(id);
}
@@ -109,21 +105,19 @@
@VisibleForTesting
@Inject
- public Factory(Args args,
- Provider<InternalChangeQuery> queryProvider,
- ProjectCache projectCache) {
+ public Factory(
+ Args args, Provider<InternalChangeQuery> queryProvider, ProjectCache projectCache) {
this.args = args;
this.queryProvider = queryProvider;
this.projectCache = projectCache;
}
- public ChangeNotes createChecked(ReviewDb db, Change c)
- throws OrmException {
+ public ChangeNotes createChecked(ReviewDb db, Change c) throws OrmException {
return createChecked(db, c.getProject(), c.getId());
}
- public ChangeNotes createChecked(ReviewDb db, Project.NameKey project,
- Change.Id changeId) throws OrmException {
+ public ChangeNotes createChecked(ReviewDb db, Project.NameKey project, Change.Id changeId)
+ throws OrmException {
Change change = readOneReviewDbChange(db, changeId);
if (change == null) {
if (!args.migration.readChanges()) {
@@ -145,25 +139,22 @@
throw new NoSuchChangeException(changeId);
}
if (changes.size() != 1) {
- log.error(
- String.format("Multiple changes found for %d", changeId.get()));
+ log.error(String.format("Multiple changes found for %d", changeId.get()));
throw new NoSuchChangeException(changeId);
}
return changes.get(0).notes();
}
- public static Change newNoteDbOnlyChange(
- Project.NameKey project, Change.Id changeId) {
- Change change = new Change(
- null, changeId, null,
- new Branch.NameKey(project, "INVALID_NOTE_DB_ONLY"),
- null);
+ public static Change newNoteDbOnlyChange(Project.NameKey project, Change.Id changeId) {
+ Change change =
+ new Change(
+ null, changeId, null, new Branch.NameKey(project, "INVALID_NOTE_DB_ONLY"), null);
change.setNoteDbState(NoteDbChangeState.NOTE_DB_PRIMARY_STATE);
return change;
}
- private Change loadChangeFromDb(ReviewDb db, Project.NameKey project,
- Change.Id changeId) throws OrmException {
+ private Change loadChangeFromDb(ReviewDb db, Project.NameKey project, Change.Id changeId)
+ throws OrmException {
checkArgument(project != null, "project is required");
Change change = readOneReviewDbChange(db, changeId);
@@ -173,10 +164,12 @@
change = newNoteDbOnlyChange(project, changeId);
} else {
checkNotNull(change, "change %s not found in ReviewDb", changeId);
- checkArgument(change.getProject().equals(project),
- "passed project %s when creating ChangeNotes for %s, but actual"
- + " project is %s",
- project, changeId, change.getProject());
+ checkArgument(
+ change.getProject().equals(project),
+ "passed project %s when creating ChangeNotes for %s, but actual" + " project is %s",
+ project,
+ changeId,
+ change.getProject());
}
// TODO: Throw NoSuchChangeException when the change is not found in the
@@ -184,22 +177,20 @@
return change;
}
- public ChangeNotes create(ReviewDb db, Project.NameKey project,
- Change.Id changeId) throws OrmException {
- return new ChangeNotes(args, loadChangeFromDb(db, project, changeId))
+ public ChangeNotes create(ReviewDb db, Project.NameKey project, Change.Id changeId)
+ throws OrmException {
+ return new ChangeNotes(args, loadChangeFromDb(db, project, changeId)).load();
+ }
+
+ public ChangeNotes createWithAutoRebuildingDisabled(
+ ReviewDb db, Project.NameKey project, Change.Id changeId) throws OrmException {
+ return new ChangeNotes(args, loadChangeFromDb(db, project, changeId), true, false, null)
.load();
}
- public ChangeNotes createWithAutoRebuildingDisabled(ReviewDb db,
- Project.NameKey project, Change.Id changeId) throws OrmException {
- return new ChangeNotes(
- args, loadChangeFromDb(db, project, changeId), true, false, null).load();
- }
-
/**
- * Create change notes for a change that was loaded from index. This method
- * should only be used when database access is harmful and potentially stale
- * data from the index is acceptable.
+ * Create change notes for a change that was loaded from index. This method should only be used
+ * when database access is harmful and potentially stale data from the index is acceptable.
*
* @param change change loaded from secondary index
* @return change notes
@@ -213,25 +204,24 @@
return new ChangeNotes(args, change, shouldExist, false, null).load();
}
- public ChangeNotes createWithAutoRebuildingDisabled(Change change,
- RefCache refs) throws OrmException {
+ public ChangeNotes createWithAutoRebuildingDisabled(Change change, RefCache refs)
+ throws OrmException {
return new ChangeNotes(args, change, true, false, refs).load();
}
// TODO(ekempin): Remove when database backend is deleted
/**
- * Instantiate ChangeNotes for a change that has been loaded by a batch read
- * from the database.
+ * Instantiate ChangeNotes for a change that has been loaded by a batch read from the database.
*/
- private ChangeNotes createFromChangeOnlyWhenNoteDbDisabled(Change change)
- throws OrmException {
- checkState(!args.migration.readChanges(), "do not call"
- + " createFromChangeWhenNoteDbDisabled when NoteDb is enabled");
+ private ChangeNotes createFromChangeOnlyWhenNoteDbDisabled(Change change) throws OrmException {
+ checkState(
+ !args.migration.readChanges(),
+ "do not call" + " createFromChangeWhenNoteDbDisabled when NoteDb is enabled");
return new ChangeNotes(args, change).load();
}
- public List<ChangeNotes> create(ReviewDb db,
- Collection<Change.Id> changeIds) throws OrmException {
+ public List<ChangeNotes> create(ReviewDb db, Collection<Change.Id> changeIds)
+ throws OrmException {
List<ChangeNotes> notes = new ArrayList<>();
if (args.migration.enabled()) {
for (Change.Id changeId : changeIds) {
@@ -250,8 +240,11 @@
return notes;
}
- public List<ChangeNotes> create(ReviewDb db, Project.NameKey project,
- Collection<Change.Id> changeIds, Predicate<ChangeNotes> predicate)
+ public List<ChangeNotes> create(
+ ReviewDb db,
+ Project.NameKey project,
+ Collection<Change.Id> changeIds,
+ Predicate<ChangeNotes> predicate)
throws OrmException {
List<ChangeNotes> notes = new ArrayList<>();
if (args.migration.enabled()) {
@@ -275,8 +268,8 @@
return notes;
}
- public ListMultimap<Project.NameKey, ChangeNotes> create(ReviewDb db,
- Predicate<ChangeNotes> predicate) throws IOException, OrmException {
+ public ListMultimap<Project.NameKey, ChangeNotes> create(
+ ReviewDb db, Predicate<ChangeNotes> predicate) throws IOException, OrmException {
ListMultimap<Project.NameKey, ChangeNotes> m =
MultimapBuilder.hashKeys().arrayListValues().build();
if (args.migration.readChanges()) {
@@ -301,8 +294,8 @@
return ImmutableListMultimap.copyOf(m);
}
- public List<ChangeNotes> scan(Repository repo, ReviewDb db,
- Project.NameKey project) throws OrmException, IOException {
+ public List<ChangeNotes> scan(Repository repo, ReviewDb db, Project.NameKey project)
+ throws OrmException, IOException {
if (!args.migration.readChanges()) {
return scanDb(repo, db);
}
@@ -324,8 +317,8 @@
return notes;
}
- private List<ChangeNotes> scanNoteDb(Repository repo, ReviewDb db,
- Project.NameKey project) throws OrmException, IOException {
+ private List<ChangeNotes> scanNoteDb(Repository repo, ReviewDb db, Project.NameKey project)
+ throws OrmException, IOException {
Set<Change.Id> ids = scan(repo);
List<ChangeNotes> changeNotes = new ArrayList<>(ids.size());
PrimaryStorage defaultStorage = args.migration.changePrimaryStorage();
@@ -333,30 +326,28 @@
Change change = readOneReviewDbChange(db, id);
if (change == null) {
if (defaultStorage == PrimaryStorage.REVIEW_DB) {
- log.warn("skipping change {} found in project {} " +
- "but not in ReviewDb",
- id, project);
+ log.warn(
+ "skipping change {} found in project {} " + "but not in ReviewDb", id, project);
continue;
}
// TODO(dborowitz): See discussion in BatchUpdate#newChangeContext.
change = newNoteDbOnlyChange(project, id);
} else if (!change.getProject().equals(project)) {
log.error(
- "skipping change {} found in project {} " +
- "because ReviewDb change has project {}",
- id, project, change.getProject());
+ "skipping change {} found in project {} " + "because ReviewDb change has project {}",
+ id,
+ project,
+ change.getProject());
continue;
}
log.debug("adding change {} found in project {}", id, project);
changeNotes.add(new ChangeNotes(args, change).load());
-
}
return changeNotes;
}
public static Set<Change.Id> scan(Repository repo) throws IOException {
- Map<String, Ref> refs =
- repo.getRefDatabase().getRefs(RefNames.REFS_CHANGES);
+ Map<String, Ref> refs = repo.getRefDatabase().getRefs(RefNames.REFS_CHANGES);
Set<Change.Id> ids = new HashSet<>(refs.size());
for (Ref r : refs.values()) {
Change.Id id = Change.Id.fromRef(r.getName());
@@ -393,8 +384,8 @@
this(args, change, true, true, null);
}
- private ChangeNotes(Args args, Change change, boolean shouldExist,
- boolean autoRebuild, @Nullable RefCache refs) {
+ private ChangeNotes(
+ Args args, Change change, boolean shouldExist, boolean autoRebuild, @Nullable RefCache refs) {
super(args, change.getId(), PrimaryStorage.of(change), autoRebuild);
this.change = new Change(change);
this.shouldExist = shouldExist;
@@ -441,32 +432,24 @@
return state.reviewerUpdates();
}
- /**
- * @return an ImmutableSet of Account.Ids of all users that have been assigned
- * to this change.
- */
+ /** @return an ImmutableSet of Account.Ids of all users that have been assigned to this change. */
public ImmutableSet<Account.Id> getPastAssignees() {
return state.pastAssignees();
}
- /**
- * @return a ImmutableSet of all hashtags for this change sorted in
- * alphabetical order.
- */
+ /** @return a ImmutableSet of all hashtags for this change sorted in alphabetical order. */
public ImmutableSet<String> getHashtags() {
return ImmutableSortedSet.copyOf(state.hashtags());
}
- /**
- * @return a list of all users who have ever been a reviewer on this change.
- */
+ /** @return a list of all users who have ever been a reviewer on this change. */
public ImmutableList<Account.Id> getAllPastReviewers() {
return state.allPastReviewers();
}
/**
- * @return submit records stored during the most recent submit; only for
- * changes that were actually submitted.
+ * @return submit records stored during the most recent submit; only for changes that were
+ * actually submitted.
*/
public ImmutableList<SubmitRecord> getSubmitRecords() {
return state.submitRecords();
@@ -477,12 +460,8 @@
return state.allChangeMessages();
}
- /**
- * @return change messages by patch set, in chronological order, oldest
- * first.
- */
- public ImmutableListMultimap<PatchSet.Id, ChangeMessage>
- getChangeMessagesByPatchSet() {
+ /** @return change messages by patch set, in chronological order, oldest first. */
+ public ImmutableListMultimap<PatchSet.Id, ChangeMessage> getChangeMessagesByPatchSet() {
return state.changeMessagesByPatchSet();
}
@@ -502,8 +481,8 @@
return commentKeys;
}
- public ImmutableListMultimap<RevId, Comment> getDraftComments(
- Account.Id author) throws OrmException {
+ public ImmutableListMultimap<RevId, Comment> getDraftComments(Account.Id author)
+ throws OrmException {
return getDraftComments(author, null);
}
@@ -515,29 +494,23 @@
// during the publish operation failed.
return ImmutableListMultimap.copyOf(
Multimaps.filterEntries(
- draftCommentNotes.getComments(),
- e -> !getCommentKeys().contains(e.getValue().key)));
+ draftCommentNotes.getComments(), e -> !getCommentKeys().contains(e.getValue().key)));
}
- public ImmutableListMultimap<RevId, RobotComment> getRobotComments()
- throws OrmException {
+ public ImmutableListMultimap<RevId, RobotComment> getRobotComments() throws OrmException {
loadRobotComments();
return robotCommentNotes.getComments();
}
/**
- * If draft comments have already been loaded for this author, then they will
- * not be reloaded. However, this method will load the comments if no draft
- * comments have been loaded or if the caller would like the drafts for
- * another author.
+ * If draft comments have already been loaded for this author, then they will not be reloaded.
+ * However, this method will load the comments if no draft comments have been loaded or if the
+ * caller would like the drafts for another author.
*/
- private void loadDraftComments(Account.Id author, @Nullable Ref ref)
- throws OrmException {
- if (draftCommentNotes == null
- || !author.equals(draftCommentNotes.getAuthor())
- || ref != null) {
- draftCommentNotes = new DraftCommentNotes(
- args, change, author, autoRebuild, rebuildResult, ref);
+ private void loadDraftComments(Account.Id author, @Nullable Ref ref) throws OrmException {
+ if (draftCommentNotes == null || !author.equals(draftCommentNotes.getAuthor()) || ref != null) {
+ draftCommentNotes =
+ new DraftCommentNotes(args, change, author, autoRebuild, rebuildResult, ref);
draftCommentNotes.load();
}
}
@@ -582,8 +555,7 @@
public PatchSet getCurrentPatchSet() {
PatchSet.Id psId = change.currentPatchSetId();
- return checkNotNull(getPatchSets().get(psId),
- "missing current patch set %s", psId.get());
+ return checkNotNull(getPatchSets().get(psId), "missing current patch set %s", psId.get());
}
@Override
@@ -600,8 +572,8 @@
return;
}
- ChangeNotesCache.Value v = args.cache.get().get(
- getProjectName(), getChangeId(), rev, handle.walk());
+ ChangeNotesCache.Value v =
+ args.cache.get().get(getProjectName(), getChangeId(), rev, handle.walk());
state = v.state();
state.copyColumnsTo(change);
revisionNoteMap = v.revisionNoteMap();
@@ -619,14 +591,11 @@
@Override
protected ObjectId readRef(Repository repo) throws IOException {
- return refs != null
- ? refs.get(getRefName()).orElse(null)
- : super.readRef(repo);
+ return refs != null ? refs.get(getRefName()).orElse(null) : super.readRef(repo);
}
@Override
- protected LoadHandle openHandle(Repository repo)
- throws NoSuchChangeException, IOException {
+ protected LoadHandle openHandle(Repository repo) throws NoSuchChangeException, IOException {
if (autoRebuild) {
NoteDbChangeState state = NoteDbChangeState.parse(change);
ObjectId id = readRef(repo);
@@ -645,8 +614,7 @@
return super.openHandle(repo);
}
- private LoadHandle rebuildAndOpen(Repository repo, ObjectId oldId)
- throws IOException {
+ private LoadHandle rebuildAndOpen(Repository repo, ObjectId oldId) throws IOException {
Timer1.Context timer = args.metrics.autoRebuildLatency.start(CHANGES);
try {
Change.Id cid = getChangeId();
@@ -672,27 +640,26 @@
//
// Parse notes from the staged result so we can return something useful
// to the caller instead of throwing.
- log.debug("Rebuilding change {} failed: {}",
- getChangeId(), e.getMessage());
+ log.debug("Rebuilding change {} failed: {}", getChangeId(), e.getMessage());
args.metrics.autoRebuildFailureCount.increment(CHANGES);
rebuildResult = checkNotNull(r);
checkNotNull(r.newState());
checkNotNull(r.staged());
return LoadHandle.create(
- ChangeNotesCommit.newStagedRevWalk(
- repo, r.staged().changeObjects()),
+ ChangeNotesCommit.newStagedRevWalk(repo, r.staged().changeObjects()),
r.newState().getChangeMetaId());
}
}
- return LoadHandle.create(
- ChangeNotesCommit.newRevWalk(repo), r.newState().getChangeMetaId());
+ return LoadHandle.create(ChangeNotesCommit.newRevWalk(repo), r.newState().getChangeMetaId());
} catch (NoSuchChangeException e) {
return super.openHandle(repo, oldId);
} catch (OrmException e) {
throw new IOException(e);
} finally {
- log.debug("Rebuilt change {} in project {} in {} ms",
- getChangeId(), getProjectName(),
+ log.debug(
+ "Rebuilt change {} in project {} in {} ms",
+ getChangeId(),
+ getProjectName(),
TimeUnit.MILLISECONDS.convert(timer.stop(), TimeUnit.NANOSECONDS));
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/ChangeNotesCache.java b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/ChangeNotesCache.java
index 92ad17d..9626911 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/ChangeNotesCache.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/ChangeNotesCache.java
@@ -28,32 +28,27 @@
import com.google.inject.Module;
import com.google.inject.Singleton;
import com.google.inject.name.Named;
-
-import org.eclipse.jgit.errors.ConfigInvalidException;
-import org.eclipse.jgit.lib.ObjectId;
-
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
+import org.eclipse.jgit.errors.ConfigInvalidException;
+import org.eclipse.jgit.lib.ObjectId;
@Singleton
public class ChangeNotesCache {
- @VisibleForTesting
- static final String CACHE_NAME = "change_notes";
+ @VisibleForTesting static final String CACHE_NAME = "change_notes";
public static Module module() {
return new CacheModule() {
@Override
protected void configure() {
bind(ChangeNotesCache.class);
- cache(CACHE_NAME,
- Key.class,
- ChangeNotesState.class)
- .weigher(Weigher.class)
- .maximumWeight(10 << 20);
+ cache(CACHE_NAME, Key.class, ChangeNotesState.class)
+ .weigher(Weigher.class)
+ .maximumWeight(10 << 20);
}
};
}
@@ -61,12 +56,13 @@
@AutoValue
public abstract static class Key {
abstract Project.NameKey project();
+
abstract Change.Id changeId();
+
abstract ObjectId id();
}
- public static class Weigher
- implements com.google.common.cache.Weigher<Key, ChangeNotesState> {
+ public static class Weigher implements com.google.common.cache.Weigher<Key, ChangeNotesState> {
// Single object overhead.
private static final int O = 16;
@@ -85,31 +81,48 @@
// estimated average element sizes rather than iterating over collections.
// Numbers are largely hand-wavy based on
// http://stackoverflow.com/questions/258120/what-is-the-memory-consumption-of-an-object-in-java
- return
- P + O + 20 // metaId
+ return P
+ + O
+ + 20 // metaId
+ K // changeId
+ str(40) // changeKey
+ T // createdOn
+ T // lastUpdatedOn
- + P + K // owner
- + P + str(state.columns().branch())
- + P + patchSetId() // currentPatchSetId
- + P + str(state.columns().subject())
- + P + str(state.columns().topic())
- + P + str(state.columns().originalSubject())
- + P + str(state.columns().submissionId())
+ + P
+ + K // owner
+ + P
+ + str(state.columns().branch())
+ + P
+ + patchSetId() // currentPatchSetId
+ + P
+ + str(state.columns().subject())
+ + P
+ + str(state.columns().topic())
+ + P
+ + str(state.columns().originalSubject())
+ + P
+ + str(state.columns().submissionId())
+ ptr(state.columns().assignee(), K) // assignee
+ P // status
- + P + set(state.pastAssignees(), K)
- + P + set(state.hashtags(), str(10))
- + P + list(state.patchSets(), patchSet())
- + P + list(state.allPastReviewers(), approval())
- + P + list(state.reviewerUpdates(), 4 * O + K + K + P)
- + P + list(state.submitRecords(), P + list(2, str(4) + P + K) + P)
- + P + list(state.allChangeMessages(), changeMessage())
+ + P
+ + set(state.pastAssignees(), K)
+ + P
+ + set(state.hashtags(), str(10))
+ + P
+ + list(state.patchSets(), patchSet())
+ + P
+ + list(state.allPastReviewers(), approval())
+ + P
+ + list(state.reviewerUpdates(), 4 * O + K + K + P)
+ + P
+ + list(state.submitRecords(), P + list(2, str(4) + P + K) + P)
+ + P
+ + list(state.allChangeMessages(), changeMessage())
// Just key overhead for map, already counted messages in previous.
- + P + map(state.changeMessagesByPatchSet().asMap(), patchSetId())
- + P + map(state.publishedComments().asMap(), comment());
+ + P
+ + map(state.changeMessagesByPatchSet().asMap(), patchSetId())
+ + P
+ + map(state.publishedComments().asMap(), comment());
}
private static int ptr(Object o, int size) {
@@ -165,10 +178,13 @@
private static int patchSet() {
return O
- + P + patchSetId()
+ + P
+ + patchSetId()
+ str(40) // revision
- + P + K // uploader
- + P + T // createdOn
+ + P
+ + K // uploader
+ + P
+ + T // createdOn
+ 1 // draft
+ str(40) // groups
+ P; // pushCertificate
@@ -176,9 +192,16 @@
private static int approval() {
return O
- + P + patchSetId() + P + K + P + O + str(10)
+ + P
+ + patchSetId()
+ + P
+ + K
+ + P
+ + O
+ + str(10)
+ 2 // value
- + P + T // granted
+ + P
+ + T // granted
+ P // tag
+ P; // realAccountId
}
@@ -186,11 +209,15 @@
private static int changeMessage() {
int key = K + str(20);
return O
- + P + key
- + P + K // author
- + P + T // writtenON
+ + P
+ + key
+ + P
+ + K // author
+ + P
+ + T // writtenON
+ str(64) // message
- + P + patchSetId()
+ + P
+ + patchSetId()
+ P
+ P; // realAuthor
}
@@ -199,18 +226,24 @@
int key = P + str(20) + P + str(32) + 4;
int ident = O + 4;
return O
- + P + key
+ + P
+ + key
+ 4 // lineNbr
- + P + ident // author
- + P + ident //realAuthor
- + P + T // writtenOn
+ + P
+ + ident // author
+ + P
+ + ident //realAuthor
+ + P
+ + T // writtenOn
+ 2 // side
+ str(32) // message
+ str(10) // parentUuid
+ (P + O + 4 + 4 + 4 + 4) / 2 // range on 50% of comments
+ P // tag
- + P + str(40) // revId
- + P + str(36); // serverId
+ + P
+ + str(40) // revId
+ + P
+ + str(36); // serverId
}
}
@@ -220,13 +253,13 @@
/**
* The {@link RevisionNoteMap} produced while parsing this change.
- * <p>
- * These instances are mutable and non-threadsafe, so it is only safe to
- * return it to the caller that actually incurred the cache miss. It is only
- * used as an optimization; {@link ChangeNotes} is capable of lazily loading
- * it as necessary.
+ *
+ * <p>These instances are mutable and non-threadsafe, so it is only safe to return it to the
+ * caller that actually incurred the cache miss. It is only used as an optimization; {@link
+ * ChangeNotes} is capable of lazily loading it as necessary.
*/
- @Nullable abstract RevisionNoteMap<ChangeRevisionNote> revisionNoteMap();
+ @Nullable
+ abstract RevisionNoteMap<ChangeRevisionNote> revisionNoteMap();
}
private class Loader implements Callable<ChangeNotesState> {
@@ -242,8 +275,8 @@
@Override
public ChangeNotesState call() throws ConfigInvalidException, IOException {
- ChangeNotesParser parser = new ChangeNotesParser(
- key.changeId(), key.id(), rw, args.noteUtil, args.metrics);
+ ChangeNotesParser parser =
+ new ChangeNotesParser(key.changeId(), key.id(), rw, args.noteUtil, args.metrics);
ChangeNotesState result = parser.parseAll();
// This assignment only happens if call() was actually called, which only
// happens when Cache#get(K, Callable<V>) incurs a cache miss.
@@ -256,23 +289,21 @@
private final Args args;
@Inject
- ChangeNotesCache(
- @Named(CACHE_NAME) Cache<Key, ChangeNotesState> cache,
- Args args) {
+ ChangeNotesCache(@Named(CACHE_NAME) Cache<Key, ChangeNotesState> cache, Args args) {
this.cache = cache;
this.args = args;
}
- Value get(Project.NameKey project, Change.Id changeId,
- ObjectId metaId, ChangeNotesRevWalk rw) throws IOException {
+ Value get(Project.NameKey project, Change.Id changeId, ObjectId metaId, ChangeNotesRevWalk rw)
+ throws IOException {
try {
- Key key =
- new AutoValue_ChangeNotesCache_Key(project, changeId, metaId.copy());
+ Key key = new AutoValue_ChangeNotesCache_Key(project, changeId, metaId.copy());
Loader loader = new Loader(key, rw);
ChangeNotesState s = cache.get(key, loader);
return new AutoValue_ChangeNotesCache_Value(s, loader.revisionNoteMap);
} catch (ExecutionException e) {
- throw new IOException(String.format(
+ throw new IOException(
+ String.format(
"Error loading %s in %s at %s",
RefNames.changeMetaRef(changeId), project, metaId.name()),
e);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/ChangeNotesCommit.java b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/ChangeNotesCommit.java
index 4dd272d5..78f6afc 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/ChangeNotesCommit.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/ChangeNotesCommit.java
@@ -20,7 +20,8 @@
import com.google.common.collect.MultimapBuilder;
import com.google.gerrit.server.git.InMemoryInserter;
import com.google.gerrit.server.git.InsertedObject;
-
+import java.io.IOException;
+import java.util.List;
import org.eclipse.jgit.errors.IncorrectObjectTypeException;
import org.eclipse.jgit.errors.MissingObjectException;
import org.eclipse.jgit.lib.AnyObjectId;
@@ -31,15 +32,14 @@
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;
-import java.io.IOException;
-import java.util.List;
-
/**
* Commit implementation with some optimizations for change notes parsing.
+ *
* <p>
+ *
* <ul>
- * <li>Caches the result of {@link #getFooterLines()}, which is
- * otherwise very wasteful with allocations.</li>
+ * <li>Caches the result of {@link #getFooterLines()}, which is otherwise very wasteful with
+ * allocations.
* </ul>
*/
public class ChangeNotesCommit extends RevCommit {
@@ -47,8 +47,8 @@
return new ChangeNotesRevWalk(repo);
}
- public static ChangeNotesRevWalk newStagedRevWalk(Repository repo,
- Iterable<InsertedObject> stagedObjs) {
+ public static ChangeNotesRevWalk newStagedRevWalk(
+ Repository repo, Iterable<InsertedObject> stagedObjs) {
final InMemoryInserter ins = new InMemoryInserter(repo);
for (InsertedObject obj : stagedObjs) {
ins.insert(obj);
@@ -77,21 +77,21 @@
}
@Override
- public ChangeNotesCommit next() throws MissingObjectException,
- IncorrectObjectTypeException, IOException {
+ public ChangeNotesCommit next()
+ throws MissingObjectException, IncorrectObjectTypeException, IOException {
return (ChangeNotesCommit) super.next();
}
@Override
- public void markStart(RevCommit c) throws MissingObjectException,
- IncorrectObjectTypeException, IOException {
+ public void markStart(RevCommit c)
+ throws MissingObjectException, IncorrectObjectTypeException, IOException {
checkArgument(c instanceof ChangeNotesCommit);
super.markStart(c);
}
@Override
- public void markUninteresting(RevCommit c) throws MissingObjectException,
- IncorrectObjectTypeException, IOException {
+ public void markUninteresting(RevCommit c)
+ throws MissingObjectException, IncorrectObjectTypeException, IOException {
checkArgument(c instanceof ChangeNotesCommit);
super.markUninteresting(c);
}
@@ -103,8 +103,7 @@
@Override
public ChangeNotesCommit parseCommit(AnyObjectId id)
- throws MissingObjectException, IncorrectObjectTypeException,
- IOException {
+ throws MissingObjectException, IncorrectObjectTypeException, IOException {
return (ChangeNotesCommit) super.parseCommit(id);
}
}
@@ -118,8 +117,7 @@
public List<String> getFooterLineValues(FooterKey key) {
if (footerLines == null) {
List<FooterLine> src = getFooterLines();
- footerLines =
- MultimapBuilder.hashKeys(src.size()).arrayListValues(1).build();
+ footerLines = MultimapBuilder.hashKeys(src.size()).arrayListValues(1).build();
for (FooterLine fl : src) {
footerLines.put(fl.getKey().toLowerCase(), fl.getValue());
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/ChangeNotesParser.java b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/ChangeNotesParser.java
index 07de733..3a817e4 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/ChangeNotesParser.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/ChangeNotesParser.java
@@ -65,18 +65,6 @@
import com.google.gerrit.server.ReviewerStatusUpdate;
import com.google.gerrit.server.notedb.ChangeNotesCommit.ChangeNotesRevWalk;
import com.google.gerrit.server.util.LabelVote;
-
-import org.eclipse.jgit.errors.ConfigInvalidException;
-import org.eclipse.jgit.errors.InvalidObjectIdException;
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.lib.ObjectReader;
-import org.eclipse.jgit.lib.PersonIdent;
-import org.eclipse.jgit.notes.NoteMap;
-import org.eclipse.jgit.revwalk.FooterKey;
-import org.eclipse.jgit.util.RawParseUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.io.IOException;
import java.nio.charset.Charset;
import java.sql.Timestamp;
@@ -94,26 +82,34 @@
import java.util.Set;
import java.util.TreeSet;
import java.util.function.Function;
+import org.eclipse.jgit.errors.ConfigInvalidException;
+import org.eclipse.jgit.errors.InvalidObjectIdException;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.lib.ObjectReader;
+import org.eclipse.jgit.lib.PersonIdent;
+import org.eclipse.jgit.notes.NoteMap;
+import org.eclipse.jgit.revwalk.FooterKey;
+import org.eclipse.jgit.util.RawParseUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
class ChangeNotesParser {
- private static final Logger log =
- LoggerFactory.getLogger(ChangeNotesParser.class);
+ private static final Logger log = LoggerFactory.getLogger(ChangeNotesParser.class);
// Sentinel RevId indicating a mutable field on a patch set was parsed, but
// the parser does not yet know its commit SHA-1.
- private static final RevId PARTIAL_PATCH_SET =
- new RevId("INVALID PARTIAL PATCH SET");
+ private static final RevId PARTIAL_PATCH_SET = new RevId("INVALID PARTIAL PATCH SET");
@AutoValue
abstract static class ApprovalKey {
abstract PatchSet.Id psId();
+
abstract Account.Id accountId();
+
abstract String label();
- private static ApprovalKey create(PatchSet.Id psId, Account.Id accountId,
- String label) {
- return new AutoValue_ChangeNotesParser_ApprovalKey(
- psId, accountId, label);
+ private static ApprovalKey create(PatchSet.Id psId, Account.Id accountId, String label) {
+ return new AutoValue_ChangeNotesParser_ApprovalKey(psId, accountId, label);
}
}
@@ -138,8 +134,7 @@
private final Map<ApprovalKey, PatchSetApproval> approvals;
private final List<PatchSetApproval> bufferedApprovals;
private final List<ChangeMessage> allChangeMessages;
- private final ListMultimap<PatchSet.Id, ChangeMessage>
- changeMessagesByPatchSet;
+ private final ListMultimap<PatchSet.Id, ChangeMessage> changeMessagesByPatchSet;
// Non-final private members filled in during the parsing process.
private String branch;
@@ -158,8 +153,12 @@
private String tag;
private RevisionNoteMap<ChangeRevisionNote> revisionNoteMap;
- ChangeNotesParser(Change.Id changeId, ObjectId tip, ChangeNotesRevWalk walk,
- ChangeNoteUtil noteUtil, NoteDbMetrics metrics) {
+ ChangeNotesParser(
+ Change.Id changeId,
+ ObjectId tip,
+ ChangeNotesRevWalk walk,
+ ChangeNoteUtil noteUtil,
+ NoteDbMetrics metrics) {
this.id = changeId;
this.tip = tip;
this.walk = walk;
@@ -180,8 +179,7 @@
currentPatchSets = new ArrayList<>();
}
- ChangeNotesState parseAll()
- throws ConfigInvalidException, IOException {
+ ChangeNotesState parseAll() throws ConfigInvalidException, IOException {
// Don't include initial parse in timer, as this might do more I/O to page
// in the block containing most commits. Later reads are not guaranteed to
// avoid I/O, but often should.
@@ -224,7 +222,6 @@
submissionId,
assignee != null ? assignee.orElse(null) : null,
status,
-
Sets.newLinkedHashSet(Lists.reverse(pastAssignees)),
hashtags,
patchSets,
@@ -271,8 +268,7 @@
List<ReviewerStatusUpdate> result = new ArrayList<>();
HashMap<Account.Id, ReviewerStateInternal> lastState = new HashMap<>();
for (ReviewerStatusUpdate u : Lists.reverse(reviewerUpdates)) {
- if (!Objects.equals(ownerId, u.reviewer()) &&
- lastState.get(u.reviewer()) != u.state()) {
+ if (!Objects.equals(ownerId, u.reviewer()) && lastState.get(u.reviewer()) != u.state()) {
result.add(u);
lastState.put(u.reviewer(), u.state());
}
@@ -285,16 +281,14 @@
}
private ListMultimap<PatchSet.Id, ChangeMessage> buildMessagesByPatchSet() {
- for (Collection<ChangeMessage> v :
- changeMessagesByPatchSet.asMap().values()) {
+ for (Collection<ChangeMessage> v : changeMessagesByPatchSet.asMap().values()) {
Collections.reverse((List<ChangeMessage>) v);
}
return changeMessagesByPatchSet;
}
private void parse(ChangeNotesCommit commit) throws ConfigInvalidException {
- Timestamp ts =
- new Timestamp(commit.getCommitterIdent().getWhen().getTime());
+ Timestamp ts = new Timestamp(commit.getCommitterIdent().getWhen().getTime());
createdOn = ts;
parseTag(commit);
@@ -382,29 +376,25 @@
parseDescription(psId, commit);
}
- private String parseSubmissionId(ChangeNotesCommit commit)
- throws ConfigInvalidException {
+ private String parseSubmissionId(ChangeNotesCommit commit) throws ConfigInvalidException {
return parseOneFooter(commit, FOOTER_SUBMISSION_ID);
}
- private String parseBranch(ChangeNotesCommit commit)
- throws ConfigInvalidException {
+ private String parseBranch(ChangeNotesCommit commit) throws ConfigInvalidException {
String branch = parseOneFooter(commit, FOOTER_BRANCH);
return branch != null ? RefNames.fullName(branch) : null;
}
- private String parseChangeId(ChangeNotesCommit commit)
- throws ConfigInvalidException {
+ private String parseChangeId(ChangeNotesCommit commit) throws ConfigInvalidException {
return parseOneFooter(commit, FOOTER_CHANGE_ID);
}
- private String parseSubject(ChangeNotesCommit commit)
- throws ConfigInvalidException {
+ private String parseSubject(ChangeNotesCommit commit) throws ConfigInvalidException {
return parseOneFooter(commit, FOOTER_SUBJECT);
}
- private Account.Id parseRealAccountId(ChangeNotesCommit commit,
- Account.Id effectiveAccountId) throws ConfigInvalidException {
+ private Account.Id parseRealAccountId(ChangeNotesCommit commit, Account.Id effectiveAccountId)
+ throws ConfigInvalidException {
String realUser = parseOneFooter(commit, FOOTER_REAL_USER);
if (realUser == null) {
return effectiveAccountId;
@@ -413,8 +403,7 @@
return noteUtil.parseIdent(ident, id);
}
- private String parseTopic(ChangeNotesCommit commit)
- throws ConfigInvalidException {
+ private String parseTopic(ChangeNotesCommit commit) throws ConfigInvalidException {
return parseOneFooter(commit, FOOTER_TOPIC);
}
@@ -429,17 +418,16 @@
return footerLines.get(0);
}
- private String parseExactlyOneFooter(ChangeNotesCommit commit,
- FooterKey footerKey) throws ConfigInvalidException {
+ private String parseExactlyOneFooter(ChangeNotesCommit commit, FooterKey footerKey)
+ throws ConfigInvalidException {
String line = parseOneFooter(commit, footerKey);
if (line == null) {
- throw expectedOneFooter(footerKey, Collections.<String> emptyList());
+ throw expectedOneFooter(footerKey, Collections.<String>emptyList());
}
return line;
}
- private ObjectId parseRevision(ChangeNotesCommit commit)
- throws ConfigInvalidException {
+ private ObjectId parseRevision(ChangeNotesCommit commit) throws ConfigInvalidException {
String sha = parseOneFooter(commit, FOOTER_COMMIT);
if (sha == null) {
return null;
@@ -453,11 +441,10 @@
}
}
- private void parsePatchSet(PatchSet.Id psId, ObjectId rev,
- Account.Id accountId, Timestamp ts) throws ConfigInvalidException {
+ private void parsePatchSet(PatchSet.Id psId, ObjectId rev, Account.Id accountId, Timestamp ts)
+ throws ConfigInvalidException {
if (accountId == null) {
- throw parseException(
- "patch set %s requires an identified user as uploader", psId.get());
+ throw parseException("patch set %s requires an identified user as uploader", psId.get());
}
PatchSet ps = patchSets.get(psId);
if (ps == null) {
@@ -518,8 +505,7 @@
}
}
- private void parseHashtags(ChangeNotesCommit commit)
- throws ConfigInvalidException {
+ private void parseHashtags(ChangeNotesCommit commit) throws ConfigInvalidException {
// Commits are parsed in reverse order and only the last set of hashtags
// should be used.
if (hashtags != null) {
@@ -537,8 +523,7 @@
}
}
- private void parseAssignee(ChangeNotesCommit commit)
- throws ConfigInvalidException {
+ private void parseAssignee(ChangeNotesCommit commit) throws ConfigInvalidException {
if (pastAssignees == null) {
pastAssignees = Lists.newArrayList();
}
@@ -561,8 +546,7 @@
}
}
- private void parseTag(ChangeNotesCommit commit)
- throws ConfigInvalidException {
+ private void parseTag(ChangeNotesCommit commit) throws ConfigInvalidException {
tag = null;
List<String> tagLines = commit.getFooterLineValues(FOOTER_TAG);
if (tagLines.isEmpty()) {
@@ -574,16 +558,15 @@
}
}
- private Change.Status parseStatus(ChangeNotesCommit commit)
- throws ConfigInvalidException {
+ private Change.Status parseStatus(ChangeNotesCommit commit) throws ConfigInvalidException {
List<String> statusLines = commit.getFooterLineValues(FOOTER_STATUS);
if (statusLines.isEmpty()) {
return null;
} else if (statusLines.size() > 1) {
throw expectedOneFooter(FOOTER_STATUS, statusLines);
}
- Change.Status status = Enums.getIfPresent(
- Change.Status.class, statusLines.get(0).toUpperCase()).orNull();
+ Change.Status status =
+ Enums.getIfPresent(Change.Status.class, statusLines.get(0).toUpperCase()).orNull();
if (status == null) {
throw invalidFooter(FOOTER_STATUS, statusLines.get(0));
}
@@ -599,8 +582,7 @@
return status;
}
- private PatchSet.Id parsePatchSetId(ChangeNotesCommit commit)
- throws ConfigInvalidException {
+ private PatchSet.Id parsePatchSetId(ChangeNotesCommit commit) throws ConfigInvalidException {
String psIdLine = parseExactlyOneFooter(commit, FOOTER_PATCH_SET);
int s = psIdLine.indexOf(' ');
String psIdStr = s < 0 ? psIdLine : psIdLine.substring(0, s);
@@ -611,8 +593,7 @@
return new PatchSet.Id(id, psId);
}
- private PatchSetState parsePatchSetState(ChangeNotesCommit commit)
- throws ConfigInvalidException {
+ private PatchSetState parsePatchSetState(ChangeNotesCommit commit) throws ConfigInvalidException {
String psIdLine = parseExactlyOneFooter(commit, FOOTER_PATCH_SET);
int s = psIdLine.indexOf(' ');
if (s < 0) {
@@ -620,9 +601,11 @@
}
String withParens = psIdLine.substring(s + 1);
if (withParens.startsWith("(") && withParens.endsWith(")")) {
- PatchSetState state = Enums.getIfPresent(PatchSetState.class,
- withParens.substring(1, withParens.length() - 1).toUpperCase())
- .orNull();
+ PatchSetState state =
+ Enums.getIfPresent(
+ PatchSetState.class,
+ withParens.substring(1, withParens.length() - 1).toUpperCase())
+ .orNull();
if (state != null) {
return state;
}
@@ -632,8 +615,7 @@
private void parseDescription(PatchSet.Id psId, ChangeNotesCommit commit)
throws ConfigInvalidException {
- List<String> descLines =
- commit.getFooterLineValues(FOOTER_PATCH_SET_DESCRIPTION);
+ List<String> descLines = commit.getFooterLineValues(FOOTER_PATCH_SET_DESCRIPTION);
if (descLines.isEmpty()) {
return;
} else if (descLines.size() == 1) {
@@ -652,9 +634,12 @@
}
}
- private void parseChangeMessage(PatchSet.Id psId,
- Account.Id accountId, Account.Id realAccountId,
- ChangeNotesCommit commit, Timestamp ts) {
+ private void parseChangeMessage(
+ PatchSet.Id psId,
+ Account.Id accountId,
+ Account.Id realAccountId,
+ ChangeNotesCommit commit,
+ Timestamp ts) {
byte[] raw = commit.getRawBuffer();
int size = raw.length;
Charset enc = RawParseUtils.parseEncoding(raw);
@@ -699,11 +684,11 @@
return;
}
- String changeMsgString = RawParseUtils.decode(enc, raw,
- changeMessageStart, changeMessageEnd + 1);
- ChangeMessage changeMessage = new ChangeMessage(
- new ChangeMessage.Key(psId.getParentKey(), commit.name()),
- accountId, ts, psId);
+ String changeMsgString =
+ RawParseUtils.decode(enc, raw, changeMessageStart, changeMessageEnd + 1);
+ ChangeMessage changeMessage =
+ new ChangeMessage(
+ new ChangeMessage.Key(psId.getParentKey(), commit.name()), accountId, ts, psId);
changeMessage.setMessage(changeMsgString);
changeMessage.setTag(tag);
changeMessage.setRealAuthor(realAccountId);
@@ -711,13 +696,16 @@
allChangeMessages.add(changeMessage);
}
- private void parseNotes()
- throws IOException, ConfigInvalidException {
+ private void parseNotes() throws IOException, ConfigInvalidException {
ObjectReader reader = walk.getObjectReader();
ChangeNotesCommit tipCommit = walk.parseCommit(tip);
- revisionNoteMap = RevisionNoteMap.parse(
- noteUtil, id, reader, NoteMap.read(reader, tipCommit),
- PatchLineComment.Status.PUBLISHED);
+ revisionNoteMap =
+ RevisionNoteMap.parse(
+ noteUtil,
+ id,
+ reader,
+ NoteMap.read(reader, tipCommit),
+ PatchLineComment.Status.PUBLISHED);
Map<RevId, ChangeRevisionNote> rns = revisionNoteMap.revisionNotes;
for (Map.Entry<RevId, ChangeRevisionNote> e : rns.entrySet()) {
@@ -734,12 +722,11 @@
}
}
- private void parseApproval(PatchSet.Id psId, Account.Id accountId,
- Account.Id realAccountId, Timestamp ts, String line)
+ private void parseApproval(
+ PatchSet.Id psId, Account.Id accountId, Account.Id realAccountId, Timestamp ts, String line)
throws ConfigInvalidException {
if (accountId == null) {
- throw parseException(
- "patch set %s requires an identified user as uploader", psId.get());
+ throw parseException("patch set %s requires an identified user as uploader", psId.get());
}
PatchSetApproval psa;
if (line.startsWith("-")) {
@@ -750,9 +737,8 @@
bufferedApprovals.add(psa);
}
- private PatchSetApproval parseAddApproval(PatchSet.Id psId,
- Account.Id committerId, Account.Id realAccountId, Timestamp ts,
- String line)
+ private PatchSetApproval parseAddApproval(
+ PatchSet.Id psId, Account.Id committerId, Account.Id realAccountId, Timestamp ts, String line)
throws ConfigInvalidException {
// There are potentially 3 accounts involved here:
// 1. The account from the commit, which is the effective IdentifiedUser
@@ -783,34 +769,30 @@
try {
l = LabelVote.parseWithEquals(labelVoteStr);
} catch (IllegalArgumentException e) {
- ConfigInvalidException pe =
- parseException("invalid %s: %s", FOOTER_LABEL, line);
+ ConfigInvalidException pe = parseException("invalid %s: %s", FOOTER_LABEL, line);
pe.initCause(e);
throw pe;
}
- PatchSetApproval psa = new PatchSetApproval(
- new PatchSetApproval.Key(
- psId,
- effectiveAccountId,
- new LabelId(l.label())),
- l.value(),
- ts);
+ PatchSetApproval psa =
+ new PatchSetApproval(
+ new PatchSetApproval.Key(psId, effectiveAccountId, new LabelId(l.label())),
+ l.value(),
+ ts);
psa.setTag(tag);
if (!Objects.equals(realAccountId, committerId)) {
psa.setRealAccountId(realAccountId);
}
- ApprovalKey k =
- ApprovalKey.create(psId, effectiveAccountId, l.label());
+ ApprovalKey k = ApprovalKey.create(psId, effectiveAccountId, l.label());
if (!approvals.containsKey(k)) {
approvals.put(k, psa);
}
return psa;
}
- private PatchSetApproval parseRemoveApproval(PatchSet.Id psId,
- Account.Id committerId, Account.Id realAccountId, Timestamp ts,
- String line) throws ConfigInvalidException {
+ private PatchSetApproval parseRemoveApproval(
+ PatchSet.Id psId, Account.Id committerId, Account.Id realAccountId, Timestamp ts, String line)
+ throws ConfigInvalidException {
// See comments in parseAddApproval about the various users involved.
Account.Id effectiveAccountId;
String label;
@@ -828,8 +810,7 @@
try {
LabelType.checkNameInternal(label);
} catch (IllegalArgumentException e) {
- ConfigInvalidException pe =
- parseException("invalid %s: %s", FOOTER_LABEL, line);
+ ConfigInvalidException pe = parseException("invalid %s: %s", FOOTER_LABEL, line);
pe.initCause(e);
throw pe;
}
@@ -840,13 +821,9 @@
// confusion and special-casing of NoteDb.
// - More importantly, ApprovalCopier needs an actual approval in order to
// block copying an earlier approval over a later delete.
- PatchSetApproval remove = new PatchSetApproval(
- new PatchSetApproval.Key(
- psId,
- effectiveAccountId,
- new LabelId(label)),
- (short) 0,
- ts);
+ PatchSetApproval remove =
+ new PatchSetApproval(
+ new PatchSetApproval.Key(psId, effectiveAccountId, new LabelId(label)), (short) 0, ts);
if (!Objects.equals(realAccountId, committerId)) {
remove.setRealAccountId(realAccountId);
}
@@ -857,8 +834,7 @@
return remove;
}
- private void parseSubmitRecords(List<String> lines)
- throws ConfigInvalidException {
+ private void parseSubmitRecords(List<String> lines) throws ConfigInvalidException {
SubmitRecord rec = null;
for (String line : lines) {
@@ -868,8 +844,7 @@
submitRecords.add(rec);
int s = line.indexOf(' ');
String statusStr = s >= 0 ? line.substring(0, s) : line;
- rec.status =
- Enums.getIfPresent(SubmitRecord.Status.class, statusStr).orNull();
+ rec.status = Enums.getIfPresent(SubmitRecord.Status.class, statusStr).orNull();
checkFooter(rec.status != null, FOOTER_SUBMITTED_WITH, line);
if (s >= 0) {
rec.errorMessage = line.substring(s);
@@ -882,14 +857,13 @@
}
rec.labels.add(label);
- label.status = Enums.getIfPresent(
- SubmitRecord.Label.Status.class, line.substring(0, c)).orNull();
+ label.status =
+ Enums.getIfPresent(SubmitRecord.Label.Status.class, line.substring(0, c)).orNull();
checkFooter(label.status != null, FOOTER_SUBMITTED_WITH, line);
int c2 = line.indexOf(": ", c + 2);
if (c2 >= 0) {
label.label = line.substring(c + 2, c2);
- PersonIdent ident =
- RawParseUtils.parsePersonIdent(line.substring(c2 + 2));
+ PersonIdent ident = RawParseUtils.parsePersonIdent(line.substring(c2 + 2));
checkFooter(ident != null, FOOTER_SUBMITTED_WITH, line);
label.appliedBy = noteUtil.parseIdent(ident, id);
} else {
@@ -899,28 +873,25 @@
}
}
- private Account.Id parseIdent(ChangeNotesCommit commit)
- throws ConfigInvalidException {
+ private Account.Id parseIdent(ChangeNotesCommit commit) throws ConfigInvalidException {
// Check if the author name/email is the same as the committer name/email,
// i.e. was the server ident at the time this commit was made.
PersonIdent a = commit.getAuthorIdent();
PersonIdent c = commit.getCommitterIdent();
- if (a.getName().equals(c.getName())
- && a.getEmailAddress().equals(c.getEmailAddress())) {
+ if (a.getName().equals(c.getName()) && a.getEmailAddress().equals(c.getEmailAddress())) {
return null;
}
return noteUtil.parseIdent(commit.getAuthorIdent(), id);
}
- private void parseReviewer(Timestamp ts, ReviewerStateInternal state,
- String line) throws ConfigInvalidException {
+ private void parseReviewer(Timestamp ts, ReviewerStateInternal state, String line)
+ throws ConfigInvalidException {
PersonIdent ident = RawParseUtils.parsePersonIdent(line);
if (ident == null) {
throw invalidFooter(state.getFooterKey(), line);
}
Account.Id accountId = noteUtil.parseIdent(ident, id);
- reviewerUpdates.add(
- ReviewerStatusUpdate.create(ts, ownerId, accountId, state));
+ reviewerUpdates.add(ReviewerStatusUpdate.create(ts, ownerId, accountId, state));
if (!reviewers.containsRow(accountId)) {
reviewers.put(accountId, state, ts);
}
@@ -939,8 +910,7 @@
private void updatePatchSetStates() {
Set<PatchSet.Id> missing = new TreeSet<>(ReviewDbUtil.intKeyOrdering());
- for (Iterator<PatchSet> it = patchSets.values().iterator();
- it.hasNext();) {
+ for (Iterator<PatchSet> it = patchSets.values().iterator(); it.hasNext(); ) {
PatchSet ps = it.next();
if (ps.getRevision().equals(PARTIAL_PATCH_SET)) {
missing.add(ps.getId());
@@ -972,25 +942,24 @@
// set was deleted.
changeMessagesByPatchSet.keys().retainAll(patchSets.keySet());
- int pruned = pruneEntitiesForMissingPatchSets(
- allChangeMessages, ChangeMessage::getPatchSetId, missing);
- pruned += pruneEntitiesForMissingPatchSets(
- comments.values(), c -> new PatchSet.Id(id, c.key.patchSetId), missing);
- pruned += pruneEntitiesForMissingPatchSets(
- approvals.values(), PatchSetApproval::getPatchSetId, missing);
+ int pruned =
+ pruneEntitiesForMissingPatchSets(allChangeMessages, ChangeMessage::getPatchSetId, missing);
+ pruned +=
+ pruneEntitiesForMissingPatchSets(
+ comments.values(), c -> new PatchSet.Id(id, c.key.patchSetId), missing);
+ pruned +=
+ pruneEntitiesForMissingPatchSets(
+ approvals.values(), PatchSetApproval::getPatchSetId, missing);
if (!missing.isEmpty()) {
- log.warn(
- "ignoring {} additional entities due to missing patch sets: {}",
- pruned, missing);
+ log.warn("ignoring {} additional entities due to missing patch sets: {}", pruned, missing);
}
}
private <T> int pruneEntitiesForMissingPatchSets(
- Iterable<T> ents, Function<T, PatchSet.Id> psIdFunc,
- Set<PatchSet.Id> missing) {
+ Iterable<T> ents, Function<T, PatchSet.Id> psIdFunc, Set<PatchSet.Id> missing) {
int pruned = 0;
- for (Iterator<T> it = ents.iterator(); it.hasNext();) {
+ for (Iterator<T> it = ents.iterator(); it.hasNext(); ) {
PatchSet.Id psId = psIdFunc.apply(it.next());
if (!patchSets.containsKey(psId)) {
pruned++;
@@ -1015,19 +984,16 @@
missing.add(FOOTER_SUBJECT);
}
if (!missing.isEmpty()) {
- throw parseException("Missing footers: "
- + missing.stream().map(FooterKey::getName).collect(joining(", ")));
+ throw parseException(
+ "Missing footers: " + missing.stream().map(FooterKey::getName).collect(joining(", ")));
}
}
- private ConfigInvalidException expectedOneFooter(FooterKey footer,
- List<String> actual) {
- return parseException("missing or multiple %s: %s",
- footer.getName(), actual);
+ private ConfigInvalidException expectedOneFooter(FooterKey footer, List<String> actual) {
+ return parseException("missing or multiple %s: %s", footer.getName(), actual);
}
- private ConfigInvalidException invalidFooter(FooterKey footer,
- String actual) {
+ private ConfigInvalidException invalidFooter(FooterKey footer, String actual) {
return parseException("invalid %s: %s", footer.getName(), actual);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/ChangeNotesState.java b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/ChangeNotesState.java
index 6c15c7e..62df01b 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/ChangeNotesState.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/ChangeNotesState.java
@@ -37,25 +37,21 @@
import com.google.gerrit.server.ReviewerSet;
import com.google.gerrit.server.ReviewerStatusUpdate;
import com.google.gerrit.server.notedb.NoteDbChangeState.PrimaryStorage;
-
-import org.eclipse.jgit.lib.ObjectId;
-
import java.io.IOException;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;
import java.util.Set;
+import org.eclipse.jgit.lib.ObjectId;
/**
* Immutable state associated with a change meta ref at a given commit.
- * <p>
- * One instance is the output of a single {@link ChangeNotesParser}, and
- * contains types required to support public methods on {@link ChangeNotes}. It
- * is intended to be cached in-process.
- * <p>
- * Note that {@link ChangeNotes} contains more than just a single {@code
- * ChangeNoteState}, such as per-draft information, so that class is not cached
- * directly.
+ *
+ * <p>One instance is the output of a single {@link ChangeNotesParser}, and contains types required
+ * to support public methods on {@link ChangeNotes}. It is intended to be cached in-process.
+ *
+ * <p>Note that {@link ChangeNotes} contains more than just a single {@code ChangeNoteState}, such
+ * as per-draft information, so that class is not cached directly.
*/
@AutoValue
public abstract class ChangeNotesState {
@@ -135,67 +131,90 @@
ImmutableListMultimap.copyOf(publishedComments));
}
-
/**
* Subset of Change columns that can be represented in NoteDb.
- * <p>
- * Notable exceptions include rowVersion and noteDbState, which are only make
- * sense when read from NoteDb, so they cannot be cached.
- * <p>
- * Fields are in listed column order.
+ *
+ * <p>Notable exceptions include rowVersion and noteDbState, which are only make sense when read
+ * from NoteDb, so they cannot be cached.
+ *
+ * <p>Fields are in listed column order.
*/
@AutoValue
abstract static class ChangeColumns {
abstract Change.Key changeKey();
+
abstract Timestamp createdOn();
+
abstract Timestamp lastUpdatedOn();
+
abstract Account.Id owner();
// Project not included, as it's not stored anywhere in the meta ref.
abstract String branch();
- @Nullable abstract PatchSet.Id currentPatchSetId();
+ @Nullable
+ abstract PatchSet.Id currentPatchSetId();
+
abstract String subject();
- @Nullable abstract String topic();
- @Nullable abstract String originalSubject();
- @Nullable abstract String submissionId();
- @Nullable abstract Account.Id assignee();
+
+ @Nullable
+ abstract String topic();
+
+ @Nullable
+ abstract String originalSubject();
+
+ @Nullable
+ abstract String submissionId();
+
+ @Nullable
+ abstract Account.Id assignee();
// TODO(dborowitz): Use a sensible default other than null
- @Nullable abstract Change.Status status();
+ @Nullable
+ abstract Change.Status status();
}
// Only null if NoteDb is disabled.
- @Nullable abstract ObjectId metaId();
+ @Nullable
+ abstract ObjectId metaId();
abstract Change.Id changeId();
// Only null if NoteDb is disabled.
- @Nullable abstract ChangeColumns columns();
+ @Nullable
+ abstract ChangeColumns columns();
// Other related to this Change.
abstract ImmutableSet<Account.Id> pastAssignees();
+
abstract ImmutableSet<String> hashtags();
+
abstract ImmutableList<Map.Entry<PatchSet.Id, PatchSet>> patchSets();
+
abstract ImmutableList<Map.Entry<PatchSet.Id, PatchSetApproval>> approvals();
abstract ReviewerSet reviewers();
+
abstract ImmutableList<Account.Id> allPastReviewers();
+
abstract ImmutableList<ReviewerStatusUpdate> reviewerUpdates();
abstract ImmutableList<SubmitRecord> submitRecords();
+
abstract ImmutableList<ChangeMessage> allChangeMessages();
- abstract ImmutableListMultimap<PatchSet.Id, ChangeMessage>
- changeMessagesByPatchSet();
+
+ abstract ImmutableListMultimap<PatchSet.Id, ChangeMessage> changeMessagesByPatchSet();
+
abstract ImmutableListMultimap<RevId, Comment> publishedComments();
Change newChange(Project.NameKey project) {
ChangeColumns c = checkNotNull(columns(), "columns are required");
- Change change = new Change(
- c.changeKey(),
- changeId(),
- c.owner(),
- new Branch.NameKey(project, c.branch()),
- c.createdOn());
+ Change change =
+ new Change(
+ c.changeKey(),
+ changeId(),
+ c.owner(),
+ new Branch.NameKey(project, c.branch()),
+ c.createdOn());
copyNonConstructorColumnsTo(change);
change.setNoteDbState(NoteDbChangeState.NOTE_DB_PRIMARY_STATE);
return change;
@@ -203,7 +222,8 @@
void copyColumnsTo(Change change) throws IOException {
ChangeColumns c = columns();
- checkState(c != null && metaId() != null,
+ checkState(
+ c != null && metaId() != null,
"missing columns or metaId in ChangeNotesState; is NoteDb enabled? %s",
this);
checkMetaId(change);
@@ -225,9 +245,12 @@
ObjectId idFromState = state.getRefState().get().changeMetaId();
if (!idFromState.equals(metaId())) {
throw new IOException(
- "cannot copy ChangeNotesState into Change " + changeId()
- + "; this ChangeNotesState was created from " + metaId()
- + ", but change requires state " + idFromState);
+ "cannot copy ChangeNotesState into Change "
+ + changeId()
+ + "; this ChangeNotesState was created from "
+ + metaId()
+ + ", but change requires state "
+ + idFromState);
}
}
@@ -242,8 +265,7 @@
change.setAssignee(c.assignee());
if (!patchSets().isEmpty()) {
- change.setCurrentPatchSet(
- c.currentPatchSetId(), c.subject(), c.originalSubject());
+ change.setCurrentPatchSet(c.currentPatchSetId(), c.subject(), c.originalSubject());
} else {
// TODO(dborowitz): This should be an error, but for now it's required for
// some tests to pass.
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/ChangeRevisionNote.java b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/ChangeRevisionNote.java
index 2bd61a7..153c9c3 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/ChangeRevisionNote.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/ChangeRevisionNote.java
@@ -20,34 +20,34 @@
import com.google.gerrit.reviewdb.client.Change;
import com.google.gerrit.reviewdb.client.Comment;
import com.google.gerrit.reviewdb.client.PatchLineComment;
-
-import org.eclipse.jgit.errors.ConfigInvalidException;
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.lib.ObjectReader;
-import org.eclipse.jgit.util.MutableInteger;
-import org.eclipse.jgit.util.RawParseUtils;
-
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.List;
+import org.eclipse.jgit.errors.ConfigInvalidException;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.lib.ObjectReader;
+import org.eclipse.jgit.util.MutableInteger;
+import org.eclipse.jgit.util.RawParseUtils;
class ChangeRevisionNote extends RevisionNote<Comment> {
- private static final byte[] CERT_HEADER =
- "certificate version ".getBytes(UTF_8);
+ private static final byte[] CERT_HEADER = "certificate version ".getBytes(UTF_8);
// See org.eclipse.jgit.transport.PushCertificateParser.END_SIGNATURE
- private static final byte[] END_SIGNATURE =
- "-----END PGP SIGNATURE-----\n".getBytes(UTF_8);
+ private static final byte[] END_SIGNATURE = "-----END PGP SIGNATURE-----\n".getBytes(UTF_8);
private final ChangeNoteUtil noteUtil;
private final Change.Id changeId;
private final PatchLineComment.Status status;
private String pushCert;
- ChangeRevisionNote(ChangeNoteUtil noteUtil, Change.Id changeId,
- ObjectReader reader, ObjectId noteId, PatchLineComment.Status status) {
+ ChangeRevisionNote(
+ ChangeNoteUtil noteUtil,
+ Change.Id changeId,
+ ObjectReader reader,
+ ObjectId noteId,
+ PatchLineComment.Status status) {
super(reader, noteId);
this.noteUtil = noteUtil;
this.changeId = changeId;
@@ -60,8 +60,7 @@
}
@Override
- protected List<Comment> parse(byte[] raw, int offset)
- throws IOException, ConfigInvalidException {
+ protected List<Comment> parse(byte[] raw, int offset) throws IOException, ConfigInvalidException {
MutableInteger p = new MutableInteger();
p.value = offset;
@@ -88,24 +87,22 @@
return raw[offset] == '{' || raw[offset] == '[';
}
- private RevisionNoteData parseJson(ChangeNoteUtil noteUtil, byte[] raw,
- int offset) throws IOException {
- try (InputStream is = new ByteArrayInputStream(
- raw, offset, raw.length - offset);
+ private RevisionNoteData parseJson(ChangeNoteUtil noteUtil, byte[] raw, int offset)
+ throws IOException {
+ try (InputStream is = new ByteArrayInputStream(raw, offset, raw.length - offset);
Reader r = new InputStreamReader(is, UTF_8)) {
return noteUtil.getGson().fromJson(r, RevisionNoteData.class);
}
}
- private static String parsePushCert(Change.Id changeId, byte[] bytes,
- MutableInteger p) throws ConfigInvalidException {
+ private static String parsePushCert(Change.Id changeId, byte[] bytes, MutableInteger p)
+ throws ConfigInvalidException {
if (RawParseUtils.match(bytes, p.value, CERT_HEADER) < 0) {
return null;
}
int end = Bytes.indexOf(bytes, END_SIGNATURE);
if (end < 0) {
- throw ChangeNotes.parseException(
- changeId, "invalid push certificate in note");
+ throw ChangeNotes.parseException(changeId, "invalid push certificate in note");
}
int start = p.value;
p.value = end + END_SIGNATURE.length;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/ChangeUpdate.java b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/ChangeUpdate.java
index b78178f..068f368 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/ChangeUpdate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/ChangeUpdate.java
@@ -65,17 +65,6 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
-
-import org.eclipse.jgit.errors.ConfigInvalidException;
-import org.eclipse.jgit.lib.CommitBuilder;
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.lib.ObjectInserter;
-import org.eclipse.jgit.lib.PersonIdent;
-import org.eclipse.jgit.notes.NoteMap;
-import org.eclipse.jgit.revwalk.FooterKey;
-import org.eclipse.jgit.revwalk.RevCommit;
-import org.eclipse.jgit.revwalk.RevWalk;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
@@ -87,22 +76,31 @@
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
+import org.eclipse.jgit.errors.ConfigInvalidException;
+import org.eclipse.jgit.lib.CommitBuilder;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.lib.ObjectInserter;
+import org.eclipse.jgit.lib.PersonIdent;
+import org.eclipse.jgit.notes.NoteMap;
+import org.eclipse.jgit.revwalk.FooterKey;
+import org.eclipse.jgit.revwalk.RevCommit;
+import org.eclipse.jgit.revwalk.RevWalk;
/**
* A delta to apply to a change.
- * <p>
- * This delta will become two unique commits: one in the AllUsers repo that will
- * contain the draft comments on this change and one in the notes branch that
- * will contain approvals, reviewers, change status, subject, submit records,
- * the change message, and published comments. There are limitations on the set
- * of modifications that can be handled in a single update. In particular, there
- * is a single author and timestamp for each update.
- * <p>
- * This class is not thread-safe.
+ *
+ * <p>This delta will become two unique commits: one in the AllUsers repo that will contain the
+ * draft comments on this change and one in the notes branch that will contain approvals, reviewers,
+ * change status, subject, submit records, the change message, and published comments. There are
+ * limitations on the set of modifications that can be handled in a single update. In particular,
+ * there is a single author and timestamp for each update.
+ *
+ * <p>This class is not thread-safe.
*/
public class ChangeUpdate extends AbstractChangeUpdate {
public interface Factory {
ChangeUpdate create(ChangeControl ctl);
+
ChangeUpdate create(ChangeControl ctl, Date when);
ChangeUpdate create(
@@ -114,8 +112,7 @@
Comparator<String> labelNameComparator);
@VisibleForTesting
- ChangeUpdate create(ChangeControl ctl, Date when,
- Comparator<String> labelNameComparator);
+ ChangeUpdate create(ChangeControl ctl, Date when, Comparator<String> labelNameComparator);
}
private final AccountCache accountCache;
@@ -162,9 +159,18 @@
ProjectCache projectCache,
@Assisted ChangeControl ctl,
ChangeNoteUtil noteUtil) {
- this(serverIdent, anonymousCowardName, migration, accountCache,
- updateManagerFactory, draftUpdateFactory, robotCommentUpdateFactory,
- projectCache, ctl, serverIdent.getWhen(), noteUtil);
+ this(
+ serverIdent,
+ anonymousCowardName,
+ migration,
+ accountCache,
+ updateManagerFactory,
+ draftUpdateFactory,
+ robotCommentUpdateFactory,
+ projectCache,
+ ctl,
+ serverIdent.getWhen(),
+ noteUtil);
}
@AssistedInject
@@ -180,9 +186,16 @@
@Assisted ChangeControl ctl,
@Assisted Date when,
ChangeNoteUtil noteUtil) {
- this(serverIdent, anonymousCowardName, migration, accountCache,
- updateManagerFactory, draftUpdateFactory, robotCommentUpdateFactory,
- ctl, when,
+ this(
+ serverIdent,
+ anonymousCowardName,
+ migration,
+ accountCache,
+ updateManagerFactory,
+ draftUpdateFactory,
+ robotCommentUpdateFactory,
+ ctl,
+ when,
projectCache.get(getProjectName(ctl)).getLabelTypes().nameComparator(),
noteUtil);
}
@@ -209,8 +222,7 @@
@Assisted Date when,
@Assisted Comparator<String> labelNameComparator,
ChangeNoteUtil noteUtil) {
- super(migration, ctl, serverIdent,
- anonymousCowardName, noteUtil, when);
+ super(migration, ctl, serverIdent, anonymousCowardName, noteUtil, when);
this.accountCache = accountCache;
this.draftUpdateFactory = draftUpdateFactory;
this.robotCommentUpdateFactory = robotCommentUpdateFactory;
@@ -234,8 +246,17 @@
@Assisted PersonIdent authorIdent,
@Assisted Date when,
@Assisted Comparator<String> labelNameComparator) {
- super(migration, noteUtil, serverIdent, anonymousCowardName, null, change,
- accountId, realAccountId, authorIdent, when);
+ super(
+ migration,
+ noteUtil,
+ serverIdent,
+ anonymousCowardName,
+ null,
+ change,
+ accountId,
+ realAccountId,
+ authorIdent,
+ when);
this.accountCache = accountCache;
this.draftUpdateFactory = draftUpdateFactory;
this.robotCommentUpdateFactory = robotCommentUpdateFactory;
@@ -244,8 +265,7 @@
}
public ObjectId commit() throws IOException, OrmException {
- try (NoteDbUpdateManager updateManager =
- updateManagerFactory.create(getProjectName())) {
+ try (NoteDbUpdateManager updateManager = updateManagerFactory.create(getProjectName())) {
updateManager.add(this);
updateManager.stageAndApplyDelta(getChange());
updateManager.execute();
@@ -255,9 +275,11 @@
public void setChangeId(String changeId) {
String old = getChange().getKey().get();
- checkArgument(old.equals(changeId),
+ checkArgument(
+ old.equals(changeId),
"The Change-Id was already set to %s, so we cannot set this Change-Id: %s",
- old, changeId);
+ old,
+ changeId);
this.changeId = changeId;
}
@@ -266,8 +288,7 @@
}
public void setStatus(Change.Status status) {
- checkArgument(status != Change.Status.MERGED,
- "use merge(Iterable<SubmitRecord>)");
+ checkArgument(status != Change.Status.MERGED, "use merge(Iterable<SubmitRecord>)");
this.status = status;
}
@@ -291,13 +312,11 @@
approvals.put(label, reviewer, Optional.empty());
}
- public void merge(RequestId submissionId,
- Iterable<SubmitRecord> submitRecords) {
+ public void merge(RequestId submissionId, Iterable<SubmitRecord> submitRecords) {
this.status = Change.Status.MERGED;
this.submissionId = submissionId.toStringForStorage();
this.submitRecords = ImmutableList.copyOf(submitRecords);
- checkArgument(!this.submitRecords.isEmpty(),
- "no submit records specified at submit time");
+ checkArgument(!this.submitRecords.isEmpty(), "no submit records specified at submit time");
}
@Deprecated // Only until we improve ChangeRebuilder to call merge().
@@ -361,11 +380,10 @@
if (draftUpdate == null) {
ChangeNotes notes = getNotes();
if (notes != null) {
- draftUpdate = draftUpdateFactory.create(
- notes, accountId, realAccountId, authorIdent, when);
+ draftUpdate = draftUpdateFactory.create(notes, accountId, realAccountId, authorIdent, when);
} else {
- draftUpdate = draftUpdateFactory.create(
- getChange(), accountId, realAccountId, authorIdent, when);
+ draftUpdate =
+ draftUpdateFactory.create(getChange(), accountId, realAccountId, authorIdent, when);
}
}
return draftUpdate;
@@ -376,11 +394,12 @@
if (robotCommentUpdate == null) {
ChangeNotes notes = getNotes();
if (notes != null) {
- robotCommentUpdate = robotCommentUpdateFactory.create(
- notes, accountId, realAccountId, authorIdent, when);
+ robotCommentUpdate =
+ robotCommentUpdateFactory.create(notes, accountId, realAccountId, authorIdent, when);
} else {
- robotCommentUpdate = robotCommentUpdateFactory.create(
- getChange(), accountId, realAccountId, authorIdent, when);
+ robotCommentUpdate =
+ robotCommentUpdateFactory.create(
+ getChange(), accountId, realAccountId, authorIdent, when);
}
}
return robotCommentUpdate;
@@ -394,8 +413,7 @@
setCommit(rw, id, null);
}
- public void setCommit(RevWalk rw, ObjectId id, String pushCert)
- throws IOException {
+ public void setCommit(RevWalk rw, ObjectId id, String pushCert) throws IOException {
RevCommit commit = rw.parseCommit(id);
rw.parseBody(commit);
this.commit = commit.name();
@@ -404,8 +422,8 @@
}
/**
- * Set the revision without depending on the commit being present in the
- * repository; should only be used for converting old corrupt commits.
+ * Set the revision without depending on the commit being present in the repository; should only
+ * be used for converting old corrupt commits.
*/
public void setRevisionForMissingCommit(String id, String pushCert) {
commit = id;
@@ -452,8 +470,8 @@
}
/** @return the tree id for the updated tree */
- private ObjectId storeRevisionNotes(RevWalk rw, ObjectInserter inserter,
- ObjectId curr) throws ConfigInvalidException, OrmException, IOException {
+ private ObjectId storeRevisionNotes(RevWalk rw, ObjectInserter inserter, ObjectId curr)
+ throws ConfigInvalidException, OrmException, IOException {
if (comments.isEmpty() && pushCert == null) {
return null;
}
@@ -472,16 +490,16 @@
checkComments(rnm.revisionNotes, builders);
for (Map.Entry<RevId, RevisionNoteBuilder> e : builders.entrySet()) {
- ObjectId data = inserter.insert(
- OBJ_BLOB, e.getValue().build(noteUtil, noteUtil.getWriteJson()));
+ ObjectId data =
+ inserter.insert(OBJ_BLOB, e.getValue().build(noteUtil, noteUtil.getWriteJson()));
rnm.noteMap.set(ObjectId.fromString(e.getKey().get()), data);
}
return rnm.noteMap.writeTree(inserter);
}
- private RevisionNoteMap<ChangeRevisionNote> getRevisionNoteMap(RevWalk rw,
- ObjectId curr) throws ConfigInvalidException, OrmException, IOException {
+ private RevisionNoteMap<ChangeRevisionNote> getRevisionNoteMap(RevWalk rw, ObjectId curr)
+ throws ConfigInvalidException, OrmException, IOException {
if (curr.equals(ObjectId.zeroId())) {
return RevisionNoteMap.emptyMap();
}
@@ -491,8 +509,7 @@
// hasn't advanced.
ChangeNotes notes = getNotes();
if (notes != null && notes.revisionNoteMap != null) {
- ObjectId idFromNotes =
- firstNonNull(notes.load().getRevision(), ObjectId.zeroId());
+ ObjectId idFromNotes = firstNonNull(notes.load().getRevision(), ObjectId.zeroId());
if (idFromNotes.equals(curr)) {
return notes.revisionNoteMap;
}
@@ -502,15 +519,12 @@
// Even though reading from changes might not be enabled, we need to
// parse any existing revision notes so we can merge them.
return RevisionNoteMap.parse(
- noteUtil,
- getId(),
- rw.getObjectReader(),
- noteMap,
- PatchLineComment.Status.PUBLISHED);
+ noteUtil, getId(), rw.getObjectReader(), noteMap, PatchLineComment.Status.PUBLISHED);
}
- private void checkComments(Map<RevId, ChangeRevisionNote> existingNotes,
- Map<RevId, RevisionNoteBuilder> toUpdate) throws OrmException {
+ private void checkComments(
+ Map<RevId, ChangeRevisionNote> existingNotes, Map<RevId, RevisionNoteBuilder> toUpdate)
+ throws OrmException {
// Prohibit various kinds of illegal operations on comments.
Set<Comment.Key> existing = new HashSet<>();
for (ChangeRevisionNote rn : existingNotes.values()) {
@@ -540,8 +554,7 @@
for (RevisionNoteBuilder b : toUpdate.values()) {
for (Comment c : b.put.values()) {
if (existing.contains(c.key)) {
- throw new OrmException(
- "Cannot update existing published comment: " + c);
+ throw new OrmException("Cannot update existing published comment: " + c);
}
}
}
@@ -553,8 +566,8 @@
}
@Override
- protected CommitBuilder applyImpl(RevWalk rw, ObjectInserter ins,
- ObjectId curr) throws OrmException, IOException {
+ protected CommitBuilder applyImpl(RevWalk rw, ObjectInserter ins, ObjectId curr)
+ throws OrmException, IOException {
CommitBuilder cb = new CommitBuilder();
int ps = psId != null ? psId.get() : getChange().currentPatchSetId().get();
@@ -632,14 +645,12 @@
addIdent(msg, e.getKey()).append('\n');
}
- for (Table.Cell<String, Account.Id, Optional<Short>> c
- : approvals.cellSet()) {
+ for (Table.Cell<String, Account.Id, Optional<Short>> c : approvals.cellSet()) {
addFooter(msg, FOOTER_LABEL);
if (!c.getValue().isPresent()) {
msg.append('-').append(c.getRowKey());
} else {
- msg.append(LabelVote.create(
- c.getRowKey(), c.getValue().get()).formatWithEquals());
+ msg.append(LabelVote.create(c.getRowKey(), c.getValue().get()).formatWithEquals());
}
Account.Id id = c.getColumnKey();
if (!id.equals(getAccountId())) {
@@ -654,8 +665,7 @@
if (submitRecords != null) {
for (SubmitRecord rec : submitRecords) {
- addFooter(msg, FOOTER_SUBMITTED_WITH)
- .append(rec.status);
+ addFooter(msg, FOOTER_SUBMITTED_WITH).append(rec.status);
if (rec.errorMessage != null) {
msg.append(' ').append(sanitizeFooter(rec.errorMessage));
}
@@ -664,7 +674,9 @@
if (rec.labels != null) {
for (SubmitRecord.Label label : rec.labels) {
addFooter(msg, FOOTER_SUBMITTED_WITH)
- .append(label.status).append(": ").append(label.label);
+ .append(label.status)
+ .append(": ")
+ .append(label.label);
if (label.appliedBy != null) {
msg.append(": ");
addIdent(msg, label.appliedBy);
@@ -749,8 +761,7 @@
return sb.append(footer.getName()).append(": ");
}
- private static void addFooter(StringBuilder sb, FooterKey footer,
- Object... values) {
+ private static void addFooter(StringBuilder sb, FooterKey footer, Object... values) {
addFooter(sb, footer);
for (Object value : values) {
sb.append(value);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/ConfigNotesMigration.java b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/ConfigNotesMigration.java
index 3d2d4fd..0dc20ed 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/ConfigNotesMigration.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/ConfigNotesMigration.java
@@ -24,20 +24,17 @@
import com.google.inject.AbstractModule;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.lib.Config;
-
import java.util.HashSet;
import java.util.Set;
+import org.eclipse.jgit.lib.Config;
/**
* Implement NoteDb migration stages using {@code gerrit.config}.
- * <p>
- * This class controls the state of the migration according to options in
- * {@code gerrit.config}. In general, any changes to these options should only
- * be made by adventurous administrators, who know what they're doing, on
- * non-production data, for the purposes of testing the NoteDb implementation.
- * Changing options quite likely requires re-running {@code RebuildNoteDb}. For
+ *
+ * <p>This class controls the state of the migration according to options in {@code gerrit.config}.
+ * In general, any changes to these options should only be made by adventurous administrators, who
+ * know what they're doing, on non-production data, for the purposes of testing the NoteDb
+ * implementation. Changing options quite likely requires re-running {@code RebuildNoteDb}. For
* these reasons, the options remain undocumented.
*/
@Singleton
@@ -62,17 +59,16 @@
for (NoteDbTable t : NoteDbTable.values()) {
keys.add(t.key().toLowerCase());
}
- Set<String> allowed = ImmutableSet.of(
- PRIMARY_STORAGE.toLowerCase(),
- READ.toLowerCase(),
- WRITE.toLowerCase(),
- SEQUENCE.toLowerCase());
+ Set<String> allowed =
+ ImmutableSet.of(
+ PRIMARY_STORAGE.toLowerCase(),
+ READ.toLowerCase(),
+ WRITE.toLowerCase(),
+ SEQUENCE.toLowerCase());
for (String t : cfg.getSubsections(NOTE_DB)) {
- checkArgument(keys.contains(t.toLowerCase()),
- "invalid NoteDb table: %s", t);
+ checkArgument(keys.contains(t.toLowerCase()), "invalid NoteDb table: %s", t);
for (String key : cfg.getNames(NOTE_DB, t)) {
- checkArgument(allowed.contains(key.toLowerCase()),
- "invalid NoteDb key: %s.%s", t, key);
+ checkArgument(allowed.contains(key.toLowerCase()), "invalid NoteDb key: %s.%s", t, key);
}
}
}
@@ -107,8 +103,8 @@
// NoteDb. This decision for the default may be reevaluated later.
readChangeSequence = cfg.getBoolean(NOTE_DB, CHANGES.key(), SEQUENCE, false);
- changePrimaryStorage = cfg.getEnum(
- NOTE_DB, CHANGES.key(), PRIMARY_STORAGE, PrimaryStorage.REVIEW_DB);
+ changePrimaryStorage =
+ cfg.getEnum(NOTE_DB, CHANGES.key(), PRIMARY_STORAGE, PrimaryStorage.REVIEW_DB);
writeAccounts = cfg.getBoolean(NOTE_DB, ACCOUNTS.key(), WRITE, false);
readAccounts = cfg.getBoolean(NOTE_DB, ACCOUNTS.key(), READ, false);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/DraftCommentNotes.java b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/DraftCommentNotes.java
index 0408ffa..008f31f 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/DraftCommentNotes.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/DraftCommentNotes.java
@@ -40,7 +40,8 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
-
+import java.io.IOException;
+import java.util.concurrent.TimeUnit;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.ObjectReader;
@@ -52,21 +53,14 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.util.concurrent.TimeUnit;
-
-/**
- * View of the draft comments for a single {@link Change} based on the log of
- * its drafts branch.
- */
+/** View of the draft comments for a single {@link Change} based on the log of its drafts branch. */
public class DraftCommentNotes extends AbstractChangeNotes<DraftCommentNotes> {
- private static final Logger log =
- LoggerFactory.getLogger(DraftCommentNotes.class);
+ private static final Logger log = LoggerFactory.getLogger(DraftCommentNotes.class);
public interface Factory {
DraftCommentNotes create(Change change, Account.Id accountId);
- DraftCommentNotes createWithAutoRebuildingDisabled(
- Change.Id changeId, Account.Id accountId);
+
+ DraftCommentNotes createWithAutoRebuildingDisabled(Change.Id changeId, Account.Id accountId);
}
private final Change change;
@@ -78,18 +72,12 @@
private RevisionNoteMap<ChangeRevisionNote> revisionNoteMap;
@AssistedInject
- DraftCommentNotes(
- Args args,
- @Assisted Change change,
- @Assisted Account.Id author) {
+ DraftCommentNotes(Args args, @Assisted Change change, @Assisted Account.Id author) {
this(args, change, author, true, null, null);
}
@AssistedInject
- DraftCommentNotes(
- Args args,
- @Assisted Change.Id changeId,
- @Assisted Account.Id author) {
+ DraftCommentNotes(Args args, @Assisted Change.Id changeId, @Assisted Account.Id author) {
// PrimaryStorage is unknown; this should only called by
// PatchLineCommentsUtil#draftByAuthor, which can live with this.
super(args, changeId, null, false);
@@ -115,7 +103,9 @@
checkArgument(
ref.getName().equals(getRefName()),
"draft ref not for change %s and account %s: %s",
- getChangeId(), author, ref.getName());
+ getChangeId(),
+ author,
+ ref.getName());
}
}
@@ -154,8 +144,7 @@
}
@Override
- protected void onLoad(LoadHandle handle)
- throws IOException, ConfigInvalidException {
+ protected void onLoad(LoadHandle handle) throws IOException, ConfigInvalidException {
ObjectId rev = handle.id();
if (rev == null) {
loadDefaults();
@@ -164,11 +153,14 @@
RevCommit tipCommit = handle.walk().parseCommit(rev);
ObjectReader reader = handle.walk().getObjectReader();
- revisionNoteMap = RevisionNoteMap.parse(
- args.noteUtil, getChangeId(), reader, NoteMap.read(reader, tipCommit),
- PatchLineComment.Status.DRAFT);
- ListMultimap<RevId, Comment> cs =
- MultimapBuilder.hashKeys().arrayListValues().build();
+ revisionNoteMap =
+ RevisionNoteMap.parse(
+ args.noteUtil,
+ getChangeId(),
+ reader,
+ NoteMap.read(reader, tipCommit),
+ PatchLineComment.Status.DRAFT);
+ ListMultimap<RevId, Comment> cs = MultimapBuilder.hashKeys().arrayListValues().build();
for (ChangeRevisionNote rn : revisionNoteMap.revisionNotes.values()) {
for (Comment c : rn.getComments()) {
cs.put(new RevId(c.revId), c);
@@ -188,8 +180,7 @@
}
@Override
- protected LoadHandle openHandle(Repository repo)
- throws NoSuchChangeException, IOException {
+ protected LoadHandle openHandle(Repository repo) throws NoSuchChangeException, IOException {
if (rebuildResult != null) {
StagedResult sr = checkNotNull(rebuildResult.staged());
return LoadHandle.create(
@@ -207,8 +198,7 @@
return super.openHandle(repo);
}
- private static ObjectId findNewId(
- Iterable<ReceiveCommand> cmds, String refName) {
+ private static ObjectId findNewId(Iterable<ReceiveCommand> cmds, String refName) {
for (ReceiveCommand cmd : cmds) {
if (cmd.getRefName().equals(refName)) {
return cmd.getNewId();
@@ -217,8 +207,7 @@
return null;
}
- private LoadHandle rebuildAndOpen(Repository repo)
- throws NoSuchChangeException, IOException {
+ private LoadHandle rebuildAndOpen(Repository repo) throws NoSuchChangeException, IOException {
Timer1.Context timer = args.metrics.autoRebuildLatency.start(CHANGES);
try {
Change.Id cid = getChangeId();
@@ -235,14 +224,11 @@
repo.scanForRepoChanges();
} catch (OrmException | IOException e) {
// See ChangeNotes#rebuildAndOpen.
- log.debug("Rebuilding change {} via drafts failed: {}",
- getChangeId(), e.getMessage());
+ log.debug("Rebuilding change {} via drafts failed: {}", getChangeId(), e.getMessage());
args.metrics.autoRebuildFailureCount.increment(CHANGES);
checkNotNull(r.staged());
return LoadHandle.create(
- ChangeNotesCommit.newStagedRevWalk(
- repo, r.staged().allUsersObjects()),
- draftsId(r));
+ ChangeNotesCommit.newStagedRevWalk(repo, r.staged().allUsersObjects()), draftsId(r));
}
}
return LoadHandle.create(ChangeNotesCommit.newRevWalk(repo), draftsId(r));
@@ -251,11 +237,10 @@
} catch (OrmException e) {
throw new IOException(e);
} finally {
- log.debug("Rebuilt change {} in {} in {} ms via drafts",
+ log.debug(
+ "Rebuilt change {} in {} in {} ms via drafts",
getChangeId(),
- change != null
- ? "project " + change.getProject()
- : "unknown project",
+ change != null ? "project " + change.getProject() : "unknown project",
TimeUnit.MILLISECONDS.convert(timer.stop(), TimeUnit.NANOSECONDS));
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/GwtormChangeBundleReader.java b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/GwtormChangeBundleReader.java
index e401a52..ee28d29 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/GwtormChangeBundleReader.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/GwtormChangeBundleReader.java
@@ -22,22 +22,18 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
import java.util.List;
@Singleton
public class GwtormChangeBundleReader implements ChangeBundleReader {
@Inject
- GwtormChangeBundleReader() {
- }
+ GwtormChangeBundleReader() {}
@Override
- public ChangeBundle fromReviewDb(ReviewDb db, Change.Id id)
- throws OrmException {
+ public ChangeBundle fromReviewDb(ReviewDb db, Change.Id id) throws OrmException {
db.changes().beginTransaction(id);
try {
- List<PatchSetApproval> approvals =
- db.patchSetApprovals().byChange(id).toList();
+ List<PatchSetApproval> approvals = db.patchSetApprovals().byChange(id).toList();
return new ChangeBundle(
db.changes().get(id),
db.changeMessages().byChange(id),
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/NoteDbChangeState.java b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/NoteDbChangeState.java
index d488fcb..1350a1f 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/NoteDbChangeState.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/NoteDbChangeState.java
@@ -36,10 +36,6 @@
import com.google.gerrit.reviewdb.server.ReviewDbUtil;
import com.google.gerrit.server.git.RefCache;
import com.google.gwtorm.server.OrmRuntimeException;
-
-import org.eclipse.jgit.lib.Config;
-import org.eclipse.jgit.lib.ObjectId;
-
import java.io.IOException;
import java.sql.Timestamp;
import java.util.HashMap;
@@ -48,21 +44,23 @@
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
+import org.eclipse.jgit.lib.Config;
+import org.eclipse.jgit.lib.ObjectId;
/**
- * The state of all relevant NoteDb refs across all repos corresponding to a
- * given Change entity.
- * <p>
- * Stored serialized in the {@code Change#noteDbState} field, and used to
- * determine whether the state in NoteDb is out of date.
- * <p>
- * Serialized in one of the forms:
+ * The state of all relevant NoteDb refs across all repos corresponding to a given Change entity.
+ *
+ * <p>Stored serialized in the {@code Change#noteDbState} field, and used to determine whether the
+ * state in NoteDb is out of date.
+ *
+ * <p>Serialized in one of the forms:
+ *
* <ul>
- * <li>[meta-sha],[account1]=[drafts-sha],[account2]=[drafts-sha]...
- * <li>R,[meta-sha],[account1]=[drafts-sha],[account2]=[drafts-sha]...
- * <li>R=[read-only-until],[meta-sha],[account1]=[drafts-sha],[account2]=[drafts-sha]...
- * <li>N
- * <li>N=[read-only-until]
+ * <li>[meta-sha],[account1]=[drafts-sha],[account2]=[drafts-sha]...
+ * <li>R,[meta-sha],[account1]=[drafts-sha],[account2]=[drafts-sha]...
+ * <li>R=[read-only-until],[meta-sha],[account1]=[drafts-sha],[account2]=[drafts-sha]...
+ * <li>N
+ * <li>N=[read-only-until]
* </ul>
*
* in numeric account ID order, with hex SHA-1s for human readability.
@@ -92,54 +90,50 @@
@AutoValue
public abstract static class Delta {
@VisibleForTesting
- public static Delta create(Change.Id changeId,
+ public static Delta create(
+ Change.Id changeId,
Optional<ObjectId> newChangeMetaId,
Map<Account.Id, ObjectId> newDraftIds) {
if (newDraftIds == null) {
newDraftIds = ImmutableMap.of();
}
return new AutoValue_NoteDbChangeState_Delta(
- changeId,
- newChangeMetaId,
- ImmutableMap.copyOf(newDraftIds));
+ changeId, newChangeMetaId, ImmutableMap.copyOf(newDraftIds));
}
abstract Change.Id changeId();
+
abstract Optional<ObjectId> newChangeMetaId();
+
abstract ImmutableMap<Account.Id, ObjectId> newDraftIds();
}
@AutoValue
public abstract static class RefState {
@VisibleForTesting
- public static RefState create(ObjectId changeMetaId,
- Map<Account.Id, ObjectId> draftIds) {
+ public static RefState create(ObjectId changeMetaId, Map<Account.Id, ObjectId> draftIds) {
return new AutoValue_NoteDbChangeState_RefState(
changeMetaId.copy(),
- ImmutableMap.copyOf(
- Maps.filterValues(draftIds, id -> !ObjectId.zeroId().equals(id))));
+ ImmutableMap.copyOf(Maps.filterValues(draftIds, id -> !ObjectId.zeroId().equals(id))));
}
- private static Optional<RefState> parse(Change.Id changeId,
- List<String> parts) {
- checkArgument(!parts.isEmpty(),
- "missing state string for change %s", changeId);
+ private static Optional<RefState> parse(Change.Id changeId, List<String> parts) {
+ checkArgument(!parts.isEmpty(), "missing state string for change %s", changeId);
ObjectId changeMetaId = ObjectId.fromString(parts.get(0));
- Map<Account.Id, ObjectId> draftIds =
- Maps.newHashMapWithExpectedSize(parts.size() - 1);
+ Map<Account.Id, ObjectId> draftIds = Maps.newHashMapWithExpectedSize(parts.size() - 1);
Splitter s = Splitter.on('=');
for (int i = 1; i < parts.size(); i++) {
String p = parts.get(i);
List<String> draftParts = s.splitToList(p);
- checkArgument(draftParts.size() == 2,
- "invalid draft state part for change %s: %s", changeId, p);
- draftIds.put(Account.Id.parse(draftParts.get(0)),
- ObjectId.fromString(draftParts.get(1)));
+ checkArgument(
+ draftParts.size() == 2, "invalid draft state part for change %s: %s", changeId, p);
+ draftIds.put(Account.Id.parse(draftParts.get(0)), ObjectId.fromString(draftParts.get(1)));
}
return Optional.of(create(changeMetaId, draftIds));
}
abstract ObjectId changeMetaId();
+
abstract ImmutableMap<Account.Id, ObjectId> draftIds();
@Override
@@ -149,12 +143,8 @@
StringBuilder appendTo(StringBuilder sb) {
sb.append(changeMetaId().name());
- for (Account.Id id : ReviewDbUtil.intKeyOrdering()
- .sortedCopy(draftIds().keySet())) {
- sb.append(',')
- .append(id.get())
- .append('=')
- .append(draftIds().get(id).name());
+ for (Account.Id id : ReviewDbUtil.intKeyOrdering().sortedCopy(draftIds().keySet())) {
+ sb.append(',').append(id.get()).append('=').append(draftIds().get(id).name());
}
return sb;
}
@@ -177,8 +167,7 @@
// Only valid NOTE_DB state is "N".
if (parts.size() == 1 && first.charAt(0) == NOTE_DB.code) {
- return new NoteDbChangeState(
- id, NOTE_DB, Optional.empty(), readOnlyUntil);
+ return new NoteDbChangeState(id, NOTE_DB, Optional.empty(), readOnlyUntil);
}
// Otherwise it must be REVIEW_DB, either "R,<RefState>" or just
@@ -195,8 +184,8 @@
throw invalidState(id, str);
}
- private static Optional<Timestamp> parseReadOnlyUntil(Change.Id id,
- String fullStr, String first) {
+ private static Optional<Timestamp> parseReadOnlyUntil(
+ Change.Id id, String fullStr, String first) {
if (first.length() > 2 && first.charAt(1) == '=') {
Long ts = Longs.tryParse(first.substring(2));
if (ts == null) {
@@ -207,25 +196,20 @@
return Optional.empty();
}
- private static IllegalArgumentException invalidState(Change.Id id,
- String str) {
- return new IllegalArgumentException(
- "invalid state string for change " + id + ": " + str);
+ private static IllegalArgumentException invalidState(Change.Id id, String str) {
+ return new IllegalArgumentException("invalid state string for change " + id + ": " + str);
}
/**
* Apply a delta to the state stored in a change entity.
- * <p>
- * This method does not check whether the old state was read-only; it is up to
- * the caller to not violate read-only semantics when storing the change back
- * in ReviewDb.
*
- * @param change change entity. The delta is applied against this entity's
- * {@code noteDbState} and the new state is stored back in the entity as a
- * side effect.
+ * <p>This method does not check whether the old state was read-only; it is up to the caller to
+ * not violate read-only semantics when storing the change back in ReviewDb.
+ *
+ * @param change change entity. The delta is applied against this entity's {@code noteDbState} and
+ * the new state is stored back in the entity as a side effect.
* @param delta delta to apply.
- * @return new state, equivalent to what is stored in {@code change} as a side
- * effect.
+ * @return new state, equivalent to what is stored in {@code change} as a side effect.
*/
public static NoteDbChangeState applyDelta(Change change, Delta delta) {
if (delta == null) {
@@ -267,16 +251,15 @@
}
}
- NoteDbChangeState state = new NoteDbChangeState(
- change.getId(),
- oldState != null
- ? oldState.getPrimaryStorage()
- : REVIEW_DB,
- Optional.of(RefState.create(changeMetaId, draftIds)),
- // Copy old read-only deadline rather than advancing it; the caller is
- // still responsible for finishing the rest of its work before the lease
- // runs out.
- oldState != null ? oldState.getReadOnlyUntil() : Optional.empty());
+ NoteDbChangeState state =
+ new NoteDbChangeState(
+ change.getId(),
+ oldState != null ? oldState.getPrimaryStorage() : REVIEW_DB,
+ Optional.of(RefState.create(changeMetaId, draftIds)),
+ // Copy old read-only deadline rather than advancing it; the caller is
+ // still responsible for finishing the rest of its work before the lease
+ // runs out.
+ oldState != null ? oldState.getReadOnlyUntil() : Optional.empty());
change.setNoteDbState(state.toString());
return state;
}
@@ -287,8 +270,9 @@
// - can't be methods on NoteDbChangeState because state is nullable (though
// we could also solve this by inventing an empty-but-non-null state)
// Also we should clean up duplicated code between static/non-static methods.
- public static boolean isChangeUpToDate(@Nullable NoteDbChangeState state,
- RefCache changeRepoRefs, Change.Id changeId) throws IOException {
+ public static boolean isChangeUpToDate(
+ @Nullable NoteDbChangeState state, RefCache changeRepoRefs, Change.Id changeId)
+ throws IOException {
if (PrimaryStorage.of(state) == NOTE_DB) {
return true; // Primary storage is NoteDb, up to date by definition.
}
@@ -298,22 +282,23 @@
return state.isChangeUpToDate(changeRepoRefs);
}
- public static boolean areDraftsUpToDate(@Nullable NoteDbChangeState state,
- RefCache draftsRepoRefs, Change.Id changeId, Account.Id accountId)
+ public static boolean areDraftsUpToDate(
+ @Nullable NoteDbChangeState state,
+ RefCache draftsRepoRefs,
+ Change.Id changeId,
+ Account.Id accountId)
throws IOException {
if (PrimaryStorage.of(state) == NOTE_DB) {
return true; // Primary storage is NoteDb, up to date by definition.
}
if (state == null) {
- return !draftsRepoRefs.get(refsDraftComments(changeId, accountId))
- .isPresent();
+ return !draftsRepoRefs.get(refsDraftComments(changeId, accountId)).isPresent();
}
return state.areDraftsUpToDate(draftsRepoRefs, accountId);
}
public static long getReadOnlySkew(Config cfg) {
- return cfg.getTimeUnit(
- "notedb", null, "maxTimestampSkew", 1000, TimeUnit.MILLISECONDS);
+ return cfg.getTimeUnit("notedb", null, "maxTimestampSkew", 1000, TimeUnit.MILLISECONDS);
}
private static Timestamp timeForReadOnlyCheck(long skewMs) {
@@ -326,14 +311,15 @@
checkNotReadOnly(parse(change), skewMs);
}
- public static void checkNotReadOnly(@Nullable NoteDbChangeState state,
- long skewMs) {
+ public static void checkNotReadOnly(@Nullable NoteDbChangeState state, long skewMs) {
if (state == null) {
return; // No state means ReviewDb primary non-read-only.
} else if (state.isReadOnly(timeForReadOnlyCheck(skewMs))) {
throw new OrmRuntimeException(
- "change " + state.getChangeId() + " is read-only until "
- + state.getReadOnlyUntil().get());
+ "change "
+ + state.getChangeId()
+ + " is read-only until "
+ + state.getReadOnlyUntil().get());
}
}
@@ -357,17 +343,18 @@
checkArgument(
refState.isPresent(),
"expected RefState for change %s with primary storage %s",
- changeId, primaryStorage);
+ changeId,
+ primaryStorage);
break;
case NOTE_DB:
checkArgument(
!refState.isPresent(),
"expected no RefState for change %s with primary storage %s",
- changeId, primaryStorage);
+ changeId,
+ primaryStorage);
break;
default:
- throw new IllegalStateException(
- "invalid PrimaryStorage: " + primaryStorage);
+ throw new IllegalStateException("invalid PrimaryStorage: " + primaryStorage);
}
}
@@ -391,16 +378,14 @@
if (primaryStorage == NOTE_DB) {
return true; // Primary storage is NoteDb, up to date by definition.
}
- Optional<ObjectId> id =
- draftsRepoRefs.get(refsDraftComments(changeId, accountId));
+ Optional<ObjectId> id = draftsRepoRefs.get(refsDraftComments(changeId, accountId));
if (!id.isPresent()) {
return !getDraftIds().containsKey(accountId);
}
return id.get().equals(getDraftIds().get(accountId));
}
- public boolean isUpToDate(RefCache changeRepoRefs, RefCache draftsRepoRefs)
- throws IOException {
+ public boolean isUpToDate(RefCache changeRepoRefs, RefCache draftsRepoRefs) throws IOException {
if (primaryStorage == NOTE_DB) {
return true; // Primary storage is NoteDb, up to date by definition.
}
@@ -424,8 +409,7 @@
}
public NoteDbChangeState withReadOnlyUntil(Timestamp ts) {
- return new NoteDbChangeState(
- changeId, primaryStorage, refState, Optional.of(ts));
+ return new NoteDbChangeState(changeId, primaryStorage, refState, Optional.of(ts));
}
public Change.Id getChangeId() {
@@ -445,8 +429,7 @@
}
private RefState refState() {
- checkState(refState.isPresent(),
- "state for %s has no RefState: %s", changeId, this);
+ checkState(refState.isPresent(), "state for %s has no RefState: %s", changeId, this);
return refState.get();
}
@@ -458,16 +441,14 @@
// Don't include enum field, just IDs (though parse would accept it).
return refState().toString();
}
- return primaryStorage.code + "=" + readOnlyUntil.get().getTime()
- + "," + refState.get();
+ return primaryStorage.code + "=" + readOnlyUntil.get().getTime() + "," + refState.get();
case NOTE_DB:
if (!readOnlyUntil.isPresent()) {
return NOTE_DB_PRIMARY_STATE;
}
return primaryStorage.code + "=" + readOnlyUntil.get().getTime();
default:
- throw new IllegalArgumentException(
- "Unsupported PrimaryStorage: " + primaryStorage);
+ throw new IllegalArgumentException("Unsupported PrimaryStorage: " + primaryStorage);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/NoteDbMetrics.java b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/NoteDbMetrics.java
index 24e87de..be06d11 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/NoteDbMetrics.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/NoteDbMetrics.java
@@ -29,30 +29,25 @@
final Timer1<NoteDbTable> updateLatency;
/**
- * The portion of {@link #updateLatency} due to preparing the sequence of
- * updates.
- * <p>
- * May include some I/O (e.g. reading old refs), but excludes writes.
+ * The portion of {@link #updateLatency} due to preparing the sequence of updates.
+ *
+ * <p>May include some I/O (e.g. reading old refs), but excludes writes.
*/
final Timer1<NoteDbTable> stageUpdateLatency;
- /**
- * End-to-end latency for reading changes from NoteDb, including reading
- * ref(s) and parsing.
- */
+ /** End-to-end latency for reading changes from NoteDb, including reading ref(s) and parsing. */
final Timer1<NoteDbTable> readLatency;
/**
- * The portion of {@link #readLatency} due to parsing commits, but excluding
- * I/O (to a best effort).
+ * The portion of {@link #readLatency} due to parsing commits, but excluding I/O (to a best
+ * effort).
*/
final Timer1<NoteDbTable> parseLatency;
/**
* Latency due to auto-rebuilding entities when out of date.
- * <p>
- * Excludes latency from reading ref to check whether the entity is up to
- * date.
+ *
+ * <p>Excludes latency from reading ref to check whether the entity is up to date.
*/
final Timer1<NoteDbTable> autoRebuildLatency;
@@ -63,45 +58,50 @@
NoteDbMetrics(MetricMaker metrics) {
Field<NoteDbTable> view = Field.ofEnum(NoteDbTable.class, "table");
- updateLatency = metrics.newTimer(
- "notedb/update_latency",
- new Description("NoteDb update latency by table")
- .setCumulative()
- .setUnit(Units.MILLISECONDS),
- view);
+ updateLatency =
+ metrics.newTimer(
+ "notedb/update_latency",
+ new Description("NoteDb update latency by table")
+ .setCumulative()
+ .setUnit(Units.MILLISECONDS),
+ view);
- stageUpdateLatency = metrics.newTimer(
- "notedb/stage_update_latency",
- new Description("Latency for staging updates to NoteDb by table")
- .setCumulative()
- .setUnit(Units.MICROSECONDS),
- view);
+ stageUpdateLatency =
+ metrics.newTimer(
+ "notedb/stage_update_latency",
+ new Description("Latency for staging updates to NoteDb by table")
+ .setCumulative()
+ .setUnit(Units.MICROSECONDS),
+ view);
- readLatency = metrics.newTimer(
- "notedb/read_latency",
- new Description("NoteDb read latency by table")
- .setCumulative()
- .setUnit(Units.MILLISECONDS),
- view);
+ readLatency =
+ metrics.newTimer(
+ "notedb/read_latency",
+ new Description("NoteDb read latency by table")
+ .setCumulative()
+ .setUnit(Units.MILLISECONDS),
+ view);
- parseLatency = metrics.newTimer(
- "notedb/parse_latency",
- new Description("NoteDb parse latency by table")
- .setCumulative()
- .setUnit(Units.MICROSECONDS),
- view);
+ parseLatency =
+ metrics.newTimer(
+ "notedb/parse_latency",
+ new Description("NoteDb parse latency by table")
+ .setCumulative()
+ .setUnit(Units.MICROSECONDS),
+ view);
- autoRebuildLatency = metrics.newTimer(
- "notedb/auto_rebuild_latency",
- new Description("NoteDb auto-rebuilding latency by table")
- .setCumulative()
- .setUnit(Units.MILLISECONDS),
- view);
+ autoRebuildLatency =
+ metrics.newTimer(
+ "notedb/auto_rebuild_latency",
+ new Description("NoteDb auto-rebuilding latency by table")
+ .setCumulative()
+ .setUnit(Units.MILLISECONDS),
+ view);
- autoRebuildFailureCount = metrics.newCounter(
- "notedb/auto_rebuild_failure_count",
- new Description("NoteDb auto-rebuilding attempts that failed by table")
- .setCumulative(),
- view);
+ autoRebuildFailureCount =
+ metrics.newCounter(
+ "notedb/auto_rebuild_failure_count",
+ new Description("NoteDb auto-rebuilding attempts that failed by table").setCumulative(),
+ view);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/NoteDbModule.java b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/NoteDbModule.java
index 7934884..0b01e14 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/NoteDbModule.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/NoteDbModule.java
@@ -25,7 +25,6 @@
import com.google.gerrit.server.notedb.rebuild.ChangeRebuilderImpl;
import com.google.inject.TypeLiteral;
import com.google.inject.name.Names;
-
import org.eclipse.jgit.lib.Config;
public class NoteDbModule extends FactoryModule {
@@ -63,44 +62,43 @@
bind(ChangeRebuilder.class).to(ChangeRebuilderImpl.class);
}
} else {
- bind(ChangeRebuilder.class).toInstance(new ChangeRebuilder(null) {
- @Override
- public Result rebuild(ReviewDb db, Change.Id changeId) {
- return null;
- }
+ bind(ChangeRebuilder.class)
+ .toInstance(
+ new ChangeRebuilder(null) {
+ @Override
+ public Result rebuild(ReviewDb db, Change.Id changeId) {
+ return null;
+ }
- @Override
- public Result rebuildEvenIfReadOnly(ReviewDb db, Id changeId) {
- return null;
- }
+ @Override
+ public Result rebuildEvenIfReadOnly(ReviewDb db, Id changeId) {
+ return null;
+ }
- @Override
- public Result rebuild(NoteDbUpdateManager manager,
- ChangeBundle bundle) {
- return null;
- }
+ @Override
+ public Result rebuild(NoteDbUpdateManager manager, ChangeBundle bundle) {
+ return null;
+ }
- @Override
- public NoteDbUpdateManager stage(ReviewDb db, Change.Id changeId) {
- return null;
- }
+ @Override
+ public NoteDbUpdateManager stage(ReviewDb db, Change.Id changeId) {
+ return null;
+ }
- @Override
- public Result execute(ReviewDb db, Change.Id changeId,
- NoteDbUpdateManager manager) {
- return null;
- }
+ @Override
+ public Result execute(
+ ReviewDb db, Change.Id changeId, NoteDbUpdateManager manager) {
+ return null;
+ }
- @Override
- public void buildUpdates(NoteDbUpdateManager manager,
- ChangeBundle bundle) {
- // Do nothing.
- }
- });
+ @Override
+ public void buildUpdates(NoteDbUpdateManager manager, ChangeBundle bundle) {
+ // Do nothing.
+ }
+ });
bind(new TypeLiteral<Cache<ChangeNotesCache.Key, ChangeNotesState>>() {})
.annotatedWith(Names.named(ChangeNotesCache.CACHE_NAME))
- .toInstance(CacheBuilder.newBuilder()
- .<ChangeNotesCache.Key, ChangeNotesState>build());
+ .toInstance(CacheBuilder.newBuilder().<ChangeNotesCache.Key, ChangeNotesState>build());
}
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/NoteDbUpdateManager.java b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/NoteDbUpdateManager.java
index b5adea6..cc738e5 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/NoteDbUpdateManager.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/NoteDbUpdateManager.java
@@ -45,7 +45,13 @@
import com.google.inject.Provider;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
-
+import java.io.IOException;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
import org.eclipse.jgit.lib.BatchRefUpdate;
import org.eclipse.jgit.lib.NullProgressMonitor;
import org.eclipse.jgit.lib.ObjectId;
@@ -57,22 +63,14 @@
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.transport.ReceiveCommand;
-import java.io.IOException;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Optional;
-import java.util.Set;
-
/**
* Object to manage a single sequence of updates to NoteDb.
- * <p>
- * Instances are one-time-use. Handles updating both the change repo and the
- * All-Users repo for any affected changes, with proper ordering.
- * <p>
- * To see the state that would be applied prior to executing the full sequence
- * of updates, use {@link #stage()}.
+ *
+ * <p>Instances are one-time-use. Handles updating both the change repo and the All-Users repo for
+ * any affected changes, with proper ordering.
+ *
+ * <p>To see the state that would be applied prior to executing the full sequence of updates, use
+ * {@link #stage()}.
*/
public class NoteDbUpdateManager implements AutoCloseable {
public static final String CHANGES_READ_ONLY = "NoteDb changes are read-only";
@@ -83,9 +81,8 @@
@AutoValue
public abstract static class StagedResult {
- private static StagedResult create(Change.Id id,
- NoteDbChangeState.Delta delta, OpenRepo changeRepo,
- OpenRepo allUsersRepo) {
+ private static StagedResult create(
+ Change.Id id, NoteDbChangeState.Delta delta, OpenRepo changeRepo, OpenRepo allUsersRepo) {
ImmutableList<ReceiveCommand> changeCommands = ImmutableList.of();
ImmutableList<InsertedObject> changeObjects = ImmutableList.of();
if (changeRepo != null) {
@@ -105,24 +102,30 @@
}
public abstract Change.Id id();
- @Nullable public abstract NoteDbChangeState.Delta delta();
+
+ @Nullable
+ public abstract NoteDbChangeState.Delta delta();
+
public abstract ImmutableList<ReceiveCommand> changeCommands();
+
public abstract ImmutableList<InsertedObject> changeObjects();
public abstract ImmutableList<ReceiveCommand> allUsersCommands();
+
public abstract ImmutableList<InsertedObject> allUsersObjects();
}
@AutoValue
public abstract static class Result {
- static Result create(NoteDbUpdateManager.StagedResult staged,
- NoteDbChangeState newState) {
+ static Result create(NoteDbUpdateManager.StagedResult staged, NoteDbChangeState newState) {
return new AutoValue_NoteDbUpdateManager_Result(newState, staged);
}
- @Nullable public abstract NoteDbChangeState newState();
+ @Nullable
+ public abstract NoteDbChangeState newState();
- @Nullable abstract NoteDbUpdateManager.StagedResult staged();
+ @Nullable
+ abstract NoteDbUpdateManager.StagedResult staged();
}
public static class OpenRepo implements AutoCloseable {
@@ -135,12 +138,18 @@
private final boolean close;
- private OpenRepo(Repository repo, RevWalk rw, @Nullable ObjectInserter ins,
- ChainedReceiveCommands cmds, boolean close) {
+ private OpenRepo(
+ Repository repo,
+ RevWalk rw,
+ @Nullable ObjectInserter ins,
+ ChainedReceiveCommands cmds,
+ boolean close) {
ObjectReader reader = rw.getObjectReader();
- checkArgument(ins == null || reader.getCreatedFromInserter() == ins,
+ checkArgument(
+ ins == null || reader.getCreatedFromInserter() == ins,
"expected reader to be created from %s, but was %s",
- ins, reader.getCreatedFromInserter());
+ ins,
+ reader.getCreatedFromInserter());
this.repo = checkNotNull(repo);
this.tempIns = new InMemoryInserter(rw.getObjectReader());
this.rw = new RevWalk(tempIns.newReader());
@@ -197,7 +206,8 @@
private PersonIdent refLogIdent;
@AssistedInject
- NoteDbUpdateManager(@GerritPersonIdent Provider<PersonIdent> serverIdent,
+ NoteDbUpdateManager(
+ @GerritPersonIdent Provider<PersonIdent> serverIdent,
GitRepositoryManager repoManager,
NotesMigration migration,
AllUsersName allUsersName,
@@ -232,15 +242,15 @@
}
}
- public NoteDbUpdateManager setChangeRepo(Repository repo, RevWalk rw,
- @Nullable ObjectInserter ins, ChainedReceiveCommands cmds) {
+ public NoteDbUpdateManager setChangeRepo(
+ Repository repo, RevWalk rw, @Nullable ObjectInserter ins, ChainedReceiveCommands cmds) {
checkState(changeRepo == null, "change repo already initialized");
changeRepo = new OpenRepo(repo, rw, ins, cmds, false);
return this;
}
- public NoteDbUpdateManager setAllUsersRepo(Repository repo, RevWalk rw,
- @Nullable ObjectInserter ins, ChainedReceiveCommands cmds) {
+ public NoteDbUpdateManager setAllUsersRepo(
+ Repository repo, RevWalk rw, @Nullable ObjectInserter ins, ChainedReceiveCommands cmds) {
checkState(allUsersRepo == null, "All-Users repo already initialized");
allUsersRepo = new OpenRepo(repo, rw, ins, cmds, false);
return this;
@@ -286,8 +296,8 @@
private OpenRepo openRepo(Project.NameKey p) throws IOException {
Repository repo = repoManager.openRepository(p);
ObjectInserter ins = repo.newObjectInserter();
- return new OpenRepo(repo, new RevWalk(ins.newReader()), ins,
- new ChainedReceiveCommands(repo), true);
+ return new OpenRepo(
+ repo, new RevWalk(ins.newReader()), ins, new ChainedReceiveCommands(repo), true);
}
private boolean isEmpty() {
@@ -302,16 +312,18 @@
/**
* Add an update to the list of updates to execute.
- * <p>
- * Updates should only be added to the manager after all mutations have been
- * made, as this method may eagerly access the update.
+ *
+ * <p>Updates should only be added to the manager after all mutations have been made, as this
+ * method may eagerly access the update.
*
* @param update the update to add.
*/
public void add(ChangeUpdate update) {
- checkArgument(update.getProjectName().equals(projectName),
- "update for project %s cannot be added to manager for project %s",
- update.getProjectName(), projectName);
+ checkArgument(
+ update.getProjectName().equals(projectName),
+ "update for project %s cannot be added to manager for project %s",
+ update.getProjectName(),
+ projectName);
checkState(staged == null, "cannot add new update after staging");
changeUpdates.put(update.getRefName(), update);
ChangeDraftUpdate du = update.getDraftUpdate();
@@ -337,13 +349,12 @@
/**
* Stage updates in the manager's internal list of commands.
*
- * @return map of the state that would get written to the applicable repo(s)
- * for each affected change.
+ * @return map of the state that would get written to the applicable repo(s) for each affected
+ * change.
* @throws OrmException if a database layer error occurs.
* @throws IOException if a storage layer error occurs.
*/
- public Map<Change.Id, StagedResult> stage()
- throws OrmException, IOException {
+ public Map<Change.Id, StagedResult> stage() throws OrmException, IOException {
if (staged != null) {
return staged;
}
@@ -372,20 +383,23 @@
changeId,
NoteDbChangeState.Delta.create(
changeId, metaId, allDraftIds.rowMap().remove(changeId)),
- changeRepo, allUsersRepo));
+ changeRepo,
+ allUsersRepo));
}
- for (Map.Entry<Change.Id, Map<Account.Id, ObjectId>> e
- : allDraftIds.rowMap().entrySet()) {
+ for (Map.Entry<Change.Id, Map<Account.Id, ObjectId>> e : allDraftIds.rowMap().entrySet()) {
// If a change remains in the table at this point, it means we are
// updating its drafts but not the change itself.
- StagedResult r = StagedResult.create(
- e.getKey(),
- NoteDbChangeState.Delta.create(
- e.getKey(), Optional.empty(), e.getValue()),
- changeRepo, allUsersRepo);
- checkState(r.changeCommands().isEmpty(),
- "should not have change commands when updating only drafts: %s", r);
+ StagedResult r =
+ StagedResult.create(
+ e.getKey(),
+ NoteDbChangeState.Delta.create(e.getKey(), Optional.empty(), e.getValue()),
+ changeRepo,
+ allUsersRepo);
+ checkState(
+ r.changeCommands().isEmpty(),
+ "should not have change commands when updating only drafts: %s",
+ r);
staged.put(r.id(), r);
}
@@ -393,8 +407,7 @@
}
}
- public Result stageAndApplyDelta(Change change)
- throws OrmException, IOException {
+ public Result stageAndApplyDelta(Change change) throws OrmException, IOException {
StagedResult sr = stage().get(change.getId());
NoteDbChangeState newState =
NoteDbChangeState.applyDelta(change, sr != null ? sr.delta() : null);
@@ -409,8 +422,7 @@
for (ReceiveCommand cmd : allUsersRepo.getCommandsSnapshot()) {
String r = cmd.getRefName();
if (r.startsWith(REFS_DRAFT_COMMENTS)) {
- Change.Id changeId =
- Change.Id.fromRefPart(r.substring(REFS_DRAFT_COMMENTS.length()));
+ Change.Id changeId = Change.Id.fromRefPart(r.substring(REFS_DRAFT_COMMENTS.length()));
Account.Id accountId = Account.Id.fromRefSuffix(r);
checkDraftRef(accountId != null && changeId != null, r);
draftIds.put(changeId, accountId, cmd.getNewId());
@@ -459,8 +471,7 @@
}
or.flush();
BatchRefUpdate bru = or.repo.getRefDatabase().newBatchUpdate();
- bru.setRefLogMessage(
- firstNonNull(refLogMessage, "Update NoteDb refs"), false);
+ bru.setRefLogMessage(firstNonNull(refLogMessage, "Update NoteDb refs"), false);
bru.setRefLogIdent(refLogIdent != null ? refLogIdent : serverIdent.get());
or.cmds.addTo(bru);
bru.setAllowNonFastForwards(true);
@@ -497,17 +508,15 @@
String metaRef = RefNames.changeMetaRef(id);
Optional<ObjectId> old = changeRepo.cmds.get(metaRef);
if (old.isPresent()) {
- changeRepo.cmds.add(
- new ReceiveCommand(old.get(), ObjectId.zeroId(), metaRef));
+ changeRepo.cmds.add(new ReceiveCommand(old.get(), ObjectId.zeroId(), metaRef));
}
// Just scan repo for ref names, but get "old" values from cmds.
- for (Ref r : allUsersRepo.repo.getRefDatabase().getRefs(
- RefNames.refsDraftCommentsPrefix(id)).values()) {
+ for (Ref r :
+ allUsersRepo.repo.getRefDatabase().getRefs(RefNames.refsDraftCommentsPrefix(id)).values()) {
old = allUsersRepo.cmds.get(r.getName());
if (old.isPresent()) {
- allUsersRepo.cmds.add(
- new ReceiveCommand(old.get(), ObjectId.zeroId(), r.getName()));
+ allUsersRepo.cmds.add(new ReceiveCommand(old.get(), ObjectId.zeroId(), r.getName()));
}
}
}
@@ -516,10 +525,10 @@
private static final long serialVersionUID = 1L;
private MismatchedStateException(Change.Id id, NoteDbChangeState expectedState) {
- super(String.format(
- "cannot apply NoteDb updates for change %s;"
- + " change meta ref does not match %s",
- id, expectedState.getChangeMetaId().name()));
+ super(
+ String.format(
+ "cannot apply NoteDb updates for change %s;" + " change meta ref does not match %s",
+ id, expectedState.getChangeMetaId().name()));
}
}
@@ -565,27 +574,25 @@
ChangeDraftUpdate u = us.iterator().next();
NoteDbChangeState expectedState = NoteDbChangeState.parse(u.getChange());
- if (expectedState == null
- || expectedState.getPrimaryStorage() == PrimaryStorage.NOTE_DB) {
+ if (expectedState == null || expectedState.getPrimaryStorage() == PrimaryStorage.NOTE_DB) {
continue; // See above.
}
Account.Id accountId = u.getAccountId();
- if (!expectedState.areDraftsUpToDate(
- allUsersRepo.cmds.getRepoRefCache(), accountId)) {
- ObjectId expectedDraftId = firstNonNull(
- expectedState.getDraftIds().get(accountId), ObjectId.zeroId());
- throw new OrmConcurrencyException(String.format(
- "cannot apply NoteDb updates for change %s;"
- + " draft ref for account %s does not match %s",
- u.getId(), accountId, expectedDraftId.name()));
+ if (!expectedState.areDraftsUpToDate(allUsersRepo.cmds.getRepoRefCache(), accountId)) {
+ ObjectId expectedDraftId =
+ firstNonNull(expectedState.getDraftIds().get(accountId), ObjectId.zeroId());
+ throw new OrmConcurrencyException(
+ String.format(
+ "cannot apply NoteDb updates for change %s;"
+ + " draft ref for account %s does not match %s",
+ u.getId(), accountId, expectedDraftId.name()));
}
}
}
private static <U extends AbstractChangeUpdate> void addUpdates(
- ListMultimap<String, U> all, OpenRepo or)
- throws OrmException, IOException {
+ ListMultimap<String, U> all, OpenRepo or) throws OrmException, IOException {
for (Map.Entry<String, Collection<U>> e : all.asMap().entrySet()) {
String refName = e.getKey();
Collection<U> updates = e.getValue();
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/NotesMigration.java b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/NotesMigration.java
index 6afe87d..773042d 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/NotesMigration.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/NotesMigration.java
@@ -18,58 +18,52 @@
/**
* Holds the current state of the NoteDb migration.
- * <p>
- * The migration will proceed one root entity type at a time. A <em>root
- * entity</em> is an entity stored in ReviewDb whose key's
- * {@code getParentKey()} method returns null. For an example of the entity
- * hierarchy rooted at Change, see the diagram in
- * {@code com.google.gerrit.reviewdb.client.Change}.
- * <p>
- * During a transitional period, each root entity group from ReviewDb may be
- * either <em>written to</em> or <em>both written to and read from</em> NoteDb.
- * <p>
- * This class controls the state of the migration according to options in
- * {@code gerrit.config}. In general, any changes to these options should only
- * be made by adventurous administrators, who know what they're doing, on
- * non-production data, for the purposes of testing the NoteDb implementation.
- * Changing options quite likely requires re-running {@code RebuildNoteDb}. For
+ *
+ * <p>The migration will proceed one root entity type at a time. A <em>root entity</em> is an entity
+ * stored in ReviewDb whose key's {@code getParentKey()} method returns null. For an example of the
+ * entity hierarchy rooted at Change, see the diagram in {@code
+ * com.google.gerrit.reviewdb.client.Change}.
+ *
+ * <p>During a transitional period, each root entity group from ReviewDb may be either <em>written
+ * to</em> or <em>both written to and read from</em> NoteDb.
+ *
+ * <p>This class controls the state of the migration according to options in {@code gerrit.config}.
+ * In general, any changes to these options should only be made by adventurous administrators, who
+ * know what they're doing, on non-production data, for the purposes of testing the NoteDb
+ * implementation. Changing options quite likely requires re-running {@code RebuildNoteDb}. For
* these reasons, the options remain undocumented.
*/
public abstract class NotesMigration {
/**
* Read changes from NoteDb.
- * <p>
- * Change data is read from NoteDb refs, but ReviewDb is still the source of
- * truth. If the loader determines NoteDb is out of date, the change data in
- * NoteDb will be transparently rebuilt. This means that some code paths that
- * look read-only may in fact attempt to write.
- * <p>
- * If true and {@code writeChanges() = false}, changes can still be read from
- * NoteDb, but any attempts to write will generate an error.
+ *
+ * <p>Change data is read from NoteDb refs, but ReviewDb is still the source of truth. If the
+ * loader determines NoteDb is out of date, the change data in NoteDb will be transparently
+ * rebuilt. This means that some code paths that look read-only may in fact attempt to write.
+ *
+ * <p>If true and {@code writeChanges() = false}, changes can still be read from NoteDb, but any
+ * attempts to write will generate an error.
*/
public abstract boolean readChanges();
/**
* Write changes to NoteDb.
- * <p>
- * Updates to change data are written to NoteDb refs, but ReviewDb is still
- * the source of truth. Change data will not be written unless the NoteDb refs
- * are already up to date, and the write path will attempt to rebuild the
- * change if not.
- * <p>
- * If false, the behavior when attempting to write depends on
- * {@code readChanges()}. If {@code readChanges() = false}, writes to NoteDb
- * are simply ignored; if {@code true}, any attempts to write will generate an
- * error.
+ *
+ * <p>Updates to change data are written to NoteDb refs, but ReviewDb is still the source of
+ * truth. Change data will not be written unless the NoteDb refs are already up to date, and the
+ * write path will attempt to rebuild the change if not.
+ *
+ * <p>If false, the behavior when attempting to write depends on {@code readChanges()}. If {@code
+ * readChanges() = false}, writes to NoteDb are simply ignored; if {@code true}, any attempts to
+ * write will generate an error.
*/
protected abstract boolean writeChanges();
/**
* Read sequential change ID numbers from NoteDb.
- * <p>
- * If true, change IDs are read from {@code refs/sequences/changes} in
- * All-Projects. If false, change IDs are read from ReviewDb's native
- * sequences.
+ *
+ * <p>If true, change IDs are read from {@code refs/sequences/changes} in All-Projects. If false,
+ * change IDs are read from ReviewDb's native sequences.
*/
public abstract boolean readChangeSequence();
@@ -82,8 +76,8 @@
/**
* Whether to fail when reading any data from NoteDb.
- * <p>
- * Used in conjunction with {@link #readChanges()} for tests.
+ *
+ * <p>Used in conjunction with {@link #readChanges()} for tests.
*/
public boolean failOnLoad() {
return false;
@@ -108,7 +102,6 @@
}
public boolean enabled() {
- return writeChanges() || readChanges()
- || writeAccounts() || readAccounts();
+ return writeChanges() || readChanges() || writeAccounts() || readAccounts();
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/PatchSetState.java b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/PatchSetState.java
index 39cd6cc..32be9c5 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/PatchSetState.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/PatchSetState.java
@@ -15,7 +15,7 @@
package com.google.gerrit.server.notedb;
public enum PatchSetState {
- /** Published and visible to anyone who can see the change; the default.*/
+ /** Published and visible to anyone who can see the change; the default. */
PUBLISHED,
/** Draft patch set, only visible to certain users. */
@@ -23,9 +23,9 @@
/**
* Deleted patch set.
- * <p>
- * Used internally as a tombstone; patch sets exposed by public NoteDb
- * interfaces never have this state.
+ *
+ * <p>Used internally as a tombstone; patch sets exposed by public NoteDb interfaces never have
+ * this state.
*/
DELETED;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/PrimaryStorageMigrator.java b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/PrimaryStorageMigrator.java
index 0a5c014..10345c8 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/PrimaryStorageMigrator.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/PrimaryStorageMigrator.java
@@ -19,6 +19,11 @@
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
+import com.github.rholder.retry.RetryException;
+import com.github.rholder.retry.Retryer;
+import com.github.rholder.retry.RetryerBuilder;
+import com.github.rholder.retry.StopStrategies;
+import com.github.rholder.retry.WaitStrategies;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Stopwatch;
import com.google.gerrit.common.Nullable;
@@ -39,30 +44,21 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
-import com.github.rholder.retry.RetryException;
-import com.github.rholder.retry.Retryer;
-import com.github.rholder.retry.RetryerBuilder;
-import com.github.rholder.retry.StopStrategies;
-import com.github.rholder.retry.WaitStrategies;
-
+import java.io.IOException;
+import java.sql.Timestamp;
+import java.util.Objects;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.atomic.AtomicBoolean;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.lib.Repository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.sql.Timestamp;
-import java.util.Objects;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.atomic.AtomicBoolean;
-
/** Helper to migrate the {@link PrimaryStorage} of individual changes. */
@Singleton
public class PrimaryStorageMigrator {
- private static final Logger log =
- LoggerFactory.getLogger(PrimaryStorageMigrator.class);
+ private static final Logger log = LoggerFactory.getLogger(PrimaryStorageMigrator.class);
private final Provider<ReviewDb> db;
private final GitRepositoryManager repoManager;
@@ -74,7 +70,8 @@
private final Retryer<NoteDbChangeState> testEnsureRebuiltRetryer;
@Inject
- PrimaryStorageMigrator(@GerritServerConfig Config cfg,
+ PrimaryStorageMigrator(
+ @GerritServerConfig Config cfg,
Provider<ReviewDb> db,
GitRepositoryManager repoManager,
AllUsersName allUsers,
@@ -83,7 +80,8 @@
}
@VisibleForTesting
- public PrimaryStorageMigrator(Config cfg,
+ public PrimaryStorageMigrator(
+ Config cfg,
Provider<ReviewDb> db,
GitRepositoryManager repoManager,
AllUsersName allUsers,
@@ -97,38 +95,37 @@
skewMs = NoteDbChangeState.getReadOnlySkew(cfg);
String s = "notedb";
- timeoutMs = cfg.getTimeUnit(
- s, null, "primaryStorageMigrationTimeout",
- MILLISECONDS.convert(60, SECONDS), MILLISECONDS);
+ timeoutMs =
+ cfg.getTimeUnit(
+ s,
+ null,
+ "primaryStorageMigrationTimeout",
+ MILLISECONDS.convert(60, SECONDS),
+ MILLISECONDS);
}
/**
* Migrate a change's primary storage from ReviewDb to NoteDb.
- * <p>
- * This method will return only if the primary storage of the change is NoteDb
- * afterwards. (It may return early if the primary storage was already
- * NoteDb.)
- * <p>
- * If this method throws an exception, then the primary storage of the change
- * is probably not NoteDb. (It is possible that the primary storage of the
- * change is NoteDb in this case, but there was an error reading the state.)
- * Moreover, after an exception, the change may be read-only until a lease
- * expires. If the caller chooses to retry, they should wait until the
- * read-only lease expires; this method will fail relatively quickly if called
- * on a read-only change.
- * <p>
- * Note that if the change is read-only after this method throws an exception,
- * that does not necessarily guarantee that the read-only lease was acquired
- * during that particular method invocation; this call may have in fact failed
- * because another thread acquired the lease first.
+ *
+ * <p>This method will return only if the primary storage of the change is NoteDb afterwards. (It
+ * may return early if the primary storage was already NoteDb.)
+ *
+ * <p>If this method throws an exception, then the primary storage of the change is probably not
+ * NoteDb. (It is possible that the primary storage of the change is NoteDb in this case, but
+ * there was an error reading the state.) Moreover, after an exception, the change may be
+ * read-only until a lease expires. If the caller chooses to retry, they should wait until the
+ * read-only lease expires; this method will fail relatively quickly if called on a read-only
+ * change.
+ *
+ * <p>Note that if the change is read-only after this method throws an exception, that does not
+ * necessarily guarantee that the read-only lease was acquired during that particular method
+ * invocation; this call may have in fact failed because another thread acquired the lease first.
*
* @param id change ID.
- *
* @throws OrmException if a ReviewDb-level error occurs.
* @throws IOException if a repo-level error occurs.
*/
- public void migrateToNoteDbPrimary(Change.Id id)
- throws OrmException, IOException {
+ public void migrateToNoteDbPrimary(Change.Id id) throws OrmException, IOException {
// Since there are multiple non-atomic steps in this method, we need to
// consider what happens when there is another writer concurrent with the
// thread executing this method.
@@ -200,10 +197,14 @@
NoteDbChangeState rebuiltState;
try {
// MR,MN
- rebuiltState = ensureRebuiltRetryer(sw).call(
- () -> ensureRebuilt(
- readOnlyChange.getProject(), id,
- NoteDbChangeState.parse(readOnlyChange)));
+ rebuiltState =
+ ensureRebuiltRetryer(sw)
+ .call(
+ () ->
+ ensureRebuilt(
+ readOnlyChange.getProject(),
+ id,
+ NoteDbChangeState.parse(readOnlyChange)));
} catch (RetryException | ExecutionException e) {
throw new OrmException(e);
}
@@ -213,36 +214,39 @@
// the primary storage to NoteDb.
setPrimaryStorageNoteDb(id, rebuiltState);
- log.info("Migrated change {} to NoteDb primary in {}ms", id,
- sw.elapsed(MILLISECONDS));
+ log.info("Migrated change {} to NoteDb primary in {}ms", id, sw.elapsed(MILLISECONDS));
}
private Change setReadOnly(Change.Id id) throws OrmException {
AtomicBoolean alreadyMigrated = new AtomicBoolean(false);
- Change result = db().changes().atomicUpdate(id, new AtomicUpdate<Change>() {
- @Override
- public Change update(Change change) {
- NoteDbChangeState state = NoteDbChangeState.parse(change);
- if (state == null) {
- // Could rebuild the change here, but that's more complexity, and this
- // really shouldn't happen.
- throw new OrmRuntimeException(
- "change " + id + " has no note_db_state; rebuild it first");
- }
- // If the change is already read-only, then the lease is held by another
- // (likely failed) migrator thread. Fail early, as we can't take over
- // the lease.
- NoteDbChangeState.checkNotReadOnly(change, skewMs);
- if (state.getPrimaryStorage() != PrimaryStorage.NOTE_DB) {
- Timestamp now = TimeUtil.nowTs();
- Timestamp until = new Timestamp(now.getTime() + timeoutMs);
- change.setNoteDbState(state.withReadOnlyUntil(until).toString());
- } else {
- alreadyMigrated.set(true);
- }
- return change;
- }
- });
+ Change result =
+ db().changes()
+ .atomicUpdate(
+ id,
+ new AtomicUpdate<Change>() {
+ @Override
+ public Change update(Change change) {
+ NoteDbChangeState state = NoteDbChangeState.parse(change);
+ if (state == null) {
+ // Could rebuild the change here, but that's more complexity, and this
+ // really shouldn't happen.
+ throw new OrmRuntimeException(
+ "change " + id + " has no note_db_state; rebuild it first");
+ }
+ // If the change is already read-only, then the lease is held by another
+ // (likely failed) migrator thread. Fail early, as we can't take over
+ // the lease.
+ NoteDbChangeState.checkNotReadOnly(change, skewMs);
+ if (state.getPrimaryStorage() != PrimaryStorage.NOTE_DB) {
+ Timestamp now = TimeUtil.nowTs();
+ Timestamp until = new Timestamp(now.getTime() + timeoutMs);
+ change.setNoteDbState(state.withReadOnlyUntil(until).toString());
+ } else {
+ alreadyMigrated.set(true);
+ }
+ return change;
+ }
+ });
return alreadyMigrated.get() ? null : result;
}
@@ -252,67 +256,64 @@
}
// Retry the ensureRebuilt step with backoff until half the timeout has
// expired, leaving the remaining half for the rest of the steps.
- long remainingNanos =
- (MILLISECONDS.toNanos(timeoutMs) / 2) - sw.elapsed(NANOSECONDS);
+ long remainingNanos = (MILLISECONDS.toNanos(timeoutMs) / 2) - sw.elapsed(NANOSECONDS);
remainingNanos = Math.max(remainingNanos, 0);
return RetryerBuilder.<NoteDbChangeState>newBuilder()
- .retryIfException(
- e -> (e instanceof IOException) || (e instanceof OrmException))
+ .retryIfException(e -> (e instanceof IOException) || (e instanceof OrmException))
.withWaitStrategy(
WaitStrategies.join(
WaitStrategies.exponentialWait(250, MILLISECONDS),
WaitStrategies.randomWait(50, MILLISECONDS)))
- .withStopStrategy(
- StopStrategies.stopAfterDelay(remainingNanos, NANOSECONDS))
+ .withStopStrategy(StopStrategies.stopAfterDelay(remainingNanos, NANOSECONDS))
.build();
}
- private NoteDbChangeState ensureRebuilt(Project.NameKey project, Change.Id id,
- NoteDbChangeState readOnlyState)
+ private NoteDbChangeState ensureRebuilt(
+ Project.NameKey project, Change.Id id, NoteDbChangeState readOnlyState)
throws IOException, OrmException, RepositoryNotFoundException {
try (Repository changeRepo = repoManager.openRepository(project);
Repository allUsersRepo = repoManager.openRepository(allUsers)) {
- if (!readOnlyState.isUpToDate(
- new RepoRefCache(changeRepo), new RepoRefCache(allUsersRepo))) {
- NoteDbUpdateManager.Result r =
- rebuilder.rebuildEvenIfReadOnly(db(), id);
+ if (!readOnlyState.isUpToDate(new RepoRefCache(changeRepo), new RepoRefCache(allUsersRepo))) {
+ NoteDbUpdateManager.Result r = rebuilder.rebuildEvenIfReadOnly(db(), id);
checkState(
- r.newState().getReadOnlyUntil()
- .equals(readOnlyState.getReadOnlyUntil()),
+ r.newState().getReadOnlyUntil().equals(readOnlyState.getReadOnlyUntil()),
"state after rebuilding has different read-only lease: %s != %s",
- r.newState(), readOnlyState);
+ r.newState(),
+ readOnlyState);
readOnlyState = r.newState();
}
}
return readOnlyState;
}
- private void setPrimaryStorageNoteDb(Change.Id id,
- NoteDbChangeState expectedState) throws OrmException {
- db().changes().atomicUpdate(id, new AtomicUpdate<Change>() {
- @Override
- public Change update(Change change) {
- NoteDbChangeState state = NoteDbChangeState.parse(change);
- if (!Objects.equals(state, expectedState)) {
- throw new OrmRuntimeException(badState(state, expectedState));
- }
- Timestamp until = state.getReadOnlyUntil().get();
- if (TimeUtil.nowTs().after(until)) {
- throw new OrmRuntimeException(
- "read-only lease on change " + id + " expired at " + until);
- }
- change.setNoteDbState(NoteDbChangeState.NOTE_DB_PRIMARY_STATE);
- return change;
- }
- });
+ private void setPrimaryStorageNoteDb(Change.Id id, NoteDbChangeState expectedState)
+ throws OrmException {
+ db().changes()
+ .atomicUpdate(
+ id,
+ new AtomicUpdate<Change>() {
+ @Override
+ public Change update(Change change) {
+ NoteDbChangeState state = NoteDbChangeState.parse(change);
+ if (!Objects.equals(state, expectedState)) {
+ throw new OrmRuntimeException(badState(state, expectedState));
+ }
+ Timestamp until = state.getReadOnlyUntil().get();
+ if (TimeUtil.nowTs().after(until)) {
+ throw new OrmRuntimeException(
+ "read-only lease on change " + id + " expired at " + until);
+ }
+ change.setNoteDbState(NoteDbChangeState.NOTE_DB_PRIMARY_STATE);
+ return change;
+ }
+ });
}
private ReviewDb db() {
return ReviewDbUtil.unwrapDb(db.get());
}
- private String badState(NoteDbChangeState actual,
- NoteDbChangeState expected) {
+ private String badState(NoteDbChangeState actual, NoteDbChangeState expected) {
return "state changed unexpectedly: " + actual + " != " + expected;
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/RepoSequence.java b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/RepoSequence.java
index e4a6f7c..0101cd7 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/RepoSequence.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/RepoSequence.java
@@ -19,6 +19,11 @@
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.eclipse.jgit.lib.Constants.OBJ_BLOB;
+import com.github.rholder.retry.RetryException;
+import com.github.rholder.retry.Retryer;
+import com.github.rholder.retry.RetryerBuilder;
+import com.github.rholder.retry.StopStrategies;
+import com.github.rholder.retry.WaitStrategies;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.CharMatcher;
import com.google.common.base.Predicates;
@@ -31,13 +36,14 @@
import com.google.gerrit.reviewdb.client.RefNames;
import com.google.gerrit.server.git.GitRepositoryManager;
import com.google.gwtorm.server.OrmException;
-
-import com.github.rholder.retry.RetryException;
-import com.github.rholder.retry.Retryer;
-import com.github.rholder.retry.RetryerBuilder;
-import com.github.rholder.retry.StopStrategies;
-import com.github.rholder.retry.WaitStrategies;
-
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
import org.eclipse.jgit.errors.IncorrectObjectTypeException;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.ObjectInserter;
@@ -47,25 +53,15 @@
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevWalk;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.Callable;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.locks.Lock;
-import java.util.concurrent.locks.ReentrantLock;
-
/**
* Class for managing an incrementing sequence backed by a git repository.
- * <p>
- * The current sequence number is stored as UTF-8 text in a blob pointed to
- * by a ref in the {@code refs/sequences/*} namespace. Multiple processes can
- * share the same sequence by incrementing the counter using normal git ref
- * updates. To amortize the cost of these ref updates, processes can increment
- * the counter by a larger number and hand out numbers from that range in memory
- * until they run out. This means concurrent processes will hand out somewhat
- * non-monotonic numbers.
+ *
+ * <p>The current sequence number is stored as UTF-8 text in a blob pointed to by a ref in the
+ * {@code refs/sequences/*} namespace. Multiple processes can share the same sequence by
+ * incrementing the counter using normal git ref updates. To amortize the cost of these ref updates,
+ * processes can increment the counter by a larger number and hand out numbers from that range in
+ * memory until they run out. This means concurrent processes will hand out somewhat non-monotonic
+ * numbers.
*/
public class RepoSequence {
public interface Seed {
@@ -74,17 +70,16 @@
@VisibleForTesting
static RetryerBuilder<RefUpdate.Result> retryerBuilder() {
- return RetryerBuilder.<RefUpdate.Result> newBuilder()
+ return RetryerBuilder.<RefUpdate.Result>newBuilder()
.retryIfResult(Predicates.equalTo(RefUpdate.Result.LOCK_FAILURE))
.withWaitStrategy(
WaitStrategies.join(
- WaitStrategies.exponentialWait(5, TimeUnit.SECONDS),
- WaitStrategies.randomWait(50, TimeUnit.MILLISECONDS)))
+ WaitStrategies.exponentialWait(5, TimeUnit.SECONDS),
+ WaitStrategies.randomWait(50, TimeUnit.MILLISECONDS)))
.withStopStrategy(StopStrategies.stopAfterDelay(30, TimeUnit.SECONDS));
}
- private static final Retryer<RefUpdate.Result> RETRYER =
- retryerBuilder().build();
+ private static final Retryer<RefUpdate.Result> RETRYER = retryerBuilder().build();
private final GitRepositoryManager repoManager;
private final Project.NameKey projectName;
@@ -100,8 +95,7 @@
private int limit;
private int counter;
- @VisibleForTesting
- int acquireCount;
+ @VisibleForTesting int acquireCount;
public RepoSequence(
GitRepositoryManager repoManager,
@@ -109,8 +103,7 @@
String name,
Seed seed,
int batchSize) {
- this(repoManager, projectName, name, seed, batchSize, Runnables.doNothing(),
- RETRYER);
+ this(repoManager, projectName, name, seed, batchSize, Runnables.doNothing(), RETRYER);
}
@VisibleForTesting
@@ -248,19 +241,17 @@
// may do it properly (certainly InMemoryRepository doesn't).
throw new IncorrectObjectTypeException(id, OBJ_BLOB);
}
- String str = CharMatcher.whitespace().trimFrom(
- new String(ol.getCachedBytes(), UTF_8));
+ String str = CharMatcher.whitespace().trimFrom(new String(ol.getCachedBytes(), UTF_8));
Integer val = Ints.tryParse(str);
if (val == null) {
- throw new OrmException(
- "invalid value in " + refName + " blob at " + id.name());
+ throw new OrmException("invalid value in " + refName + " blob at " + id.name());
}
return val;
}
}
- private RefUpdate.Result store(Repository repo, RevWalk rw,
- @Nullable ObjectId oldId, int val) throws IOException {
+ private RefUpdate.Result store(Repository repo, RevWalk rw, @Nullable ObjectId oldId, int val)
+ throws IOException {
ObjectId newId;
try (ObjectInserter ins = repo.newObjectInserter()) {
newId = ins.insert(OBJ_BLOB, Integer.toString(val).getBytes(UTF_8));
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/ReviewerStateInternal.java b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/ReviewerStateInternal.java
index be7f8d5..f250646 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/ReviewerStateInternal.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/ReviewerStateInternal.java
@@ -15,10 +15,8 @@
package com.google.gerrit.server.notedb;
import com.google.gerrit.extensions.client.ReviewerState;
-
-import org.eclipse.jgit.revwalk.FooterKey;
-
import java.util.Arrays;
+import org.eclipse.jgit.revwalk.FooterKey;
/** State of a reviewer on a change. */
public enum ReviewerStateInternal {
@@ -40,9 +38,11 @@
ok &= s.name().equals(s.state.name());
}
if (!ok) {
- throw new IllegalStateException("Mismatched reviewer state mapping: "
- + Arrays.asList(ReviewerStateInternal.values()) + " != "
- + Arrays.asList(ReviewerState.values()));
+ throw new IllegalStateException(
+ "Mismatched reviewer state mapping: "
+ + Arrays.asList(ReviewerStateInternal.values())
+ + " != "
+ + Arrays.asList(ReviewerState.values()));
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/RevisionNote.java b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/RevisionNote.java
index 46e6dc5..aec8442 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/RevisionNote.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/RevisionNote.java
@@ -19,15 +19,13 @@
import com.google.common.collect.ImmutableList;
import com.google.gerrit.reviewdb.client.Comment;
-
+import java.io.IOException;
+import java.util.List;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.ObjectReader;
import org.eclipse.jgit.util.MutableInteger;
-import java.io.IOException;
-import java.util.List;
-
abstract class RevisionNote<T extends Comment> {
static final int MAX_NOTE_SZ = 25 << 20;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/RevisionNoteBuilder.java b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/RevisionNoteBuilder.java
index 46a0802..b341ea8 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/RevisionNoteBuilder.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/RevisionNoteBuilder.java
@@ -23,7 +23,6 @@
import com.google.common.collect.MultimapBuilder;
import com.google.gerrit.reviewdb.client.Comment;
import com.google.gerrit.reviewdb.client.RevId;
-
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
@@ -37,12 +36,10 @@
class RevisionNoteBuilder {
static class Cache {
- private final RevisionNoteMap<?
- extends RevisionNote<? extends Comment>> revisionNoteMap;
+ private final RevisionNoteMap<? extends RevisionNote<? extends Comment>> revisionNoteMap;
private final Map<RevId, RevisionNoteBuilder> builders;
- Cache(RevisionNoteMap<?
- extends RevisionNote<? extends Comment>> revisionNoteMap) {
+ Cache(RevisionNoteMap<? extends RevisionNote<? extends Comment>> revisionNoteMap) {
this.revisionNoteMap = revisionNoteMap;
this.builders = new HashMap<>();
}
@@ -50,8 +47,7 @@
RevisionNoteBuilder get(RevId revId) {
RevisionNoteBuilder b = builders.get(revId);
if (b == null) {
- b = new RevisionNoteBuilder(
- revisionNoteMap.revisionNotes.get(revId));
+ b = new RevisionNoteBuilder(revisionNoteMap.revisionNotes.get(revId));
builders.put(revId, b);
}
return b;
@@ -86,8 +82,7 @@
delete = new HashSet<>();
}
- public byte[] build(ChangeNoteUtil noteUtil, boolean writeJson)
- throws IOException {
+ public byte[] build(ChangeNoteUtil noteUtil, boolean writeJson) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
if (writeJson) {
buildNoteJson(noteUtil, out);
@@ -98,8 +93,7 @@
}
void putComment(Comment comment) {
- checkArgument(!delete.contains(comment.key),
- "cannot both delete and put %s", comment.key);
+ checkArgument(!delete.contains(comment.key), "cannot both delete and put %s", comment.key);
put.put(comment.key, comment);
}
@@ -113,8 +107,7 @@
}
private ListMultimap<Integer, Comment> buildCommentMap() {
- ListMultimap<Integer, Comment> all =
- MultimapBuilder.hashKeys().arrayListValues().build();
+ ListMultimap<Integer, Comment> all = MultimapBuilder.hashKeys().arrayListValues().build();
for (Comment c : baseComments) {
if (!delete.contains(c.key) && !put.containsKey(c.key)) {
@@ -129,8 +122,7 @@
return all;
}
- private void buildNoteJson(ChangeNoteUtil noteUtil, OutputStream out)
- throws IOException {
+ private void buildNoteJson(ChangeNoteUtil noteUtil, OutputStream out) throws IOException {
ListMultimap<Integer, Comment> comments = buildCommentMap();
if (comments.isEmpty() && pushCert == null) {
return;
@@ -145,8 +137,7 @@
}
}
- private void buildNoteLegacy(ChangeNoteUtil noteUtil, OutputStream out)
- throws IOException {
+ private void buildNoteLegacy(ChangeNoteUtil noteUtil, OutputStream out) throws IOException {
if (pushCert != null) {
byte[] certBytes = pushCert.getBytes(UTF_8);
out.write(certBytes, 0, trimTrailingNewlines(certBytes));
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/RevisionNoteData.java b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/RevisionNoteData.java
index e0ee934..1e16b22 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/RevisionNoteData.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/RevisionNoteData.java
@@ -15,11 +15,11 @@
package com.google.gerrit.server.notedb;
import com.google.gerrit.reviewdb.client.Comment;
-
import java.util.List;
/**
* Holds the raw data of a RevisionNote.
+ *
* <p>It is intended for (de)serialization to JSON only.
*/
class RevisionNoteData {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/RevisionNoteMap.java b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/RevisionNoteMap.java
index 8a9f711..aa82d1a 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/RevisionNoteMap.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/RevisionNoteMap.java
@@ -19,28 +19,29 @@
import com.google.gerrit.reviewdb.client.Comment;
import com.google.gerrit.reviewdb.client.PatchLineComment;
import com.google.gerrit.reviewdb.client.RevId;
-
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.lib.ObjectReader;
import org.eclipse.jgit.notes.Note;
import org.eclipse.jgit.notes.NoteMap;
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.Map;
-
class RevisionNoteMap<T extends RevisionNote<? extends Comment>> {
final NoteMap noteMap;
final ImmutableMap<RevId, T> revisionNotes;
- static RevisionNoteMap<ChangeRevisionNote> parse(ChangeNoteUtil noteUtil,
- Change.Id changeId, ObjectReader reader, NoteMap noteMap,
+ static RevisionNoteMap<ChangeRevisionNote> parse(
+ ChangeNoteUtil noteUtil,
+ Change.Id changeId,
+ ObjectReader reader,
+ NoteMap noteMap,
PatchLineComment.Status status)
- throws ConfigInvalidException, IOException {
+ throws ConfigInvalidException, IOException {
Map<RevId, ChangeRevisionNote> result = new HashMap<>();
for (Note note : noteMap) {
- ChangeRevisionNote rn = new ChangeRevisionNote(
- noteUtil, changeId, reader, note.getData(), status);
+ ChangeRevisionNote rn =
+ new ChangeRevisionNote(noteUtil, changeId, reader, note.getData(), status);
rn.parse();
result.put(new RevId(note.name()), rn);
}
@@ -49,25 +50,22 @@
static RevisionNoteMap<RobotCommentsRevisionNote> parseRobotComments(
ChangeNoteUtil noteUtil, ObjectReader reader, NoteMap noteMap)
- throws ConfigInvalidException, IOException {
+ throws ConfigInvalidException, IOException {
Map<RevId, RobotCommentsRevisionNote> result = new HashMap<>();
for (Note note : noteMap) {
- RobotCommentsRevisionNote rn = new RobotCommentsRevisionNote(
- noteUtil, reader, note.getData());
+ RobotCommentsRevisionNote rn =
+ new RobotCommentsRevisionNote(noteUtil, reader, note.getData());
rn.parse();
result.put(new RevId(note.name()), rn);
}
return new RevisionNoteMap<>(noteMap, ImmutableMap.copyOf(result));
}
- static <T extends RevisionNote<? extends Comment>> RevisionNoteMap<T>
- emptyMap() {
- return new RevisionNoteMap<>(NoteMap.newEmptyMap(),
- ImmutableMap.<RevId, T> of());
+ static <T extends RevisionNote<? extends Comment>> RevisionNoteMap<T> emptyMap() {
+ return new RevisionNoteMap<>(NoteMap.newEmptyMap(), ImmutableMap.<RevId, T>of());
}
- private RevisionNoteMap(NoteMap noteMap,
- ImmutableMap<RevId, T> revisionNotes) {
+ private RevisionNoteMap(NoteMap noteMap, ImmutableMap<RevId, T> revisionNotes) {
this.noteMap = noteMap;
this.revisionNotes = revisionNotes;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/RobotCommentNotes.java b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/RobotCommentNotes.java
index ae2edd6..e6549f0 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/RobotCommentNotes.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/RobotCommentNotes.java
@@ -26,15 +26,13 @@
import com.google.gerrit.server.notedb.NoteDbChangeState.PrimaryStorage;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
-
+import java.io.IOException;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.ObjectReader;
import org.eclipse.jgit.notes.NoteMap;
import org.eclipse.jgit.revwalk.RevCommit;
-import java.io.IOException;
-
public class RobotCommentNotes extends AbstractChangeNotes<RobotCommentNotes> {
public interface Factory {
RobotCommentNotes create(Change change);
@@ -47,9 +45,7 @@
private ObjectId metaId;
@AssistedInject
- RobotCommentNotes(
- Args args,
- @Assisted Change change) {
+ RobotCommentNotes(Args args, @Assisted Change change) {
super(args, change.getId(), PrimaryStorage.of(change), false);
this.change = change;
}
@@ -82,8 +78,7 @@
}
@Override
- protected void onLoad(LoadHandle handle)
- throws IOException, ConfigInvalidException {
+ protected void onLoad(LoadHandle handle) throws IOException, ConfigInvalidException {
metaId = handle.id();
if (metaId == null) {
loadDefaults();
@@ -93,12 +88,10 @@
RevCommit tipCommit = handle.walk().parseCommit(metaId);
ObjectReader reader = handle.walk().getObjectReader();
- revisionNoteMap = RevisionNoteMap.parseRobotComments(args.noteUtil, reader,
- NoteMap.read(reader, tipCommit));
- ListMultimap<RevId, RobotComment> cs =
- MultimapBuilder.hashKeys().arrayListValues().build();
- for (RobotCommentsRevisionNote rn :
- revisionNoteMap.revisionNotes.values()) {
+ revisionNoteMap =
+ RevisionNoteMap.parseRobotComments(args.noteUtil, reader, NoteMap.read(reader, tipCommit));
+ ListMultimap<RevId, RobotComment> cs = MultimapBuilder.hashKeys().arrayListValues().build();
+ for (RobotCommentsRevisionNote rn : revisionNoteMap.revisionNotes.values()) {
for (RobotComment c : rn.getComments()) {
cs.put(new RevId(c.revId), c);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/RobotCommentUpdate.java b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/RobotCommentUpdate.java
index 9744632..9ce4b54 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/RobotCommentUpdate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/RobotCommentUpdate.java
@@ -29,7 +29,13 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
-
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.lib.CommitBuilder;
import org.eclipse.jgit.lib.ObjectId;
@@ -38,21 +44,13 @@
import org.eclipse.jgit.notes.NoteMap;
import org.eclipse.jgit.revwalk.RevWalk;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Date;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
/**
* A single delta to apply atomically to a change.
- * <p>
- * This delta contains only robot comments on a single patch set of a change by
- * a single author. This delta will become a single commit in the repository.
- * <p>
- * This class is not thread safe.
+ *
+ * <p>This delta contains only robot comments on a single patch set of a change by a single author.
+ * This delta will become a single commit in the repository.
+ *
+ * <p>This class is not thread safe.
*/
public class RobotCommentUpdate extends AbstractChangeUpdate {
public interface Factory {
@@ -84,8 +82,17 @@
@Assisted("real") Account.Id realAccountId,
@Assisted PersonIdent authorIdent,
@Assisted Date when) {
- super(migration, noteUtil, serverIdent, anonymousCowardName, notes, null,
- accountId, realAccountId, authorIdent, when);
+ super(
+ migration,
+ noteUtil,
+ serverIdent,
+ anonymousCowardName,
+ notes,
+ null,
+ accountId,
+ realAccountId,
+ authorIdent,
+ when);
}
@AssistedInject
@@ -99,8 +106,17 @@
@Assisted("real") Account.Id realAccountId,
@Assisted PersonIdent authorIdent,
@Assisted Date when) {
- super(migration, noteUtil, serverIdent, anonymousCowardName, null, change,
- accountId, realAccountId, authorIdent, when);
+ super(
+ migration,
+ noteUtil,
+ serverIdent,
+ anonymousCowardName,
+ null,
+ change,
+ accountId,
+ realAccountId,
+ authorIdent,
+ when);
}
public void putComment(RobotComment c) {
@@ -108,13 +124,11 @@
put.add(c);
}
- private CommitBuilder storeCommentsInNotes(RevWalk rw, ObjectInserter ins,
- ObjectId curr, CommitBuilder cb)
+ private CommitBuilder storeCommentsInNotes(
+ RevWalk rw, ObjectInserter ins, ObjectId curr, CommitBuilder cb)
throws ConfigInvalidException, OrmException, IOException {
- RevisionNoteMap<RobotCommentsRevisionNote> rnm =
- getRevisionNoteMap(rw, curr);
- Set<RevId> updatedRevs =
- Sets.newHashSetWithExpectedSize(rnm.revisionNotes.size());
+ RevisionNoteMap<RobotCommentsRevisionNote> rnm = getRevisionNoteMap(rw, curr);
+ Set<RevId> updatedRevs = Sets.newHashSetWithExpectedSize(rnm.revisionNotes.size());
RevisionNoteBuilder.Cache cache = new RevisionNoteBuilder.Cache(rnm);
for (RobotComment c : put) {
@@ -158,9 +172,8 @@
return cb;
}
- private RevisionNoteMap<RobotCommentsRevisionNote> getRevisionNoteMap(
- RevWalk rw, ObjectId curr)
- throws ConfigInvalidException, OrmException, IOException {
+ private RevisionNoteMap<RobotCommentsRevisionNote> getRevisionNoteMap(RevWalk rw, ObjectId curr)
+ throws ConfigInvalidException, OrmException, IOException {
if (curr.equals(ObjectId.zeroId())) {
return RevisionNoteMap.emptyMap();
}
@@ -170,13 +183,10 @@
// hasn't advanced.
ChangeNotes changeNotes = getNotes();
if (changeNotes != null) {
- RobotCommentNotes robotCommentNotes =
- changeNotes.load().getRobotCommentNotes();
+ RobotCommentNotes robotCommentNotes = changeNotes.load().getRobotCommentNotes();
if (robotCommentNotes != null) {
- ObjectId idFromNotes =
- firstNonNull(robotCommentNotes.getRevision(), ObjectId.zeroId());
- RevisionNoteMap<RobotCommentsRevisionNote> rnm =
- robotCommentNotes.getRevisionNoteMap();
+ ObjectId idFromNotes = firstNonNull(robotCommentNotes.getRevision(), ObjectId.zeroId());
+ RevisionNoteMap<RobotCommentsRevisionNote> rnm = robotCommentNotes.getRevisionNoteMap();
if (idFromNotes.equals(curr) && rnm != null) {
return rnm;
}
@@ -191,15 +201,12 @@
}
// Even though reading from changes might not be enabled, we need to
// parse any existing revision notes so we can merge them.
- return RevisionNoteMap.parseRobotComments(
- noteUtil,
- rw.getObjectReader(),
- noteMap);
+ return RevisionNoteMap.parseRobotComments(noteUtil, rw.getObjectReader(), noteMap);
}
@Override
- protected CommitBuilder applyImpl(RevWalk rw, ObjectInserter ins,
- ObjectId curr) throws OrmException, IOException {
+ protected CommitBuilder applyImpl(RevWalk rw, ObjectInserter ins, ObjectId curr)
+ throws OrmException, IOException {
CommitBuilder cb = new CommitBuilder();
cb.setMessage("Update robot comments");
try {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/RobotCommentsRevisionNote.java b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/RobotCommentsRevisionNote.java
index 0dca408..aa229ab 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/RobotCommentsRevisionNote.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/RobotCommentsRevisionNote.java
@@ -17,34 +17,28 @@
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.gerrit.reviewdb.client.RobotComment;
-
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.lib.ObjectReader;
-
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.List;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.lib.ObjectReader;
public class RobotCommentsRevisionNote extends RevisionNote<RobotComment> {
private final ChangeNoteUtil noteUtil;
- RobotCommentsRevisionNote(ChangeNoteUtil noteUtil, ObjectReader reader,
- ObjectId noteId) {
+ RobotCommentsRevisionNote(ChangeNoteUtil noteUtil, ObjectReader reader, ObjectId noteId) {
super(reader, noteId);
this.noteUtil = noteUtil;
}
@Override
- protected List<RobotComment> parse(byte[] raw, int offset)
- throws IOException {
- try (InputStream is = new ByteArrayInputStream(
- raw, offset, raw.length - offset);
+ protected List<RobotComment> parse(byte[] raw, int offset) throws IOException {
+ try (InputStream is = new ByteArrayInputStream(raw, offset, raw.length - offset);
Reader r = new InputStreamReader(is, UTF_8)) {
- return noteUtil.getGson().fromJson(r,
- RobotCommentsRevisionNoteData.class).comments;
+ return noteUtil.getGson().fromJson(r, RobotCommentsRevisionNoteData.class).comments;
}
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/RobotCommentsRevisionNoteData.java b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/RobotCommentsRevisionNoteData.java
index ea3a149..116b30e 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/RobotCommentsRevisionNoteData.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/RobotCommentsRevisionNoteData.java
@@ -15,7 +15,6 @@
package com.google.gerrit.server.notedb;
import com.google.gerrit.reviewdb.client.RobotComment;
-
import java.util.List;
public class RobotCommentsRevisionNoteData {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/TestChangeRebuilderWrapper.java b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/TestChangeRebuilderWrapper.java
index ffe0fcb..4ee84dc 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/TestChangeRebuilderWrapper.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/TestChangeRebuilderWrapper.java
@@ -24,7 +24,6 @@
import com.google.gwtorm.server.SchemaFactory;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
import java.io.IOException;
import java.util.concurrent.atomic.AtomicBoolean;
@@ -36,8 +35,7 @@
private final AtomicBoolean stealNextUpdate;
@Inject
- TestChangeRebuilderWrapper(SchemaFactory<ReviewDb> schemaFactory,
- ChangeRebuilderImpl rebuilder) {
+ TestChangeRebuilderWrapper(SchemaFactory<ReviewDb> schemaFactory, ChangeRebuilderImpl rebuilder) {
super(schemaFactory);
this.delegate = rebuilder;
this.failNextUpdate = new AtomicBoolean();
@@ -53,8 +51,7 @@
}
@Override
- public Result rebuild(ReviewDb db, Change.Id changeId)
- throws IOException, OrmException {
+ public Result rebuild(ReviewDb db, Change.Id changeId) throws IOException, OrmException {
return rebuild(db, changeId, true);
}
@@ -64,14 +61,15 @@
return rebuild(db, changeId, false);
}
- private Result rebuild(ReviewDb db, Change.Id changeId,
- boolean checkReadOnly) throws IOException, OrmException {
+ private Result rebuild(ReviewDb db, Change.Id changeId, boolean checkReadOnly)
+ throws IOException, OrmException {
if (failNextUpdate.getAndSet(false)) {
throw new IOException("Update failed");
}
- Result result = checkReadOnly
- ? delegate.rebuild(db, changeId)
- : delegate.rebuildEvenIfReadOnly(db, changeId);
+ Result result =
+ checkReadOnly
+ ? delegate.rebuild(db, changeId)
+ : delegate.rebuildEvenIfReadOnly(db, changeId);
if (stealNextUpdate.getAndSet(false)) {
throw new IOException("Update stolen");
}
@@ -79,8 +77,8 @@
}
@Override
- public Result rebuild(NoteDbUpdateManager manager,
- ChangeBundle bundle) throws IOException, OrmException {
+ public Result rebuild(NoteDbUpdateManager manager, ChangeBundle bundle)
+ throws IOException, OrmException {
// stealNextUpdate doesn't really apply in this case because the IOException
// would normally come from the manager.execute() method, which isn't called
// here.
@@ -95,8 +93,8 @@
}
@Override
- public Result execute(ReviewDb db, Change.Id changeId,
- NoteDbUpdateManager manager) throws OrmException, IOException {
+ public Result execute(ReviewDb db, Change.Id changeId, NoteDbUpdateManager manager)
+ throws OrmException, IOException {
if (failNextUpdate.getAndSet(false)) {
throw new IOException("Update failed");
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/ApprovalEvent.java b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/ApprovalEvent.java
index 4fed25d..b369281 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/ApprovalEvent.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/ApprovalEvent.java
@@ -16,15 +16,19 @@
import com.google.gerrit.reviewdb.client.PatchSetApproval;
import com.google.gerrit.server.notedb.ChangeUpdate;
-
import java.sql.Timestamp;
class ApprovalEvent extends Event {
private PatchSetApproval psa;
ApprovalEvent(PatchSetApproval psa, Timestamp changeCreatedOn) {
- super(psa.getPatchSetId(), psa.getAccountId(), psa.getRealAccountId(),
- psa.getGranted(), changeCreatedOn, psa.getTag());
+ super(
+ psa.getPatchSetId(),
+ psa.getAccountId(),
+ psa.getRealAccountId(),
+ psa.getGranted(),
+ changeCreatedOn,
+ psa.getTag());
this.psa = psa;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/ChangeMessageEvent.java b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/ChangeMessageEvent.java
index ed5cd8b..84858b4e 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/ChangeMessageEvent.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/ChangeMessageEvent.java
@@ -18,26 +18,27 @@
import com.google.gerrit.reviewdb.client.ChangeMessage;
import com.google.gerrit.server.notedb.ChangeUpdate;
import com.google.gwtorm.server.OrmException;
-
import java.sql.Timestamp;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class ChangeMessageEvent extends Event {
- private static final Pattern TOPIC_SET_REGEXP =
- Pattern.compile("^Topic set to (.+)$");
+ private static final Pattern TOPIC_SET_REGEXP = Pattern.compile("^Topic set to (.+)$");
private static final Pattern TOPIC_CHANGED_REGEXP =
Pattern.compile("^Topic changed from (.+) to (.+)$");
- private static final Pattern TOPIC_REMOVED_REGEXP =
- Pattern.compile("^Topic (.+) removed$");
+ private static final Pattern TOPIC_REMOVED_REGEXP = Pattern.compile("^Topic (.+) removed$");
private final ChangeMessage message;
private final Change noteDbChange;
- ChangeMessageEvent(ChangeMessage message, Change noteDbChange,
- Timestamp changeCreatedOn) {
- super(message.getPatchSetId(), message.getAuthor(), message.getRealAuthor(),
- message.getWrittenOn(), changeCreatedOn, message.getTag());
+ ChangeMessageEvent(ChangeMessage message, Change noteDbChange, Timestamp changeCreatedOn) {
+ super(
+ message.getPatchSetId(),
+ message.getAuthor(),
+ message.getRealAuthor(),
+ message.getWrittenOn(),
+ changeCreatedOn,
+ message.getTag());
this.message = message;
this.noteDbChange = noteDbChange;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/ChangeRebuilder.java b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/ChangeRebuilder.java
index ea456da..c8d9bb3 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/ChangeRebuilder.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/ChangeRebuilder.java
@@ -23,7 +23,6 @@
import com.google.gerrit.server.notedb.NoteDbUpdateManager.Result;
import com.google.gwtorm.server.OrmException;
import com.google.gwtorm.server.SchemaFactory;
-
import java.io.IOException;
import java.util.concurrent.Callable;
@@ -32,8 +31,7 @@
private static final long serialVersionUID = 1L;
NoPatchSetsException(Change.Id changeId) {
- super("Change " + changeId
- + " cannot be rebuilt because it has no patch sets");
+ super("Change " + changeId + " cannot be rebuilt because it has no patch sets");
}
}
@@ -45,31 +43,31 @@
public final ListenableFuture<Result> rebuildAsync(
final Change.Id id, ListeningExecutorService executor) {
- return executor.submit(new Callable<Result>() {
- @Override
- public Result call() throws Exception {
- try (ReviewDb db = schemaFactory.open()) {
- return rebuild(db, id);
- }
- }
- });
+ return executor.submit(
+ new Callable<Result>() {
+ @Override
+ public Result call() throws Exception {
+ try (ReviewDb db = schemaFactory.open()) {
+ return rebuild(db, id);
+ }
+ }
+ });
}
- public abstract Result rebuild(ReviewDb db, Change.Id changeId)
- throws IOException, OrmException;
+ public abstract Result rebuild(ReviewDb db, Change.Id changeId) throws IOException, OrmException;
public abstract Result rebuildEvenIfReadOnly(ReviewDb db, Change.Id changeId)
throws IOException, OrmException;
- public abstract Result rebuild(NoteDbUpdateManager manager,
- ChangeBundle bundle) throws IOException, OrmException;
+ public abstract Result rebuild(NoteDbUpdateManager manager, ChangeBundle bundle)
+ throws IOException, OrmException;
- public abstract void buildUpdates(NoteDbUpdateManager manager,
- ChangeBundle bundle) throws IOException, OrmException;
+ public abstract void buildUpdates(NoteDbUpdateManager manager, ChangeBundle bundle)
+ throws IOException, OrmException;
public abstract NoteDbUpdateManager stage(ReviewDb db, Change.Id changeId)
throws IOException, OrmException;
- public abstract Result execute(ReviewDb db, Change.Id changeId,
- NoteDbUpdateManager manager) throws OrmException, IOException;
+ public abstract Result execute(ReviewDb db, Change.Id changeId, NoteDbUpdateManager manager)
+ throws OrmException, IOException;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/ChangeRebuilderImpl.java b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/ChangeRebuilderImpl.java
index ffd11a7..326ceb3 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/ChangeRebuilderImpl.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/ChangeRebuilderImpl.java
@@ -72,16 +72,6 @@
import com.google.gwtorm.server.OrmException;
import com.google.gwtorm.server.SchemaFactory;
import com.google.inject.Inject;
-
-import org.eclipse.jgit.errors.ConfigInvalidException;
-import org.eclipse.jgit.lib.Config;
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.lib.PersonIdent;
-import org.eclipse.jgit.lib.Ref;
-import org.eclipse.jgit.revwalk.RevCommit;
-import org.eclipse.jgit.revwalk.RevWalk;
-import org.eclipse.jgit.transport.ReceiveCommand;
-
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
@@ -92,22 +82,29 @@
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
+import org.eclipse.jgit.errors.ConfigInvalidException;
+import org.eclipse.jgit.lib.Config;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.lib.PersonIdent;
+import org.eclipse.jgit.lib.Ref;
+import org.eclipse.jgit.revwalk.RevCommit;
+import org.eclipse.jgit.revwalk.RevWalk;
+import org.eclipse.jgit.transport.ReceiveCommand;
public class ChangeRebuilderImpl extends ChangeRebuilder {
/**
- * The maximum amount of time between the ReviewDb timestamp of the first and
- * last events batched together into a single NoteDb update.
- * <p>
- * Used to account for the fact that different records with their own
- * timestamps (e.g. {@link PatchSetApproval} and {@link ChangeMessage})
- * historically didn't necessarily use the same timestamp, and tended to call
- * {@code System.currentTimeMillis()} independently.
+ * The maximum amount of time between the ReviewDb timestamp of the first and last events batched
+ * together into a single NoteDb update.
+ *
+ * <p>Used to account for the fact that different records with their own timestamps (e.g. {@link
+ * PatchSetApproval} and {@link ChangeMessage}) historically didn't necessarily use the same
+ * timestamp, and tended to call {@code System.currentTimeMillis()} independently.
*/
public static final long MAX_WINDOW_MS = SECONDS.toMillis(3);
/**
- * The maximum amount of time between two consecutive events to consider them
- * to be in the same batch.
+ * The maximum amount of time between two consecutive events to consider them to be in the same
+ * batch.
*/
static final long MAX_DELTA_MS = SECONDS.toMillis(1);
@@ -126,7 +123,8 @@
private final long skewMs;
@Inject
- ChangeRebuilderImpl(@GerritServerConfig Config cfg,
+ ChangeRebuilderImpl(
+ @GerritServerConfig Config cfg,
SchemaFactory<ReviewDb> schemaFactory,
AccountCache accountCache,
ChangeBundleReader bundleReader,
@@ -157,8 +155,7 @@
}
@Override
- public Result rebuild(ReviewDb db, Change.Id changeId)
- throws IOException, OrmException {
+ public Result rebuild(ReviewDb db, Change.Id changeId) throws IOException, OrmException {
return rebuild(db, changeId, true);
}
@@ -177,17 +174,15 @@
if (change == null) {
throw new NoSuchChangeException(changeId);
}
- try (NoteDbUpdateManager manager =
- updateManagerFactory.create(change.getProject())) {
+ try (NoteDbUpdateManager manager = updateManagerFactory.create(change.getProject())) {
buildUpdates(manager, bundleReader.fromReviewDb(db, changeId));
return execute(db, changeId, manager, checkReadOnly);
}
}
@Override
- public Result rebuild(NoteDbUpdateManager manager,
- ChangeBundle bundle) throws NoSuchChangeException, IOException,
- OrmException {
+ public Result rebuild(NoteDbUpdateManager manager, ChangeBundle bundle)
+ throws NoSuchChangeException, IOException, OrmException {
Change change = new Change(bundle.getChange());
buildUpdates(manager, bundle);
return manager.stageAndApplyDelta(change);
@@ -197,30 +192,27 @@
public NoteDbUpdateManager stage(ReviewDb db, Change.Id changeId)
throws IOException, OrmException {
db = ReviewDbUtil.unwrapDb(db);
- Change change =
- checkNoteDbState(ChangeNotes.readOneReviewDbChange(db, changeId));
+ Change change = checkNoteDbState(ChangeNotes.readOneReviewDbChange(db, changeId));
if (change == null) {
throw new NoSuchChangeException(changeId);
}
- NoteDbUpdateManager manager =
- updateManagerFactory.create(change.getProject());
+ NoteDbUpdateManager manager = updateManagerFactory.create(change.getProject());
buildUpdates(manager, bundleReader.fromReviewDb(db, changeId));
manager.stage();
return manager;
}
@Override
- public Result execute(ReviewDb db, Change.Id changeId,
- NoteDbUpdateManager manager) throws OrmException, IOException {
+ public Result execute(ReviewDb db, Change.Id changeId, NoteDbUpdateManager manager)
+ throws OrmException, IOException {
return execute(db, changeId, manager, true);
}
- public Result execute(ReviewDb db, Change.Id changeId,
- NoteDbUpdateManager manager, boolean checkReadOnly)
+ public Result execute(
+ ReviewDb db, Change.Id changeId, NoteDbUpdateManager manager, boolean checkReadOnly)
throws OrmException, IOException {
db = ReviewDbUtil.unwrapDb(db);
- Change change =
- checkNoteDbState(ChangeNotes.readOneReviewDbChange(db, changeId));
+ Change change = checkNoteDbState(ChangeNotes.readOneReviewDbChange(db, changeId));
if (change == null) {
throw new NoSuchChangeException(changeId);
}
@@ -229,24 +221,27 @@
Result r = manager.stageAndApplyDelta(change);
final String newNoteDbState = change.getNoteDbState();
try {
- db.changes().atomicUpdate(changeId, new AtomicUpdate<Change>() {
- @Override
- public Change update(Change change) {
- if (checkReadOnly) {
- NoteDbChangeState.checkNotReadOnly(change, skewMs);
- }
- String currNoteDbState = change.getNoteDbState();
- if (Objects.equals(currNoteDbState, newNoteDbState)) {
- // Another thread completed the same rebuild we were about to.
- throw new AbortUpdateException();
- } else if (!Objects.equals(oldNoteDbState, currNoteDbState)) {
- // Another thread updated the state to something else.
- throw new ConflictingUpdateException(change, oldNoteDbState);
- }
- change.setNoteDbState(newNoteDbState);
- return change;
- }
- });
+ db.changes()
+ .atomicUpdate(
+ changeId,
+ new AtomicUpdate<Change>() {
+ @Override
+ public Change update(Change change) {
+ if (checkReadOnly) {
+ NoteDbChangeState.checkNotReadOnly(change, skewMs);
+ }
+ String currNoteDbState = change.getNoteDbState();
+ if (Objects.equals(currNoteDbState, newNoteDbState)) {
+ // Another thread completed the same rebuild we were about to.
+ throw new AbortUpdateException();
+ } else if (!Objects.equals(oldNoteDbState, currNoteDbState)) {
+ // Another thread updated the state to something else.
+ throw new ConflictingUpdateException(change, oldNoteDbState);
+ }
+ change.setNoteDbState(newNoteDbState);
+ return change;
+ }
+ });
} catch (ConflictingUpdateException e) {
// Rethrow as an OrmException so the caller knows to use staged results.
// Strictly speaking they are not completely up to date, but result we
@@ -254,9 +249,10 @@
// the other thread.
throw new OrmException(e.getMessage());
} catch (AbortUpdateException e) {
- if (NoteDbChangeState.parse(changeId, newNoteDbState).isUpToDate(
- manager.getChangeRepo().cmds.getRepoRefCache(),
- manager.getAllUsersRepo().cmds.getRepoRefCache())) {
+ if (NoteDbChangeState.parse(changeId, newNoteDbState)
+ .isUpToDate(
+ manager.getChangeRepo().cmds.getRepoRefCache(),
+ manager.getAllUsersRepo().cmds.getRepoRefCache())) {
// If the state in ReviewDb matches NoteDb at this point, it means
// another thread successfully completed this rebuild. It's ok to not
// execute the update in this case, since the object referenced in the
@@ -280,8 +276,8 @@
// Can only rebuild a change if its primary storage is ReviewDb.
NoteDbChangeState s = NoteDbChangeState.parse(c);
if (s != null && s.getPrimaryStorage() != PrimaryStorage.REVIEW_DB) {
- throw new OrmException(String.format(
- "cannot rebuild change " + c.getId() + " with state " + s));
+ throw new OrmException(
+ String.format("cannot rebuild change " + c.getId() + " with state " + s));
}
return c;
}
@@ -289,8 +285,7 @@
@Override
public void buildUpdates(NoteDbUpdateManager manager, ChangeBundle bundle)
throws IOException, OrmException {
- manager.setCheckExpectedState(false)
- .setRefLogMessage("Rebuilding change");
+ manager.setCheckExpectedState(false).setRefLogMessage("Rebuilding change");
Change change = new Change(bundle.getChange());
if (bundle.getPatchSets().isEmpty()) {
throw new NoPatchSetsException(change.getId());
@@ -313,18 +308,15 @@
Maps.newHashMapWithExpectedSize(bundle.getPatchSets().size());
for (PatchSet ps : bundle.getPatchSets()) {
- PatchSetEvent pse =
- new PatchSetEvent(change, ps, manager.getChangeRepo().rw);
+ PatchSetEvent pse = new PatchSetEvent(change, ps, manager.getChangeRepo().rw);
patchSetEvents.put(ps.getId(), pse);
events.add(pse);
for (Comment c : getComments(bundle, serverId, Status.PUBLISHED, ps)) {
- CommentEvent e =
- new CommentEvent(c, change, ps, patchListCache);
+ CommentEvent e = new CommentEvent(c, change, ps, patchListCache);
events.add(e.addDep(pse));
}
for (Comment c : getComments(bundle, serverId, Status.DRAFT, ps)) {
- DraftCommentEvent e =
- new DraftCommentEvent(c, change, ps, patchListCache);
+ DraftCommentEvent e = new DraftCommentEvent(c, change, ps, patchListCache);
draftCommentEvents.put(c.author.getId(), e);
}
}
@@ -356,8 +348,7 @@
events.addAll(msgEvents);
}
- sortAndFillEvents(
- change, noteDbChange, bundle.getPatchSets(), events, minPsNum);
+ sortAndFillEvents(change, noteDbChange, bundle.getPatchSets(), events, minPsNum);
EventList<Event> el = new EventList<>();
for (Event e : events) {
@@ -371,8 +362,7 @@
EventList<DraftCommentEvent> plcel = new EventList<>();
for (Account.Id author : draftCommentEvents.keys()) {
- for (DraftCommentEvent e :
- Ordering.natural().sortedCopy(draftCommentEvents.get(author))) {
+ for (DraftCommentEvent e : Ordering.natural().sortedCopy(draftCommentEvents.get(author))) {
if (!plcel.canAdd(e)) {
flushEventsToDraftUpdate(manager, plcel, change);
checkState(plcel.canAdd(e));
@@ -383,12 +373,10 @@
}
}
- private List<Event> parseChangeMessage(ChangeMessage msg, Change change,
- Change noteDbChange) {
+ private List<Event> parseChangeMessage(ChangeMessage msg, Change change, Change noteDbChange) {
List<Event> events = new ArrayList<>(2);
events.add(new ChangeMessageEvent(msg, noteDbChange, change.getCreatedOn()));
- Optional<StatusChangeEvent> sce =
- StatusChangeEvent.parseFromMessage(msg, change, noteDbChange);
+ Optional<StatusChangeEvent> sce = StatusChangeEvent.parseFromMessage(msg, change, noteDbChange);
if (sce.isPresent()) {
events.add(sce.get());
}
@@ -406,18 +394,23 @@
return minPsNum;
}
- private static List<Comment> getComments(ChangeBundle bundle, String serverId,
- PatchLineComment.Status status, PatchSet ps) {
- return bundle.getPatchLineComments().stream()
- .filter(c -> c.getPatchSetId().equals(ps.getId())
- && c.getStatus() == status)
- .map(plc -> plc.asComment(serverId)).sorted(CommentsUtil.COMMENT_ORDER)
+ private static List<Comment> getComments(
+ ChangeBundle bundle, String serverId, PatchLineComment.Status status, PatchSet ps) {
+ return bundle
+ .getPatchLineComments()
+ .stream()
+ .filter(c -> c.getPatchSetId().equals(ps.getId()) && c.getStatus() == status)
+ .map(plc -> plc.asComment(serverId))
+ .sorted(CommentsUtil.COMMENT_ORDER)
.collect(toList());
}
- private void sortAndFillEvents(Change change, Change noteDbChange,
+ private void sortAndFillEvents(
+ Change change,
+ Change noteDbChange,
ImmutableCollection<PatchSet> patchSets,
- List<Event> events, Integer minPsNum) {
+ List<Event> events,
+ Integer minPsNum) {
Event finalUpdates = new FinalUpdatesEvent(change, noteDbChange, patchSets);
events.add(finalUpdates);
setPostSubmitDeps(events);
@@ -426,8 +419,7 @@
// Ensure the first event in the list creates the change, setting the author
// and any required footers.
Event first = events.get(0);
- if (first instanceof PatchSetEvent
- && change.getOwner().equals(first.user)) {
+ if (first instanceof PatchSetEvent && change.getOwner().equals(first.user)) {
((PatchSetEvent) first).createChange = true;
} else {
events.add(0, new CreateChangeEvent(change, minPsNum));
@@ -470,37 +462,35 @@
}
private void setPostSubmitDeps(List<Event> events) {
- Optional<Event> submitEvent = Lists.reverse(events).stream()
- .filter(Event::isSubmit)
- .findFirst();
+ Optional<Event> submitEvent =
+ Lists.reverse(events).stream().filter(Event::isSubmit).findFirst();
if (submitEvent.isPresent()) {
- events.stream()
- .filter(Event::isPostSubmitApproval)
- .forEach(e -> e.addDep(submitEvent.get()));
+ events.stream().filter(Event::isPostSubmitApproval).forEach(e -> e.addDep(submitEvent.get()));
}
}
- private void flushEventsToUpdate(NoteDbUpdateManager manager,
- EventList<Event> events, Change change) throws OrmException, IOException {
+ private void flushEventsToUpdate(
+ NoteDbUpdateManager manager, EventList<Event> events, Change change)
+ throws OrmException, IOException {
if (events.isEmpty()) {
return;
}
Comparator<String> labelNameComparator;
if (projectCache != null) {
- labelNameComparator = projectCache.get(change.getProject())
- .getLabelTypes().nameComparator();
+ labelNameComparator = projectCache.get(change.getProject()).getLabelTypes().nameComparator();
} else {
// No project cache available, bail and use natural ordering; there's no
// semantic difference anyway difference.
labelNameComparator = Ordering.natural();
}
- ChangeUpdate update = updateFactory.create(
- change,
- events.getAccountId(),
- events.getRealAccountId(),
- newAuthorIdent(events),
- events.getWhen(),
- labelNameComparator);
+ ChangeUpdate update =
+ updateFactory.create(
+ change,
+ events.getAccountId(),
+ events.getRealAccountId(),
+ newAuthorIdent(events),
+ events.getWhen(),
+ labelNameComparator);
update.setAllowWriteToNewRef(true);
update.setPatchSetId(events.getPatchSetId());
update.setTag(events.getTag());
@@ -511,18 +501,19 @@
events.clear();
}
- private void flushEventsToDraftUpdate(NoteDbUpdateManager manager,
- EventList<DraftCommentEvent> events, Change change)
+ private void flushEventsToDraftUpdate(
+ NoteDbUpdateManager manager, EventList<DraftCommentEvent> events, Change change)
throws OrmException {
if (events.isEmpty()) {
return;
}
- ChangeDraftUpdate update = draftUpdateFactory.create(
- change,
- events.getAccountId(),
- events.getRealAccountId(),
- newAuthorIdent(events),
- events.getWhen());
+ ChangeDraftUpdate update =
+ draftUpdateFactory.create(
+ change,
+ events.getAccountId(),
+ events.getRealAccountId(),
+ newAuthorIdent(events),
+ events.getWhen());
update.setPatchSetId(events.getPatchSetId());
for (DraftCommentEvent e : events) {
e.applyDraft(update);
@@ -537,12 +528,11 @@
return new PersonIdent(serverIdent, events.getWhen());
}
return changeNoteUtil.newIdent(
- accountCache.get(id).getAccount(), events.getWhen(), serverIdent,
- anonymousCowardName);
+ accountCache.get(id).getAccount(), events.getWhen(), serverIdent, anonymousCowardName);
}
- private List<HashtagsEvent> getHashtagsEvents(Change change,
- NoteDbUpdateManager manager) throws IOException {
+ private List<HashtagsEvent> getHashtagsEvents(Change change, NoteDbUpdateManager manager)
+ throws IOException {
String refName = changeMetaRef(change.getId());
Optional<ObjectId> old = manager.getChangeRepo().getObjectId(refName);
if (!old.isPresent()) {
@@ -556,8 +546,7 @@
for (RevCommit commit : rw) {
Account.Id authorId;
try {
- authorId =
- changeNoteUtil.parseIdent(commit.getAuthorIdent(), change.getId());
+ authorId = changeNoteUtil.parseIdent(commit.getAuthorIdent(), change.getId());
} catch (ConfigInvalidException e) {
continue; // Corrupt data, no valid hashtags in this commit.
}
@@ -567,10 +556,8 @@
continue;
}
- Timestamp commitTime =
- new Timestamp(commit.getCommitterIdent().getWhen().getTime());
- events.add(new HashtagsEvent(psId, authorId, commitTime, hashtags,
- change.getCreatedOn()));
+ Timestamp commitTime = new Timestamp(commit.getCommitterIdent().getWhen().getTime());
+ events.add(new HashtagsEvent(psId, authorId, commitTime, hashtags, change.getCreatedOn()));
}
return events;
}
@@ -599,8 +586,7 @@
return new PatchSet.Id(change.getId(), psId);
}
- private void deleteChangeMetaRef(Change change, ChainedReceiveCommands cmds)
- throws IOException {
+ private void deleteChangeMetaRef(Change change, ChainedReceiveCommands cmds) throws IOException {
String refName = changeMetaRef(change.getId());
Optional<ObjectId> old = cmds.get(refName);
if (old.isPresent()) {
@@ -608,12 +594,14 @@
}
}
- private void deleteDraftRefs(Change change, OpenRepo allUsersRepo)
- throws IOException {
- for (Ref r : allUsersRepo.repo.getRefDatabase()
- .getRefs(RefNames.refsDraftCommentsPrefix(change.getId())).values()) {
- allUsersRepo.cmds.add(
- new ReceiveCommand(r.getObjectId(), ObjectId.zeroId(), r.getName()));
+ private void deleteDraftRefs(Change change, OpenRepo allUsersRepo) throws IOException {
+ for (Ref r :
+ allUsersRepo
+ .repo
+ .getRefDatabase()
+ .getRefs(RefNames.refsDraftCommentsPrefix(change.getId()))
+ .values()) {
+ allUsersRepo.cmds.add(new ReceiveCommand(r.getObjectId(), ObjectId.zeroId(), r.getName()));
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/CommentEvent.java b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/CommentEvent.java
index 8f461a2..1be5598 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/CommentEvent.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/CommentEvent.java
@@ -31,10 +31,14 @@
private final PatchSet ps;
private final PatchListCache cache;
- CommentEvent(Comment c, Change change, PatchSet ps,
- PatchListCache cache) {
- super(CommentsUtil.getCommentPsId(change.getId(), c), c.author.getId(),
- c.getRealAuthor().getId(), c.writtenOn, change.getCreatedOn(), c.tag);
+ CommentEvent(Comment c, Change change, PatchSet ps, PatchListCache cache) {
+ super(
+ CommentsUtil.getCommentPsId(change.getId(), c),
+ c.author.getId(),
+ c.getRealAuthor().getId(),
+ c.writtenOn,
+ change.getCreatedOn(),
+ c.tag);
this.c = c;
this.change = change;
this.ps = ps;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/ConflictingUpdateException.java b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/ConflictingUpdateException.java
index 2098727..c6ffffc 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/ConflictingUpdateException.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/ConflictingUpdateException.java
@@ -21,8 +21,9 @@
private static final long serialVersionUID = 1L;
ConflictingUpdateException(Change change, String expectedNoteDbState) {
- super(String.format(
- "Expected change %s to have noteDbState %s but was %s",
- change.getId(), expectedNoteDbState, change.getNoteDbState()));
+ super(
+ String.format(
+ "Expected change %s to have noteDbState %s but was %s",
+ change.getId(), expectedNoteDbState, change.getNoteDbState()));
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/CreateChangeEvent.java b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/CreateChangeEvent.java
index b020911..d01071b 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/CreateChangeEvent.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/CreateChangeEvent.java
@@ -18,7 +18,6 @@
import com.google.gerrit.reviewdb.client.PatchSet;
import com.google.gerrit.server.notedb.ChangeUpdate;
import com.google.gwtorm.server.OrmException;
-
import java.io.IOException;
class CreateChangeEvent extends Event {
@@ -37,8 +36,13 @@
}
CreateChangeEvent(Change change, Integer minPsNum) {
- super(psId(change, minPsNum), change.getOwner(), change.getOwner(),
- change.getCreatedOn(), change.getCreatedOn(), null);
+ super(
+ psId(change, minPsNum),
+ change.getOwner(),
+ change.getOwner(),
+ change.getCreatedOn(),
+ change.getCreatedOn(),
+ null);
this.change = change;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/DraftCommentEvent.java b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/DraftCommentEvent.java
index 2938480..3cb3eb5 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/DraftCommentEvent.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/DraftCommentEvent.java
@@ -31,10 +31,14 @@
private final PatchSet ps;
private final PatchListCache cache;
- DraftCommentEvent(Comment c, Change change, PatchSet ps,
- PatchListCache cache) {
- super(CommentsUtil.getCommentPsId(change.getId(), c), c.author.getId(),
- c.getRealAuthor().getId(), c.writtenOn, change.getCreatedOn(), c.tag);
+ DraftCommentEvent(Comment c, Change change, PatchSet ps, PatchListCache cache) {
+ super(
+ CommentsUtil.getCommentPsId(change.getId(), c),
+ c.author.getId(),
+ c.getRealAuthor().getId(),
+ c.writtenOn,
+ change.getCreatedOn(),
+ c.tag);
this.c = c;
this.change = change;
this.ps = ps;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/Event.java b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/Event.java
index 147a467..10adbab 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/Event.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/Event.java
@@ -25,7 +25,6 @@
import com.google.gerrit.server.notedb.AbstractChangeUpdate;
import com.google.gerrit.server.notedb.ChangeUpdate;
import com.google.gwtorm.server.OrmException;
-
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
@@ -41,10 +40,7 @@
final String tag;
final boolean predatesChange;
- /**
- * Dependencies of this event; other events that must happen before this
- * one.
- */
+ /** Dependencies of this event; other events that must happen before this one. */
final List<Event> deps;
Timestamp when;
@@ -68,15 +64,21 @@
}
protected void checkUpdate(AbstractChangeUpdate update) {
- checkState(Objects.equals(update.getPatchSetId(), psId),
+ checkState(
+ Objects.equals(update.getPatchSetId(), psId),
"cannot apply event for %s to update for %s",
- update.getPatchSetId(), psId);
- checkState(when.getTime() - update.getWhen().getTime() <= MAX_WINDOW_MS,
+ update.getPatchSetId(),
+ psId);
+ checkState(
+ when.getTime() - update.getWhen().getTime() <= MAX_WINDOW_MS,
"event at %s outside update window starting at %s",
- when, update.getWhen());
- checkState(Objects.equals(update.getNullableAccountId(), user),
+ when,
+ update.getWhen());
+ checkState(
+ Objects.equals(update.getNullableAccountId(), user),
"cannot apply event by %s to update by %s",
- user, update.getNullableAccountId());
+ user,
+ update.getNullableAccountId());
}
Event addDep(Event e) {
@@ -85,8 +87,8 @@
}
/**
- * @return whether this event type must be unique per {@link ChangeUpdate},
- * i.e. there may be at most one of this type.
+ * @return whether this event type must be unique per {@link ChangeUpdate}, i.e. there may be at
+ * most one of this type.
*/
abstract boolean uniquePerUpdate();
@@ -117,11 +119,9 @@
.compare(this.when, other.when)
.compareTrueFirst(isPatchSet(), isPatchSet())
.compareTrueFirst(this.predatesChange, other.predatesChange)
- .compare(this.user, other.user,
- ReviewDbUtil.intKeyOrdering())
+ .compare(this.user, other.user, ReviewDbUtil.intKeyOrdering())
.compare(this.realUser, other.realUser, ReviewDbUtil.intKeyOrdering())
- .compare(this.psId, other.psId,
- ReviewDbUtil.intKeyOrdering().nullsLast())
+ .compare(this.psId, other.psId, ReviewDbUtil.intKeyOrdering().nullsLast())
.result();
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/EventList.java b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/EventList.java
index 59ff49e..f0faef1 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/EventList.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/EventList.java
@@ -20,7 +20,6 @@
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.reviewdb.client.PatchSet;
-
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Iterator;
@@ -74,9 +73,9 @@
long t = e.when.getTime();
long tFirst = getFirstTime();
long tLast = getLastTime();
- checkArgument(t >= tLast,
- "event %s is before previous event in list %s", e, last);
- if (t - tLast > ChangeRebuilderImpl.MAX_DELTA_MS || t - tFirst > ChangeRebuilderImpl.MAX_WINDOW_MS) {
+ checkArgument(t >= tLast, "event %s is before previous event in list %s", e, last);
+ if (t - tLast > ChangeRebuilderImpl.MAX_DELTA_MS
+ || t - tFirst > ChangeRebuilderImpl.MAX_WINDOW_MS) {
return false; // Too much time elapsed.
}
@@ -102,8 +101,8 @@
PatchSet.Id getPatchSetId() {
PatchSet.Id id = checkNotNull(get(0).psId);
for (int i = 1; i < size(); i++) {
- checkState(get(i).psId.equals(id),
- "mismatched patch sets in EventList: %s != %s", id, get(i).psId);
+ checkState(
+ get(i).psId.equals(id), "mismatched patch sets in EventList: %s != %s", id, get(i).psId);
}
return id;
}
@@ -111,8 +110,11 @@
Account.Id getAccountId() {
Account.Id id = get(0).user;
for (int i = 1; i < size(); i++) {
- checkState(Objects.equals(id, get(i).user),
- "mismatched users in EventList: %s != %s", id, get(i).user);
+ checkState(
+ Objects.equals(id, get(i).user),
+ "mismatched users in EventList: %s != %s",
+ id,
+ get(i).user);
}
return id;
}
@@ -120,8 +122,11 @@
Account.Id getRealAccountId() {
Account.Id id = get(0).realUser;
for (int i = 1; i < size(); i++) {
- checkState(Objects.equals(id, get(i).realUser),
- "mismatched real users in EventList: %s != %s", id, get(i).realUser);
+ checkState(
+ Objects.equals(id, get(i).realUser),
+ "mismatched real users in EventList: %s != %s",
+ id,
+ get(i).realUser);
}
return id;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/EventSorter.java b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/EventSorter.java
index d0847cd..077a027 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/EventSorter.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/EventSorter.java
@@ -20,7 +20,6 @@
import com.google.common.collect.ListMultimap;
import com.google.common.collect.MultimapBuilder;
import com.google.common.collect.SetMultimap;
-
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
@@ -28,18 +27,18 @@
/**
* Helper to sort a list of events.
- * <p>
- * Events are sorted in two passes:
+ *
+ * <p>Events are sorted in two passes:
+ *
* <ol>
- * <li>Sort by natural order (timestamp, patch set, author, etc.)</li>
- * <li>Postpone any events with dependencies to occur only after all of their
- * dependencies, where this violates natural order.</li>
+ * <li>Sort by natural order (timestamp, patch set, author, etc.)
+ * <li>Postpone any events with dependencies to occur only after all of their dependencies, where
+ * this violates natural order.
* </ol>
*
- * {@link #sort()} modifies the event list in place (similar to {@link
- * Collections#sort(List)}), but does not modify any event. In particular,
- * events might end up out of order with respect to timestamp; callers are
- * responsible for adjusting timestamps later if they prefer monotonicity.
+ * {@link #sort()} modifies the event list in place (similar to {@link Collections#sort(List)}), but
+ * does not modify any event. In particular, events might end up out of order with respect to
+ * timestamp; callers are responsible for adjusting timestamps later if they prefer monotonicity.
*/
class EventSorter {
private final List<Event> out;
@@ -80,8 +79,8 @@
while (!todo.isEmpty()) {
process(todo.remove(), todo);
}
- checkState(sorted.size() == size,
- "event sort expected %s elements, got %s", size, sorted.size());
+ checkState(
+ sorted.size() == size, "event sort expected %s elements, got %s", size, sorted.size());
// Modify out in-place a la Collections#sort.
out.clear();
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/FinalUpdatesEvent.java b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/FinalUpdatesEvent.java
index a9b51a4..474a7e0 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/FinalUpdatesEvent.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/FinalUpdatesEvent.java
@@ -21,7 +21,6 @@
import com.google.gerrit.reviewdb.client.PatchSet;
import com.google.gerrit.server.notedb.ChangeUpdate;
import com.google.gwtorm.server.OrmException;
-
import java.util.Objects;
class FinalUpdatesEvent extends Event {
@@ -29,10 +28,14 @@
private final Change noteDbChange;
private final ImmutableCollection<PatchSet> patchSets;
- FinalUpdatesEvent(Change change, Change noteDbChange,
- ImmutableCollection<PatchSet> patchSets) {
- super(change.currentPatchSetId(), change.getOwner(), change.getOwner(),
- change.getLastUpdatedOn(), change.getCreatedOn(), null);
+ FinalUpdatesEvent(Change change, Change noteDbChange, ImmutableCollection<PatchSet> patchSets) {
+ super(
+ change.currentPatchSetId(),
+ change.getOwner(),
+ change.getOwner(),
+ change.getLastUpdatedOn(),
+ change.getCreatedOn(),
+ null);
this.change = change;
this.noteDbChange = noteDbChange;
this.patchSets = patchSets;
@@ -53,8 +56,7 @@
// TODO(dborowitz): Stamp approximate approvals at this time.
update.fixStatus(change.getStatus());
}
- if (change.getSubmissionId() != null
- && noteDbChange.getSubmissionId() == null) {
+ if (change.getSubmissionId() != null && noteDbChange.getSubmissionId() == null) {
update.setSubmissionId(change.getSubmissionId());
}
if (!Objects.equals(change.getAssignee(), noteDbChange.getAssignee())) {
@@ -70,8 +72,7 @@
}
private boolean highestNumberedPatchSetIsCurrent() {
- PatchSet.Id max =
- patchSets.stream().map(PatchSet::getId).max(intKeyOrdering()).get();
+ PatchSet.Id max = patchSets.stream().map(PatchSet::getId).max(intKeyOrdering()).get();
return max.equals(change.currentPatchSetId());
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/HashtagsEvent.java b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/HashtagsEvent.java
index f5bea3e..028abfe 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/HashtagsEvent.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/HashtagsEvent.java
@@ -18,16 +18,24 @@
import com.google.gerrit.reviewdb.client.PatchSet;
import com.google.gerrit.server.notedb.ChangeUpdate;
import com.google.gwtorm.server.OrmException;
-
import java.sql.Timestamp;
import java.util.Set;
class HashtagsEvent extends Event {
private final Set<String> hashtags;
- HashtagsEvent(PatchSet.Id psId, Account.Id who, Timestamp when,
- Set<String> hashtags, Timestamp changeCreatdOn) {
- super(psId, who, who, when, changeCreatdOn,
+ HashtagsEvent(
+ PatchSet.Id psId,
+ Account.Id who,
+ Timestamp when,
+ Set<String> hashtags,
+ Timestamp changeCreatdOn) {
+ super(
+ psId,
+ who,
+ who,
+ when,
+ changeCreatdOn,
// Somewhat confusingly, hashtags do not use the setTag method on
// AbstractChangeUpdate, so pass null as the tag.
null);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/PatchSetEvent.java b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/PatchSetEvent.java
index eeeec55..e0ad640 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/PatchSetEvent.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/PatchSetEvent.java
@@ -19,15 +19,13 @@
import com.google.gerrit.server.notedb.ChangeUpdate;
import com.google.gerrit.server.notedb.PatchSetState;
import com.google.gwtorm.server.OrmException;
-
+import java.io.IOException;
+import java.util.List;
import org.eclipse.jgit.errors.InvalidObjectIdException;
import org.eclipse.jgit.errors.MissingObjectException;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.revwalk.RevWalk;
-import java.io.IOException;
-import java.util.List;
-
class PatchSetEvent extends Event {
private final Change change;
private final PatchSet ps;
@@ -35,8 +33,13 @@
boolean createChange;
PatchSetEvent(Change change, PatchSet ps, RevWalk rw) {
- super(ps.getId(), ps.getUploader(), ps.getUploader(), ps.getCreatedOn(),
- change.getCreatedOn(), null);
+ super(
+ ps.getId(),
+ ps.getUploader(),
+ ps.getUploader(),
+ ps.getCreatedOn(),
+ change.getCreatedOn(),
+ null);
this.change = change;
this.ps = ps;
this.rw = rw;
@@ -67,8 +70,7 @@
}
}
- private void setRevision(ChangeUpdate update, PatchSet ps)
- throws IOException {
+ private void setRevision(ChangeUpdate update, PatchSet ps) throws IOException {
String rev = ps.getRevision().get();
String cert = ps.getPushCertificate();
ObjectId id;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/ReviewerEvent.java b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/ReviewerEvent.java
index c82f108..1d8fbfb 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/ReviewerEvent.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/ReviewerEvent.java
@@ -19,7 +19,6 @@
import com.google.gerrit.server.notedb.ChangeUpdate;
import com.google.gerrit.server.notedb.ReviewerStateInternal;
import com.google.gwtorm.server.OrmException;
-
import java.io.IOException;
import java.sql.Timestamp;
@@ -40,7 +39,8 @@
// diffs when run against real data.
reviewer.getColumnKey(),
reviewer.getValue(),
- changeCreatedOn, null);
+ changeCreatedOn,
+ null);
this.reviewer = reviewer;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/StatusChangeEvent.java b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/StatusChangeEvent.java
index 5bc05d0..025b6c8 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/StatusChangeEvent.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/notedb/rebuild/StatusChangeEvent.java
@@ -21,7 +21,6 @@
import com.google.gerrit.reviewdb.client.PatchSet;
import com.google.gerrit.server.notedb.ChangeUpdate;
import com.google.gwtorm.server.OrmException;
-
import java.sql.Timestamp;
import java.util.Map;
import java.util.Optional;
@@ -31,21 +30,20 @@
private static final ImmutableMap<Change.Status, Pattern> PATTERNS =
ImmutableMap.of(
Change.Status.ABANDONED, Pattern.compile("^Abandoned(\n.*)*$"),
- Change.Status.MERGED, Pattern.compile(
- "^Change has been successfully"
- + " (merged|cherry-picked|rebased|pushed).*$"),
+ Change.Status.MERGED,
+ Pattern.compile(
+ "^Change has been successfully" + " (merged|cherry-picked|rebased|pushed).*$"),
Change.Status.NEW, Pattern.compile("^Restored(\n.*)*$"));
- static Optional<StatusChangeEvent> parseFromMessage(ChangeMessage message,
- Change change, Change noteDbChange) {
+ static Optional<StatusChangeEvent> parseFromMessage(
+ ChangeMessage message, Change change, Change noteDbChange) {
String msg = message.getMessage();
if (msg == null) {
return Optional.empty();
}
for (Map.Entry<Change.Status, Pattern> e : PATTERNS.entrySet()) {
if (e.getValue().matcher(msg).matches()) {
- return Optional.of(new StatusChangeEvent(
- message, change, noteDbChange, e.getKey()));
+ return Optional.of(new StatusChangeEvent(message, change, noteDbChange, e.getKey()));
}
}
return Optional.empty();
@@ -55,16 +53,26 @@
private final Change change;
private final Change noteDbChange;
- private StatusChangeEvent(ChangeMessage message, Change change,
- Change noteDbChange, Change.Status status) {
- this(message.getPatchSetId(), message.getAuthor(),
- message.getWrittenOn(), change, noteDbChange, message.getTag(),
+ private StatusChangeEvent(
+ ChangeMessage message, Change change, Change noteDbChange, Change.Status status) {
+ this(
+ message.getPatchSetId(),
+ message.getAuthor(),
+ message.getWrittenOn(),
+ change,
+ noteDbChange,
+ message.getTag(),
status);
}
- private StatusChangeEvent(PatchSet.Id psId, Account.Id author,
- Timestamp when, Change change, Change noteDbChange,
- String tag, Change.Status status) {
+ private StatusChangeEvent(
+ PatchSet.Id psId,
+ Account.Id author,
+ Timestamp when,
+ Change change,
+ Change noteDbChange,
+ String tag,
+ Change.Status status) {
super(psId, author, author, when, change.getCreatedOn(), tag);
this.change = change;
this.noteDbChange = noteDbChange;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/patch/AutoMerger.java b/gerrit-server/src/main/java/com/google/gerrit/server/patch/AutoMerger.java
index aa8879a..74a3132 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/patch/AutoMerger.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/patch/AutoMerger.java
@@ -23,7 +23,10 @@
import com.google.gerrit.server.config.GerritServerConfig;
import com.google.gerrit.server.git.InMemoryInserter;
import com.google.inject.Inject;
-
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.HashMap;
+import java.util.Map;
import org.eclipse.jgit.diff.Sequence;
import org.eclipse.jgit.dircache.DirCache;
import org.eclipse.jgit.dircache.DirCacheBuilder;
@@ -49,11 +52,6 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.HashMap;
-import java.util.Map;
-
public class AutoMerger {
private static final Logger log = LoggerFactory.getLogger(AutoMerger.class);
@@ -65,9 +63,7 @@
private final boolean save;
@Inject
- AutoMerger(
- @GerritServerConfig Config cfg,
- @GerritPersonIdent PersonIdent gerritIdent) {
+ AutoMerger(@GerritServerConfig Config cfg, @GerritPersonIdent PersonIdent gerritIdent) {
save = cacheAutomerge(cfg);
this.gerritIdent = gerritIdent;
}
@@ -75,11 +71,15 @@
/**
* Perform an auto-merge of the parents of the given merge commit.
*
- * @return auto-merge commit or {@code null} if an auto-merge commit
- * couldn't be created. Headers of the returned RevCommit are parsed.
+ * @return auto-merge commit or {@code null} if an auto-merge commit couldn't be created. Headers
+ * of the returned RevCommit are parsed.
*/
- public RevCommit merge(Repository repo, RevWalk rw, final ObjectInserter ins,
- RevCommit merge, ThreeWayMergeStrategy mergeStrategy)
+ public RevCommit merge(
+ Repository repo,
+ RevWalk rw,
+ final ObjectInserter ins,
+ RevCommit merge,
+ ThreeWayMergeStrategy mergeStrategy)
throws IOException {
checkArgument(rw.getObjectReader().getCreatedFromInserter() == ins);
InMemoryInserter tmpIns = null;
@@ -135,20 +135,22 @@
String oursMsg = ours.getShortMessage();
String theirsMsg = theirs.getShortMessage();
- String oursName = String.format("HEAD (%s %s)",
- ours.abbreviate(6).name(),
- oursMsg.substring(0, Math.min(oursMsg.length(), 60)));
- String theirsName = String.format("BRANCH (%s %s)",
- theirs.abbreviate(6).name(),
- theirsMsg.substring(0, Math.min(theirsMsg.length(), 60)));
+ String oursName =
+ String.format(
+ "HEAD (%s %s)",
+ ours.abbreviate(6).name(), oursMsg.substring(0, Math.min(oursMsg.length(), 60)));
+ String theirsName =
+ String.format(
+ "BRANCH (%s %s)",
+ theirs.abbreviate(6).name(),
+ theirsMsg.substring(0, Math.min(theirsMsg.length(), 60)));
MergeFormatter fmt = new MergeFormatter();
Map<String, MergeResult<? extends Sequence>> r = m.getMergeResults();
Map<String, ObjectId> resolved = new HashMap<>();
for (Map.Entry<String, MergeResult<? extends Sequence>> entry : r.entrySet()) {
MergeResult<? extends Sequence> p = entry.getValue();
- try (TemporaryBuffer buf =
- new TemporaryBuffer.LocalFile(null, 10 * 1024 * 1024)) {
+ try (TemporaryBuffer buf = new TemporaryBuffer.LocalFile(null, 10 * 1024 * 1024)) {
fmt.formatMerge(buf, p, "BASE", oursName, theirsName, UTF_8.name());
buf.close();
@@ -160,7 +162,7 @@
DirCacheBuilder builder = dc.builder();
int cnt = dc.getEntryCount();
- for (int i = 0; i < cnt;) {
+ for (int i = 0; i < cnt; ) {
DirCacheEntry entry = dc.getEntry(i);
if (entry.getStage() == 0) {
builder.add(entry);
@@ -214,14 +216,14 @@
ObjectInserter ins,
String refName,
ObjectId tree,
- RevCommit merge) throws IOException {
+ RevCommit merge)
+ throws IOException {
rw.parseHeaders(merge);
// For maximum stability, choose a single ident using the committer time of
// the input commit, using the server name and timezone.
- PersonIdent ident = new PersonIdent(
- gerritIdent,
- merge.getCommitterIdent().getWhen(),
- gerritIdent.getTimeZone());
+ PersonIdent ident =
+ new PersonIdent(
+ gerritIdent, merge.getCommitterIdent().getWhen(), gerritIdent.getTimeZone());
CommitBuilder cb = new CommitBuilder();
cb.setAuthor(ident);
cb.setCommitter(ident);
@@ -264,11 +266,9 @@
}
@Override
- public void flush() {
- }
+ public void flush() {}
@Override
- public void close() {
- }
+ public void close() {}
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/patch/DiffExecutor.java b/gerrit-server/src/main/java/com/google/gerrit/server/patch/DiffExecutor.java
index 564ca58..072c2da 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/patch/DiffExecutor.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/patch/DiffExecutor.java
@@ -17,15 +17,12 @@
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import com.google.inject.BindingAnnotation;
-
import java.lang.annotation.Retention;
import java.util.concurrent.ExecutorService;
/**
- * Marker on {@link ExecutorService} used by
- * {@link IntraLineLoader} and {@link PatchListLoader}.
+ * Marker on {@link ExecutorService} used by {@link IntraLineLoader} and {@link PatchListLoader}.
*/
@Retention(RUNTIME)
@BindingAnnotation
-public @interface DiffExecutor {
-}
+public @interface DiffExecutor {}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/patch/DiffExecutorModule.java b/gerrit-server/src/main/java/com/google/gerrit/server/patch/DiffExecutorModule.java
index 9eaea3a..5359479 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/patch/DiffExecutorModule.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/patch/DiffExecutorModule.java
@@ -18,7 +18,6 @@
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.Singleton;
-
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@@ -26,14 +25,13 @@
public class DiffExecutorModule extends AbstractModule {
@Override
- protected void configure() {
- }
+ protected void configure() {}
@Provides
@Singleton
@DiffExecutor
public ExecutorService createDiffExecutor() {
- return Executors.newCachedThreadPool(new ThreadFactoryBuilder()
- .setNameFormat("Diff-%d").setDaemon(true).build());
+ return Executors.newCachedThreadPool(
+ new ThreadFactoryBuilder().setNameFormat("Diff-%d").setDaemon(true).build());
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/patch/DiffSummaryKey.java b/gerrit-server/src/main/java/com/google/gerrit/server/patch/DiffSummaryKey.java
index 4c708c4..bfa7ec3 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/patch/DiffSummaryKey.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/patch/DiffSummaryKey.java
@@ -20,14 +20,12 @@
import static org.eclipse.jgit.lib.ObjectIdSerialization.writeNotNull;
import com.google.gerrit.extensions.client.DiffPreferencesInfo.Whitespace;
-
-import org.eclipse.jgit.lib.ObjectId;
-
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Objects;
+import org.eclipse.jgit.lib.ObjectId;
public class DiffSummaryKey implements Serializable {
public static final long serialVersionUID = 1L;
@@ -42,12 +40,11 @@
private transient Whitespace whitespace;
public static DiffSummaryKey fromPatchListKey(PatchListKey plk) {
- return new DiffSummaryKey(plk.getOldId(), plk.getParentNum(),
- plk.getNewId(), plk.getWhitespace());
+ return new DiffSummaryKey(
+ plk.getOldId(), plk.getParentNum(), plk.getNewId(), plk.getWhitespace());
}
- private DiffSummaryKey(ObjectId oldId, Integer parentNum, ObjectId newId,
- Whitespace whitespace) {
+ private DiffSummaryKey(ObjectId oldId, Integer parentNum, ObjectId newId, Whitespace whitespace) {
this.oldId = oldId;
this.parentNum = parentNum;
this.newId = newId;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/patch/DiffSummaryLoader.java b/gerrit-server/src/main/java/com/google/gerrit/server/patch/DiffSummaryLoader.java
index 43e2392..8aa76cb 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/patch/DiffSummaryLoader.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/patch/DiffSummaryLoader.java
@@ -18,14 +18,12 @@
import com.google.gerrit.reviewdb.client.Project;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class DiffSummaryLoader implements Callable<DiffSummary> {
static final Logger log = LoggerFactory.getLogger(DiffSummaryLoader.class);
@@ -39,9 +37,7 @@
private final Project.NameKey project;
@AssistedInject
- DiffSummaryLoader(PatchListCache plc,
- @Assisted DiffSummaryKey k,
- @Assisted Project.NameKey p) {
+ DiffSummaryLoader(PatchListCache plc, @Assisted DiffSummaryKey k, @Assisted Project.NameKey p) {
patchListCache = plc;
key = k;
project = p;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/patch/DiffSummaryWeigher.java b/gerrit-server/src/main/java/com/google/gerrit/server/patch/DiffSummaryWeigher.java
index 548f999..2627792 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/patch/DiffSummaryWeigher.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/patch/DiffSummaryWeigher.java
@@ -17,17 +17,26 @@
import com.google.common.cache.Weigher;
/** Computes memory usage for {@link DiffSummary} in bytes of memory used. */
-public class DiffSummaryWeigher implements
- Weigher<DiffSummaryKey, DiffSummary> {
+public class DiffSummaryWeigher implements Weigher<DiffSummaryKey, DiffSummary> {
@Override
public int weigh(DiffSummaryKey key, DiffSummary value) {
- int size = 16 + 4 * 8 + 2 * 36 // Size of DiffSummaryKey, 64 bit JVM
- + 16 + 8 // Size of DiffSummary
- + 16 + 8; // String[]
+ int size =
+ 16
+ + 4 * 8
+ + 2 * 36 // Size of DiffSummaryKey, 64 bit JVM
+ + 16
+ + 8 // Size of DiffSummary
+ + 16
+ + 8; // String[]
for (String p : value.getPaths()) {
- size += 16 + 8 + 4 * 4 // String
- + 16 + 8 + p.length() * 2; // char[]
+ size +=
+ 16
+ + 8
+ + 4 * 4 // String
+ + 16
+ + 8
+ + p.length() * 2; // char[]
}
return size;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/patch/IntraLineDiff.java b/gerrit-server/src/main/java/com/google/gerrit/server/patch/IntraLineDiff.java
index 60b97c7..e51b4ab 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/patch/IntraLineDiff.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/patch/IntraLineDiff.java
@@ -20,10 +20,6 @@
import static com.google.gerrit.server.ioutil.BasicSerialization.writeVarInt32;
import com.google.gerrit.reviewdb.client.CodedEnum;
-
-import org.eclipse.jgit.diff.Edit;
-import org.eclipse.jgit.diff.ReplaceEdit;
-
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
@@ -33,12 +29,17 @@
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
+import org.eclipse.jgit.diff.Edit;
+import org.eclipse.jgit.diff.ReplaceEdit;
public class IntraLineDiff implements Serializable {
static final long serialVersionUID = IntraLineDiffKey.serialVersionUID;
public enum Status implements CodedEnum {
- EDIT_LIST('e'), DISABLED('D'), TIMEOUT('T'), ERROR('E');
+ EDIT_LIST('e'),
+ DISABLED('D'),
+ TIMEOUT('T'),
+ ERROR('E');
private final char code;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/patch/IntraLineDiffArgs.java b/gerrit-server/src/main/java/com/google/gerrit/server/patch/IntraLineDiffArgs.java
index 4a61e2d..46ee56a 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/patch/IntraLineDiffArgs.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/patch/IntraLineDiffArgs.java
@@ -16,24 +16,31 @@
import com.google.auto.value.AutoValue;
import com.google.gerrit.reviewdb.client.Project;
-
+import java.util.List;
import org.eclipse.jgit.diff.Edit;
import org.eclipse.jgit.lib.ObjectId;
-import java.util.List;
-
@AutoValue
public abstract class IntraLineDiffArgs {
- public static IntraLineDiffArgs create(Text aText, Text bText, List<Edit> edits,
- Project.NameKey project, ObjectId commit, String path) {
- return new AutoValue_IntraLineDiffArgs(aText, bText, edits,
- project, commit, path);
+ public static IntraLineDiffArgs create(
+ Text aText,
+ Text bText,
+ List<Edit> edits,
+ Project.NameKey project,
+ ObjectId commit,
+ String path) {
+ return new AutoValue_IntraLineDiffArgs(aText, bText, edits, project, commit, path);
}
public abstract Text aText();
+
public abstract Text bText();
+
public abstract List<Edit> edits();
+
public abstract Project.NameKey project();
+
public abstract ObjectId commit();
+
public abstract String path();
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/patch/IntraLineDiffKey.java b/gerrit-server/src/main/java/com/google/gerrit/server/patch/IntraLineDiffKey.java
index cdde12a..ed58408 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/patch/IntraLineDiffKey.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/patch/IntraLineDiffKey.java
@@ -16,17 +16,14 @@
import com.google.auto.value.AutoValue;
import com.google.gerrit.extensions.client.DiffPreferencesInfo.Whitespace;
-
-import org.eclipse.jgit.lib.ObjectId;
-
import java.io.Serializable;
+import org.eclipse.jgit.lib.ObjectId;
@AutoValue
public abstract class IntraLineDiffKey implements Serializable {
public static final long serialVersionUID = 5L;
- public static IntraLineDiffKey create(ObjectId aId, ObjectId bId,
- Whitespace whitespace) {
+ public static IntraLineDiffKey create(ObjectId aId, ObjectId bId, Whitespace whitespace) {
return new AutoValue_IntraLineDiffKey(aId, bId, whitespace);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/patch/IntraLineLoader.java b/gerrit-server/src/main/java/com/google/gerrit/server/patch/IntraLineLoader.java
index ae37c01..a571c46 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/patch/IntraLineLoader.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/patch/IntraLineLoader.java
@@ -20,14 +20,6 @@
import com.google.gerrit.server.config.GerritServerConfig;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
-
-import org.eclipse.jgit.diff.Edit;
-import org.eclipse.jgit.diff.MyersDiff;
-import org.eclipse.jgit.diff.ReplaceEdit;
-import org.eclipse.jgit.lib.Config;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
@@ -36,6 +28,12 @@
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.regex.Pattern;
+import org.eclipse.jgit.diff.Edit;
+import org.eclipse.jgit.diff.MyersDiff;
+import org.eclipse.jgit.diff.ReplaceEdit;
+import org.eclipse.jgit.lib.Config;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
class IntraLineLoader implements Callable<IntraLineDiff> {
static final Logger log = LoggerFactory.getLogger(IntraLineLoader.class);
@@ -44,11 +42,10 @@
IntraLineLoader create(IntraLineDiffKey key, IntraLineDiffArgs args);
}
- private static final Pattern BLANK_LINE_RE = Pattern
- .compile("^[ \\t]*(|[{}]|/\\*\\*?|\\*)[ \\t]*$");
+ private static final Pattern BLANK_LINE_RE =
+ Pattern.compile("^[ \\t]*(|[{}]|/\\*\\*?|\\*)[ \\t]*$");
- private static final Pattern CONTROL_BLOCK_START_RE = Pattern
- .compile("[{:][ \\t]*$");
+ private static final Pattern CONTROL_BLOCK_START_RE = Pattern.compile("[{:][ \\t]*$");
private final ExecutorService diffExecutor;
private final long timeoutMillis;
@@ -56,14 +53,19 @@
private final IntraLineDiffArgs args;
@AssistedInject
- IntraLineLoader(@DiffExecutor ExecutorService diffExecutor,
+ IntraLineLoader(
+ @DiffExecutor ExecutorService diffExecutor,
@GerritServerConfig Config cfg,
@Assisted IntraLineDiffKey key,
@Assisted IntraLineDiffArgs args) {
this.diffExecutor = diffExecutor;
timeoutMillis =
- ConfigUtil.getTimeUnit(cfg, "cache", PatchListCacheImpl.INTRA_NAME,
- "timeout", TimeUnit.MILLISECONDS.convert(5, TimeUnit.SECONDS),
+ ConfigUtil.getTimeUnit(
+ cfg,
+ "cache",
+ PatchListCacheImpl.INTRA_NAME,
+ "timeout",
+ TimeUnit.MILLISECONDS.convert(5, TimeUnit.SECONDS),
TimeUnit.MILLISECONDS);
this.key = key;
this.args = args;
@@ -71,23 +73,30 @@
@Override
public IntraLineDiff call() throws Exception {
- Future<IntraLineDiff> result = diffExecutor.submit(
- new Callable<IntraLineDiff>() {
- @Override
- public IntraLineDiff call() throws Exception {
- return IntraLineLoader.compute(args.aText(), args.bText(),
- args.edits());
- }
- });
+ Future<IntraLineDiff> result =
+ diffExecutor.submit(
+ new Callable<IntraLineDiff>() {
+ @Override
+ public IntraLineDiff call() throws Exception {
+ return IntraLineLoader.compute(args.aText(), args.bText(), args.edits());
+ }
+ });
try {
return result.get(timeoutMillis, TimeUnit.MILLISECONDS);
} catch (InterruptedException | TimeoutException e) {
- log.warn(timeoutMillis + " ms timeout reached for IntraLineDiff"
- + " in project " + args.project()
- + " on commit " + args.commit().name()
- + " for path " + args.path()
- + " comparing " + key.getBlobA().name()
- + ".." + key.getBlobB().name());
+ log.warn(
+ timeoutMillis
+ + " ms timeout reached for IntraLineDiff"
+ + " in project "
+ + args.project()
+ + " on commit "
+ + args.commit().name()
+ + " for path "
+ + args.path()
+ + " comparing "
+ + key.getBlobA().name()
+ + ".."
+ + key.getBlobB().name());
result.cancel(true);
return new IntraLineDiff(IntraLineDiff.Status.TIMEOUT);
} catch (ExecutionException e) {
@@ -98,8 +107,7 @@
}
}
- static IntraLineDiff compute(Text aText, Text bText, List<Edit> edits)
- throws Exception {
+ static IntraLineDiff compute(Text aText, Text bText, List<Edit> edits) throws Exception {
combineLineEdits(edits, aText, bText);
for (int i = 0; i < edits.size(); i++) {
@@ -116,12 +124,11 @@
// just a few characters apart we tend to get better results
// by joining them together and taking the whole span.
//
- for (int j = 0; j < wordEdits.size() - 1;) {
+ for (int j = 0; j < wordEdits.size() - 1; ) {
Edit c = wordEdits.get(j);
Edit n = wordEdits.get(j + 1);
- if (n.getBeginA() - c.getEndA() <= 5
- || n.getBeginB() - c.getEndB() <= 5) {
+ if (n.getBeginA() - c.getEndA() <= 5 || n.getBeginB() - c.getEndB() <= 5) {
int ab = c.getBeginA();
int ae = n.getEndA();
@@ -188,7 +195,9 @@
// text might be identical. Slide down that edit and use the tail
// rather than the leading bit.
//
- while (0 < ab && ab < ae && a.charAt(ab - 1) != '\n'
+ while (0 < ab
+ && ab < ae
+ && a.charAt(ab - 1) != '\n'
&& cmp.equals(a, ab - 1, a, ae - 1)) {
ab--;
ae--;
@@ -203,7 +212,9 @@
}
}
- while (0 < bb && bb < be && b.charAt(bb - 1) != '\n'
+ while (0 < bb
+ && bb < be
+ && b.charAt(bb - 1) != '\n'
&& cmp.equals(b, bb - 1, b, be - 1)) {
bb--;
be--;
@@ -223,13 +234,15 @@
//
if (ab < ae //
&& (ab == 0 || a.charAt(ab - 1) == '\n') //
- && ae < a.size() && a.charAt(ae - 1) != '\n'
+ && ae < a.size()
+ && a.charAt(ae - 1) != '\n'
&& a.charAt(ae) == '\n') {
ae++;
}
if (bb < be //
&& (bb == 0 || b.charAt(bb - 1) == '\n') //
- && be < b.size() && b.charAt(be - 1) != '\n'
+ && be < b.size()
+ && b.charAt(be - 1) != '\n'
&& b.charAt(be) == '\n') {
be++;
}
@@ -245,7 +258,7 @@
}
private static void combineLineEdits(List<Edit> edits, Text a, Text b) {
- for (int j = 0; j < edits.size() - 1;) {
+ for (int j = 0; j < edits.size() - 1; ) {
Edit c = edits.get(j);
Edit n = edits.get(j + 1);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/patch/IntraLineWeigher.java b/gerrit-server/src/main/java/com/google/gerrit/server/patch/IntraLineWeigher.java
index 7088fe8..7bd37af 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/patch/IntraLineWeigher.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/patch/IntraLineWeigher.java
@@ -17,12 +17,18 @@
import com.google.common.cache.Weigher;
/** Approximates memory usage for IntralineDiff in bytes of memory used. */
-public class IntraLineWeigher implements
- Weigher<IntraLineDiffKey, IntraLineDiff> {
+public class IntraLineWeigher implements Weigher<IntraLineDiffKey, IntraLineDiff> {
@Override
public int weigh(IntraLineDiffKey key, IntraLineDiff value) {
- return 16 + 8 * 8 + 2 * 36 // Size of IntraLineDiffKey, 64 bit JVM
- + 16 + 2 * 8 + 16 + 8 + 4 + 20 // Size of IntraLineDiff, 64 bit JVM
+ return 16
+ + 8 * 8
+ + 2 * 36 // Size of IntraLineDiffKey, 64 bit JVM
+ + 16
+ + 2 * 8
+ + 16
+ + 8
+ + 4
+ + 20 // Size of IntraLineDiff, 64 bit JVM
+ (8 + 16 + 4 * 4) * value.getEdits().size();
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/patch/MergeListBuilder.java b/gerrit-server/src/main/java/com/google/gerrit/server/patch/MergeListBuilder.java
index 8f54e48..433fcad 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/patch/MergeListBuilder.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/patch/MergeListBuilder.java
@@ -15,17 +15,15 @@
package com.google.gerrit.server.patch;
import com.google.common.collect.ImmutableList;
-
-import org.eclipse.jgit.revwalk.RevCommit;
-import org.eclipse.jgit.revwalk.RevWalk;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
+import org.eclipse.jgit.revwalk.RevCommit;
+import org.eclipse.jgit.revwalk.RevWalk;
public class MergeListBuilder {
- public static List<RevCommit> build(RevWalk rw, RevCommit merge,
- int uninterestingParent) throws IOException {
+ public static List<RevCommit> build(RevWalk rw, RevCommit merge, int uninterestingParent)
+ throws IOException {
rw.reset();
rw.parseBody(merge);
if (merge.getParentCount() < 2) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/patch/PatchFile.java b/gerrit-server/src/main/java/com/google/gerrit/server/patch/PatchFile.java
index d2a6d2b..b4c2fbe 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/patch/PatchFile.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/patch/PatchFile.java
@@ -18,7 +18,7 @@
import com.google.gerrit.common.errors.NoSuchEntityException;
import com.google.gerrit.reviewdb.client.Patch;
-
+import java.io.IOException;
import org.eclipse.jgit.errors.CorruptObjectException;
import org.eclipse.jgit.errors.IncorrectObjectTypeException;
import org.eclipse.jgit.errors.MissingObjectException;
@@ -32,8 +32,6 @@
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.treewalk.TreeWalk;
-import java.io.IOException;
-
/** State supporting processing of a single {@link Patch} instance. */
public class PatchFile {
private final Repository repo;
@@ -59,9 +57,7 @@
} else {
// For the initial commit, we have an empty tree on Side A
RevObject object = rw.parseAny(patchList.getOldId());
- a = object instanceof RevCommit
- ? Text.forCommit(reader, object)
- : Text.EMPTY;
+ a = object instanceof RevCommit ? Text.forCommit(reader, object) : Text.EMPTY;
}
b = Text.forCommit(reader, bCommit);
@@ -70,9 +66,10 @@
} else if (Patch.MERGE_LIST.equals(fileName)) {
// For the initial commit, we have an empty tree on Side A
RevObject object = rw.parseAny(patchList.getOldId());
- a = object instanceof RevCommit
- ? Text.forMergeList(patchList.getComparisonType(), reader, object)
- : Text.EMPTY;
+ a =
+ object instanceof RevCommit
+ ? Text.forMergeList(patchList.getComparisonType(), reader, object)
+ : Text.EMPTY;
b = Text.forMergeList(patchList.getComparisonType(), reader, bCommit);
aTree = null;
@@ -99,8 +96,7 @@
* @throws IOException the patch or complete file content cannot be read.
* @throws NoSuchEntityException
*/
- public String getLine(final int file, final int line)
- throws IOException, NoSuchEntityException {
+ public String getLine(final int file, final int line) throws IOException, NoSuchEntityException {
switch (file) {
case 0:
if (a == null) {
@@ -127,8 +123,7 @@
* @throws IOException the patch or complete file content cannot be read.
* @throws NoSuchEntityException the file is not exist.
*/
- public int getLineCount(final int file)
- throws IOException, NoSuchEntityException {
+ public int getLineCount(final int file) throws IOException, NoSuchEntityException {
switch (file) {
case 0:
if (a == null) {
@@ -148,8 +143,8 @@
}
private Text load(final ObjectId tree, final String path)
- throws MissingObjectException, IncorrectObjectTypeException,
- CorruptObjectException, IOException {
+ throws MissingObjectException, IncorrectObjectTypeException, CorruptObjectException,
+ IOException {
if (path == null) {
return Text.EMPTY;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/patch/PatchList.java b/gerrit-server/src/main/java/com/google/gerrit/server/patch/PatchList.java
index 2cfd007..d9a5f4f 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/patch/PatchList.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/patch/PatchList.java
@@ -14,7 +14,6 @@
package com.google.gerrit.server.patch;
-
import static com.google.gerrit.server.ioutil.BasicSerialization.readBytes;
import static com.google.gerrit.server.ioutil.BasicSerialization.readVarInt32;
import static com.google.gerrit.server.ioutil.BasicSerialization.writeBytes;
@@ -27,10 +26,6 @@
import com.google.gerrit.common.Nullable;
import com.google.gerrit.reviewdb.client.Patch;
import com.google.gerrit.reviewdb.client.PatchSet;
-
-import org.eclipse.jgit.lib.AnyObjectId;
-import org.eclipse.jgit.lib.ObjectId;
-
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@@ -44,6 +39,8 @@
import java.util.List;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.InflaterInputStream;
+import org.eclipse.jgit.lib.AnyObjectId;
+import org.eclipse.jgit.lib.ObjectId;
public class PatchList implements Serializable {
private static final long serialVersionUID = PatchListKey.serialVersionUID;
@@ -55,8 +52,7 @@
}
};
- @Nullable
- private transient ObjectId oldId;
+ @Nullable private transient ObjectId oldId;
private transient ObjectId newId;
private transient boolean isMerge;
private transient ComparisonType comparisonType;
@@ -64,8 +60,11 @@
private transient int deletions;
private transient PatchListEntry[] patches;
- public PatchList(@Nullable AnyObjectId oldId, AnyObjectId newId,
- boolean isMerge, ComparisonType comparisonType,
+ public PatchList(
+ @Nullable AnyObjectId oldId,
+ AnyObjectId newId,
+ boolean isMerge,
+ ComparisonType comparisonType,
PatchListEntry[] patches) {
this.oldId = oldId != null ? oldId.copy() : null;
this.newId = newId.copy();
@@ -117,17 +116,18 @@
/**
* Get a sorted, modifiable list of all files in this list.
- * <p>
- * The returned list items do not populate:
+ *
+ * <p>The returned list items do not populate:
+ *
* <ul>
- * <li>{@link Patch#getCommentCount()}
- * <li>{@link Patch#getDraftCount()}
- * <li>{@link Patch#isReviewedByCurrentUser()}
+ * <li>{@link Patch#getCommentCount()}
+ * <li>{@link Patch#getDraftCount()}
+ * <li>{@link Patch#isReviewedByCurrentUser()}
* </ul>
*
- * @param setId the patch set identity these patches belong to. This really
- * should not need to be specified, but is a current legacy artifact of
- * how the cache is keyed versus how the database is keyed.
+ * @param setId the patch set identity these patches belong to. This really should not need to be
+ * specified, but is a current legacy artifact of how the cache is keyed versus how the
+ * database is keyed.
*/
public List<Patch> toPatchList(final PatchSet.Id setId) {
final ArrayList<Patch> r = new ArrayList<>(patches.length);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/patch/PatchListCache.java b/gerrit-server/src/main/java/com/google/gerrit/server/patch/PatchListCache.java
index 848b78f..fd8baad 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/patch/PatchListCache.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/patch/PatchListCache.java
@@ -17,22 +17,18 @@
import com.google.gerrit.reviewdb.client.Change;
import com.google.gerrit.reviewdb.client.PatchSet;
import com.google.gerrit.reviewdb.client.Project;
-
import org.eclipse.jgit.lib.ObjectId;
/** Provides a cached list of {@link PatchListEntry}. */
public interface PatchListCache {
- PatchList get(PatchListKey key, Project.NameKey project)
- throws PatchListNotAvailableException;
+ PatchList get(PatchListKey key, Project.NameKey project) throws PatchListNotAvailableException;
- PatchList get(Change change, PatchSet patchSet)
- throws PatchListNotAvailableException;
+ PatchList get(Change change, PatchSet patchSet) throws PatchListNotAvailableException;
ObjectId getOldId(Change change, PatchSet patchSet, Integer parentNum)
throws PatchListNotAvailableException;
- IntraLineDiff getIntraLineDiff(IntraLineDiffKey key,
- IntraLineDiffArgs args);
+ IntraLineDiff getIntraLineDiff(IntraLineDiffKey key, IntraLineDiffArgs args);
DiffSummary getDiffSummary(Change change, PatchSet patchSet)
throws PatchListNotAvailableException;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/patch/PatchListCacheImpl.java b/gerrit-server/src/main/java/com/google/gerrit/server/patch/PatchListCacheImpl.java
index f1490f6f..25f0dda 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/patch/PatchListCacheImpl.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/patch/PatchListCacheImpl.java
@@ -29,13 +29,11 @@
import com.google.inject.Module;
import com.google.inject.Singleton;
import com.google.inject.name.Named;
-
+import java.util.concurrent.ExecutionException;
import org.eclipse.jgit.errors.LargeObjectException;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.lib.ObjectId;
-import java.util.concurrent.ExecutionException;
-
/** Provides a cached list of {@link PatchListEntry}. */
@Singleton
public class PatchListCacheImpl implements PatchListCache {
@@ -94,8 +92,8 @@
this.diffSummaryLoaderFactory = diffSummaryLoaderFactory;
this.computeIntraline =
- cfg.getBoolean("cache", INTRA_NAME, "enabled",
- cfg.getBoolean("cache", "diff", "intraline", true));
+ cfg.getBoolean(
+ "cache", INTRA_NAME, "enabled", cfg.getBoolean("cache", "diff", "intraline", true));
}
@Override
@@ -103,9 +101,7 @@
throws PatchListNotAvailableException {
try {
PatchList pl = fileCache.get(key, fileLoaderFactory.create(key, project));
- diffSummaryCache.put(
- DiffSummaryKey.fromPatchListKey(key),
- toDiffSummary(pl));
+ diffSummaryCache.put(DiffSummaryKey.fromPatchListKey(key), toDiffSummary(pl));
return pl;
} catch (ExecutionException e) {
PatchListLoader.log.warn("Error computing " + key, e);
@@ -120,8 +116,7 @@
}
@Override
- public PatchList get(Change change, PatchSet patchSet)
- throws PatchListNotAvailableException {
+ public PatchList get(Change change, PatchSet patchSet) throws PatchListNotAvailableException {
return get(change, patchSet, null);
}
@@ -135,8 +130,7 @@
throws PatchListNotAvailableException {
Project.NameKey project = change.getProject();
if (patchSet.getRevision() == null) {
- throw new PatchListNotAvailableException(
- "revision is null for " + patchSet.getId());
+ throw new PatchListNotAvailableException("revision is null for " + patchSet.getId());
}
ObjectId b = ObjectId.fromString(patchSet.getRevision().get());
Whitespace ws = Whitespace.IGNORE_NONE;
@@ -147,8 +141,7 @@
}
@Override
- public IntraLineDiff getIntraLineDiff(IntraLineDiffKey key,
- IntraLineDiffArgs args) {
+ public IntraLineDiff getIntraLineDiff(IntraLineDiffKey key, IntraLineDiffArgs args) {
if (computeIntraline) {
try {
return intraCache.get(key, intraLoaderFactory.create(key, args));
@@ -167,16 +160,13 @@
ObjectId b = ObjectId.fromString(patchSet.getRevision().get());
Whitespace ws = Whitespace.IGNORE_NONE;
return getDiffSummary(
- DiffSummaryKey.fromPatchListKey(
- PatchListKey.againstDefaultBase(b, ws)),
- project);
+ DiffSummaryKey.fromPatchListKey(PatchListKey.againstDefaultBase(b, ws)), project);
}
- private DiffSummary getDiffSummary(DiffSummaryKey key,
- Project.NameKey project) throws PatchListNotAvailableException {
+ private DiffSummary getDiffSummary(DiffSummaryKey key, Project.NameKey project)
+ throws PatchListNotAvailableException {
try {
- return diffSummaryCache.get(key,
- diffSummaryLoaderFactory.create(key, project));
+ return diffSummaryCache.get(key, diffSummaryLoaderFactory.create(key, project));
} catch (ExecutionException e) {
PatchListLoader.log.warn("Error computing " + key, e);
throw new PatchListNotAvailableException(e);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/patch/PatchListEntry.java b/gerrit-server/src/main/java/com/google/gerrit/server/patch/PatchListEntry.java
index 3266f01..a8a8b79 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/patch/PatchListEntry.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/patch/PatchListEntry.java
@@ -29,14 +29,6 @@
import com.google.gerrit.reviewdb.client.Patch.ChangeType;
import com.google.gerrit.reviewdb.client.Patch.PatchType;
import com.google.gerrit.reviewdb.client.PatchSet;
-
-import org.eclipse.jgit.diff.Edit;
-import org.eclipse.jgit.lib.Constants;
-import org.eclipse.jgit.patch.CombinedFileHeader;
-import org.eclipse.jgit.patch.FileHeader;
-import org.eclipse.jgit.util.IntList;
-import org.eclipse.jgit.util.RawParseUtils;
-
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@@ -44,13 +36,28 @@
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
+import org.eclipse.jgit.diff.Edit;
+import org.eclipse.jgit.lib.Constants;
+import org.eclipse.jgit.patch.CombinedFileHeader;
+import org.eclipse.jgit.patch.FileHeader;
+import org.eclipse.jgit.util.IntList;
+import org.eclipse.jgit.util.RawParseUtils;
public class PatchListEntry {
private static final byte[] EMPTY_HEADER = {};
static PatchListEntry empty(final String fileName) {
- return new PatchListEntry(ChangeType.MODIFIED, PatchType.UNIFIED, null,
- fileName, EMPTY_HEADER, Collections.<Edit> emptyList(), 0, 0, 0, 0);
+ return new PatchListEntry(
+ ChangeType.MODIFIED,
+ PatchType.UNIFIED,
+ null,
+ fileName,
+ EMPTY_HEADER,
+ Collections.<Edit>emptyList(),
+ 0,
+ 0,
+ 0,
+ 0);
}
private final ChangeType changeType;
@@ -66,8 +73,7 @@
// Note: When adding new fields, the serialVersionUID in PatchListKey must be
// incremented so that entries from the cache are automatically invalidated.
- PatchListEntry(FileHeader hdr, List<Edit> editList, long size,
- long sizeDelta) {
+ PatchListEntry(FileHeader hdr, List<Edit> editList, long size, long sizeDelta) {
changeType = toChangeType(hdr);
patchType = toPatchType(hdr);
@@ -114,9 +120,17 @@
this.sizeDelta = sizeDelta;
}
- private PatchListEntry(ChangeType changeType, PatchType patchType,
- String oldName, String newName, byte[] header, List<Edit> edits,
- int insertions, int deletions, long size, long sizeDelta) {
+ private PatchListEntry(
+ ChangeType changeType,
+ PatchType patchType,
+ String oldName,
+ String newName,
+ byte[] header,
+ List<Edit> edits,
+ int insertions,
+ int deletions,
+ long size,
+ long sizeDelta) {
this.changeType = changeType;
this.patchType = patchType;
this.oldName = oldName;
@@ -246,8 +260,8 @@
editArray[i] = new Edit(beginA, endA, beginB, endB);
}
- return new PatchListEntry(changeType, patchType, oldName, newName, hdr,
- toList(editArray), ins, del, size, sizeDelta);
+ return new PatchListEntry(
+ changeType, patchType, oldName, newName, hdr, toList(editArray), ins, del, size, sizeDelta);
}
private static List<Edit> toList(Edit[] l) {
@@ -288,8 +302,7 @@
case COPY:
return Patch.ChangeType.COPIED;
default:
- throw new IllegalArgumentException("Unsupported type "
- + hdr.getChangeType());
+ throw new IllegalArgumentException("Unsupported type " + hdr.getChangeType());
}
}
@@ -305,8 +318,7 @@
pt = Patch.PatchType.BINARY;
break;
default:
- throw new IllegalArgumentException("Unsupported type "
- + hdr.getPatchType());
+ throw new IllegalArgumentException("Unsupported type " + hdr.getPatchType());
}
if (pt != PatchType.BINARY) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/patch/PatchListKey.java b/gerrit-server/src/main/java/com/google/gerrit/server/patch/PatchListKey.java
index 6bb32a2..37a636d 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/patch/PatchListKey.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/patch/PatchListKey.java
@@ -24,56 +24,53 @@
import com.google.common.collect.ImmutableBiMap;
import com.google.gerrit.common.Nullable;
import com.google.gerrit.extensions.client.DiffPreferencesInfo.Whitespace;
-
-import org.eclipse.jgit.lib.AnyObjectId;
-import org.eclipse.jgit.lib.ObjectId;
-
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Objects;
+import org.eclipse.jgit.lib.AnyObjectId;
+import org.eclipse.jgit.lib.ObjectId;
public class PatchListKey implements Serializable {
public static final long serialVersionUID = 24L;
- public static final BiMap<Whitespace, Character> WHITESPACE_TYPES = ImmutableBiMap.of(
- Whitespace.IGNORE_NONE, 'N',
- Whitespace.IGNORE_TRAILING, 'E',
- Whitespace.IGNORE_LEADING_AND_TRAILING, 'S',
- Whitespace.IGNORE_ALL, 'A');
+ public static final BiMap<Whitespace, Character> WHITESPACE_TYPES =
+ ImmutableBiMap.of(
+ Whitespace.IGNORE_NONE, 'N',
+ Whitespace.IGNORE_TRAILING, 'E',
+ Whitespace.IGNORE_LEADING_AND_TRAILING, 'S',
+ Whitespace.IGNORE_ALL, 'A');
static {
checkState(WHITESPACE_TYPES.size() == Whitespace.values().length);
}
- public static PatchListKey againstDefaultBase(AnyObjectId newId,
- Whitespace ws) {
+ public static PatchListKey againstDefaultBase(AnyObjectId newId, Whitespace ws) {
return new PatchListKey(null, newId, ws);
}
- public static PatchListKey againstParentNum(int parentNum, AnyObjectId newId,
- Whitespace ws) {
+ public static PatchListKey againstParentNum(int parentNum, AnyObjectId newId, Whitespace ws) {
return new PatchListKey(parentNum, newId, ws);
}
/**
* Old patch-set ID
- * <p>
- * When null, it represents the Base of the newId for a non-merge commit.
- * <p>
- * When newId is a merge commit, null value of the oldId represents either
- * the auto-merge commit of the newId or a parent commit of the newId.
- * These two cases are distinguished by the parentNum.
+ *
+ * <p>When null, it represents the Base of the newId for a non-merge commit.
+ *
+ * <p>When newId is a merge commit, null value of the oldId represents either the auto-merge
+ * commit of the newId or a parent commit of the newId. These two cases are distinguished by the
+ * parentNum.
*/
private transient ObjectId oldId;
/**
* 1-based parent number when newId is a merge commit
- * <p>
- * For the auto-merge case this field is null.
- * <p>
- * Used only when oldId is null and newId is a merge commit
+ *
+ * <p>For the auto-merge case this field is null.
+ *
+ * <p>Used only when oldId is null and newId is a merge commit
*/
private transient Integer parentNum;
@@ -93,8 +90,7 @@
}
/** For use only by DiffSummaryKey. */
- PatchListKey(ObjectId oldId, Integer parentNum, ObjectId newId,
- Whitespace whitespace) {
+ PatchListKey(ObjectId oldId, Integer parentNum, ObjectId newId, Whitespace whitespace) {
this.oldId = oldId;
this.parentNum = parentNum;
this.newId = newId;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/patch/PatchListLoader.java b/gerrit-server/src/main/java/com/google/gerrit/server/patch/PatchListLoader.java
index e1829bc..124fe8e 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/patch/PatchListLoader.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/patch/PatchListLoader.java
@@ -31,7 +31,18 @@
import com.google.gerrit.server.git.MergeUtil;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
-
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.stream.Stream;
import org.eclipse.jgit.diff.DiffEntry;
import org.eclipse.jgit.diff.DiffFormatter;
import org.eclipse.jgit.diff.Edit;
@@ -58,19 +69,6 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.Set;
-import java.util.concurrent.Callable;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Future;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.TimeoutException;
-import java.util.stream.Stream;
-
public class PatchListLoader implements Callable<PatchList> {
static final Logger log = LoggerFactory.getLogger(PatchListLoader.class);
@@ -89,7 +87,8 @@
private final boolean save;
@AssistedInject
- PatchListLoader(GitRepositoryManager mgr,
+ PatchListLoader(
+ GitRepositoryManager mgr,
PatchListCache plc,
@GerritServerConfig Config cfg,
@DiffExecutor ExecutorService de,
@@ -104,15 +103,18 @@
key = k;
project = p;
timeoutMillis =
- ConfigUtil.getTimeUnit(cfg, "cache", PatchListCacheImpl.FILE_NAME,
- "timeout", TimeUnit.MILLISECONDS.convert(5, TimeUnit.SECONDS),
+ ConfigUtil.getTimeUnit(
+ cfg,
+ "cache",
+ PatchListCacheImpl.FILE_NAME,
+ "timeout",
+ TimeUnit.MILLISECONDS.convert(5, TimeUnit.SECONDS),
TimeUnit.MILLISECONDS);
save = AutoMerger.cacheAutomerge(cfg);
}
@Override
- public PatchList call() throws IOException,
- PatchListNotAvailableException {
+ public PatchList call() throws IOException, PatchListNotAvailableException {
try (Repository repo = repoManager.openRepository(project);
ObjectInserter ins = newInserter(repo);
ObjectReader reader = ins.newReader();
@@ -139,13 +141,11 @@
}
private ObjectInserter newInserter(Repository repo) {
- return save
- ? repo.newObjectInserter()
- : new InMemoryInserter(repo);
+ return save ? repo.newObjectInserter() : new InMemoryInserter(repo);
}
- public PatchList readPatchList(Repository repo, RevWalk rw,
- ObjectInserter ins) throws IOException, PatchListNotAvailableException {
+ public PatchList readPatchList(Repository repo, RevWalk rw, ObjectInserter ins)
+ throws IOException, PatchListNotAvailableException {
ObjectReader reader = rw.getObjectReader();
checkArgument(reader.getCreatedFromInserter() == ins);
RawTextComparator cmp = comparatorFor(key.getWhitespace());
@@ -180,42 +180,43 @@
Set<String> paths = null;
if (key.getOldId() != null && b.getParentCount() == 1) {
- PatchListKey newKey = PatchListKey.againstDefaultBase(
- key.getNewId(), key.getWhitespace());
- PatchListKey oldKey = PatchListKey.againstDefaultBase(
- key.getOldId(), key.getWhitespace());
- paths = Stream.concat(
- patchListCache.get(newKey, project).getPatches().stream(),
- patchListCache.get(oldKey, project).getPatches().stream())
- .map(PatchListEntry::getNewName)
- .collect(toSet());
+ PatchListKey newKey = PatchListKey.againstDefaultBase(key.getNewId(), key.getWhitespace());
+ PatchListKey oldKey = PatchListKey.againstDefaultBase(key.getOldId(), key.getWhitespace());
+ paths =
+ Stream.concat(
+ patchListCache.get(newKey, project).getPatches().stream(),
+ patchListCache.get(oldKey, project).getPatches().stream())
+ .map(PatchListEntry::getNewName)
+ .collect(toSet());
}
int cnt = diffEntries.size();
List<PatchListEntry> entries = new ArrayList<>();
- entries.add(newCommitMessage(cmp, reader,
- comparisonType.isAgainstParentOrAutoMerge() ? null : aCommit, b));
+ entries.add(
+ newCommitMessage(
+ cmp, reader, comparisonType.isAgainstParentOrAutoMerge() ? null : aCommit, b));
boolean isMerge = b.getParentCount() > 1;
if (isMerge) {
- entries.add(newMergeList(cmp, reader,
- comparisonType.isAgainstParentOrAutoMerge() ? null : aCommit, b,
- comparisonType));
+ entries.add(
+ newMergeList(
+ cmp,
+ reader,
+ comparisonType.isAgainstParentOrAutoMerge() ? null : aCommit,
+ b,
+ comparisonType));
}
for (int i = 0; i < cnt; i++) {
DiffEntry e = diffEntries.get(i);
- if (paths == null || paths.contains(e.getNewPath())
- || paths.contains(e.getOldPath())) {
+ if (paths == null || paths.contains(e.getNewPath()) || paths.contains(e.getOldPath())) {
FileHeader fh = toFileHeader(key, df, e);
- long oldSize =
- getFileSize(reader, e.getOldMode(), e.getOldPath(), aTree);
- long newSize =
- getFileSize(reader, e.getNewMode(), e.getNewPath(), bTree);
+ long oldSize = getFileSize(reader, e.getOldMode(), e.getOldPath(), aTree);
+ long newSize = getFileSize(reader, e.getNewMode(), e.getNewPath(), bTree);
entries.add(newEntry(aTree, fh, newSize, newSize - oldSize));
}
}
- return new PatchList(a, b, isMerge, comparisonType,
- entries.toArray(new PatchListEntry[entries.size()]));
+ return new PatchList(
+ a, b, isMerge, comparisonType, entries.toArray(new PatchListEntry[entries.size()]));
}
}
@@ -233,15 +234,13 @@
return ComparisonType.againstOtherPatchSet();
}
- private static long getFileSize(ObjectReader reader,
- FileMode mode, String path, RevTree t) throws IOException {
+ private static long getFileSize(ObjectReader reader, FileMode mode, String path, RevTree t)
+ throws IOException {
if (!isBlob(mode)) {
return 0;
}
try (TreeWalk tw = TreeWalk.forPath(reader, path, t)) {
- return tw != null
- ? reader.open(tw.getObjectId(0), OBJ_BLOB).getSize()
- : 0;
+ return tw != null ? reader.open(tw.getObjectId(0), OBJ_BLOB).getSize() : 0;
}
}
@@ -250,28 +249,37 @@
return t == FileMode.TYPE_FILE || t == FileMode.TYPE_SYMLINK;
}
- private FileHeader toFileHeader(PatchListKey key,
- final DiffFormatter diffFormatter, final DiffEntry diffEntry)
+ private FileHeader toFileHeader(
+ PatchListKey key, final DiffFormatter diffFormatter, final DiffEntry diffEntry)
throws IOException {
- Future<FileHeader> result = diffExecutor.submit(new Callable<FileHeader>() {
- @Override
- public FileHeader call() throws IOException {
- synchronized (diffEntry) {
- return diffFormatter.toFileHeader(diffEntry);
- }
- }
- });
+ Future<FileHeader> result =
+ diffExecutor.submit(
+ new Callable<FileHeader>() {
+ @Override
+ public FileHeader call() throws IOException {
+ synchronized (diffEntry) {
+ return diffFormatter.toFileHeader(diffEntry);
+ }
+ }
+ });
try {
return result.get(timeoutMillis, TimeUnit.MILLISECONDS);
} catch (InterruptedException | TimeoutException e) {
- log.warn(timeoutMillis + " ms timeout reached for Diff loader"
- + " in project " + project
- + " on commit " + key.getNewId().name()
- + " on path " + diffEntry.getNewPath()
- + " comparing " + diffEntry.getOldId().name()
- + ".." + diffEntry.getNewId().name());
+ log.warn(
+ timeoutMillis
+ + " ms timeout reached for Diff loader"
+ + " in project "
+ + project
+ + " on commit "
+ + key.getNewId().name()
+ + " on path "
+ + diffEntry.getNewPath()
+ + " comparing "
+ + diffEntry.getOldId().name()
+ + ".."
+ + diffEntry.getNewId().name());
result.cancel(true);
synchronized (diffEntry) {
return toFileHeaderWithoutMyersDiff(diffFormatter, diffEntry);
@@ -284,37 +292,36 @@
}
}
- private FileHeader toFileHeaderWithoutMyersDiff(DiffFormatter diffFormatter,
- DiffEntry diffEntry) throws IOException {
+ private FileHeader toFileHeaderWithoutMyersDiff(DiffFormatter diffFormatter, DiffEntry diffEntry)
+ throws IOException {
HistogramDiff histogramDiff = new HistogramDiff();
histogramDiff.setFallbackAlgorithm(null);
diffFormatter.setDiffAlgorithm(histogramDiff);
return diffFormatter.toFileHeader(diffEntry);
}
- private PatchListEntry newCommitMessage(RawTextComparator cmp,
- ObjectReader reader, RevCommit aCommit, RevCommit bCommit)
- throws IOException {
- Text aText = aCommit != null
- ? Text.forCommit(reader, aCommit)
- : Text.EMPTY;
+ private PatchListEntry newCommitMessage(
+ RawTextComparator cmp, ObjectReader reader, RevCommit aCommit, RevCommit bCommit)
+ throws IOException {
+ Text aText = aCommit != null ? Text.forCommit(reader, aCommit) : Text.EMPTY;
Text bText = Text.forCommit(reader, bCommit);
return createPatchListEntry(cmp, aCommit, aText, bText, Patch.COMMIT_MSG);
}
- private PatchListEntry newMergeList(RawTextComparator cmp,
- ObjectReader reader, RevCommit aCommit, RevCommit bCommit,
- ComparisonType comparisonType) throws IOException {
- Text aText = aCommit != null
- ? Text.forMergeList(comparisonType, reader, aCommit)
- : Text.EMPTY;
- Text bText =
- Text.forMergeList(comparisonType, reader, bCommit);
+ private PatchListEntry newMergeList(
+ RawTextComparator cmp,
+ ObjectReader reader,
+ RevCommit aCommit,
+ RevCommit bCommit,
+ ComparisonType comparisonType)
+ throws IOException {
+ Text aText = aCommit != null ? Text.forMergeList(comparisonType, reader, aCommit) : Text.EMPTY;
+ Text bText = Text.forMergeList(comparisonType, reader, bCommit);
return createPatchListEntry(cmp, aCommit, aText, bText, Patch.MERGE_LIST);
}
- private static PatchListEntry createPatchListEntry(RawTextComparator cmp,
- RevCommit aCommit, Text aText, Text bText, String fileName) {
+ private static PatchListEntry createPatchListEntry(
+ RawTextComparator cmp, RevCommit aCommit, Text aText, Text bText, String fileName) {
byte[] rawHdr = getRawHeader(aCommit != null, fileName);
byte[] aContent = aText.getContent();
byte[] bContent = bText.getContent();
@@ -347,25 +354,22 @@
return hdr.toString().getBytes(UTF_8);
}
- private PatchListEntry newEntry(RevTree aTree, FileHeader fileHeader,
- long size, long sizeDelta) {
+ private PatchListEntry newEntry(RevTree aTree, FileHeader fileHeader, long size, long sizeDelta) {
if (aTree == null // want combined diff
|| fileHeader.getPatchType() != PatchType.UNIFIED
|| fileHeader.getHunks().isEmpty()) {
- return new PatchListEntry(fileHeader, Collections.<Edit> emptyList(),
- size, sizeDelta);
+ return new PatchListEntry(fileHeader, Collections.<Edit>emptyList(), size, sizeDelta);
}
List<Edit> edits = fileHeader.toEditList();
if (edits.isEmpty()) {
- return new PatchListEntry(fileHeader, Collections.<Edit> emptyList(),
- size, sizeDelta);
+ return new PatchListEntry(fileHeader, Collections.<Edit>emptyList(), size, sizeDelta);
}
return new PatchListEntry(fileHeader, edits, size, sizeDelta);
}
- private RevObject aFor(PatchListKey key,
- Repository repo, RevWalk rw, ObjectInserter ins, RevCommit b)
+ private RevObject aFor(
+ PatchListKey key, Repository repo, RevWalk rw, ObjectInserter ins, RevCommit b)
throws IOException {
if (key.getOldId() != null) {
return rw.parseAny(key.getOldId());
@@ -374,11 +378,12 @@
switch (b.getParentCount()) {
case 0:
return rw.parseAny(emptyTree(ins));
- case 1: {
- RevCommit r = b.getParent(0);
- rw.parseBody(r);
- return r;
- }
+ case 1:
+ {
+ RevCommit r = b.getParent(0);
+ rw.parseBody(r);
+ return r;
+ }
case 2:
if (key.getParentNum() != null) {
RevCommit r = b.getParent(key.getParentNum() - 1);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/patch/PatchListWeigher.java b/gerrit-server/src/main/java/com/google/gerrit/server/patch/PatchListWeigher.java
index 2362986..f40eac6 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/patch/PatchListWeigher.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/patch/PatchListWeigher.java
@@ -20,8 +20,14 @@
public class PatchListWeigher implements Weigher<PatchListKey, PatchList> {
@Override
public int weigh(PatchListKey key, PatchList value) {
- int size = 16 + 4 * 8 + 2 * 36 // Size of PatchListKey, 64 bit JVM
- + 16 + 3 * 8 + 3 * 4 + 20; // Size of PatchList, 64 bit JVM
+ int size =
+ 16
+ + 4 * 8
+ + 2 * 36 // Size of PatchListKey, 64 bit JVM
+ + 16
+ + 3 * 8
+ + 3 * 4
+ + 20; // Size of PatchList, 64 bit JVM
for (PatchListEntry e : value.getPatches()) {
size += e.weigh();
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/patch/PatchScriptBuilder.java b/gerrit-server/src/main/java/com/google/gerrit/server/patch/PatchScriptBuilder.java
index 246d7a5..db495b8 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/patch/PatchScriptBuilder.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/patch/PatchScriptBuilder.java
@@ -27,10 +27,13 @@
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.server.mime.FileTypeRegistry;
import com.google.inject.Inject;
-
import eu.medsea.mimeutil.MimeType;
import eu.medsea.mimeutil.MimeUtil2;
-
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
import org.eclipse.jgit.diff.Edit;
import org.eclipse.jgit.errors.CorruptObjectException;
import org.eclipse.jgit.errors.IncorrectObjectTypeException;
@@ -44,22 +47,17 @@
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.treewalk.TreeWalk;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.List;
-
class PatchScriptBuilder {
static final int MAX_CONTEXT = 5000000;
static final int BIG_FILE = 9000;
- private static final Comparator<Edit> EDIT_SORT = new Comparator<Edit>() {
- @Override
- public int compare(final Edit o1, final Edit o2) {
- return o1.getBeginA() - o2.getBeginA();
- }
- };
+ private static final Comparator<Edit> EDIT_SORT =
+ new Comparator<Edit>() {
+ @Override
+ public int compare(final Edit o1, final Edit o2) {
+ return o1.getBeginA() - o2.getBeginA();
+ }
+ };
private Repository db;
private Project.NameKey projectKey;
@@ -79,8 +77,7 @@
private int context;
@Inject
- PatchScriptBuilder(FileTypeRegistry ftr,
- PatchListCache plc) {
+ PatchScriptBuilder(FileTypeRegistry ftr, PatchListCache plc) {
a = new Side();
b = new Side();
registry = ftr;
@@ -113,8 +110,8 @@
bId = b;
}
- PatchScript toPatchScript(final PatchListEntry content,
- final CommentDetail comments, final List<Patch> history)
+ PatchScript toPatchScript(
+ final PatchListEntry content, final CommentDetail comments, final List<Patch> history)
throws IOException {
reader = db.newObjectReader();
try {
@@ -124,8 +121,8 @@
}
}
- private PatchScript build(final PatchListEntry content,
- final CommentDetail comments, final List<Patch> history)
+ private PatchScript build(
+ final PatchListEntry content, final CommentDetail comments, final List<Patch> history)
throws IOException {
boolean intralineDifferenceIsPossible = true;
boolean intralineFailure = false;
@@ -144,11 +141,8 @@
} else if (diffPrefs.intralineDifference) {
IntraLineDiff d =
patchListCache.getIntraLineDiff(
- IntraLineDiffKey.create(
- a.id, b.id,
- diffPrefs.ignoreWhitespace),
- IntraLineDiffArgs.create(
- a.src, b.src, edits, projectKey, bId, b.path));
+ IntraLineDiffKey.create(a.id, b.id, diffPrefs.ignoreWhitespace),
+ IntraLineDiffArgs.create(a.src, b.src, edits, projectKey, bId, b.path));
if (d != null) {
switch (d.getStatus()) {
case EDIT_LIST:
@@ -180,8 +174,7 @@
}
boolean hugeFile = false;
- if (a.src == b.src && a.size() <= context
- && content.getEdits().isEmpty()) {
+ if (a.src == b.src && a.size() <= context && content.getEdits().isEmpty()) {
// Odd special case; the files are identical (100% rename or copy)
// and the user has asked for context that is larger than the file.
// Send them the entire file, with an empty edit after the last line.
@@ -198,7 +191,6 @@
// the browser client.
//
hugeFile = true;
-
}
// In order to expand the skipped common lines or syntax highlight the
@@ -210,12 +202,28 @@
packContent(diffPrefs.ignoreWhitespace != Whitespace.IGNORE_NONE);
}
- return new PatchScript(change.getKey(), content.getChangeType(),
- content.getOldName(), content.getNewName(), a.fileMode, b.fileMode,
- content.getHeaderLines(), diffPrefs, a.dst, b.dst, edits,
- a.displayMethod, b.displayMethod, a.mimeType.toString(),
- b.mimeType.toString(), comments, history, hugeFile,
- intralineDifferenceIsPossible, intralineFailure, intralineTimeout,
+ return new PatchScript(
+ change.getKey(),
+ content.getChangeType(),
+ content.getOldName(),
+ content.getNewName(),
+ a.fileMode,
+ b.fileMode,
+ content.getHeaderLines(),
+ diffPrefs,
+ a.dst,
+ b.dst,
+ edits,
+ a.displayMethod,
+ b.displayMethod,
+ a.mimeType.toString(),
+ b.mimeType.toString(),
+ comments,
+ history,
+ hugeFile,
+ intralineDifferenceIsPossible,
+ intralineFailure,
+ intralineTimeout,
content.getPatchType() == Patch.PatchType.BINARY,
aId == null ? null : aId.getName(),
bId == null ? null : bId.getName());
@@ -480,9 +488,10 @@
id = tw != null ? tw.getObjectId(0) : ObjectId.zeroId();
mode = tw != null ? tw.getFileMode(0) : FileMode.MISSING;
- reuse = other != null
- && other.id.equals(id)
- && (other.mode == mode || isBothFile(other.mode, mode));
+ reuse =
+ other != null
+ && other.id.equals(id)
+ && (other.mode == mode || isBothFile(other.mode, mode));
if (reuse) {
srcContent = other.srcContent;
@@ -505,8 +514,7 @@
} else if (srcContent.length > 0 && FileMode.SYMLINK != mode) {
mimeType = registry.getMimeType(path, srcContent);
- if ("image".equals(mimeType.getMediaType())
- && registry.isSafeInline(mimeType)) {
+ if ("image".equals(mimeType.getMediaType()) && registry.isSafeInline(mimeType)) {
displayMethod = DisplayMethod.IMG;
}
}
@@ -540,8 +548,9 @@
}
}
- private TreeWalk find(final ObjectId within) throws MissingObjectException,
- IncorrectObjectTypeException, CorruptObjectException, IOException {
+ private TreeWalk find(final ObjectId within)
+ throws MissingObjectException, IncorrectObjectTypeException, CorruptObjectException,
+ IOException {
if (path == null || within == null) {
return null;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/patch/PatchScriptFactory.java b/gerrit-server/src/main/java/com/google/gerrit/server/patch/PatchScriptFactory.java
index 44b3966..82c6150 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/patch/PatchScriptFactory.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/patch/PatchScriptFactory.java
@@ -45,13 +45,6 @@
import com.google.inject.Provider;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
-
-import org.eclipse.jgit.errors.RepositoryNotFoundException;
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.lib.Repository;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
@@ -59,7 +52,11 @@
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.Callable;
-
+import org.eclipse.jgit.errors.RepositoryNotFoundException;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.lib.Repository;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class PatchScriptFactory implements Callable<PatchScript> {
public interface Factory {
@@ -78,8 +75,7 @@
DiffPreferencesInfo diffPrefs);
}
- private static final Logger log =
- LoggerFactory.getLogger(PatchScriptFactory.class);
+ private static final Logger log = LoggerFactory.getLogger(PatchScriptFactory.class);
private final GitRepositoryManager repoManager;
private final PatchSetUtil psUtil;
@@ -89,8 +85,7 @@
private final CommentsUtil commentsUtil;
private final String fileName;
- @Nullable
- private final PatchSet.Id psa;
+ @Nullable private final PatchSet.Id psa;
private final int parentNum;
private final PatchSet.Id psb;
private final DiffPreferencesInfo diffPrefs;
@@ -110,7 +105,8 @@
private CommentDetail comments;
@AssistedInject
- PatchScriptFactory(GitRepositoryManager grm,
+ PatchScriptFactory(
+ GitRepositoryManager grm,
PatchSetUtil psUtil,
Provider<PatchScriptBuilder> builderFactory,
PatchListCache patchListCache,
@@ -141,7 +137,8 @@
}
@AssistedInject
- PatchScriptFactory(GitRepositoryManager grm,
+ PatchScriptFactory(
+ GitRepositoryManager grm,
PatchSetUtil psUtil,
Provider<PatchScriptBuilder> builderFactory,
PatchListCache patchListCache,
@@ -181,8 +178,9 @@
}
@Override
- public PatchScript call() throws OrmException, LargeObjectException,
- AuthException, InvalidChangeOperationException, IOException {
+ public PatchScript call()
+ throws OrmException, LargeObjectException, AuthException, InvalidChangeOperationException,
+ IOException {
if (parentNum < 0) {
validatePatchSetId(psa);
}
@@ -191,14 +189,12 @@
change = control.getChange();
project = change.getProject();
- PatchSet psEntityA = psa != null
- ? psUtil.get(db, control.getNotes(), psa) : null;
- PatchSet psEntityB = psb.get() == 0
- ? new PatchSet(psb)
- : psUtil.get(db, control.getNotes(), psb);
+ PatchSet psEntityA = psa != null ? psUtil.get(db, control.getNotes(), psa) : null;
+ PatchSet psEntityB =
+ psb.get() == 0 ? new PatchSet(psb) : psUtil.get(db, control.getNotes(), psb);
- if ((psEntityA != null && !control.isPatchVisible(psEntityA, db)) ||
- (psEntityB != null && !control.isPatchVisible(psEntityB, db))) {
+ if ((psEntityA != null && !control.isPatchVisible(psEntityA, db))
+ || (psEntityB != null && !control.isPatchVisible(psEntityB, db))) {
throw new NoSuchChangeException(changeId);
}
@@ -213,7 +209,8 @@
final PatchScriptBuilder b = newBuilder(list, git);
final PatchListEntry content = list.get(fileName);
- loadCommentsAndHistory(control.getNotes(),
+ loadCommentsAndHistory(
+ control.getNotes(),
content.getChangeType(),
content.getOldName(),
content.getNewName());
@@ -243,8 +240,7 @@
return PatchListKey.againstParentNum(parentNum + 1, bId, whitespace);
}
- private PatchList listFor(final PatchListKey key)
- throws PatchListNotAvailableException {
+ private PatchList listFor(final PatchListKey key) throws PatchListNotAvailableException {
return patchListCache.get(key, project);
}
@@ -257,8 +253,9 @@
return b;
}
- private ObjectId toObjectId(PatchSet ps) throws NoSuchChangeException,
- AuthException, NoSuchChangeException, IOException, OrmException {
+ private ObjectId toObjectId(PatchSet ps)
+ throws NoSuchChangeException, AuthException, NoSuchChangeException, IOException,
+ OrmException {
if (ps.getId().get() == 0) {
return getEditRev();
}
@@ -274,8 +271,8 @@
}
}
- private ObjectId getEditRev() throws AuthException,
- NoSuchChangeException, IOException, OrmException {
+ private ObjectId getEditRev()
+ throws AuthException, NoSuchChangeException, IOException, OrmException {
edit = editReader.byChange(change);
if (edit.isPresent()) {
return edit.get().getRef().getObjectId();
@@ -283,8 +280,7 @@
throw new NoSuchChangeException(change.getId());
}
- private void validatePatchSetId(final PatchSet.Id psId)
- throws NoSuchChangeException {
+ private void validatePatchSetId(final PatchSet.Id psId) throws NoSuchChangeException {
if (psId == null) { // OK, means use base;
} else if (changeId.equals(psId.getParentKey())) { // OK, same change;
} else {
@@ -292,8 +288,9 @@
}
}
- private void loadCommentsAndHistory(ChangeNotes notes, ChangeType changeType,
- String oldName, String newName) throws OrmException {
+ private void loadCommentsAndHistory(
+ ChangeNotes notes, ChangeType changeType, String oldName, String newName)
+ throws OrmException {
Map<Patch.Key, Patch> byKey = new HashMap<>();
if (loadHistory) {
@@ -330,8 +327,7 @@
byKey.put(p.getKey(), p);
}
if (edit != null && edit.isPresent()) {
- Patch p = new Patch(new Patch.Key(
- new PatchSet.Id(psb.getParentKey(), 0), fileName));
+ Patch p = new Patch(new Patch.Key(new PatchSet.Id(psb.getParentKey(), 0), fileName));
history.add(p);
byKey.put(p.getKey(), p);
}
@@ -389,8 +385,7 @@
}
}
- private void loadPublished(Map<Patch.Key, Patch> byKey, String file)
- throws OrmException {
+ private void loadPublished(Map<Patch.Key, Patch> byKey, String file) throws OrmException {
ChangeNotes notes = control.getNotes();
for (Comment c : commentsUtil.publishedByChangeFile(db, notes, changeId, file)) {
comments.include(change.getId(), c);
@@ -403,10 +398,9 @@
}
}
- private void loadDrafts(Map<Patch.Key, Patch> byKey, Account.Id me,
- String file) throws OrmException {
- for (Comment c :
- commentsUtil.draftByChangeFileAuthor(db, control.getNotes(), file, me)) {
+ private void loadDrafts(Map<Patch.Key, Patch> byKey, Account.Id me, String file)
+ throws OrmException {
+ for (Comment c : commentsUtil.draftByChangeFileAuthor(db, control.getNotes(), file, me)) {
comments.include(change.getId(), c);
PatchSet.Id psId = new PatchSet.Id(change.getId(), c.key.patchSetId);
Patch.Key pKey = new Patch.Key(psId, c.key.filename);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/patch/PatchSetInfoFactory.java b/gerrit-server/src/main/java/com/google/gerrit/server/patch/PatchSetInfoFactory.java
index 85afafc..3fc6ba6 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/patch/PatchSetInfoFactory.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/patch/PatchSetInfoFactory.java
@@ -28,7 +28,11 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
+import java.io.IOException;
+import java.sql.Timestamp;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
import org.eclipse.jgit.errors.MissingObjectException;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.PersonIdent;
@@ -36,16 +40,7 @@
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;
-import java.io.IOException;
-import java.sql.Timestamp;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Set;
-
-
-/**
- * Factory class creating PatchSetInfo from meta-data found in Git repository.
- */
+/** Factory class creating PatchSetInfo from meta-data found in Git repository. */
@Singleton
public class PatchSetInfoFactory {
private final GitRepositoryManager repoManager;
@@ -54,16 +49,13 @@
@Inject
public PatchSetInfoFactory(
- GitRepositoryManager repoManager,
- PatchSetUtil psUtil,
- AccountByEmailCache byEmailCache) {
+ GitRepositoryManager repoManager, PatchSetUtil psUtil, AccountByEmailCache byEmailCache) {
this.repoManager = repoManager;
this.psUtil = psUtil;
this.byEmailCache = byEmailCache;
}
- public PatchSetInfo get(RevWalk rw, RevCommit src, PatchSet.Id psi)
- throws IOException {
+ public PatchSetInfo get(RevWalk rw, RevCommit src, PatchSet.Id psi) throws IOException {
rw.parseBody(src);
PatchSetInfo info = new PatchSetInfo(psi);
info.setSubject(src.getShortMessage());
@@ -88,8 +80,7 @@
throws PatchSetInfoNotAvailableException {
try (Repository repo = repoManager.openRepository(project);
RevWalk rw = new RevWalk(repo)) {
- final RevCommit src =
- rw.parseCommit(ObjectId.fromString(patchSet.getRevision().get()));
+ final RevCommit src = rw.parseCommit(ObjectId.fromString(patchSet.getRevision().get()));
PatchSetInfo info = get(rw, src, patchSet.getId());
info.setParents(toParentInfos(src.getParents(), rw));
return info;
@@ -117,8 +108,8 @@
return u;
}
- private List<PatchSetInfo.ParentInfo> toParentInfos(final RevCommit[] parents,
- final RevWalk walk) throws IOException, MissingObjectException {
+ private List<PatchSetInfo.ParentInfo> toParentInfos(final RevCommit[] parents, final RevWalk walk)
+ throws IOException, MissingObjectException {
List<PatchSetInfo.ParentInfo> pInfos = new ArrayList<>(parents.length);
for (RevCommit parent : parents) {
walk.parseBody(parent);
@@ -128,5 +119,4 @@
}
return pInfos;
}
-
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/patch/PatchSetInfoNotAvailableException.java b/gerrit-server/src/main/java/com/google/gerrit/server/patch/PatchSetInfoNotAvailableException.java
index 9763d3c..0a91b32f 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/patch/PatchSetInfoNotAvailableException.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/patch/PatchSetInfoNotAvailableException.java
@@ -20,5 +20,4 @@
public PatchSetInfoNotAvailableException(Exception cause) {
super(cause);
}
-
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/patch/Text.java b/gerrit-server/src/main/java/com/google/gerrit/server/patch/Text.java
index a84dd92..f001591 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/patch/Text.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/patch/Text.java
@@ -17,6 +17,11 @@
import static java.nio.charset.StandardCharsets.ISO_8859_1;
import static java.nio.charset.StandardCharsets.UTF_8;
+import java.io.IOException;
+import java.nio.charset.Charset;
+import java.nio.charset.IllegalCharsetNameException;
+import java.nio.charset.UnsupportedCharsetException;
+import java.text.SimpleDateFormat;
import org.eclipse.jgit.diff.RawText;
import org.eclipse.jgit.errors.LargeObjectException;
import org.eclipse.jgit.errors.MissingObjectException;
@@ -32,12 +37,6 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.nio.charset.Charset;
-import java.nio.charset.IllegalCharsetNameException;
-import java.nio.charset.UnsupportedCharsetException;
-import java.text.SimpleDateFormat;
-
public class Text extends RawText {
private static final Logger log = LoggerFactory.getLogger(Text.class);
private static final int bigFileThreshold = PackConfig.DEFAULT_BIG_FILE_THRESHOLD;
@@ -58,16 +57,17 @@
switch (c.getParentCount()) {
case 0:
break;
- case 1: {
- RevCommit p = c.getParent(0);
- rw.parseBody(p);
- b.append("Parent: ");
- b.append(reader.abbreviate(p, 8).name());
- b.append(" (");
- b.append(p.getShortMessage());
- b.append(")\n");
- break;
- }
+ case 1:
+ {
+ RevCommit p = c.getParent(0);
+ rw.parseBody(p);
+ b.append("Parent: ");
+ b.append(reader.abbreviate(p, 8).name());
+ b.append(" (");
+ b.append(p.getShortMessage());
+ b.append(")\n");
+ break;
+ }
default:
for (int i = 0; i < c.getParentCount(); i++) {
RevCommit p = c.getParent(i);
@@ -87,25 +87,24 @@
}
}
- public static Text forMergeList(ComparisonType comparisonType,
- ObjectReader reader, AnyObjectId commitId) throws IOException {
+ public static Text forMergeList(
+ ComparisonType comparisonType, ObjectReader reader, AnyObjectId commitId) throws IOException {
try (RevWalk rw = new RevWalk(reader)) {
RevCommit c = rw.parseCommit(commitId);
StringBuilder b = new StringBuilder();
switch (c.getParentCount()) {
case 0:
break;
- case 1: {
- break;
- }
+ case 1:
+ {
+ break;
+ }
default:
- int uniterestingParent = comparisonType.isAgainstParent()
- ? comparisonType.getParentNum()
- : 1;
+ int uniterestingParent =
+ comparisonType.isAgainstParent() ? comparisonType.getParentNum() : 1;
b.append("Merge List:\n\n");
- for (RevCommit commit : MergeListBuilder.build(rw, c,
- uniterestingParent)) {
+ for (RevCommit commit : MergeListBuilder.build(rw, c, uniterestingParent)) {
b.append("* ");
b.append(reader.abbreviate(commit, 8).name());
b.append(" ");
@@ -117,8 +116,7 @@
}
}
- private static void appendPersonIdent(StringBuilder b, String field,
- PersonIdent person) {
+ private static void appendPersonIdent(StringBuilder b, String field, PersonIdent person) {
if (person != null) {
b.append(field).append(": ");
if (person.getName() != null) {
@@ -174,8 +172,7 @@
super(r);
}
- public Text(ObjectLoader ldr) throws MissingObjectException,
- LargeObjectException, IOException {
+ public Text(ObjectLoader ldr) throws MissingObjectException, LargeObjectException, IOException {
this(asByteArray(ldr));
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/AbstractPreloadedPluginScanner.java b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/AbstractPreloadedPluginScanner.java
index ee8f963..a578ecc 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/AbstractPreloadedPluginScanner.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/AbstractPreloadedPluginScanner.java
@@ -20,7 +20,6 @@
import com.google.gerrit.extensions.annotations.Export;
import com.google.gerrit.server.plugins.Plugin.ApiType;
import com.google.inject.Module;
-
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.lang.annotation.Annotation;
@@ -33,18 +32,16 @@
/**
* Base plugin scanner for a set of pre-loaded classes.
*
- * Utility base class for simplifying the development of Server plugin scanner
- * based on a set of externally pre-loaded classes.
+ * <p>Utility base class for simplifying the development of Server plugin scanner based on a set of
+ * externally pre-loaded classes.
*
- * Extending this class you can implement very easily a PluginContentScanner
- * from a set of pre-loaded Java Classes and an API Type.
- * The convention used by this class is:
- * - there is at most one Guice module per Gerrit module type (SysModule, HttpModule, SshModule)
- * - plugin is set to be restartable in Gerrit Plugin MANIFEST
- * - only Export and Listen annotated classes can be self-discovered
+ * <p>Extending this class you can implement very easily a PluginContentScanner from a set of
+ * pre-loaded Java Classes and an API Type. The convention used by this class is: - there is at most
+ * one Guice module per Gerrit module type (SysModule, HttpModule, SshModule) - plugin is set to be
+ * restartable in Gerrit Plugin MANIFEST - only Export and Listen annotated classes can be
+ * self-discovered
*/
-public abstract class AbstractPreloadedPluginScanner implements
- PluginContentScanner {
+public abstract class AbstractPreloadedPluginScanner implements PluginContentScanner {
protected final String pluginName;
protected final String pluginVersion;
protected final Set<Class<?>> preloadedClasses;
@@ -54,8 +51,11 @@
private Class<?> httpModuleClass;
private Class<?> sysModuleClass;
- public AbstractPreloadedPluginScanner(String pluginName, String pluginVersion,
- Set<Class<?>> preloadedClasses, Plugin.ApiType apiType) {
+ public AbstractPreloadedPluginScanner(
+ String pluginName,
+ String pluginVersion,
+ Set<Class<?>> preloadedClasses,
+ Plugin.ApiType apiType) {
this.pluginName = pluginName;
this.pluginVersion = pluginVersion;
this.preloadedClasses = preloadedClasses;
@@ -66,15 +66,21 @@
public Manifest getManifest() throws IOException {
scanGuiceModules(preloadedClasses);
StringBuilder manifestString =
- new StringBuilder("PluginName: " + pluginName + "\n"
- + "Implementation-Version: " + pluginVersion + "\n"
- + "Gerrit-ReloadMode: restart\n"
- + "Gerrit-ApiType: " + apiType + "\n");
+ new StringBuilder(
+ "PluginName: "
+ + pluginName
+ + "\n"
+ + "Implementation-Version: "
+ + pluginVersion
+ + "\n"
+ + "Gerrit-ReloadMode: restart\n"
+ + "Gerrit-ApiType: "
+ + apiType
+ + "\n");
appendIfNotNull(manifestString, "Gerrit-SshModule: ", sshModuleClass);
appendIfNotNull(manifestString, "Gerrit-HttpModule: ", httpModuleClass);
appendIfNotNull(manifestString, "Gerrit-Module: ", sysModuleClass);
- return new Manifest(new ByteArrayInputStream(manifestString.toString()
- .getBytes()));
+ return new Manifest(new ByteArrayInputStream(manifestString.toString().getBytes()));
}
@Override
@@ -89,18 +95,16 @@
result.put(annotation, classMetaDataSet);
for (Class<?> clazz : preloadedClasses) {
- if (!Modifier.isAbstract(clazz.getModifiers())
- && clazz.getAnnotation(annotation) != null) {
- classMetaDataSet.add(new ExtensionMetaData(clazz.getName(),
- getExportAnnotationValue(clazz, annotation)));
+ if (!Modifier.isAbstract(clazz.getModifiers()) && clazz.getAnnotation(annotation) != null) {
+ classMetaDataSet.add(
+ new ExtensionMetaData(clazz.getName(), getExportAnnotationValue(clazz, annotation)));
}
}
}
return result.build();
}
- private void appendIfNotNull(StringBuilder string, String header,
- Class<?> guiceModuleClass) {
+ private void appendIfNotNull(StringBuilder string, String header, Class<?> guiceModuleClass) {
if (guiceModuleClass != null) {
string.append(header);
string.append(guiceModuleClass.getName());
@@ -111,10 +115,8 @@
private void scanGuiceModules(Set<Class<?>> classes) throws IOException {
try {
Class<?> sysModuleBaseClass = Module.class;
- Class<?> httpModuleBaseClass =
- Class.forName("com.google.inject.servlet.ServletModule");
- Class<?> sshModuleBaseClass =
- Class.forName("com.google.gerrit.sshd.CommandModule");
+ Class<?> httpModuleBaseClass = Class.forName("com.google.inject.servlet.ServletModule");
+ Class<?> sshModuleBaseClass = Class.forName("com.google.gerrit.sshd.CommandModule");
sshModuleClass = null;
httpModuleClass = null;
sysModuleClass = null;
@@ -125,33 +127,33 @@
}
if (sshModuleBaseClass.isAssignableFrom(clazz)) {
- sshModuleClass =
- getUniqueGuiceModule(sshModuleBaseClass, sshModuleClass, clazz);
+ sshModuleClass = getUniqueGuiceModule(sshModuleBaseClass, sshModuleClass, clazz);
} else if (httpModuleBaseClass.isAssignableFrom(clazz)) {
- httpModuleClass =
- getUniqueGuiceModule(httpModuleBaseClass, httpModuleClass, clazz);
+ httpModuleClass = getUniqueGuiceModule(httpModuleBaseClass, httpModuleClass, clazz);
} else if (sysModuleBaseClass.isAssignableFrom(clazz)) {
- sysModuleClass =
- getUniqueGuiceModule(sysModuleBaseClass, sysModuleClass, clazz);
+ sysModuleClass = getUniqueGuiceModule(sysModuleBaseClass, sysModuleClass, clazz);
}
}
} catch (ClassNotFoundException e) {
- throw new IOException(
- "Cannot find base Gerrit classes for Guice Plugin Modules", e);
+ throw new IOException("Cannot find base Gerrit classes for Guice Plugin Modules", e);
}
}
- private Class<?> getUniqueGuiceModule(Class<?> guiceModuleBaseClass,
- Class<?> existingGuiceModuleName, Class<?> newGuiceModuleClass) {
- checkState(existingGuiceModuleName == null,
- "Multiple %s implementations: %s, %s", guiceModuleBaseClass,
- existingGuiceModuleName, newGuiceModuleClass);
+ private Class<?> getUniqueGuiceModule(
+ Class<?> guiceModuleBaseClass,
+ Class<?> existingGuiceModuleName,
+ Class<?> newGuiceModuleClass) {
+ checkState(
+ existingGuiceModuleName == null,
+ "Multiple %s implementations: %s, %s",
+ guiceModuleBaseClass,
+ existingGuiceModuleName,
+ newGuiceModuleClass);
return newGuiceModuleClass;
}
- private String getExportAnnotationValue(Class<?> scriptClass,
- Class<? extends Annotation> annotation) {
- return annotation == Export.class ? scriptClass.getAnnotation(Export.class)
- .value() : "";
+ private String getExportAnnotationValue(
+ Class<?> scriptClass, Class<? extends Annotation> annotation) {
+ return annotation == Export.class ? scriptClass.getAnnotation(Export.class).value() : "";
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/AutoRegisterModules.java b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/AutoRegisterModules.java
index 5d7e139..304d202 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/AutoRegisterModules.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/AutoRegisterModules.java
@@ -31,10 +31,6 @@
import com.google.inject.Module;
import com.google.inject.Scopes;
import com.google.inject.TypeLiteral;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.ParameterizedType;
@@ -42,6 +38,8 @@
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
class AutoRegisterModules {
private static final Logger log = LoggerFactory.getLogger(AutoRegisterModules.class);
@@ -61,7 +59,8 @@
Module sshModule;
Module httpModule;
- AutoRegisterModules(String pluginName,
+ AutoRegisterModules(
+ String pluginName,
PluginGuiceEnvironment env,
PluginContentScanner scanner,
ClassLoader classLoader) {
@@ -69,12 +68,8 @@
this.env = env;
this.scanner = scanner;
this.classLoader = classLoader;
- this.sshGen = env.hasSshModule()
- ? env.newSshModuleGenerator()
- : new ModuleGenerator.NOP();
- this.httpGen = env.hasHttpModule()
- ? env.newHttpModuleGenerator()
- : new ModuleGenerator.NOP();
+ this.sshGen = env.hasSshModule() ? env.newSshModuleGenerator() : new ModuleGenerator.NOP();
+ this.httpGen = env.hasHttpModule() ? env.newHttpModuleGenerator() : new ModuleGenerator.NOP();
}
AutoRegisterModules discover() throws InvalidPluginException {
@@ -113,8 +108,7 @@
bind(type).annotatedWith(n).to(impl);
}
if (initJs != null) {
- DynamicSet.bind(binder(), WebUiPlugin.class)
- .toInstance(new JavaScriptPlugin(initJs));
+ DynamicSet.bind(binder(), WebUiPlugin.class).toInstance(new JavaScriptPlugin(initJs));
}
}
};
@@ -140,9 +134,12 @@
initJs = STATIC_INIT_JS;
}
} catch (IOException e) {
- log.warn(String.format("Cannot access %s from plugin %s: "
- + "JavaScript auto-discovered plugin will not be registered",
- STATIC_INIT_JS, pluginName), e);
+ log.warn(
+ String.format(
+ "Cannot access %s from plugin %s: "
+ + "JavaScript auto-discovered plugin will not be registered",
+ STATIC_INIT_JS, pluginName),
+ e);
}
}
@@ -151,16 +148,17 @@
try {
clazz = Class.forName(def.className, false, classLoader);
} catch (ClassNotFoundException err) {
- throw new InvalidPluginException(String.format(
- "Cannot load %s with @Export(\"%s\")",
- def.className, def.annotationValue), err);
+ throw new InvalidPluginException(
+ String.format("Cannot load %s with @Export(\"%s\")", def.className, def.annotationValue),
+ err);
}
Export export = clazz.getAnnotation(Export.class);
if (export == null) {
- PluginLoader.log.warn(String.format(
- "In plugin %s asm incorrectly parsed %s with @Export(\"%s\")",
- pluginName, clazz.getName(), def.annotationValue));
+ PluginLoader.log.warn(
+ String.format(
+ "In plugin %s asm incorrectly parsed %s with @Export(\"%s\")",
+ pluginName, clazz.getName(), def.annotationValue));
return;
}
@@ -174,9 +172,9 @@
listen(clazz, clazz);
if (cnt == sysListen.size()) {
// If no bindings were recorded, the extension isn't recognized.
- throw new InvalidPluginException(String.format(
- "Class %s with @Export(\"%s\") not supported",
- clazz.getName(), export.value()));
+ throw new InvalidPluginException(
+ String.format(
+ "Class %s with @Export(\"%s\") not supported", clazz.getName(), export.value()));
}
}
}
@@ -186,23 +184,21 @@
try {
clazz = Class.forName(def.className, false, classLoader);
} catch (ClassNotFoundException err) {
- throw new InvalidPluginException(String.format(
- "Cannot load %s with @Listen",
- def.className), err);
+ throw new InvalidPluginException(
+ String.format("Cannot load %s with @Listen", def.className), err);
}
Listen listen = clazz.getAnnotation(Listen.class);
if (listen != null) {
listen(clazz, clazz);
} else {
- PluginLoader.log.warn(String.format(
- "In plugin %s asm incorrectly parsed %s with @Listen",
- pluginName, clazz.getName()));
+ PluginLoader.log.warn(
+ String.format(
+ "In plugin %s asm incorrectly parsed %s with @Listen", pluginName, clazz.getName()));
}
}
- private void listen(java.lang.reflect.Type type, Class<?> clazz)
- throws InvalidPluginException {
+ private void listen(java.lang.reflect.Type type, Class<?> clazz) throws InvalidPluginException {
while (type != null) {
Class<?> rawType;
if (type instanceof ParameterizedType) {
@@ -227,18 +223,20 @@
sshGen.listen(tl, clazz);
} else if (env.hasDynamicMap(tl)) {
if (clazz.getAnnotation(Export.class) == null) {
- throw new InvalidPluginException(String.format(
- "Class %s requires @Export(\"name\") annotation for %s",
- clazz.getName(), rawType.getName()));
+ throw new InvalidPluginException(
+ String.format(
+ "Class %s requires @Export(\"name\") annotation for %s",
+ clazz.getName(), rawType.getName()));
}
sysSingletons.add(clazz);
sysListen.put(tl, clazz);
httpGen.listen(tl, clazz);
sshGen.listen(tl, clazz);
} else {
- throw new InvalidPluginException(String.format(
- "Cannot register %s, server does not accept %s",
- clazz.getName(), rawType.getName()));
+ throw new InvalidPluginException(
+ String.format(
+ "Cannot register %s, server does not accept %s",
+ clazz.getName(), rawType.getName()));
}
return;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/AutoRegisterUtil.java b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/AutoRegisterUtil.java
index 3256d7f..d592d17 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/AutoRegisterUtil.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/AutoRegisterUtil.java
@@ -16,7 +16,6 @@
import com.google.gerrit.extensions.annotations.Export;
import com.google.inject.internal.UniqueAnnotations;
-
import java.lang.annotation.Annotation;
public final class AutoRegisterUtil {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/CleanupHandle.java b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/CleanupHandle.java
index 9827812..3329ab3 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/CleanupHandle.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/CleanupHandle.java
@@ -38,8 +38,11 @@
Files.deleteIfExists(tmp);
PluginLoader.log.info("Cleaned plugin " + tmp.getFileName());
} catch (IOException e) {
- PluginLoader.log.warn("Cannot delete " + tmp.toAbsolutePath()
- + ", retrying to delete it on termination of the virtual machine", e);
+ PluginLoader.log.warn(
+ "Cannot delete "
+ + tmp.toAbsolutePath()
+ + ", retrying to delete it on termination of the virtual machine",
+ e);
tmp.toFile().deleteOnExit();
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/CopyConfigModule.java b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/CopyConfigModule.java
index 1d4233a..9f937e6 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/CopyConfigModule.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/CopyConfigModule.java
@@ -29,25 +29,21 @@
import com.google.inject.Inject;
import com.google.inject.Provides;
import com.google.inject.Singleton;
-
+import java.nio.file.Path;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.lib.PersonIdent;
-import java.nio.file.Path;
-
/**
* Copies critical objects from the {@code dbInjector} into a plugin.
- * <p>
- * Most explicit bindings are copied automatically from the cfgInjector and
- * sysInjector to be made available to a plugin's private world. This module is
- * necessary to get things bound in the dbInjector that are not otherwise easily
- * available, but that a plugin author might expect to exist.
+ *
+ * <p>Most explicit bindings are copied automatically from the cfgInjector and sysInjector to be
+ * made available to a plugin's private world. This module is necessary to get things bound in the
+ * dbInjector that are not otherwise easily available, but that a plugin author might expect to
+ * exist.
*/
@Singleton
class CopyConfigModule extends AbstractModule {
- @Inject
- @SitePath
- private Path sitePath;
+ @Inject @SitePath private Path sitePath;
@Provides
@SitePath
@@ -55,25 +51,21 @@
return sitePath;
}
- @Inject
- private SitePaths sitePaths;
+ @Inject private SitePaths sitePaths;
@Provides
SitePaths getSitePaths() {
return sitePaths;
}
- @Inject
- private TrackingFooters trackingFooters;
+ @Inject private TrackingFooters trackingFooters;
@Provides
TrackingFooters getTrackingFooters() {
return trackingFooters;
}
- @Inject
- @GerritServerConfig
- private Config gerritServerConfig;
+ @Inject @GerritServerConfig private Config gerritServerConfig;
@Provides
@GerritServerConfig
@@ -81,25 +73,21 @@
return gerritServerConfig;
}
- @Inject
- private SchemaFactory<ReviewDb> schemaFactory;
+ @Inject private SchemaFactory<ReviewDb> schemaFactory;
@Provides
SchemaFactory<ReviewDb> getSchemaFactory() {
return schemaFactory;
}
- @Inject
- private GitRepositoryManager gitRepositoryManager;
+ @Inject private GitRepositoryManager gitRepositoryManager;
@Provides
GitRepositoryManager getGitRepositoryManager() {
return gitRepositoryManager;
}
- @Inject
- @AnonymousCowardName
- private String anonymousCowardName;
+ @Inject @AnonymousCowardName private String anonymousCowardName;
@Provides
@AnonymousCowardName
@@ -107,8 +95,7 @@
return anonymousCowardName;
}
- @Inject
- private GerritPersonIdentProvider serverIdentProvider;
+ @Inject private GerritPersonIdentProvider serverIdentProvider;
@Provides
@GerritPersonIdent
@@ -116,8 +103,7 @@
return serverIdentProvider.get();
}
- @Inject
- private SecureStore secureStore;
+ @Inject private SecureStore secureStore;
@Provides
SecureStore getSecureStore() {
@@ -125,10 +111,8 @@
}
@Inject
- CopyConfigModule() {
- }
+ CopyConfigModule() {}
@Override
- protected void configure() {
- }
+ protected void configure() {}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/DisablePlugin.java b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/DisablePlugin.java
index d92dce0..b63c6c0 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/DisablePlugin.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/DisablePlugin.java
@@ -27,8 +27,7 @@
@RequiresCapability(GlobalCapability.ADMINISTRATE_SERVER)
@Singleton
class DisablePlugin implements RestModifyView<PluginResource, Input> {
- static class Input {
- }
+ static class Input {}
private final PluginLoader loader;
@@ -38,11 +37,9 @@
}
@Override
- public PluginInfo apply(PluginResource resource, Input input)
- throws MethodNotAllowedException {
+ public PluginInfo apply(PluginResource resource, Input input) throws MethodNotAllowedException {
if (!loader.isRemoteAdminEnabled()) {
- throw new MethodNotAllowedException(
- "remote plugin administration is disabled");
+ throw new MethodNotAllowedException("remote plugin administration is disabled");
}
String name = resource.getName();
loader.disablePlugins(ImmutableSet.of(name));
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/EnablePlugin.java b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/EnablePlugin.java
index b6f8260..c3e52cb 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/EnablePlugin.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/EnablePlugin.java
@@ -24,15 +24,13 @@
import com.google.gerrit.server.plugins.ListPlugins.PluginInfo;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
import java.io.PrintWriter;
import java.io.StringWriter;
@RequiresCapability(GlobalCapability.ADMINISTRATE_SERVER)
@Singleton
class EnablePlugin implements RestModifyView<PluginResource, Input> {
- static class Input {
- }
+ static class Input {}
private final PluginLoader loader;
@@ -45,8 +43,7 @@
public PluginInfo apply(PluginResource resource, Input input)
throws ResourceConflictException, MethodNotAllowedException {
if (!loader.isRemoteAdminEnabled()) {
- throw new MethodNotAllowedException(
- "remote plugin administration is disabled");
+ throw new MethodNotAllowedException("remote plugin administration is disabled");
}
String name = resource.getName();
try {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/InstallPlugin.java b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/InstallPlugin.java
index 2f780bf..3882008 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/InstallPlugin.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/InstallPlugin.java
@@ -26,7 +26,6 @@
import com.google.gerrit.server.plugins.InstallPlugin.Input;
import com.google.gerrit.server.plugins.ListPlugins.PluginInfo;
import com.google.inject.Inject;
-
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
@@ -37,8 +36,7 @@
@RequiresCapability(GlobalCapability.ADMINISTRATE_SERVER)
class InstallPlugin implements RestModifyView<TopLevelResource, Input> {
static class Input {
- @DefaultInput
- String url;
+ @DefaultInput String url;
RawInput raw;
}
@@ -61,11 +59,8 @@
try {
try (InputStream in = openStream(input)) {
String pluginName = loader.installPluginFromStream(name, in);
- ListPlugins.PluginInfo info =
- new ListPlugins.PluginInfo(loader.get(pluginName));
- return created
- ? Response.created(info)
- : Response.ok(info);
+ ListPlugins.PluginInfo info = new ListPlugins.PluginInfo(loader.get(pluginName));
+ return created ? Response.created(info) : Response.ok(info);
}
} catch (PluginInstallException e) {
StringWriter buf = new StringWriter();
@@ -83,8 +78,7 @@
}
}
- private InputStream openStream(Input input)
- throws IOException, BadRequestException {
+ private InputStream openStream(Input input) throws IOException, BadRequestException {
if (input.raw != null) {
return input.raw.getInputStream();
}
@@ -108,7 +102,7 @@
public Response<PluginInfo> apply(PluginResource resource, Input input)
throws BadRequestException, MethodNotAllowedException, IOException {
return new InstallPlugin(loader, resource.getName(), false)
- .apply(TopLevelResource.INSTANCE, input);
+ .apply(TopLevelResource.INSTANCE, input);
}
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/JarPluginProvider.java b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/JarPluginProvider.java
index fa913b2..06a1a68 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/JarPluginProvider.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/JarPluginProvider.java
@@ -21,11 +21,6 @@
import com.google.gerrit.server.config.PluginConfigFactory;
import com.google.gerrit.server.config.SitePaths;
import com.google.inject.Inject;
-
-import org.eclipse.jgit.internal.storage.file.FileSnapshot;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
@@ -40,6 +35,9 @@
import java.util.List;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
+import org.eclipse.jgit.internal.storage.file.FileSnapshot;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class JarPluginProvider implements ServerPluginProvider {
static final String PLUGIN_TMP_PREFIX = "plugin_";
@@ -50,8 +48,7 @@
private final PluginConfigFactory configFactory;
@Inject
- JarPluginProvider(SitePaths sitePaths,
- PluginConfigFactory configFactory) {
+ JarPluginProvider(SitePaths sitePaths, PluginConfigFactory configFactory) {
this.tmpDir = sitePaths.tmp_dir;
this.configFactory = configFactory;
}
@@ -59,31 +56,28 @@
@Override
public boolean handles(Path srcPath) {
String fileName = srcPath.getFileName().toString();
- return fileName.endsWith(JAR_EXTENSION)
- || fileName.endsWith(JAR_EXTENSION + ".disabled");
+ return fileName.endsWith(JAR_EXTENSION) || fileName.endsWith(JAR_EXTENSION + ".disabled");
}
@Override
public String getPluginName(Path srcPath) {
try {
- return MoreObjects.firstNonNull(getJarPluginName(srcPath),
- PluginLoader.nameOf(srcPath));
+ return MoreObjects.firstNonNull(getJarPluginName(srcPath), PluginLoader.nameOf(srcPath));
} catch (IOException e) {
- throw new IllegalArgumentException("Invalid plugin file " + srcPath
- + ": cannot get plugin name", e);
+ throw new IllegalArgumentException(
+ "Invalid plugin file " + srcPath + ": cannot get plugin name", e);
}
}
public static String getJarPluginName(Path srcPath) throws IOException {
try (JarFile jarFile = new JarFile(srcPath.toFile())) {
- return jarFile.getManifest().getMainAttributes()
- .getValue("Gerrit-PluginName");
+ return jarFile.getManifest().getMainAttributes().getValue("Gerrit-PluginName");
}
}
@Override
- public ServerPlugin get(Path srcPath, FileSnapshot snapshot,
- PluginDescription description) throws InvalidPluginException {
+ public ServerPlugin get(Path srcPath, FileSnapshot snapshot, PluginDescription description)
+ throws InvalidPluginException {
try {
String name = getPluginName(srcPath);
String extension = getExtension(srcPath);
@@ -115,16 +109,16 @@
return PLUGIN_TMP_PREFIX + name + "_" + fmt.format(new Date()) + "_";
}
- public static Path storeInTemp(String pluginName, InputStream in,
- SitePaths sitePaths) throws IOException {
+ public static Path storeInTemp(String pluginName, InputStream in, SitePaths sitePaths)
+ throws IOException {
if (!Files.exists(sitePaths.tmp_dir)) {
Files.createDirectories(sitePaths.tmp_dir);
}
return asTemp(in, tempNameFor(pluginName), ".jar", sitePaths.tmp_dir);
}
- private ServerPlugin loadJarPlugin(String name, Path srcJar,
- FileSnapshot snapshot, Path tmp, PluginDescription description)
+ private ServerPlugin loadJarPlugin(
+ String name, Path srcJar, FileSnapshot snapshot, Path tmp, PluginDescription description)
throws IOException, InvalidPluginException, MalformedURLException {
JarFile jarFile = new JarFile(tmp.toFile());
boolean keep = false;
@@ -144,16 +138,22 @@
urls.add(tmp.toUri().toURL());
ClassLoader pluginLoader =
- new URLClassLoader(urls.toArray(new URL[urls.size()]),
- PluginLoader.parentFor(type));
+ new URLClassLoader(urls.toArray(new URL[urls.size()]), PluginLoader.parentFor(type));
JarScanner jarScanner = createJarScanner(tmp);
PluginConfig pluginConfig = configFactory.getFromGerritConfig(name);
- ServerPlugin plugin = new ServerPlugin(name, description.canonicalUrl,
- description.user, srcJar, snapshot, jarScanner,
- description.dataDir, pluginLoader,
- pluginConfig.getString("metricsPrefix", null));
+ ServerPlugin plugin =
+ new ServerPlugin(
+ name,
+ description.canonicalUrl,
+ description.user,
+ srcJar,
+ snapshot,
+ jarScanner,
+ description.dataDir,
+ pluginLoader,
+ pluginConfig.getString("metricsPrefix", null));
plugin.setCleanupHandle(new CleanupHandle(tmp, jarFile));
keep = true;
return plugin;
@@ -164,8 +164,7 @@
}
}
- private JarScanner createJarScanner(Path srcJar)
- throws InvalidPluginException {
+ private JarScanner createJarScanner(Path srcJar) throws InvalidPluginException {
try {
return new JarScanner(srcJar);
} catch (IOException e) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/JarScanner.java b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/JarScanner.java
index 81e7433..8d8a139 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/JarScanner.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/JarScanner.java
@@ -23,17 +23,6 @@
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.MultimapBuilder;
-
-import org.eclipse.jgit.util.IO;
-import org.objectweb.asm.AnnotationVisitor;
-import org.objectweb.asm.Attribute;
-import org.objectweb.asm.ClassReader;
-import org.objectweb.asm.ClassVisitor;
-import org.objectweb.asm.FieldVisitor;
-import org.objectweb.asm.MethodVisitor;
-import org.objectweb.asm.Opcodes;
-import org.objectweb.asm.Type;
-
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
@@ -52,10 +41,19 @@
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
+import org.eclipse.jgit.util.IO;
+import org.objectweb.asm.AnnotationVisitor;
+import org.objectweb.asm.Attribute;
+import org.objectweb.asm.ClassReader;
+import org.objectweb.asm.ClassVisitor;
+import org.objectweb.asm.FieldVisitor;
+import org.objectweb.asm.MethodVisitor;
+import org.objectweb.asm.Opcodes;
+import org.objectweb.asm.Type;
public class JarScanner implements PluginContentScanner, AutoCloseable {
- private static final int SKIP_ALL = ClassReader.SKIP_CODE
- | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES;
+ private static final int SKIP_ALL =
+ ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES;
private final JarFile jarFile;
public JarScanner(Path src) throws IOException {
@@ -69,8 +67,7 @@
Set<String> descriptors = new HashSet<>();
ListMultimap<String, JarScanner.ClassData> rawMap =
MultimapBuilder.hashKeys().arrayListValues().build();
- Map<Class<? extends Annotation>, String> classObjToClassDescr =
- new HashMap<>();
+ Map<Class<? extends Annotation>, String> classObjToClassDescr = new HashMap<>();
for (Class<? extends Annotation> annotation : annotations) {
String descriptor = Type.getType(annotation).getDescriptor();
@@ -91,19 +88,22 @@
} catch (IOException err) {
throw new InvalidPluginException("Cannot auto-register", err);
} catch (RuntimeException err) {
- PluginLoader.log.warn(String.format(
- "Plugin %s has invalid class file %s inside of %s", pluginName,
- entry.getName(), jarFile.getName()), err);
+ PluginLoader.log.warn(
+ String.format(
+ "Plugin %s has invalid class file %s inside of %s",
+ pluginName, entry.getName(), jarFile.getName()),
+ err);
continue;
}
if (!Strings.isNullOrEmpty(def.annotationName)) {
if (def.isConcrete()) {
- rawMap.put(def.annotationName, def);
+ rawMap.put(def.annotationName, def);
} else {
- PluginLoader.log.warn(String.format(
- "Plugin %s tries to @%s(\"%s\") abstract class %s", pluginName,
- def.annotationName, def.annotationValue, def.className));
+ PluginLoader.log.warn(
+ String.format(
+ "Plugin %s tries to @%s(\"%s\") abstract class %s",
+ pluginName, def.annotationName, def.annotationValue, def.className));
}
}
}
@@ -114,14 +114,11 @@
for (Class<? extends Annotation> annotoation : annotations) {
String descr = classObjToClassDescr.get(annotoation);
Collection<ClassData> discoverdData = rawMap.get(descr);
- Collection<ClassData> values =
- firstNonNull(discoverdData, Collections.<ClassData> emptySet());
+ Collection<ClassData> values = firstNonNull(discoverdData, Collections.<ClassData>emptySet());
result.put(
annotoation,
- transform(
- values,
- cd -> new ExtensionMetaData(cd.className, cd.annotationValue)));
+ transform(values, cd -> new ExtensionMetaData(cd.className, cd.annotationValue)));
}
return result.build();
@@ -151,8 +148,9 @@
try {
new ClassReader(read(jarFile, entry)).accept(def, SKIP_ALL);
} catch (RuntimeException err) {
- PluginLoader.log.warn(String.format("Jar %s has invalid class file %s",
- jarFile.getName(), entry.getName()), err);
+ PluginLoader.log.warn(
+ String.format("Jar %s has invalid class file %s", jarFile.getName(), entry.getName()),
+ err);
continue;
}
@@ -180,8 +178,7 @@
return false;
}
- private static byte[] read(JarFile jarFile, JarEntry entry)
- throws IOException {
+ private static byte[] read(JarFile jarFile, JarEntry entry) throws IOException {
byte[] data = new byte[(int) entry.getSize()];
try (InputStream in = jarFile.getInputStream(entry)) {
IO.readFully(in, data, 0, data.length);
@@ -204,13 +201,17 @@
}
boolean isConcrete() {
- return (access & Opcodes.ACC_ABSTRACT) == 0
- && (access & Opcodes.ACC_INTERFACE) == 0;
+ return (access & Opcodes.ACC_ABSTRACT) == 0 && (access & Opcodes.ACC_INTERFACE) == 0;
}
@Override
- public void visit(int version, int access, String name, String signature,
- String superName, String[] interfaces) {
+ public void visit(
+ int version,
+ int access,
+ String name,
+ String signature,
+ String superName,
+ String[] interfaces) {
this.className = Type.getObjectType(name).getClassName();
this.access = access;
this.superName = superName;
@@ -221,8 +222,7 @@
if (!visible) {
return null;
}
- Optional<String> found =
- exports.stream().filter(x -> x.equals(desc)).findAny();
+ Optional<String> found = exports.stream().filter(x -> x.equals(desc)).findAny();
if (found.isPresent()) {
annotationName = desc;
return new AbstractAnnotationVisitor() {
@@ -236,40 +236,33 @@
}
@Override
- public void visitSource(String arg0, String arg1) {
- }
+ public void visitSource(String arg0, String arg1) {}
@Override
- public void visitOuterClass(String arg0, String arg1, String arg2) {
- }
+ public void visitOuterClass(String arg0, String arg1, String arg2) {}
@Override
- public MethodVisitor visitMethod(int arg0, String arg1, String arg2,
- String arg3, String[] arg4) {
+ public MethodVisitor visitMethod(
+ int arg0, String arg1, String arg2, String arg3, String[] arg4) {
return null;
}
@Override
- public void visitInnerClass(String arg0, String arg1, String arg2, int arg3) {
- }
+ public void visitInnerClass(String arg0, String arg1, String arg2, int arg3) {}
@Override
- public FieldVisitor visitField(int arg0, String arg1, String arg2,
- String arg3, Object arg4) {
+ public FieldVisitor visitField(int arg0, String arg1, String arg2, String arg3, Object arg4) {
return null;
}
@Override
- public void visitEnd() {
- }
+ public void visitEnd() {}
@Override
- public void visitAttribute(Attribute arg0) {
- }
+ public void visitAttribute(Attribute arg0) {}
}
- private abstract static class AbstractAnnotationVisitor extends
- AnnotationVisitor {
+ private abstract static class AbstractAnnotationVisitor extends AnnotationVisitor {
AbstractAnnotationVisitor() {
super(Opcodes.ASM5);
}
@@ -285,17 +278,14 @@
}
@Override
- public void visitEnum(String arg0, String arg1, String arg2) {
- }
+ public void visitEnum(String arg0, String arg1, String arg2) {}
@Override
- public void visitEnd() {
- }
+ public void visitEnd() {}
}
@Override
- public Optional<PluginEntry> getEntry(String resourcePath)
- throws IOException {
+ public Optional<PluginEntry> getEntry(String resourcePath) throws IOException {
JarEntry jarEntry = jarFile.getJarEntry(resourcePath);
if (jarEntry == null || jarEntry.getSize() == 0) {
return Optional.empty();
@@ -306,23 +296,22 @@
@Override
public Enumeration<PluginEntry> entries() {
- return Collections.enumeration(Lists.transform(
- Collections.list(jarFile.entries()),
- jarEntry -> {
- try {
- return resourceOf(jarEntry);
- } catch (IOException e) {
- throw new IllegalArgumentException("Cannot convert jar entry "
- + jarEntry + " to a resource", e);
- }
- }));
+ return Collections.enumeration(
+ Lists.transform(
+ Collections.list(jarFile.entries()),
+ jarEntry -> {
+ try {
+ return resourceOf(jarEntry);
+ } catch (IOException e) {
+ throw new IllegalArgumentException(
+ "Cannot convert jar entry " + jarEntry + " to a resource", e);
+ }
+ }));
}
@Override
- public InputStream getInputStream(PluginEntry entry)
- throws IOException {
- return jarFile.getInputStream(jarFile
- .getEntry(entry.getName()));
+ public InputStream getInputStream(PluginEntry entry) throws IOException {
+ return jarFile.getInputStream(jarFile.getEntry(entry.getName()));
}
@Override
@@ -331,17 +320,20 @@
}
private PluginEntry resourceOf(JarEntry jarEntry) throws IOException {
- return new PluginEntry(jarEntry.getName(), jarEntry.getTime(),
- Optional.of(jarEntry.getSize()), attributesOf(jarEntry));
+ return new PluginEntry(
+ jarEntry.getName(),
+ jarEntry.getTime(),
+ Optional.of(jarEntry.getSize()),
+ attributesOf(jarEntry));
}
- private Map<Object, String> attributesOf(JarEntry jarEntry)
- throws IOException {
+ private Map<Object, String> attributesOf(JarEntry jarEntry) throws IOException {
Attributes attributes = jarEntry.getAttributes();
if (attributes == null) {
return Collections.emptyMap();
}
- return Maps.transformEntries(attributes,
+ return Maps.transformEntries(
+ attributes,
new Maps.EntryTransformer<Object, Object, String>() {
@Override
public String transformEntry(Object key, Object value) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/JsPlugin.java b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/JsPlugin.java
index 544cc5b..625bf9e 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/JsPlugin.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/JsPlugin.java
@@ -24,16 +24,13 @@
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
-
-import org.eclipse.jgit.internal.storage.file.FileSnapshot;
-
import java.nio.file.Path;
+import org.eclipse.jgit.internal.storage.file.FileSnapshot;
class JsPlugin extends Plugin {
private Injector sysInjector;
- JsPlugin(String name, Path srcFile, PluginUser pluginUser,
- FileSnapshot snapshot) {
+ JsPlugin(String name, Path srcFile, PluginUser pluginUser, FileSnapshot snapshot) {
super(name, srcFile, pluginUser, snapshot, ApiType.JS);
}
@@ -52,8 +49,7 @@
public void start(PluginGuiceEnvironment env) throws Exception {
manager = new LifecycleManager();
String fileName = getSrcFile().getFileName().toString();
- sysInjector =
- Guice.createInjector(new StandaloneJsPluginModule(getName(), fileName));
+ sysInjector = Guice.createInjector(new StandaloneJsPluginModule(getName(), fileName));
manager.start();
}
@@ -99,8 +95,7 @@
@Override
protected void configure() {
bind(String.class).annotatedWith(PluginName.class).toInstance(pluginName);
- DynamicSet.bind(binder(), WebUiPlugin.class).toInstance(
- new JavaScriptPlugin(fileName));
+ DynamicSet.bind(binder(), WebUiPlugin.class).toInstance(new JavaScriptPlugin(fileName));
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/ListPlugins.java b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/ListPlugins.java
index b9871ab..ef0b15a 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/ListPlugins.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/ListPlugins.java
@@ -25,15 +25,13 @@
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;
import com.google.inject.Inject;
-
-import org.kohsuke.args4j.Option;
-
import java.io.PrintWriter;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
+import org.kohsuke.args4j.Option;
/** List the installed plugins. */
@RequiresCapability(GlobalCapability.VIEW_PLUGINS)
@@ -44,7 +42,11 @@
@Option(name = "--format", usage = "(deprecated) output format")
private OutputFormat format = OutputFormat.TEXT;
- @Option(name = "--all", aliases = {"-a"}, usage = "List all plugins, including disabled plugins")
+ @Option(
+ name = "--all",
+ aliases = {"-a"},
+ usage = "List all plugins, including disabled plugins"
+ )
private boolean all;
@Inject
@@ -70,16 +72,19 @@
public JsonElement display(PrintWriter stdout) {
Map<String, PluginInfo> output = new TreeMap<>();
List<Plugin> plugins = Lists.newArrayList(pluginLoader.getPlugins(all));
- Collections.sort(plugins, new Comparator<Plugin>() {
- @Override
- public int compare(Plugin a, Plugin b) {
- return a.getName().compareTo(b.getName());
- }
- });
+ Collections.sort(
+ plugins,
+ new Comparator<Plugin>() {
+ @Override
+ public int compare(Plugin a, Plugin b) {
+ return a.getName().compareTo(b.getName());
+ }
+ });
if (!format.isJson()) {
stdout.format("%-30s %-10s %-8s %s\n", "Name", "Version", "Status", "File");
- stdout.print("-------------------------------------------------------------------------------\n");
+ stdout.print(
+ "-------------------------------------------------------------------------------\n");
}
for (Plugin p : plugins) {
@@ -87,7 +92,9 @@
if (format.isJson()) {
output.put(p.getName(), info);
} else {
- stdout.format("%-30s %-10s %-8s %s\n", p.getName(),
+ stdout.format(
+ "%-30s %-10s %-8s %s\n",
+ p.getName(),
Strings.nullToEmpty(info.version),
p.isDisabled() ? "DISABLED" : "ENABLED",
p.getSrcFile().getFileName());
@@ -95,12 +102,13 @@
}
if (stdout == null) {
- return OutputFormat.JSON.newGson().toJsonTree(
- output,
- new TypeToken<Map<String, Object>>() {}.getType());
+ return OutputFormat.JSON
+ .newGson()
+ .toJsonTree(output, new TypeToken<Map<String, Object>>() {}.getType());
} else if (format.isJson()) {
- format.newGson().toJson(output,
- new TypeToken<Map<String, PluginInfo>>() {}.getType(), stdout);
+ format
+ .newGson()
+ .toJson(output, new TypeToken<Map<String, PluginInfo>>() {}.getType(), stdout);
stdout.print('\n');
}
stdout.flush();
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/MultipleProvidersForPluginException.java b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/MultipleProvidersForPluginException.java
index e89eb7d..1453854 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/MultipleProvidersForPluginException.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/MultipleProvidersForPluginException.java
@@ -22,15 +22,15 @@
class MultipleProvidersForPluginException extends IllegalArgumentException {
private static final long serialVersionUID = 1L;
- MultipleProvidersForPluginException(Path pluginSrcPath,
- Iterable<ServerPluginProvider> providersHandlers) {
- super(pluginSrcPath.toAbsolutePath()
- + " is claimed to be handled by more than one plugin provider: "
- + providersListToString(providersHandlers));
+ MultipleProvidersForPluginException(
+ Path pluginSrcPath, Iterable<ServerPluginProvider> providersHandlers) {
+ super(
+ pluginSrcPath.toAbsolutePath()
+ + " is claimed to be handled by more than one plugin provider: "
+ + providersListToString(providersHandlers));
}
- private static String providersListToString(
- Iterable<ServerPluginProvider> providersHandlers) {
+ private static String providersListToString(Iterable<ServerPluginProvider> providersHandlers) {
return StreamSupport.stream(providersHandlers.spliterator(), false)
.map(ServerPluginProvider::getProviderPluginName)
.collect(joining(", "));
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/Plugin.java b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/Plugin.java
index 63a254a..5759705 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/Plugin.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/Plugin.java
@@ -21,19 +21,19 @@
import com.google.gerrit.lifecycle.LifecycleManager;
import com.google.gerrit.server.PluginUser;
import com.google.inject.Injector;
-
-import org.eclipse.jgit.internal.storage.file.FileSnapshot;
-
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
+import org.eclipse.jgit.internal.storage.file.FileSnapshot;
public abstract class Plugin {
public enum ApiType {
- EXTENSION, PLUGIN, JS
+ EXTENSION,
+ PLUGIN,
+ JS
}
/** Unique key that changes whenever a plugin reloads. */
@@ -54,8 +54,7 @@
static ApiType getApiType(Manifest manifest) throws InvalidPluginException {
Attributes main = manifest.getMainAttributes();
String v = main.getValue("Gerrit-ApiType");
- if (Strings.isNullOrEmpty(v)
- || ApiType.EXTENSION.name().equalsIgnoreCase(v)) {
+ if (Strings.isNullOrEmpty(v) || ApiType.EXTENSION.name().equalsIgnoreCase(v)) {
return ApiType.EXTENSION;
} else if (ApiType.PLUGIN.name().equalsIgnoreCase(v)) {
return ApiType.PLUGIN;
@@ -79,19 +78,15 @@
private List<ReloadableRegistrationHandle<?>> reloadableHandles;
- public Plugin(String name,
- Path srcPath,
- PluginUser pluginUser,
- FileSnapshot snapshot,
- ApiType apiType) {
+ public Plugin(
+ String name, Path srcPath, PluginUser pluginUser, FileSnapshot snapshot, ApiType apiType) {
this.name = name;
this.srcFile = srcPath;
this.apiType = apiType;
this.snapshot = snapshot;
this.pluginUser = pluginUser;
this.cacheKey = new Plugin.CacheKey(name);
- this.disabled = srcPath != null
- && srcPath.getFileName().toString().endsWith(".disabled");
+ this.disabled = srcPath != null && srcPath.getFileName().toString().endsWith(".disabled");
}
public CleanupHandle getCleanupHandle() {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/PluginCleanerTask.java b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/PluginCleanerTask.java
index 6c4c451..2916721d 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/PluginCleanerTask.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/PluginCleanerTask.java
@@ -18,7 +18,6 @@
import com.google.gerrit.server.git.WorkQueue;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
@@ -55,10 +54,10 @@
if (0 < left) {
long waiting = TimeUtil.nowMs() - start;
- PluginLoader.log.warn(String.format(
- "%d plugins still waiting to be reclaimed after %d minutes",
- pending,
- TimeUnit.MILLISECONDS.toMinutes(waiting)));
+ PluginLoader.log.warn(
+ String.format(
+ "%d plugins still waiting to be reclaimed after %d minutes",
+ pending, TimeUnit.MILLISECONDS.toMinutes(waiting)));
attempts = Math.min(attempts + 1, 15);
ensureScheduled();
} else {
@@ -87,15 +86,9 @@
private void ensureScheduled() {
if (self == null && 0 < pending) {
if (attempts == 1) {
- self = workQueue.getDefaultQueue().schedule(
- this,
- 30,
- TimeUnit.SECONDS);
+ self = workQueue.getDefaultQueue().schedule(this, 30, TimeUnit.SECONDS);
} else {
- self = workQueue.getDefaultQueue().schedule(
- this,
- attempts + 1,
- TimeUnit.MINUTES);
+ self = workQueue.getDefaultQueue().schedule(this, attempts + 1, TimeUnit.MINUTES);
}
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/PluginContentScanner.java b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/PluginContentScanner.java
index c333638..b19d6de 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/PluginContentScanner.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/PluginContentScanner.java
@@ -27,49 +27,46 @@
/**
* Scans the plugin returning classes and resources.
*
- * Gerrit uses the scanner to automatically discover the classes
- * and resources exported by the plugin for auto discovery
- * of exported SSH commands, Servlets and listeners.
+ * <p>Gerrit uses the scanner to automatically discover the classes and resources exported by the
+ * plugin for auto discovery of exported SSH commands, Servlets and listeners.
*/
public interface PluginContentScanner {
- /**
- * Scanner without resources.
- */
- PluginContentScanner EMPTY = new PluginContentScanner() {
- @Override
- public Manifest getManifest() throws IOException {
- return new Manifest();
- }
+ /** Scanner without resources. */
+ PluginContentScanner EMPTY =
+ new PluginContentScanner() {
+ @Override
+ public Manifest getManifest() throws IOException {
+ return new Manifest();
+ }
- @Override
- public Map<Class<? extends Annotation>, Iterable<ExtensionMetaData>> scan(
- String pluginName, Iterable<Class<? extends Annotation>> annotations)
- throws InvalidPluginException {
- return Collections.emptyMap();
- }
+ @Override
+ public Map<Class<? extends Annotation>, Iterable<ExtensionMetaData>> scan(
+ String pluginName, Iterable<Class<? extends Annotation>> annotations)
+ throws InvalidPluginException {
+ return Collections.emptyMap();
+ }
- @Override
- public Optional<PluginEntry> getEntry(String resourcePath) {
- return Optional.empty();
- }
+ @Override
+ public Optional<PluginEntry> getEntry(String resourcePath) {
+ return Optional.empty();
+ }
- @Override
- public InputStream getInputStream(PluginEntry entry) throws IOException {
- throw new NoSuchFileException("Empty plugin");
- }
+ @Override
+ public InputStream getInputStream(PluginEntry entry) throws IOException {
+ throw new NoSuchFileException("Empty plugin");
+ }
- @Override
- public Enumeration<PluginEntry> entries() {
- return Collections.emptyEnumeration();
- }
- };
+ @Override
+ public Enumeration<PluginEntry> entries() {
+ return Collections.emptyEnumeration();
+ }
+ };
/**
* Plugin class extension meta-data
*
- * Class name and annotation value of the class
- * provided by a plugin to extend an existing
+ * <p>Class name and annotation value of the class provided by a plugin to extend an existing
* extension point in Gerrit.
*/
class ExtensionMetaData {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/PluginEntry.java b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/PluginEntry.java
index c6077f4..f7b1e82 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/PluginEntry.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/PluginEntry.java
@@ -22,9 +22,8 @@
/**
* Plugin static resource entry
*
- * Bean representing a static resource inside a plugin.
- * All static resources are available at {@code <plugin web url>/static}
- * and served by the HttpPluginServlet.
+ * <p>Bean representing a static resource inside a plugin. All static resources are available at
+ * {@code <plugin web url>/static} and served by the HttpPluginServlet.
*/
public class PluginEntry {
public static final String ATTR_CHARACTER_ENCODING = "Character-Encoding";
@@ -45,8 +44,7 @@
private final Optional<Long> size;
private final Map<Object, String> attrs;
- public PluginEntry(String name, long time, Optional<Long> size,
- Map<Object, String> attrs) {
+ public PluginEntry(String name, long time, Optional<Long> size, Map<Object, String> attrs) {
this.name = name;
this.time = time;
this.size = size;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/PluginGuiceEnvironment.java b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/PluginGuiceEnvironment.java
index 6dc6dea..740e8d3 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/PluginGuiceEnvironment.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/PluginGuiceEnvironment.java
@@ -49,7 +49,6 @@
import com.google.inject.Singleton;
import com.google.inject.TypeLiteral;
import com.google.inject.internal.UniqueAnnotations;
-
import java.lang.annotation.Annotation;
import java.lang.reflect.ParameterizedType;
import java.util.Collections;
@@ -61,16 +60,15 @@
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
-
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Tracks Guice bindings that should be exposed to loaded plugins.
- * <p>
- * This is an internal implementation detail of how the main server is able to
- * export its explicit Guice bindings to tightly coupled plugins, giving them
- * access to singletons and request scoped resources just like any core code.
+ *
+ * <p>This is an internal implementation detail of how the main server is able to export its
+ * explicit Guice bindings to tightly coupled plugins, giving them access to singletons and request
+ * scoped resources just like any core code.
*/
@Singleton
public class PluginGuiceEnvironment {
@@ -165,15 +163,16 @@
final Module db = copy(dbInjector);
final Module cm = copy(cfgInjector);
final Module sm = copy(sysInjector);
- sysModule = new AbstractModule() {
- @Override
- protected void configure() {
- install(copyConfigModule);
- install(db);
- install(cm);
- install(sm);
- }
- };
+ sysModule =
+ new AbstractModule() {
+ @Override
+ protected void configure() {
+ install(copyConfigModule);
+ install(db);
+ install(cm);
+ install(sm);
+ }
+ };
}
public void setSshInjector(Injector injector) {
@@ -271,29 +270,25 @@
}
}
- private void attachItem(Map<TypeLiteral<?>, DynamicItem<?>> items,
- @Nullable Injector src,
- Plugin plugin) {
- for (RegistrationHandle h : PrivateInternals_DynamicTypes
- .attachItems(src, items, plugin.getName())) {
+ private void attachItem(
+ Map<TypeLiteral<?>, DynamicItem<?>> items, @Nullable Injector src, Plugin plugin) {
+ for (RegistrationHandle h :
+ PrivateInternals_DynamicTypes.attachItems(src, items, plugin.getName())) {
plugin.add(h);
}
}
- private void attachSet(Map<TypeLiteral<?>, DynamicSet<?>> sets,
- @Nullable Injector src,
- Plugin plugin) {
- for (RegistrationHandle h : PrivateInternals_DynamicTypes
- .attachSets(src, sets)) {
+ private void attachSet(
+ Map<TypeLiteral<?>, DynamicSet<?>> sets, @Nullable Injector src, Plugin plugin) {
+ for (RegistrationHandle h : PrivateInternals_DynamicTypes.attachSets(src, sets)) {
plugin.add(h);
}
}
- private void attachMap(Map<TypeLiteral<?>, DynamicMap<?>> maps,
- @Nullable Injector src,
- Plugin plugin) {
- for (RegistrationHandle h : PrivateInternals_DynamicTypes
- .attachMaps(src, plugin.getName(), maps)) {
+ private void attachMap(
+ Map<TypeLiteral<?>, DynamicMap<?>> maps, @Nullable Injector src, Plugin plugin) {
+ for (RegistrationHandle h :
+ PrivateInternals_DynamicTypes.attachMaps(src, plugin.getName(), maps)) {
plugin.add(h);
}
}
@@ -302,8 +297,7 @@
// Index all old registrations by the raw type. These may be replaced
// during the reattach calls below. Any that are not replaced will be
// removed when the old plugin does its stop routine.
- ListMultimap<TypeLiteral<?>, ReloadableRegistrationHandle<?>> old =
- LinkedListMultimap.create();
+ ListMultimap<TypeLiteral<?>, ReloadableRegistrationHandle<?>> old = LinkedListMultimap.create();
for (ReloadableRegistrationHandle<?> h : oldPlugin.getReloadableHandles()) {
old.put(h.getKey().getTypeLiteral(), h);
}
@@ -370,18 +364,14 @@
replace(newPlugin, h, b);
oldHandles.remove(type, h);
} else {
- newPlugin.add(map.put(
- newPlugin.getName(),
- b.getKey(),
- b.getProvider()));
+ newPlugin.add(map.put(newPlugin.getName(), b.getKey(), b.getProvider()));
}
}
}
}
/** Type used to declare unique annotations. Guice hides this, so extract it. */
- private static final Class<?> UNIQUE_ANNOTATION =
- UniqueAnnotations.create().annotationType();
+ private static final Class<?> UNIQUE_ANNOTATION = UniqueAnnotations.create().annotationType();
private void reattachSet(
ListMultimap<TypeLiteral<?>, ReloadableRegistrationHandle<?>> oldHandles,
@@ -439,7 +429,7 @@
} else if (oi.hasNext()) {
@SuppressWarnings("unchecked")
ReloadableRegistrationHandle<Object> h2 =
- (ReloadableRegistrationHandle<Object>) oi.next();
+ (ReloadableRegistrationHandle<Object>) oi.next();
oi.remove();
replace(newPlugin, h2, b);
} else {
@@ -465,28 +455,25 @@
@SuppressWarnings("unchecked")
DynamicItem<Object> item = (DynamicItem<Object>) e.getValue();
- Iterator<ReloadableRegistrationHandle<?>> oi =
- oldHandles.get(type).iterator();
+ Iterator<ReloadableRegistrationHandle<?>> oi = oldHandles.get(type).iterator();
for (Binding<?> binding : bindings(src, type)) {
@SuppressWarnings("unchecked")
Binding<Object> b = (Binding<Object>) binding;
if (oi.hasNext()) {
@SuppressWarnings("unchecked")
- ReloadableRegistrationHandle<Object> h =
- (ReloadableRegistrationHandle<Object>) oi.next();
+ ReloadableRegistrationHandle<Object> h = (ReloadableRegistrationHandle<Object>) oi.next();
oi.remove();
replace(newPlugin, h, b);
} else {
- newPlugin.add(item.set(b.getKey(), b.getProvider(),
- newPlugin.getName()));
+ newPlugin.add(item.set(b.getKey(), b.getProvider(), newPlugin.getName()));
}
}
}
}
- private static <T> void replace(Plugin newPlugin,
- ReloadableRegistrationHandle<T> h, Binding<T> b) {
+ private static <T> void replace(
+ Plugin newPlugin, ReloadableRegistrationHandle<T> h, Binding<T> b) {
RegistrationHandle n = h.replace(b.getKey(), b.getProvider());
if (n != null) {
newPlugin.add(n);
@@ -517,8 +504,7 @@
if (type.getRawType() == DynamicItem.class) {
ParameterizedType t = (ParameterizedType) type.getType();
dynamicItemTypes.add(TypeLiteral.get(t.getActualTypeArguments()[0]));
- } else if (type.getRawType() == DynamicSet.class
- || type.getRawType() == DynamicMap.class) {
+ } else if (type.getRawType() == DynamicSet.class || type.getRawType() == DynamicMap.class) {
ParameterizedType t = (ParameterizedType) type.getType();
dynamicTypes.add(TypeLiteral.get(t.getActualTypeArguments()[0]));
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/PluginLoader.java b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/PluginLoader.java
index 5826c58..9183579 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/PluginLoader.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/PluginLoader.java
@@ -42,12 +42,6 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.internal.storage.file.FileSnapshot;
-import org.eclipse.jgit.lib.Config;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@@ -70,14 +64,17 @@
import java.util.TreeSet;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
+import org.eclipse.jgit.internal.storage.file.FileSnapshot;
+import org.eclipse.jgit.lib.Config;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
@Singleton
public class PluginLoader implements LifecycleListener {
static final Logger log = LoggerFactory.getLogger(PluginLoader.class);
public String getPluginName(Path srcPath) {
- return MoreObjects.firstNonNull(getGerritPluginName(srcPath),
- nameOf(srcPath));
+ return MoreObjects.firstNonNull(getGerritPluginName(srcPath), nameOf(srcPath));
}
private final Path pluginsDir;
@@ -98,7 +95,8 @@
private final UniversalServerPluginProvider serverPluginFactory;
@Inject
- public PluginLoader(SitePaths sitePaths,
+ public PluginLoader(
+ SitePaths sitePaths,
PluginGuiceEnvironment pe,
ServerInformationImpl sii,
PluginUser.Factory puf,
@@ -122,12 +120,16 @@
persistentCacheFactory = cacheFactory;
serverPluginFactory = pluginFactory;
- remoteAdmin =
- cfg.getBoolean("plugins", null, "allowRemoteAdmin", false);
+ remoteAdmin = cfg.getBoolean("plugins", null, "allowRemoteAdmin", false);
- long checkFrequency = ConfigUtil.getTimeUnit(cfg,
- "plugins", null, "checkFrequency",
- TimeUnit.MINUTES.toMillis(1), TimeUnit.MILLISECONDS);
+ long checkFrequency =
+ ConfigUtil.getTimeUnit(
+ cfg,
+ "plugins",
+ null,
+ "checkFrequency",
+ TimeUnit.MINUTES.toMillis(1),
+ TimeUnit.MILLISECONDS);
if (checkFrequency > 0) {
scanner = new PluginScannerThread(this, checkFrequency);
} else {
@@ -135,26 +137,24 @@
}
}
- public static List<Path> listPlugins(Path pluginsDir, final String suffix)
- throws IOException {
+ public static List<Path> listPlugins(Path pluginsDir, final String suffix) throws IOException {
if (pluginsDir == null || !Files.exists(pluginsDir)) {
return ImmutableList.of();
}
- DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() {
- @Override
- public boolean accept(Path entry) throws IOException {
- String n = entry.getFileName().toString();
- boolean accept = !n.startsWith(".last_")
- && !n.startsWith(".next_")
- && Files.isRegularFile(entry);
- if (!Strings.isNullOrEmpty(suffix)) {
- accept &= n.endsWith(suffix);
- }
- return accept;
- }
- };
- try (DirectoryStream<Path> files = Files.newDirectoryStream(
- pluginsDir, filter)) {
+ DirectoryStream.Filter<Path> filter =
+ new DirectoryStream.Filter<Path>() {
+ @Override
+ public boolean accept(Path entry) throws IOException {
+ String n = entry.getFileName().toString();
+ boolean accept =
+ !n.startsWith(".last_") && !n.startsWith(".next_") && Files.isRegularFile(entry);
+ if (!Strings.isNullOrEmpty(suffix)) {
+ accept &= n.endsWith(suffix);
+ }
+ return accept;
+ }
+ };
+ try (DirectoryStream<Path> files = Files.newDirectoryStream(pluginsDir, filter)) {
return Ordering.natural().sortedCopy(files);
}
}
@@ -190,12 +190,12 @@
String fileName = originalName;
Path tmp = asTemp(in, ".next_" + fileName + "_", ".tmp", pluginsDir);
- String name = MoreObjects.firstNonNull(getGerritPluginName(tmp),
- nameOf(fileName));
+ String name = MoreObjects.firstNonNull(getGerritPluginName(tmp), nameOf(fileName));
if (!originalName.equals(name)) {
- log.warn(String.format("Plugin provides its own name: <%s>,"
- + " use it instead of the input name: <%s>",
- name, originalName));
+ log.warn(
+ String.format(
+ "Plugin provides its own name: <%s>," + " use it instead of the input name: <%s>",
+ name, originalName));
}
String fileExtension = getExtension(fileName);
@@ -228,8 +228,7 @@
return name;
}
- static Path asTemp(InputStream in, String prefix, String suffix, Path dir)
- throws IOException {
+ static Path asTemp(InputStream in, String prefix, String suffix, Path dir) throws IOException {
Path tmp = Files.createTempFile(dir, prefix, suffix);
boolean keep = false;
try (OutputStream out = Files.newOutputStream(tmp)) {
@@ -246,8 +245,7 @@
private synchronized void unloadPlugin(Plugin plugin) {
persistentCacheFactory.onStop(plugin);
String name = plugin.getName();
- log.info(String.format("Unloading plugin %s, version %s",
- name, plugin.getVersion()));
+ log.info(String.format("Unloading plugin %s, version %s", name, plugin.getVersion()));
plugin.stop(env);
env.onStopPlugin(plugin);
running.remove(name);
@@ -257,8 +255,8 @@
public void disablePlugins(Set<String> names) {
if (!isRemoteAdminEnabled()) {
- log.warn("Remote plugin administration is disabled,"
- + " ignoring disablePlugins(" + names + ")");
+ log.warn(
+ "Remote plugin administration is disabled," + " ignoring disablePlugins(" + names + ")");
return;
}
@@ -270,8 +268,8 @@
}
log.info(String.format("Disabling plugin %s", active.getName()));
- Path off = active.getSrcFile().resolveSibling(
- active.getSrcFile().getFileName() + ".disabled");
+ Path off =
+ active.getSrcFile().resolveSibling(active.getSrcFile().getFileName() + ".disabled");
try {
Files.move(active.getSrcFile(), off);
} catch (IOException e) {
@@ -289,9 +287,7 @@
disabled.put(name, offPlugin);
} catch (Throwable e) {
// This shouldn't happen, as the plugin was loaded earlier.
- log.warn(String.format(
- "Cannot load disabled plugin %s", active.getName()),
- e.getCause());
+ log.warn(String.format("Cannot load disabled plugin %s", active.getName()), e.getCause());
}
}
cleanInBackground();
@@ -300,8 +296,8 @@
public void enablePlugins(Set<String> names) throws PluginInstallException {
if (!isRemoteAdminEnabled()) {
- log.warn("Remote plugin administration is disabled,"
- + " ignoring enablePlugins(" + names + ")");
+ log.warn(
+ "Remote plugin administration is disabled," + " ignoring enablePlugins(" + names + ")");
return;
}
@@ -362,8 +358,7 @@
}
}
- public void reload(List<String> names)
- throws InvalidPluginException, PluginInstallException {
+ public void reload(List<String> names) throws InvalidPluginException, PluginInstallException {
synchronized (this) {
List<Plugin> reload = Lists.newArrayListWithCapacity(names.size());
List<String> bad = Lists.newArrayListWithExpectedSize(4);
@@ -376,9 +371,8 @@
}
}
if (!bad.isEmpty()) {
- throw new InvalidPluginException(String.format(
- "Plugin(s) \"%s\" not running",
- Joiner.on("\", \"").join(bad)));
+ throw new InvalidPluginException(
+ String.format("Plugin(s) \"%s\" not running", Joiner.on("\", \"").join(bad)));
}
for (Plugin active : reload) {
@@ -386,8 +380,9 @@
try {
log.info(String.format("Reloading plugin %s", name));
Plugin newPlugin = runPlugin(name, active.getSrcFile(), active);
- log.info(String.format("Reloaded plugin %s, version %s",
- newPlugin.getName(), newPlugin.getVersion()));
+ log.info(
+ String.format(
+ "Reloaded plugin %s, version %s", newPlugin.getName(), newPlugin.getVersion()));
} catch (PluginInstallException e) {
log.warn(String.format("Cannot reload plugin %s", name), e.getCause());
throw e;
@@ -433,9 +428,12 @@
try {
Plugin loadedPlugin = runPlugin(name, path, active);
if (!loadedPlugin.isDisabled()) {
- log.info(String.format("%s plugin %s, version %s",
- active == null ? "Loaded" : "Reloaded",
- loadedPlugin.getName(), loadedPlugin.getVersion()));
+ log.info(
+ String.format(
+ "%s plugin %s, version %s",
+ active == null ? "Loaded" : "Reloaded",
+ loadedPlugin.getName(),
+ loadedPlugin.getVersion()));
}
} catch (PluginInstallException e) {
log.warn(String.format("Cannot load plugin %s", name), e.getCause());
@@ -445,34 +443,32 @@
cleanInBackground();
}
- private void addAllEntries(Map<String, Path> from,
- TreeSet<Entry<String, Path>> to) {
+ private void addAllEntries(Map<String, Path> from, TreeSet<Entry<String, Path>> to) {
Iterator<Entry<String, Path>> it = from.entrySet().iterator();
while (it.hasNext()) {
- Entry<String,Path> entry = it.next();
- to.add(new AbstractMap.SimpleImmutableEntry<>(
- entry.getKey(), entry.getValue()));
+ Entry<String, Path> entry = it.next();
+ to.add(new AbstractMap.SimpleImmutableEntry<>(entry.getKey(), entry.getValue()));
}
}
- private TreeSet<Entry<String, Path>> jarsFirstSortedPluginsSet(
- Map<String, Path> activePlugins) {
+ private TreeSet<Entry<String, Path>> jarsFirstSortedPluginsSet(Map<String, Path> activePlugins) {
TreeSet<Entry<String, Path>> sortedPlugins =
- Sets.newTreeSet(new Comparator<Entry<String, Path>>() {
- @Override
- public int compare(Entry<String, Path> e1, Entry<String, Path> e2) {
- Path n1 = e1.getValue().getFileName();
- Path n2 = e2.getValue().getFileName();
- return ComparisonChain.start()
- .compareTrueFirst(isJar(n1), isJar(n2))
- .compare(n1, n2)
- .result();
- }
+ Sets.newTreeSet(
+ new Comparator<Entry<String, Path>>() {
+ @Override
+ public int compare(Entry<String, Path> e1, Entry<String, Path> e2) {
+ Path n1 = e1.getValue().getFileName();
+ Path n2 = e2.getValue().getFileName();
+ return ComparisonChain.start()
+ .compareTrueFirst(isJar(n1), isJar(n2))
+ .compare(n1, n2)
+ .result();
+ }
- private boolean isJar(Path n1) {
- return n1.toString().endsWith(".jar");
- }
- });
+ private boolean isJar(Path n1) {
+ return n1.toString().endsWith(".jar");
+ }
+ });
addAllEntries(activePlugins, sortedPlugins);
return sortedPlugins;
@@ -497,9 +493,7 @@
* safer then to reassign it.
*/
name = newPlugin.getName();
- boolean reload = oldPlugin != null
- && oldPlugin.canReload()
- && newPlugin.canReload();
+ boolean reload = oldPlugin != null && oldPlugin.canReload() && newPlugin.canReload();
if (!reload && oldPlugin != null) {
unloadPlugin(oldPlugin);
}
@@ -599,8 +593,8 @@
} else if (serverPluginFactory.handles(srcPlugin)) {
return loadServerPlugin(srcPlugin, snapshot);
} else {
- throw new InvalidPluginException(String.format(
- "Unsupported plugin type: %s", srcPlugin.getFileName()));
+ throw new InvalidPluginException(
+ String.format("Unsupported plugin type: %s", srcPlugin.getFileName()));
}
}
@@ -609,9 +603,9 @@
}
private String getPluginCanonicalWebUrl(String name) {
- String url = String.format("%s/plugins/%s/",
- CharMatcher.is('/').trimTrailingFrom(urlProvider.get()),
- name);
+ String url =
+ String.format(
+ "%s/plugins/%s/", CharMatcher.is('/').trimTrailingFrom(urlProvider.get()), name);
return url;
}
@@ -619,16 +613,19 @@
return new JsPlugin(name, srcJar, pluginUserFactory.create(name), snapshot);
}
- private ServerPlugin loadServerPlugin(Path scriptFile,
- FileSnapshot snapshot) throws InvalidPluginException {
+ private ServerPlugin loadServerPlugin(Path scriptFile, FileSnapshot snapshot)
+ throws InvalidPluginException {
String name = serverPluginFactory.getPluginName(scriptFile);
- return serverPluginFactory.get(scriptFile, snapshot, new PluginDescription(
- pluginUserFactory.create(name), getPluginCanonicalWebUrl(name),
- getPluginDataDir(name)));
+ return serverPluginFactory.get(
+ scriptFile,
+ snapshot,
+ new PluginDescription(
+ pluginUserFactory.create(name),
+ getPluginCanonicalWebUrl(name),
+ getPluginDataDir(name)));
}
- static ClassLoader parentFor(Plugin.ApiType type)
- throws InvalidPluginException {
+ static ClassLoader parentFor(Plugin.ApiType type) throws InvalidPluginException {
switch (type) {
case EXTENSION:
return PluginName.class.getClassLoader();
@@ -643,10 +640,8 @@
// Only one active plugin per plugin name can exist for each plugin name.
// Filter out disabled plugins and transform the multimap to a map
- private static Map<String, Path> filterDisabled(
- SetMultimap<String, Path> pluginPaths) {
- Map<String, Path> activePlugins = Maps.newHashMapWithExpectedSize(
- pluginPaths.keys().size());
+ private static Map<String, Path> filterDisabled(SetMultimap<String, Path> pluginPaths) {
+ Map<String, Path> activePlugins = Maps.newHashMapWithExpectedSize(pluginPaths.keys().size());
for (String name : pluginPaths.keys()) {
for (Path pluginPath : pluginPaths.asMap().get(name)) {
if (!pluginPath.getFileName().toString().endsWith(".disabled")) {
@@ -689,10 +684,12 @@
Collection<Path> elementsToRemove = new ArrayList<>();
Collection<Path> elementsToAdd = new ArrayList<>();
for (Path loser : Iterables.skip(enabled, 1)) {
- log.warn(String.format("Plugin <%s> was disabled, because"
- + " another plugin <%s>"
- + " with the same name <%s> already exists",
- loser, winner, plugin));
+ log.warn(
+ String.format(
+ "Plugin <%s> was disabled, because"
+ + " another plugin <%s>"
+ + " with the same name <%s> already exists",
+ loser, winner, plugin));
Path disabledPlugin = Paths.get(loser + ".disabled");
elementsToAdd.add(disabledPlugin);
elementsToRemove.add(loser);
@@ -717,11 +714,8 @@
}
}
- private static Iterable<Path> filterDisabledPlugins(
- Collection<Path> paths) {
- return Iterables.filter(
- paths,
- p -> !p.getFileName().toString().endsWith(".disabled"));
+ private static Iterable<Path> filterDisabledPlugins(Collection<Path> paths) {
+ return Iterables.filter(paths, p -> !p.getFileName().toString().endsWith(".disabled"));
}
public String getGerritPluginName(Path srcPath) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/PluginMetricMaker.java b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/PluginMetricMaker.java
index 23b1eee..b1a01d3 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/PluginMetricMaker.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/PluginMetricMaker.java
@@ -34,7 +34,6 @@
import com.google.gerrit.metrics.Timer1;
import com.google.gerrit.metrics.Timer2;
import com.google.gerrit.metrics.Timer3;
-
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
@@ -59,9 +58,7 @@
}
@Override
- public <F1> Counter1<F1> newCounter(
- String name, Description desc,
- Field<F1> field1) {
+ public <F1> Counter1<F1> newCounter(String name, Description desc, Field<F1> field1) {
Counter1<F1> m = root.newCounter(prefix + name, desc, field1);
cleanup.add(m);
return m;
@@ -69,8 +66,7 @@
@Override
public <F1, F2> Counter2<F1, F2> newCounter(
- String name, Description desc,
- Field<F1> field1, Field<F2> field2) {
+ String name, Description desc, Field<F1> field1, Field<F2> field2) {
Counter2<F1, F2> m = root.newCounter(prefix + name, desc, field1, field2);
cleanup.add(m);
return m;
@@ -78,10 +74,8 @@
@Override
public <F1, F2, F3> Counter3<F1, F2, F3> newCounter(
- String name, Description desc,
- Field<F1> field1, Field<F2> field2, Field<F3> field3) {
- Counter3<F1, F2, F3> m =
- root.newCounter(prefix + name, desc, field1, field2, field3);
+ String name, Description desc, Field<F1> field1, Field<F2> field2, Field<F3> field3) {
+ Counter3<F1, F2, F3> m = root.newCounter(prefix + name, desc, field1, field2, field3);
cleanup.add(m);
return m;
}
@@ -94,9 +88,7 @@
}
@Override
- public <F1> Timer1<F1> newTimer(
- String name, Description desc,
- Field<F1> field1) {
+ public <F1> Timer1<F1> newTimer(String name, Description desc, Field<F1> field1) {
Timer1<F1> m = root.newTimer(prefix + name, desc, field1);
cleanup.add(m);
return m;
@@ -104,8 +96,7 @@
@Override
public <F1, F2> Timer2<F1, F2> newTimer(
- String name, Description desc,
- Field<F1> field1, Field<F2> field2) {
+ String name, Description desc, Field<F1> field1, Field<F2> field2) {
Timer2<F1, F2> m = root.newTimer(prefix + name, desc, field1, field2);
cleanup.add(m);
return m;
@@ -113,10 +104,8 @@
@Override
public <F1, F2, F3> Timer3<F1, F2, F3> newTimer(
- String name, Description desc,
- Field<F1> field1, Field<F2> field2, Field<F3> field3) {
- Timer3<F1, F2, F3> m =
- root.newTimer(prefix + name, desc, field1, field2, field3);
+ String name, Description desc, Field<F1> field1, Field<F2> field2, Field<F3> field3) {
+ Timer3<F1, F2, F3> m = root.newTimer(prefix + name, desc, field1, field2, field3);
cleanup.add(m);
return m;
}
@@ -129,9 +118,7 @@
}
@Override
- public <F1> Histogram1<F1> newHistogram(
- String name, Description desc,
- Field<F1> field1) {
+ public <F1> Histogram1<F1> newHistogram(String name, Description desc, Field<F1> field1) {
Histogram1<F1> m = root.newHistogram(prefix + name, desc, field1);
cleanup.add(m);
return m;
@@ -139,8 +126,7 @@
@Override
public <F1, F2> Histogram2<F1, F2> newHistogram(
- String name, Description desc,
- Field<F1> field1, Field<F2> field2) {
+ String name, Description desc, Field<F1> field1, Field<F2> field2) {
Histogram2<F1, F2> m = root.newHistogram(prefix + name, desc, field1, field2);
cleanup.add(m);
return m;
@@ -148,10 +134,8 @@
@Override
public <F1, F2, F3> Histogram3<F1, F2, F3> newHistogram(
- String name, Description desc,
- Field<F1> field1, Field<F2> field2, Field<F3> field3) {
- Histogram3<F1, F2, F3> m =
- root.newHistogram(prefix + name, desc, field1, field2, field3);
+ String name, Description desc, Field<F1> field1, Field<F2> field2, Field<F3> field3) {
+ Histogram3<F1, F2, F3> m = root.newHistogram(prefix + name, desc, field1, field2, field3);
cleanup.add(m);
return m;
}
@@ -165,17 +149,15 @@
}
@Override
- public <F1, V> CallbackMetric1<F1, V> newCallbackMetric(String name,
- Class<V> valueClass, Description desc, Field<F1> field1) {
- CallbackMetric1<F1, V> m =
- root.newCallbackMetric(prefix + name, valueClass, desc, field1);
+ public <F1, V> CallbackMetric1<F1, V> newCallbackMetric(
+ String name, Class<V> valueClass, Description desc, Field<F1> field1) {
+ CallbackMetric1<F1, V> m = root.newCallbackMetric(prefix + name, valueClass, desc, field1);
cleanup.add(m);
return m;
}
@Override
- public RegistrationHandle newTrigger(Set<CallbackMetric<?>> metrics,
- Runnable trigger) {
+ public RegistrationHandle newTrigger(Set<CallbackMetric<?>> metrics, Runnable trigger) {
final RegistrationHandle handle = root.newTrigger(metrics, trigger);
cleanup.add(handle);
return new RegistrationHandle() {
@@ -188,8 +170,7 @@
}
@Override
- public void start() {
- }
+ public void start() {}
@Override
public void stop() {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/PluginModule.java b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/PluginModule.java
index 32722da..db18470 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/PluginModule.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/PluginModule.java
@@ -31,8 +31,7 @@
listener().to(PluginLoader.class);
DynamicSet.setOf(binder(), ServerPluginProvider.class);
- DynamicSet.bind(binder(), ServerPluginProvider.class).to(
- JarPluginProvider.class);
+ DynamicSet.bind(binder(), ServerPluginProvider.class).to(JarPluginProvider.class);
bind(UniversalServerPluginProvider.class);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/PluginScannerThread.java b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/PluginScannerThread.java
index e6c3dbd..705e3c0 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/PluginScannerThread.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/PluginScannerThread.java
@@ -31,7 +31,7 @@
@Override
public void run() {
- for (;;) {
+ for (; ; ) {
try {
if (done.await(checkFrequencyMillis, TimeUnit.MILLISECONDS)) {
return;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/PluginsCollection.java b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/PluginsCollection.java
index a4834ba..b8a9a9e 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/PluginsCollection.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/PluginsCollection.java
@@ -27,17 +27,16 @@
import com.google.inject.Singleton;
@Singleton
-public class PluginsCollection implements
- RestCollection<TopLevelResource, PluginResource>,
- AcceptsCreate<TopLevelResource> {
+public class PluginsCollection
+ implements RestCollection<TopLevelResource, PluginResource>, AcceptsCreate<TopLevelResource> {
private final DynamicMap<RestView<PluginResource>> views;
private final PluginLoader loader;
private final Provider<ListPlugins> list;
@Inject
- PluginsCollection(DynamicMap<RestView<PluginResource>> views,
- PluginLoader loader, Provider<ListPlugins> list) {
+ PluginsCollection(
+ DynamicMap<RestView<PluginResource>> views, PluginLoader loader, Provider<ListPlugins> list) {
this.views = views;
this.loader = loader;
this.list = list;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/ReloadPlugin.java b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/ReloadPlugin.java
index e9c5aa2..13a1179 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/ReloadPlugin.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/ReloadPlugin.java
@@ -23,15 +23,13 @@
import com.google.gerrit.server.plugins.ReloadPlugin.Input;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
import java.io.PrintWriter;
import java.io.StringWriter;
@RequiresCapability(GlobalCapability.ADMINISTRATE_SERVER)
@Singleton
class ReloadPlugin implements RestModifyView<PluginResource, Input> {
- static class Input {
- }
+ static class Input {}
private final PluginLoader loader;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/ServerPlugin.java b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/ServerPlugin.java
index 7175685..36b0631 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/ServerPlugin.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/ServerPlugin.java
@@ -25,15 +25,13 @@
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;
-
-import org.eclipse.jgit.internal.storage.file.FileSnapshot;
-
import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
+import org.eclipse.jgit.internal.storage.file.FileSnapshot;
public class ServerPlugin extends Plugin {
private final Manifest manifest;
@@ -52,7 +50,8 @@
private LifecycleManager serverManager;
private List<ReloadableRegistrationHandle<?>> reloadableHandles;
- public ServerPlugin(String name,
+ public ServerPlugin(
+ String name,
String pluginCanonicalWebUrl,
PluginUser pluginUser,
Path srcJar,
@@ -60,11 +59,14 @@
PluginContentScanner scanner,
Path dataDir,
ClassLoader classLoader,
- String metricsPrefix) throws InvalidPluginException {
- super(name, srcJar, pluginUser, snapshot,
- scanner == null
- ? ApiType.PLUGIN
- : Plugin.getApiType(getPluginManifest(scanner)));
+ String metricsPrefix)
+ throws InvalidPluginException {
+ super(
+ name,
+ srcJar,
+ pluginUser,
+ snapshot,
+ scanner == null ? ApiType.PLUGIN : Plugin.getApiType(getPluginManifest(scanner)));
this.pluginCanonicalWebUrl = pluginCanonicalWebUrl;
this.scanner = scanner;
this.dataDir = dataDir;
@@ -76,28 +78,39 @@
}
}
- public ServerPlugin(String name,
+ public ServerPlugin(
+ String name,
String pluginCanonicalWebUrl,
PluginUser pluginUser,
Path srcJar,
FileSnapshot snapshot,
PluginContentScanner scanner,
Path dataDir,
- ClassLoader classLoader) throws InvalidPluginException {
- this(name, pluginCanonicalWebUrl, pluginUser, srcJar, snapshot, scanner,
- dataDir, classLoader, null);
+ ClassLoader classLoader)
+ throws InvalidPluginException {
+ this(
+ name,
+ pluginCanonicalWebUrl,
+ pluginUser,
+ srcJar,
+ snapshot,
+ scanner,
+ dataDir,
+ classLoader,
+ null);
}
- private void loadGuiceModules(Manifest manifest, ClassLoader classLoader) throws InvalidPluginException {
+ private void loadGuiceModules(Manifest manifest, ClassLoader classLoader)
+ throws InvalidPluginException {
Attributes main = manifest.getMainAttributes();
String sysName = main.getValue("Gerrit-Module");
String sshName = main.getValue("Gerrit-SshModule");
String httpName = main.getValue("Gerrit-HttpModule");
if (!Strings.isNullOrEmpty(sshName) && getApiType() != Plugin.ApiType.PLUGIN) {
- throw new InvalidPluginException(String.format(
- "Using Gerrit-SshModule requires Gerrit-ApiType: %s",
- Plugin.ApiType.PLUGIN));
+ throw new InvalidPluginException(
+ String.format(
+ "Using Gerrit-SshModule requires Gerrit-ApiType: %s", Plugin.ApiType.PLUGIN));
}
try {
@@ -116,12 +129,10 @@
return null;
}
- Class<?> clazz =
- Class.forName(name, false, pluginLoader);
+ Class<?> clazz = Class.forName(name, false, pluginLoader);
if (!Module.class.isAssignableFrom(clazz)) {
- throw new ClassCastException(String.format(
- "Class %s does not implement %s",
- name, Module.class.getName()));
+ throw new ClassCastException(
+ String.format("Class %s does not implement %s", name, Module.class.getName()));
}
return (Class<? extends Module>) clazz;
}
@@ -141,7 +152,7 @@
private static Manifest getPluginManifest(PluginContentScanner scanner)
throws InvalidPluginException {
try {
- return scanner.getManifest();
+ return scanner.getManifest();
} catch (IOException e) {
throw new InvalidPluginException("Cannot get plugin manifest", e);
}
@@ -163,9 +174,9 @@
} else if ("restart".equalsIgnoreCase(v)) {
return false;
} else {
- PluginLoader.log.warn(String.format(
- "Plugin %s has invalid Gerrit-ReloadMode %s; assuming restart",
- getName(), v));
+ PluginLoader.log.warn(
+ String.format(
+ "Plugin %s has invalid Gerrit-ReloadMode %s; assuming restart", getName(), v));
return false;
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/ServerPluginInfoModule.java b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/ServerPluginInfoModule.java
index ff89cef4..639b278 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/ServerPluginInfoModule.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/ServerPluginInfoModule.java
@@ -24,7 +24,6 @@
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.ProvisionException;
-
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
@@ -46,24 +45,24 @@
@Override
protected void configure() {
bind(PluginUser.class).toInstance(plugin.getPluginUser());
+ bind(String.class).annotatedWith(PluginName.class).toInstance(plugin.getName());
bind(String.class)
- .annotatedWith(PluginName.class)
- .toInstance(plugin.getName());
- bind(String.class)
- .annotatedWith(PluginCanonicalWebUrl.class)
- .toInstance(plugin.getPluginCanonicalWebUrl());
+ .annotatedWith(PluginCanonicalWebUrl.class)
+ .toInstance(plugin.getPluginCanonicalWebUrl());
- install(new LifecycleModule() {
- @Override
- public void configure() {
- PluginMetricMaker metrics = new PluginMetricMaker(
- serverMetrics,
- MoreObjects.firstNonNull(plugin.getMetricsPrefix(),
- String.format("plugins/%s/", plugin.getName())));
- bind(MetricMaker.class).toInstance(metrics);
- listener().toInstance(metrics);
- }
- });
+ install(
+ new LifecycleModule() {
+ @Override
+ public void configure() {
+ PluginMetricMaker metrics =
+ new PluginMetricMaker(
+ serverMetrics,
+ MoreObjects.firstNonNull(
+ plugin.getMetricsPrefix(), String.format("plugins/%s/", plugin.getName())));
+ bind(MetricMaker.class).toInstance(metrics);
+ listener().toInstance(metrics);
+ }
+ });
}
@Provides
@@ -75,9 +74,10 @@
try {
Files.createDirectories(dataDir);
} catch (IOException e) {
- throw new ProvisionException(String.format(
- "Cannot create %s for plugin %s",
- dataDir.toAbsolutePath(), plugin.getName()), e);
+ throw new ProvisionException(
+ String.format(
+ "Cannot create %s for plugin %s", dataDir.toAbsolutePath(), plugin.getName()),
+ e);
}
ready = true;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/ServerPluginProvider.java b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/ServerPluginProvider.java
index 068d73c..632f838 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/ServerPluginProvider.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/ServerPluginProvider.java
@@ -16,27 +16,22 @@
import com.google.gerrit.extensions.annotations.ExtensionPoint;
import com.google.gerrit.server.PluginUser;
-
-import org.eclipse.jgit.internal.storage.file.FileSnapshot;
-
import java.nio.file.Path;
+import org.eclipse.jgit.internal.storage.file.FileSnapshot;
/**
* Provider of one Server plugin from one external file
*
- * Allows to load one plugin from one external file or
- * one directory by declaring the ability to handle it.
+ * <p>Allows to load one plugin from one external file or one directory by declaring the ability to
+ * handle it.
*
- * In order to load multiple files into a single plugin,
- * group them into a directory tree and then load the directory
- * root as a single plugin.
+ * <p>In order to load multiple files into a single plugin, group them into a directory tree and
+ * then load the directory root as a single plugin.
*/
@ExtensionPoint
public interface ServerPluginProvider {
- /**
- * Descriptor of the Plugin that ServerPluginProvider has to load.
- */
+ /** Descriptor of the Plugin that ServerPluginProvider has to load. */
class PluginDescription {
public final PluginUser user;
public final String canonicalUrl;
@@ -67,10 +62,9 @@
/**
* Returns the plugin name of an external file or directory
*
- * Should be called only if {@link #handles(Path) handles(srcFile)}
- * returns true and thus srcFile is a supported plugin format.
- * An IllegalArgumentException is thrown otherwise as srcFile
- * is not a valid file format for extracting its plugin name.
+ * <p>Should be called only if {@link #handles(Path) handles(srcFile)} returns true and thus
+ * srcFile is a supported plugin format. An IllegalArgumentException is thrown otherwise as
+ * srcFile is not a valid file format for extracting its plugin name.
*
* @param srcPath external file or directory
* @return plugin name
@@ -80,26 +74,24 @@
/**
* Loads an external file or directory into a Server plugin.
*
- * Should be called only if {@link #handles(Path) handles(srcFile)}
- * returns true and thus srcFile is a supported plugin format.
- * An IllegalArgumentException is thrown otherwise as srcFile
- * is not a valid file format for extracting its plugin name.
+ * <p>Should be called only if {@link #handles(Path) handles(srcFile)} returns true and thus
+ * srcFile is a supported plugin format. An IllegalArgumentException is thrown otherwise as
+ * srcFile is not a valid file format for extracting its plugin name.
*
* @param srcPath external file or directory
* @param snapshot snapshot of the external file
* @param pluginDescriptor descriptor of the ServerPlugin to load
- * @throws InvalidPluginException if plugin is supposed to be handled
- * but cannot be loaded for any other reason
+ * @throws InvalidPluginException if plugin is supposed to be handled but cannot be loaded for any
+ * other reason
*/
- ServerPlugin get(Path srcPath, FileSnapshot snapshot,
- PluginDescription pluginDescriptor) throws InvalidPluginException;
+ ServerPlugin get(Path srcPath, FileSnapshot snapshot, PluginDescription pluginDescriptor)
+ throws InvalidPluginException;
/**
* Returns the plugin name of this provider.
*
- * Allows to identify which plugin provided the current ServerPluginProvider
- * by returning the plugin name. Helpful for troubleshooting plugin loading
- * problems.
+ * <p>Allows to identify which plugin provided the current ServerPluginProvider by returning the
+ * plugin name. Helpful for troubleshooting plugin loading problems.
*
* @return plugin name of this provider
*/
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/TestServerPlugin.java b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/TestServerPlugin.java
index 98cd3d2..6897b9a 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/TestServerPlugin.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/TestServerPlugin.java
@@ -22,9 +22,14 @@
private String httpName;
private String sshName;
- public TestServerPlugin(String name, String pluginCanonicalWebUrl,
- PluginUser user, ClassLoader classloader, String sysName,
- String httpName, String sshName)
+ public TestServerPlugin(
+ String name,
+ String pluginCanonicalWebUrl,
+ PluginUser user,
+ ClassLoader classloader,
+ String sysName,
+ String httpName,
+ String sshName)
throws InvalidPluginException {
super(name, pluginCanonicalWebUrl, user, null, null, null, null, classloader);
this.classLoader = classloader;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/UniversalServerPluginProvider.java b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/UniversalServerPluginProvider.java
index afdc5b3..91441d8 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/plugins/UniversalServerPluginProvider.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/plugins/UniversalServerPluginProvider.java
@@ -17,14 +17,12 @@
import com.google.gerrit.extensions.registration.DynamicSet;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.internal.storage.file.FileSnapshot;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
+import org.eclipse.jgit.internal.storage.file.FileSnapshot;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
@Singleton
class UniversalServerPluginProvider implements ServerPluginProvider {
@@ -38,8 +36,8 @@
}
@Override
- public ServerPlugin get(Path srcPath, FileSnapshot snapshot,
- PluginDescription pluginDescription) throws InvalidPluginException {
+ public ServerPlugin get(Path srcPath, FileSnapshot snapshot, PluginDescription pluginDescription)
+ throws InvalidPluginException {
return providerOf(srcPath).get(srcPath, snapshot, pluginDescription);
}
@@ -67,8 +65,7 @@
}
private ServerPluginProvider providerOf(Path srcPath) {
- List<ServerPluginProvider> providers =
- providersForHandlingPlugin(srcPath);
+ List<ServerPluginProvider> providers = providersForHandlingPlugin(srcPath);
switch (providers.size()) {
case 1:
return providers.get(0);
@@ -81,13 +78,15 @@
}
}
- private List<ServerPluginProvider> providersForHandlingPlugin(
- final Path srcPath) {
+ private List<ServerPluginProvider> providersForHandlingPlugin(final Path srcPath) {
List<ServerPluginProvider> providers = new ArrayList<>();
for (ServerPluginProvider serverPluginProvider : serverPluginProviders) {
boolean handles = serverPluginProvider.handles(srcPath);
- log.debug("File {} handled by {} ? => {}", srcPath,
- serverPluginProvider.getProviderPluginName(), handles);
+ log.debug(
+ "File {} handled by {} ? => {}",
+ srcPath,
+ serverPluginProvider.getProviderPluginName(),
+ handles);
if (handles) {
providers.add(serverPluginProvider);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/AccessControlModule.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/AccessControlModule.java
index 8e85fd0..5c0d8d7 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/AccessControlModule.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/AccessControlModule.java
@@ -27,16 +27,15 @@
import com.google.gerrit.server.config.GitUploadPackGroups;
import com.google.gerrit.server.config.GitUploadPackGroupsProvider;
import com.google.inject.TypeLiteral;
-
import java.util.Set;
public class AccessControlModule extends FactoryModule {
@Override
protected void configure() {
bind(new TypeLiteral<ImmutableSet<GroupReference>>() {})
- .annotatedWith(AdministrateServerGroups.class)
- .toProvider(AdministrateServerGroupsProvider.class)
- .in(SINGLETON);
+ .annotatedWith(AdministrateServerGroups.class)
+ .toProvider(AdministrateServerGroupsProvider.class)
+ .in(SINGLETON);
bind(new TypeLiteral<Set<AccountGroup.UUID>>() {})
.annotatedWith(GitUploadPackGroups.class)
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/BanCommit.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/BanCommit.java
index ce97a83..41e8fbc 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/BanCommit.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/BanCommit.java
@@ -24,13 +24,11 @@
import com.google.gerrit.server.project.BanCommit.Input;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.api.errors.ConcurrentRefUpdateException;
-import org.eclipse.jgit.lib.ObjectId;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
+import org.eclipse.jgit.api.errors.ConcurrentRefUpdateException;
+import org.eclipse.jgit.lib.ObjectId;
@Singleton
public class BanCommit implements RestModifyView<ProjectResource, Input> {
@@ -58,8 +56,7 @@
@Override
public BanResultInfo apply(ProjectResource rsrc, Input input)
- throws UnprocessableEntityException, AuthException,
- ResourceConflictException, IOException {
+ throws UnprocessableEntityException, AuthException, ResourceConflictException, IOException {
BanResultInfo r = new BanResultInfo();
if (input != null && input.commits != null && !input.commits.isEmpty()) {
List<ObjectId> commitsToBan = new ArrayList<>(input.commits.size());
@@ -72,8 +69,7 @@
}
try {
- BanCommitResult result =
- banCommit.ban(rsrc.getControl(), commitsToBan, input.reason);
+ BanCommitResult result = banCommit.ban(rsrc.getControl(), commitsToBan, input.reason);
r.newlyBanned = transformCommits(result.getNewlyBannedCommits());
r.alreadyBanned = transformCommits(result.getAlreadyBannedCommits());
r.ignored = transformCommits(result.getIgnoredObjectIds());
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/BranchesCollection.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/BranchesCollection.java
index 41d4920..6867dce 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/BranchesCollection.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/BranchesCollection.java
@@ -26,23 +26,22 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.lib.Constants;
-
import java.io.IOException;
import java.util.List;
+import org.eclipse.jgit.lib.Constants;
@Singleton
-public class BranchesCollection implements
- ChildCollection<ProjectResource, BranchResource>,
- AcceptsCreate<ProjectResource> {
+public class BranchesCollection
+ implements ChildCollection<ProjectResource, BranchResource>, AcceptsCreate<ProjectResource> {
private final DynamicMap<RestView<BranchResource>> views;
private final Provider<ListBranches> list;
private final CreateBranch.Factory createBranchFactory;
@Inject
- BranchesCollection(DynamicMap<RestView<BranchResource>> views,
- Provider<ListBranches> list, CreateBranch.Factory createBranchFactory) {
+ BranchesCollection(
+ DynamicMap<RestView<BranchResource>> views,
+ Provider<ListBranches> list,
+ CreateBranch.Factory createBranchFactory) {
this.views = views;
this.list = list;
this.createBranchFactory = createBranchFactory;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/ChangeControl.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/ChangeControl.java
index 68debb9..aa28843 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/ChangeControl.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/ChangeControl.java
@@ -36,12 +36,10 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
import java.io.IOException;
import java.util.Collection;
import java.util.List;
-
/** Access control management for a user accessing a single change. */
public class ChangeControl {
@Singleton
@@ -50,24 +48,22 @@
private final ChangeNotes.Factory notesFactory;
@Inject
- GenericFactory(
- ProjectControl.GenericFactory p,
- ChangeNotes.Factory n) {
+ GenericFactory(ProjectControl.GenericFactory p, ChangeNotes.Factory n) {
projectControl = p;
notesFactory = n;
}
- public ChangeControl controlFor(ReviewDb db, Project.NameKey project,
- Change.Id changeId, CurrentUser user) throws OrmException {
+ public ChangeControl controlFor(
+ ReviewDb db, Project.NameKey project, Change.Id changeId, CurrentUser user)
+ throws OrmException {
return controlFor(notesFactory.create(db, project, changeId), user);
}
- public ChangeControl controlFor(ReviewDb db, Change change,
- CurrentUser user) throws OrmException {
+ public ChangeControl controlFor(ReviewDb db, Change change, CurrentUser user)
+ throws OrmException {
final Project.NameKey projectKey = change.getProject();
try {
- return projectControl.controlFor(projectKey, user)
- .controlFor(db, change);
+ return projectControl.controlFor(projectKey, user).controlFor(db, change);
} catch (NoSuchProjectException e) {
throw new NoSuchChangeException(change.getId(), e);
} catch (IOException e) {
@@ -79,20 +75,19 @@
public ChangeControl controlFor(ChangeNotes notes, CurrentUser user)
throws NoSuchChangeException {
try {
- return projectControl.controlFor(notes.getProjectName(), user)
- .controlFor(notes);
+ return projectControl.controlFor(notes.getProjectName(), user).controlFor(notes);
} catch (NoSuchProjectException | IOException e) {
throw new NoSuchChangeException(notes.getChangeId(), e);
}
}
- public ChangeControl validateFor(ReviewDb db, Change.Id changeId,
- CurrentUser user) throws OrmException {
+ public ChangeControl validateFor(ReviewDb db, Change.Id changeId, CurrentUser user)
+ throws OrmException {
return validateFor(db, notesFactory.createChecked(changeId), user);
}
- public ChangeControl validateFor(ReviewDb db, ChangeNotes notes,
- CurrentUser user) throws OrmException {
+ public ChangeControl validateFor(ReviewDb db, ChangeNotes notes, CurrentUser user)
+ throws OrmException {
ChangeControl c = controlFor(notes, user);
if (!c.isVisible(db)) {
throw new NoSuchChangeException(c.getId());
@@ -109,7 +104,8 @@
private final PatchSetUtil patchSetUtil;
@Inject
- Factory(ChangeData.Factory changeDataFactory,
+ Factory(
+ ChangeData.Factory changeDataFactory,
ChangeNotes.Factory notesFactory,
ApprovalsUtil approvalsUtil,
PatchSetUtil patchSetUtil) {
@@ -119,16 +115,15 @@
this.patchSetUtil = patchSetUtil;
}
- ChangeControl create(RefControl refControl, ReviewDb db, Project.NameKey
- project, Change.Id changeId) throws OrmException {
- return create(refControl,
- notesFactory.create(db, project, changeId));
+ ChangeControl create(
+ RefControl refControl, ReviewDb db, Project.NameKey project, Change.Id changeId)
+ throws OrmException {
+ return create(refControl, notesFactory.create(db, project, changeId));
}
/**
- * Create a change control for a change that was loaded from index. This
- * method should only be used when database access is harmful and potentially
- * stale data from the index is acceptable.
+ * Create a change control for a change that was loaded from index. This method should only be
+ * used when database access is harmful and potentially stale data from the index is acceptable.
*
* @param refControl ref control
* @param change change loaded from secondary index
@@ -139,8 +134,7 @@
}
ChangeControl create(RefControl refControl, ChangeNotes notes) {
- return new ChangeControl(changeDataFactory, approvalsUtil, refControl,
- notes, patchSetUtil);
+ return new ChangeControl(changeDataFactory, approvalsUtil, refControl, notes, patchSetUtil);
}
}
@@ -167,8 +161,8 @@
if (getUser().equals(who)) {
return this;
}
- return new ChangeControl(changeDataFactory, approvalsUtil,
- getRefControl().forUser(who), notes, patchSetUtil);
+ return new ChangeControl(
+ changeDataFactory, approvalsUtil, getRefControl().forUser(who), notes, patchSetUtil);
}
public RefControl getRefControl() {
@@ -205,10 +199,8 @@
}
/** Can this user see this change? */
- public boolean isVisible(ReviewDb db, @Nullable ChangeData cd)
- throws OrmException {
- if (getChange().getStatus() == Change.Status.DRAFT
- && !isDraftVisible(db, cd)) {
+ public boolean isVisible(ReviewDb db, @Nullable ChangeData cd) throws OrmException {
+ if (getChange().getStatus() == Change.Status.DRAFT && !isDraftVisible(db, cd)) {
return false;
}
return isRefVisible();
@@ -228,10 +220,9 @@
}
/** Can this user see the given patchset? */
- public boolean isPatchVisible(PatchSet ps, ChangeData cd)
- throws OrmException {
- checkArgument(cd.getId().equals(ps.getId().getParentKey()),
- "%s not for change %s", ps, cd.getId());
+ public boolean isPatchVisible(PatchSet ps, ChangeData cd) throws OrmException {
+ checkArgument(
+ cd.getId().equals(ps.getId().getParentKey()), "%s not for change %s", ps, cd.getId());
if (ps.isDraft() && !isDraftVisible(cd.db(), cd)) {
return false;
}
@@ -241,28 +232,26 @@
/** Can this user abandon this change? */
public boolean canAbandon(ReviewDb db) throws OrmException {
return (isOwner() // owner (aka creator) of the change can abandon
- || getRefControl().isOwner() // branch owner can abandon
- || getProjectControl().isOwner() // project owner can abandon
- || getUser().getCapabilities().canAdministrateServer() // site administers are god
- || getRefControl().canAbandon() // user can abandon a specific ref
- ) && !isPatchSetLocked(db);
+ || getRefControl().isOwner() // branch owner can abandon
+ || getProjectControl().isOwner() // project owner can abandon
+ || getUser().getCapabilities().canAdministrateServer() // site administers are god
+ || getRefControl().canAbandon() // user can abandon a specific ref
+ )
+ && !isPatchSetLocked(db);
}
- /** Can this user change the destination branch of this change
- to the new ref? */
+ /** Can this user change the destination branch of this change to the new ref? */
public boolean canMoveTo(String ref, ReviewDb db) throws OrmException {
return getProjectControl().controlForRef(ref).canUpload() && canAbandon(db);
}
/** Can this user publish this draft change or any draft patch set of this change? */
public boolean canPublish(final ReviewDb db) throws OrmException {
- return (isOwner() || getRefControl().canPublishDrafts())
- && isVisible(db);
+ return (isOwner() || getRefControl().canPublishDrafts()) && isVisible(db);
}
/** Can this user delete this change or any patch set of this change? */
- public boolean canDelete(ReviewDb db, Change.Status status)
- throws OrmException {
+ public boolean canDelete(ReviewDb db, Change.Status status) throws OrmException {
if (!isVisible(db)) {
return false;
}
@@ -281,8 +270,8 @@
/** Can this user rebase this change? */
public boolean canRebase(ReviewDb db) throws OrmException {
- return (isOwner() || getRefControl().canSubmit(isOwner())
- || getRefControl().canRebase()) && !isPatchSetLocked(db);
+ return (isOwner() || getRefControl().canSubmit(isOwner()) || getRefControl().canRebase())
+ && !isPatchSetLocked(db);
}
/** Can this user restore this change? */
@@ -303,8 +292,7 @@
r.add(l);
} else {
for (String refPattern : refs) {
- if (RefConfigSection.isValid(refPattern)
- && match(destBranch, refPattern)) {
+ if (RefConfigSection.isValid(refPattern) && match(destBranch, refPattern)) {
r.add(l);
break;
}
@@ -344,10 +332,11 @@
return false;
}
- for (PatchSetApproval ap : approvalsUtil.byPatchSet(db, this,
- getChange().currentPatchSetId())) {
+ for (PatchSetApproval ap :
+ approvalsUtil.byPatchSet(db, this, getChange().currentPatchSetId())) {
LabelType type = getLabelTypes().byLabel(ap.getLabel());
- if (type != null && ap.getValue() == 1
+ if (type != null
+ && ap.getValue() == 1
&& type.getFunctionName().equalsIgnoreCase("PatchSetLock")) {
return true;
}
@@ -380,8 +369,7 @@
}
/** Is this user a reviewer for the change? */
- public boolean isReviewer(ReviewDb db, @Nullable ChangeData cd)
- throws OrmException {
+ public boolean isReviewer(ReviewDb db, @Nullable ChangeData cd) throws OrmException {
if (getUser().isIdentifiedUser()) {
Collection<Account.Id> results = changeData(db, cd).reviewers().all();
return results.contains(getUser().getAccountId());
@@ -462,10 +450,10 @@
/** Can this user edit the hashtag name? */
public boolean canEditHashtags() {
return isOwner() // owner (aka creator) of the change can edit hashtags
- || getRefControl().isOwner() // branch owner can edit hashtags
- || getProjectControl().isOwner() // project owner can edit hashtags
- || getUser().getCapabilities().canAdministrateServer() // site administers are god
- || getRefControl().canEditHashtags(); // user can edit hashtag on a specific ref
+ || getRefControl().isOwner() // branch owner can edit hashtags
+ || getProjectControl().isOwner() // project owner can edit hashtags
+ || getUser().getCapabilities().canAdministrateServer() // site administers are god
+ || getRefControl().canEditHashtags(); // user can edit hashtag on a specific ref
}
public boolean canSubmit() {
@@ -477,17 +465,17 @@
}
private boolean match(String destBranch, String refPattern) {
- return RefPatternMatcher.getMatcher(refPattern).match(destBranch,
- getUser());
+ return RefPatternMatcher.getMatcher(refPattern).match(destBranch, getUser());
}
private ChangeData changeData(ReviewDb db, @Nullable ChangeData cd) {
return cd != null ? cd : changeDataFactory.create(db, this);
}
- public boolean isDraftVisible(ReviewDb db, ChangeData cd)
- throws OrmException {
- return isOwner() || isReviewer(db, cd) || getRefControl().canViewDrafts()
+ public boolean isDraftVisible(ReviewDb db, ChangeData cd) throws OrmException {
+ return isOwner()
+ || isReviewer(db, cd)
+ || getRefControl().canViewDrafts()
|| getUser().isInternalUser();
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/CheckMergeability.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/CheckMergeability.java
index 37d5295..b704fc8 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/CheckMergeability.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/CheckMergeability.java
@@ -26,7 +26,7 @@
import com.google.gerrit.server.git.MergeUtil;
import com.google.inject.Inject;
import com.google.inject.Provider;
-
+import java.io.IOException;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.lib.ObjectInserter;
import org.eclipse.jgit.lib.Ref;
@@ -37,11 +37,7 @@
import org.eclipse.jgit.revwalk.RevWalk;
import org.kohsuke.args4j.Option;
-import java.io.IOException;
-
-/**
- * Check the mergeability at current branch for a git object references expression.
- */
+/** Check the mergeability at current branch for a git object references expression. */
public class CheckMergeability implements RestReadView<BranchResource> {
private String source;
@@ -49,18 +45,24 @@
private SubmitType submitType;
private final Provider<ReviewDb> db;
- @Option(name = "--source", metaVar = "COMMIT",
- usage = "the source reference to merge, which could be any git object "
- + "references expression, refer to "
- + "org.eclipse.jgit.lib.Repository#resolve(String)",
- required = true)
+ @Option(
+ name = "--source",
+ metaVar = "COMMIT",
+ usage =
+ "the source reference to merge, which could be any git object "
+ + "references expression, refer to "
+ + "org.eclipse.jgit.lib.Repository#resolve(String)",
+ required = true
+ )
public void setSource(String source) {
this.source = source;
}
- @Option(name = "--strategy", metaVar = "STRATEGY",
- usage = "name of the merge strategy, refer to "
- + "org.eclipse.jgit.merge.MergeStrategy")
+ @Option(
+ name = "--strategy",
+ metaVar = "STRATEGY",
+ usage = "name of the merge strategy, refer to " + "org.eclipse.jgit.merge.MergeStrategy"
+ )
public void setStrategy(String strategy) {
this.strategy = strategy;
}
@@ -68,31 +70,28 @@
private final GitRepositoryManager gitManager;
@Inject
- CheckMergeability(GitRepositoryManager gitManager,
- @GerritServerConfig Config cfg,
- Provider<ReviewDb> db) {
+ CheckMergeability(
+ GitRepositoryManager gitManager, @GerritServerConfig Config cfg, Provider<ReviewDb> db) {
this.gitManager = gitManager;
this.strategy = MergeUtil.getMergeStrategy(cfg).getName();
- this.submitType = cfg.getEnum("project", null, "submitType",
- SubmitType.MERGE_IF_NECESSARY);
+ this.submitType = cfg.getEnum("project", null, "submitType", SubmitType.MERGE_IF_NECESSARY);
this.db = db;
}
@Override
public MergeableInfo apply(BranchResource resource)
throws IOException, BadRequestException, ResourceNotFoundException {
- if (!(submitType.equals(SubmitType.MERGE_ALWAYS) ||
- submitType.equals(SubmitType.MERGE_IF_NECESSARY))) {
- throw new BadRequestException(
- "Submit type: " + submitType + " is not supported");
+ if (!(submitType.equals(SubmitType.MERGE_ALWAYS)
+ || submitType.equals(SubmitType.MERGE_IF_NECESSARY))) {
+ throw new BadRequestException("Submit type: " + submitType + " is not supported");
}
MergeableInfo result = new MergeableInfo();
result.submitType = submitType;
result.strategy = strategy;
try (Repository git = gitManager.openRepository(resource.getNameKey());
- RevWalk rw = new RevWalk(git);
- ObjectInserter inserter = new InMemoryInserter(git)) {
+ RevWalk rw = new RevWalk(git);
+ ObjectInserter inserter = new InMemoryInserter(git)) {
Merger m = MergeUtil.newMerger(git, inserter, strategy);
Ref destRef = git.getRefDatabase().exactRef(resource.getRef());
@@ -104,8 +103,7 @@
RevCommit sourceCommit = MergeUtil.resolveCommit(git, rw, source);
if (!resource.getControl().canReadCommit(db.get(), git, sourceCommit)) {
- throw new BadRequestException(
- "do not have read permission for: " + source);
+ throw new BadRequestException("do not have read permission for: " + source);
}
if (rw.isMergedInto(sourceCommit, targetCommit)) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/ChildProjectResource.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/ChildProjectResource.java
index 4257825..f0d127d 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/ChildProjectResource.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/ChildProjectResource.java
@@ -40,9 +40,7 @@
}
public boolean isDirectChild() {
- ProjectState firstParent =
- Iterables.getFirst(child.getProjectState().parents(), null);
- return firstParent != null
- && parent.getNameKey().equals(firstParent.getProject().getNameKey());
+ ProjectState firstParent = Iterables.getFirst(child.getProjectState().parents(), null);
+ return firstParent != null && parent.getNameKey().equals(firstParent.getProject().getNameKey());
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/ChildProjectsCollection.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/ChildProjectsCollection.java
index faba87a..7aa5f68 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/ChildProjectsCollection.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/ChildProjectsCollection.java
@@ -24,18 +24,18 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.io.IOException;
@Singleton
-public class ChildProjectsCollection implements
- ChildCollection<ProjectResource, ChildProjectResource> {
+public class ChildProjectsCollection
+ implements ChildCollection<ProjectResource, ChildProjectResource> {
private final Provider<ListChildProjects> list;
private final ProjectsCollection projectsCollection;
private final DynamicMap<RestView<ChildProjectResource>> views;
@Inject
- ChildProjectsCollection(Provider<ListChildProjects> list,
+ ChildProjectsCollection(
+ Provider<ListChildProjects> list,
ProjectsCollection projectsCollection,
DynamicMap<RestView<ChildProjectResource>> views) {
this.list = list;
@@ -44,16 +44,14 @@
}
@Override
- public ListChildProjects list() throws ResourceNotFoundException,
- AuthException {
+ public ListChildProjects list() throws ResourceNotFoundException, AuthException {
return list.get();
}
@Override
public ChildProjectResource parse(ProjectResource parent, IdString id)
throws ResourceNotFoundException, IOException {
- ProjectResource p =
- projectsCollection.parse(TopLevelResource.INSTANCE, id);
+ ProjectResource p = projectsCollection.parse(TopLevelResource.INSTANCE, id);
for (ProjectState pp : p.getControl().getProjectState().parents()) {
if (parent.getNameKey().equals(pp.getProject().getNameKey())) {
return new ChildProjectResource(parent, p.getControl());
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/CommentLinkInfoImpl.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/CommentLinkInfoImpl.java
index ef5af20..35de963 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/CommentLinkInfoImpl.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/CommentLinkInfoImpl.java
@@ -43,16 +43,15 @@
}
}
- public CommentLinkInfoImpl(String name, String match, String link, String html,
- Boolean enabled) {
+ public CommentLinkInfoImpl(String name, String match, String link, String html, Boolean enabled) {
checkArgument(name != null, "invalid commentlink.name");
- checkArgument(!Strings.isNullOrEmpty(match),
- "invalid commentlink.%s.match", name);
+ checkArgument(!Strings.isNullOrEmpty(match), "invalid commentlink.%s.match", name);
link = Strings.emptyToNull(link);
html = Strings.emptyToNull(html);
checkArgument(
(link != null && html == null) || (link == null && html != null),
- "commentlink.%s must have either link or html", name);
+ "commentlink.%s must have either link or html",
+ name);
this.name = name;
this.match = match;
this.link = link;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/CommentLinkProvider.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/CommentLinkProvider.java
index f151b59..0d2452c 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/CommentLinkProvider.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/CommentLinkProvider.java
@@ -21,17 +21,14 @@
import com.google.gerrit.server.git.ProjectConfig;
import com.google.inject.Inject;
import com.google.inject.Provider;
-
+import java.util.List;
+import java.util.Set;
import org.eclipse.jgit.lib.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.util.List;
-import java.util.Set;
-
public class CommentLinkProvider implements Provider<List<CommentLinkInfo>> {
- private static final Logger log =
- LoggerFactory.getLogger(CommentLinkProvider.class);
+ private static final Logger log = LoggerFactory.getLogger(CommentLinkProvider.class);
private final Config cfg;
@@ -43,8 +40,7 @@
@Override
public List<CommentLinkInfo> get() {
Set<String> subsections = cfg.getSubsections(ProjectConfig.COMMENTLINK);
- List<CommentLinkInfo> cls =
- Lists.newArrayListWithCapacity(subsections.size());
+ List<CommentLinkInfo> cls = Lists.newArrayListWithCapacity(subsections.size());
for (String name : subsections) {
try {
CommentLinkInfoImpl cl = ProjectConfig.buildCommentLink(cfg, name, true);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/CommitIncludedIn.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/CommitIncludedIn.java
index 297f138..8d9127b 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/CommitIncludedIn.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/CommitIncludedIn.java
@@ -22,10 +22,8 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.revwalk.RevCommit;
-
import java.io.IOException;
+import org.eclipse.jgit.revwalk.RevCommit;
@Singleton
class CommitIncludedIn implements RestReadView<CommitResource> {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/CommitResource.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/CommitResource.java
index 36186a4..8065e0f 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/CommitResource.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/CommitResource.java
@@ -17,7 +17,6 @@
import com.google.gerrit.extensions.restapi.RestResource;
import com.google.gerrit.extensions.restapi.RestView;
import com.google.inject.TypeLiteral;
-
import org.eclipse.jgit.revwalk.RevCommit;
public class CommitResource implements RestResource {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/CommitsCollection.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/CommitsCollection.java
index 3deb7d6b..d481c014 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/CommitsCollection.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/CommitsCollection.java
@@ -24,7 +24,7 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
+import java.io.IOException;
import org.eclipse.jgit.errors.IncorrectObjectTypeException;
import org.eclipse.jgit.errors.MissingObjectException;
import org.eclipse.jgit.lib.ObjectId;
@@ -32,17 +32,15 @@
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;
-import java.io.IOException;
-
@Singleton
-public class CommitsCollection implements
- ChildCollection<ProjectResource, CommitResource> {
+public class CommitsCollection implements ChildCollection<ProjectResource, CommitResource> {
private final DynamicMap<RestView<CommitResource>> views;
private final GitRepositoryManager repoManager;
private final Provider<ReviewDb> db;
@Inject
- public CommitsCollection(DynamicMap<RestView<CommitResource>> views,
+ public CommitsCollection(
+ DynamicMap<RestView<CommitResource>> views,
GitRepositoryManager repoManager,
Provider<ReviewDb> db) {
this.views = views;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/ConfigInfoImpl.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/ConfigInfoImpl.java
index a7ba217..2f02728 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/ConfigInfoImpl.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/ConfigInfoImpl.java
@@ -32,14 +32,14 @@
import com.google.gerrit.server.extensions.webui.UiActions;
import com.google.gerrit.server.git.TransferConfig;
import com.google.inject.util.Providers;
-
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;
public class ConfigInfoImpl extends ConfigInfo {
- public ConfigInfoImpl(boolean serverEnableSignedPush,
+ public ConfigInfoImpl(
+ boolean serverEnableSignedPush,
ProjectControl control,
TransferConfig config,
DynamicMap<ProjectConfigEntry> pluginConfigEntries,
@@ -50,13 +50,11 @@
Project p = control.getProject();
this.description = Strings.emptyToNull(p.getDescription());
- InheritedBooleanInfo useContributorAgreements =
- new InheritedBooleanInfo();
+ InheritedBooleanInfo useContributorAgreements = new InheritedBooleanInfo();
InheritedBooleanInfo useSignedOffBy = new InheritedBooleanInfo();
InheritedBooleanInfo useContentMerge = new InheritedBooleanInfo();
InheritedBooleanInfo requireChangeId = new InheritedBooleanInfo();
- InheritedBooleanInfo createNewChangeForAllNotInTarget =
- new InheritedBooleanInfo();
+ InheritedBooleanInfo createNewChangeForAllNotInTarget = new InheritedBooleanInfo();
InheritedBooleanInfo enableSignedPush = new InheritedBooleanInfo();
InheritedBooleanInfo requireSignedPush = new InheritedBooleanInfo();
InheritedBooleanInfo rejectImplicitMerges = new InheritedBooleanInfo();
@@ -65,25 +63,20 @@
useSignedOffBy.value = projectState.isUseSignedOffBy();
useContentMerge.value = projectState.isUseContentMerge();
requireChangeId.value = projectState.isRequireChangeID();
- createNewChangeForAllNotInTarget.value =
- projectState.isCreateNewChangeForAllNotInTarget();
+ createNewChangeForAllNotInTarget.value = projectState.isCreateNewChangeForAllNotInTarget();
- useContributorAgreements.configuredValue =
- p.getUseContributorAgreements();
+ useContributorAgreements.configuredValue = p.getUseContributorAgreements();
useSignedOffBy.configuredValue = p.getUseSignedOffBy();
useContentMerge.configuredValue = p.getUseContentMerge();
requireChangeId.configuredValue = p.getRequireChangeID();
- createNewChangeForAllNotInTarget.configuredValue =
- p.getCreateNewChangeForAllNotInTarget();
+ createNewChangeForAllNotInTarget.configuredValue = p.getCreateNewChangeForAllNotInTarget();
enableSignedPush.configuredValue = p.getEnableSignedPush();
requireSignedPush.configuredValue = p.getRequireSignedPush();
rejectImplicitMerges.configuredValue = p.getRejectImplicitMerges();
- ProjectState parentState = Iterables.getFirst(projectState
- .parents(), null);
+ ProjectState parentState = Iterables.getFirst(projectState.parents(), null);
if (parentState != null) {
- useContributorAgreements.inheritedValue =
- parentState.isUseContributorAgreements();
+ useContributorAgreements.inheritedValue = parentState.isUseContributorAgreements();
useSignedOffBy.inheritedValue = parentState.isUseSignedOffBy();
useContentMerge.inheritedValue = parentState.isUseContentMerge();
requireChangeId.inheritedValue = parentState.isRequireChangeID();
@@ -107,16 +100,18 @@
MaxObjectSizeLimitInfo maxObjectSizeLimit = new MaxObjectSizeLimitInfo();
maxObjectSizeLimit.value =
- config.getEffectiveMaxObjectSizeLimit(projectState) == config
- .getMaxObjectSizeLimit() ? config
- .getFormattedMaxObjectSizeLimit() : p.getMaxObjectSizeLimit();
+ config.getEffectiveMaxObjectSizeLimit(projectState) == config.getMaxObjectSizeLimit()
+ ? config.getFormattedMaxObjectSizeLimit()
+ : p.getMaxObjectSizeLimit();
maxObjectSizeLimit.configuredValue = p.getMaxObjectSizeLimit();
- maxObjectSizeLimit.inheritedValue =
- config.getFormattedMaxObjectSizeLimit();
+ maxObjectSizeLimit.inheritedValue = config.getFormattedMaxObjectSizeLimit();
this.maxObjectSizeLimit = maxObjectSizeLimit;
this.submitType = p.getSubmitType();
- this.state = p.getState() != com.google.gerrit.extensions.client.ProjectState.ACTIVE ? p.getState() : null;
+ this.state =
+ p.getState() != com.google.gerrit.extensions.client.ProjectState.ACTIVE
+ ? p.getState()
+ : null;
this.commentlinks = new LinkedHashMap<>();
for (CommentLinkInfo cl : projectState.getCommentLinks()) {
@@ -124,26 +119,25 @@
}
pluginConfig =
- getPluginConfig(control.getProjectState(), pluginConfigEntries,
- cfgFactory, allProjects);
+ getPluginConfig(control.getProjectState(), pluginConfigEntries, cfgFactory, allProjects);
actions = new TreeMap<>();
- for (UiAction.Description d : UiActions.from(
- views, new ProjectResource(control),
- Providers.of(control.getUser()))) {
+ for (UiAction.Description d :
+ UiActions.from(views, new ProjectResource(control), Providers.of(control.getUser()))) {
actions.put(d.getId(), new ActionInfo(d));
}
this.theme = projectState.getTheme();
}
private Map<String, Map<String, ConfigParameterInfo>> getPluginConfig(
- ProjectState project, DynamicMap<ProjectConfigEntry> pluginConfigEntries,
- PluginConfigFactory cfgFactory, AllProjectsName allProjects) {
+ ProjectState project,
+ DynamicMap<ProjectConfigEntry> pluginConfigEntries,
+ PluginConfigFactory cfgFactory,
+ AllProjectsName allProjects) {
TreeMap<String, Map<String, ConfigParameterInfo>> pluginConfig = new TreeMap<>();
for (Entry<ProjectConfigEntry> e : pluginConfigEntries) {
ProjectConfigEntry configEntry = e.getProvider().get();
- PluginConfig cfg =
- cfgFactory.getFromProjectConfig(project, e.getPluginName());
+ PluginConfig cfg = cfgFactory.getFromProjectConfig(project, e.getPluginName());
String configuredValue = cfg.getString(e.getExportName());
ConfigParameterInfo p = new ConfigParameterInfo();
p.displayName = configEntry.getDisplayName();
@@ -152,25 +146,25 @@
p.type = configEntry.getType();
p.permittedValues = configEntry.getPermittedValues();
p.editable = configEntry.isEditable(project) ? true : null;
- if (configEntry.isInheritable()
- && !allProjects.equals(project.getProject().getNameKey())) {
+ if (configEntry.isInheritable() && !allProjects.equals(project.getProject().getNameKey())) {
PluginConfig cfgWithInheritance =
- cfgFactory.getFromProjectConfigWithInheritance(project,
- e.getPluginName());
+ cfgFactory.getFromProjectConfigWithInheritance(project, e.getPluginName());
p.inheritable = true;
- p.value = configEntry.onRead(project,
- cfgWithInheritance.getString(e.getExportName(),
- configEntry.getDefaultValue()));
+ p.value =
+ configEntry.onRead(
+ project,
+ cfgWithInheritance.getString(e.getExportName(), configEntry.getDefaultValue()));
p.configuredValue = configuredValue;
p.inheritedValue = getInheritedValue(project, cfgFactory, e);
} else {
if (configEntry.getType() == ProjectConfigEntryType.ARRAY) {
- p.values = configEntry.onRead(project,
- Arrays.asList(cfg.getStringList(e.getExportName())));
+ p.values =
+ configEntry.onRead(project, Arrays.asList(cfg.getStringList(e.getExportName())));
} else {
- p.value = configEntry.onRead(project, configuredValue != null
- ? configuredValue
- : configEntry.getDefaultValue());
+ p.value =
+ configEntry.onRead(
+ project,
+ configuredValue != null ? configuredValue : configEntry.getDefaultValue());
}
}
Map<String, ConfigParameterInfo> pc = pluginConfig.get(e.getPluginName());
@@ -183,18 +177,16 @@
return !pluginConfig.isEmpty() ? pluginConfig : null;
}
- private String getInheritedValue(ProjectState project,
- PluginConfigFactory cfgFactory, Entry<ProjectConfigEntry> e) {
+ private String getInheritedValue(
+ ProjectState project, PluginConfigFactory cfgFactory, Entry<ProjectConfigEntry> e) {
ProjectConfigEntry configEntry = e.getProvider().get();
ProjectState parent = Iterables.getFirst(project.parents(), null);
String inheritedValue = configEntry.getDefaultValue();
if (parent != null) {
PluginConfig parentCfgWithInheritance =
- cfgFactory.getFromProjectConfigWithInheritance(parent,
- e.getPluginName());
+ cfgFactory.getFromProjectConfigWithInheritance(parent, e.getPluginName());
inheritedValue =
- parentCfgWithInheritance.getString(e.getExportName(),
- configEntry.getDefaultValue());
+ parentCfgWithInheritance.getString(e.getExportName(), configEntry.getDefaultValue());
}
return inheritedValue;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/CreateBranch.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/CreateBranch.java
index c7b2922..5919ba1 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/CreateBranch.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/CreateBranch.java
@@ -30,7 +30,7 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.assistedinject.Assisted;
-
+import java.io.IOException;
import org.eclipse.jgit.errors.IncorrectObjectTypeException;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.ObjectId;
@@ -42,8 +42,6 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-
public class CreateBranch implements RestModifyView<ProjectResource, BranchInput> {
private static final Logger log = LoggerFactory.getLogger(CreateBranch.class);
@@ -59,7 +57,8 @@
private String ref;
@Inject
- CreateBranch(Provider<IdentifiedUser> identifiedUser,
+ CreateBranch(
+ Provider<IdentifiedUser> identifiedUser,
GitRepositoryManager repoManager,
Provider<ReviewDb> db,
GitReferenceUpdated referenceUpdated,
@@ -69,15 +68,13 @@
this.repoManager = repoManager;
this.db = db;
this.referenceUpdated = referenceUpdated;
- this.refCreationValidator =
- refHelperFactory.create(ReceiveCommand.Type.CREATE);
+ this.refCreationValidator = refHelperFactory.create(ReceiveCommand.Type.CREATE);
this.ref = ref;
}
@Override
public BranchInfo apply(ProjectResource rsrc, BranchInput input)
- throws BadRequestException, AuthException, ResourceConflictException,
- IOException {
+ throws BadRequestException, AuthException, ResourceConflictException, IOException {
if (input == null) {
input = new BranchInput();
}
@@ -95,8 +92,10 @@
throw new BadRequestException("invalid branch name \"" + ref + "\"");
}
if (MagicBranch.isMagicBranch(ref)) {
- throw new BadRequestException("not allowed to create branches under \""
- + MagicBranch.getMagicRefNamePrefix(ref) + "\"");
+ throw new BadRequestException(
+ "not allowed to create branches under \""
+ + MagicBranch.getMagicRefNamePrefix(ref)
+ + "\"");
}
final Branch.NameKey name = new Branch.NameKey(rsrc.getNameKey(), ref);
@@ -127,28 +126,31 @@
u.setNewObjectId(object.copy());
u.setRefLogIdent(identifiedUser.get().newRefLogIdent());
u.setRefLogMessage("created via REST from " + input.revision, false);
- refCreationValidator.validateRefOperation(
- rsrc.getName(), identifiedUser.get(), u);
+ refCreationValidator.validateRefOperation(rsrc.getName(), identifiedUser.get(), u);
final RefUpdate.Result result = u.update(rw);
switch (result) {
case FAST_FORWARD:
case NEW:
case NO_CHANGE:
referenceUpdated.fire(
- name.getParentKey(), u, ReceiveCommand.Type.CREATE,
+ name.getParentKey(),
+ u,
+ ReceiveCommand.Type.CREATE,
identifiedUser.get().getAccount());
break;
case LOCK_FAILURE:
if (repo.getRefDatabase().exactRef(ref) != null) {
- throw new ResourceConflictException("branch \"" + ref
- + "\" already exists");
+ throw new ResourceConflictException("branch \"" + ref + "\" already exists");
}
String refPrefix = RefUtil.getRefPrefix(ref);
while (!Constants.R_HEADS.equals(refPrefix)) {
if (repo.getRefDatabase().exactRef(refPrefix) != null) {
- throw new ResourceConflictException("Cannot create branch \""
- + ref + "\" since it conflicts with branch \"" + refPrefix
- + "\".");
+ throw new ResourceConflictException(
+ "Cannot create branch \""
+ + ref
+ + "\" since it conflicts with branch \""
+ + refPrefix
+ + "\".");
}
refPrefix = RefUtil.getRefPrefix(refPrefix);
}
@@ -159,9 +161,10 @@
case REJECTED:
case REJECTED_CURRENT_BRANCH:
case RENAMED:
- default: {
- throw new IOException(result.name());
- }
+ default:
+ {
+ throw new IOException(result.name());
+ }
}
BranchInfo info = new BranchInfo();
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/CreateProject.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/CreateProject.java
index 4db1ccd..ff7e31e 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/CreateProject.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/CreateProject.java
@@ -60,7 +60,10 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.assistedinject.Assisted;
-
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
import org.eclipse.jgit.lib.CommitBuilder;
@@ -75,19 +78,13 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
@RequiresCapability(GlobalCapability.CREATE_PROJECT)
public class CreateProject implements RestModifyView<TopLevelResource, ProjectInput> {
public interface Factory {
CreateProject create(String name);
}
- private static final Logger log = LoggerFactory
- .getLogger(CreateProject.class);
+ private static final Logger log = LoggerFactory.getLogger(CreateProject.class);
private final Provider<ProjectsCollection> projectsCollection;
private final Provider<GroupsCollection> groupsCollection;
@@ -109,8 +106,10 @@
private final String name;
@Inject
- CreateProject(Provider<ProjectsCollection> projectsCollection,
- Provider<GroupsCollection> groupsCollection, ProjectJson json,
+ CreateProject(
+ Provider<ProjectsCollection> projectsCollection,
+ Provider<GroupsCollection> groupsCollection,
+ ProjectJson json,
DynamicSet<ProjectCreationValidationListener> projectCreationValidationListeners,
ProjectControl.GenericFactory projectControlFactory,
GitRepositoryManager repoManager,
@@ -147,10 +146,9 @@
}
@Override
- public Response<ProjectInfo> apply(TopLevelResource resource,
- ProjectInput input) throws BadRequestException,
- UnprocessableEntityException, ResourceConflictException,
- ResourceNotFoundException, IOException, ConfigInvalidException {
+ public Response<ProjectInfo> apply(TopLevelResource resource, ProjectInput input)
+ throws BadRequestException, UnprocessableEntityException, ResourceConflictException,
+ ResourceNotFoundException, IOException, ConfigInvalidException {
if (input == null) {
input = new ProjectInput();
}
@@ -161,44 +159,36 @@
CreateProjectArgs args = new CreateProjectArgs();
args.setProjectName(ProjectUtil.stripGitSuffix(name));
- String parentName = MoreObjects.firstNonNull(
- Strings.emptyToNull(input.parent), allProjects.get());
- args.newParent =
- projectsCollection.get().parse(parentName, false).getControl();
+ String parentName =
+ MoreObjects.firstNonNull(Strings.emptyToNull(input.parent), allProjects.get());
+ args.newParent = projectsCollection.get().parse(parentName, false).getControl();
args.createEmptyCommit = input.createEmptyCommit;
args.permissionsOnly = input.permissionsOnly;
args.projectDescription = Strings.emptyToNull(input.description);
args.submitType = input.submitType;
args.branch = normalizeBranchNames(input.branches);
if (input.owners == null || input.owners.isEmpty()) {
- args.ownerIds =
- new ArrayList<>(projectOwnerGroups.create(args.getProject()).get());
+ args.ownerIds = new ArrayList<>(projectOwnerGroups.create(args.getProject()).get());
} else {
- args.ownerIds =
- Lists.newArrayListWithCapacity(input.owners.size());
+ args.ownerIds = Lists.newArrayListWithCapacity(input.owners.size());
for (String owner : input.owners) {
args.ownerIds.add(groupsCollection.get().parse(owner).getGroupUUID());
}
}
args.contributorAgreements =
- MoreObjects.firstNonNull(input.useContributorAgreements,
- InheritableBoolean.INHERIT);
- args.signedOffBy =
- MoreObjects.firstNonNull(input.useSignedOffBy,
- InheritableBoolean.INHERIT);
+ MoreObjects.firstNonNull(input.useContributorAgreements, InheritableBoolean.INHERIT);
+ args.signedOffBy = MoreObjects.firstNonNull(input.useSignedOffBy, InheritableBoolean.INHERIT);
args.contentMerge =
input.submitType == SubmitType.FAST_FORWARD_ONLY
- ? InheritableBoolean.FALSE : MoreObjects.firstNonNull(
- input.useContentMerge,
- InheritableBoolean.INHERIT);
+ ? InheritableBoolean.FALSE
+ : MoreObjects.firstNonNull(input.useContentMerge, InheritableBoolean.INHERIT);
args.newChangeForAllNotInTarget =
- MoreObjects.firstNonNull(input.createNewChangeForAllNotInTarget,
- InheritableBoolean.INHERIT);
+ MoreObjects.firstNonNull(
+ input.createNewChangeForAllNotInTarget, InheritableBoolean.INHERIT);
args.changeIdRequired =
MoreObjects.firstNonNull(input.requireChangeId, InheritableBoolean.INHERIT);
try {
- args.maxObjectSizeLimit =
- ProjectConfig.validMaxObjectSizeLimit(input.maxObjectSizeLimit);
+ args.maxObjectSizeLimit = ProjectConfig.validMaxObjectSizeLimit(input.maxObjectSizeLimit);
} catch (ConfigInvalidException e) {
throw new BadRequestException(e.getMessage());
}
@@ -215,8 +205,8 @@
if (input.pluginConfigValues != null) {
try {
- ProjectControl projectControl = projectControlFactory.controlFor(
- p.getNameKey(), identifiedUser.get());
+ ProjectControl projectControl =
+ projectControlFactory.controlFor(p.getNameKey(), identifiedUser.get());
ConfigInput in = new ConfigInput();
in.pluginConfigValues = input.pluginConfigValues;
putConfig.get().apply(projectControl, in);
@@ -229,13 +219,10 @@
}
private Project createProject(CreateProjectArgs args)
- throws BadRequestException, ResourceConflictException, IOException,
- ConfigInvalidException {
+ throws BadRequestException, ResourceConflictException, IOException, ConfigInvalidException {
final Project.NameKey nameKey = args.getProject();
try {
- final String head =
- args.permissionsOnly ? RefNames.REFS_CONFIG
- : args.branch.get(0);
+ final String head = args.permissionsOnly ? RefNames.REFS_CONFIG : args.branch.get(0);
try (Repository repo = repoManager.openRepository(nameKey)) {
if (repo.getObjectDatabase().exists()) {
throw new ResourceConflictException("project \"" + nameKey + "\" exists");
@@ -250,8 +237,7 @@
createProjectConfig(args);
- if (!args.permissionsOnly
- && args.createEmptyCommit) {
+ if (!args.permissionsOnly && args.createEmptyCommit) {
createEmptyCommits(repo, nameKey, args.branch);
}
@@ -260,10 +246,12 @@
return projectCache.get(nameKey).getProject();
}
} catch (RepositoryCaseMismatchException e) {
- throw new ResourceConflictException("Cannot create " + nameKey.get()
- + " because the name is already occupied by another project."
- + " The other project has the same name, only spelled in a"
- + " different case.");
+ throw new ResourceConflictException(
+ "Cannot create "
+ + nameKey.get()
+ + " because the name is already occupied by another project."
+ + " The other project has the same name, only spelled in a"
+ + " different case.");
} catch (RepositoryNotFoundException badName) {
throw new BadRequestException("invalid project name: " + nameKey);
} catch (ConfigInvalidException e) {
@@ -273,35 +261,33 @@
}
}
- private void createProjectConfig(CreateProjectArgs args) throws IOException, ConfigInvalidException {
+ private void createProjectConfig(CreateProjectArgs args)
+ throws IOException, ConfigInvalidException {
try (MetaDataUpdate md = metaDataUpdateFactory.create(args.getProject())) {
ProjectConfig config = ProjectConfig.read(md);
Project newProject = config.getProject();
newProject.setDescription(args.projectDescription);
- newProject.setSubmitType(MoreObjects.firstNonNull(args.submitType,
- repositoryCfg.getDefaultSubmitType(args.getProject())));
- newProject
- .setUseContributorAgreements(args.contributorAgreements);
+ newProject.setSubmitType(
+ MoreObjects.firstNonNull(
+ args.submitType, repositoryCfg.getDefaultSubmitType(args.getProject())));
+ newProject.setUseContributorAgreements(args.contributorAgreements);
newProject.setUseSignedOffBy(args.signedOffBy);
newProject.setUseContentMerge(args.contentMerge);
newProject.setCreateNewChangeForAllNotInTarget(args.newChangeForAllNotInTarget);
newProject.setRequireChangeID(args.changeIdRequired);
newProject.setMaxObjectSizeLimit(args.maxObjectSizeLimit);
if (args.newParent != null) {
- newProject.setParentName(args.newParent.getProject()
- .getNameKey());
+ newProject.setParentName(args.newParent.getProject().getNameKey());
}
if (!args.ownerIds.isEmpty()) {
- AccessSection all =
- config.getAccessSection(AccessSection.ALL, true);
+ AccessSection all = config.getAccessSection(AccessSection.ALL, true);
for (AccountGroup.UUID ownerId : args.ownerIds) {
GroupDescription.Basic g = groupBackend.get(ownerId);
if (g != null) {
GroupReference group = config.resolve(GroupReference.forGroup(g));
- all.getPermission(Permission.OWNER, true).add(
- new PermissionRule(group));
+ all.getPermission(Permission.OWNER, true).add(new PermissionRule(group));
}
}
}
@@ -313,8 +299,7 @@
projectCache.onCreateProject(args.getProject());
}
- private List<String> normalizeBranchNames(List<String> branches)
- throws BadRequestException {
+ private List<String> normalizeBranchNames(List<String> branches) throws BadRequestException {
if (branches == null || branches.isEmpty()) {
return Collections.singletonList(Constants.R_HEADS + Constants.MASTER);
}
@@ -326,8 +311,7 @@
}
branch = RefNames.fullName(branch);
if (!Repository.isValidRefName(branch)) {
- throw new BadRequestException(String.format(
- "Branch \"%s\" is not a valid name.", branch));
+ throw new BadRequestException(String.format("Branch \"%s\" is not a valid name.", branch));
}
if (!normalizedBranches.contains(branch)) {
normalizedBranches.add(branch);
@@ -336,8 +320,8 @@
return normalizedBranches;
}
- private void createEmptyCommits(Repository repo, Project.NameKey project,
- List<String> refs) throws IOException {
+ private void createEmptyCommits(Repository repo, Project.NameKey project, List<String> refs)
+ throws IOException {
try (ObjectInserter oi = repo.newObjectInserter()) {
CommitBuilder cb = new CommitBuilder();
cb.setTreeId(oi.insert(Constants.OBJ_TREE, new byte[] {}));
@@ -354,8 +338,8 @@
Result result = ru.update();
switch (result) {
case NEW:
- referenceUpdated.fire(project, ru, ReceiveCommand.Type.CREATE,
- identifiedUser.get().getAccount());
+ referenceUpdated.fire(
+ project, ru, ReceiveCommand.Type.CREATE, identifiedUser.get().getAccount());
break;
case FAST_FORWARD:
case FORCED:
@@ -366,16 +350,15 @@
case REJECTED:
case REJECTED_CURRENT_BRANCH:
case RENAMED:
- default: {
- throw new IOException(String.format(
- "Failed to create ref \"%s\": %s", ref, result.name()));
- }
+ default:
+ {
+ throw new IOException(
+ String.format("Failed to create ref \"%s\": %s", ref, result.name()));
+ }
}
}
} catch (IOException e) {
- log.error(
- "Cannot create empty commit for "
- + project.get(), e);
+ log.error("Cannot create empty commit for " + project.get(), e);
throw e;
}
}
@@ -395,8 +378,7 @@
}
}
- static class Event extends AbstractNoNotifyEvent
- implements NewProjectCreatedListener.Event {
+ static class Event extends AbstractNoNotifyEvent implements NewProjectCreatedListener.Event {
private final Project.NameKey name;
private final String head;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/CreateProjectArgs.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/CreateProjectArgs.java
index bbecb33..5642721 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/CreateProjectArgs.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/CreateProjectArgs.java
@@ -18,7 +18,6 @@
import com.google.gerrit.extensions.client.SubmitType;
import com.google.gerrit.reviewdb.client.AccountGroup;
import com.google.gerrit.reviewdb.client.Project;
-
import java.util.List;
public class CreateProjectArgs {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/CreateTag.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/CreateTag.java
index 31e59de..ed38c47 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/CreateTag.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/CreateTag.java
@@ -35,7 +35,8 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.assistedinject.Assisted;
-
+import java.io.IOException;
+import java.util.TimeZone;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.TagCommand;
import org.eclipse.jgit.api.errors.GitAPIException;
@@ -48,9 +49,6 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.util.TimeZone;
-
public class CreateTag implements RestModifyView<ProjectResource, TagInput> {
private static final Logger log = LoggerFactory.getLogger(CreateTag.class);
@@ -65,7 +63,8 @@
private String ref;
@Inject
- CreateTag(Provider<IdentifiedUser> identifiedUser,
+ CreateTag(
+ Provider<IdentifiedUser> identifiedUser,
GitRepositoryManager repoManager,
TagCache tagCache,
GitReferenceUpdated referenceUpdated,
@@ -94,45 +93,45 @@
RefControl refControl = resource.getControl().controlForRef(ref);
try (Repository repo = repoManager.openRepository(resource.getNameKey())) {
- ObjectId revid = RefUtil.parseBaseRevision(
- repo, resource.getNameKey(), input.revision);
+ ObjectId revid = RefUtil.parseBaseRevision(repo, resource.getNameKey(), input.revision);
RevWalk rw = RefUtil.verifyConnected(repo, revid);
RevObject object = rw.parseAny(revid);
rw.reset();
boolean isAnnotated = Strings.emptyToNull(input.message) != null;
- boolean isSigned = isAnnotated
- && input.message.contains("-----BEGIN PGP SIGNATURE-----\n");
+ boolean isSigned = isAnnotated && input.message.contains("-----BEGIN PGP SIGNATURE-----\n");
if (isSigned) {
- throw new MethodNotAllowedException(
- "Cannot create signed tag \"" + ref + "\"");
+ throw new MethodNotAllowedException("Cannot create signed tag \"" + ref + "\"");
} else if (isAnnotated && !refControl.canPerform(Permission.CREATE_TAG)) {
throw new AuthException("Cannot create annotated tag \"" + ref + "\"");
} else if (!refControl.canPerform(Permission.CREATE)) {
throw new AuthException("Cannot create tag \"" + ref + "\"");
}
if (repo.getRefDatabase().exactRef(ref) != null) {
- throw new ResourceConflictException(
- "tag \"" + ref + "\" already exists");
+ throw new ResourceConflictException("tag \"" + ref + "\" already exists");
}
try (Git git = new Git(repo)) {
- TagCommand tag = git.tag()
- .setObjectId(object)
- .setName(ref.substring(R_TAGS.length()))
- .setAnnotated(isAnnotated)
- .setSigned(isSigned);
+ TagCommand tag =
+ git.tag()
+ .setObjectId(object)
+ .setName(ref.substring(R_TAGS.length()))
+ .setAnnotated(isAnnotated)
+ .setSigned(isSigned);
if (isAnnotated) {
tag.setMessage(input.message)
- .setTagger(identifiedUser.get()
- .newCommitterIdent(TimeUtil.nowTs(), TimeZone.getDefault()));
+ .setTagger(
+ identifiedUser.get().newCommitterIdent(TimeUtil.nowTs(), TimeZone.getDefault()));
}
Ref result = tag.call();
- tagCache.updateFastForward(resource.getNameKey(), ref,
- ObjectId.zeroId(), result.getObjectId());
- referenceUpdated.fire(resource.getNameKey(), ref,
- ObjectId.zeroId(), result.getObjectId(),
+ tagCache.updateFastForward(
+ resource.getNameKey(), ref, ObjectId.zeroId(), result.getObjectId());
+ referenceUpdated.fire(
+ resource.getNameKey(),
+ ref,
+ ObjectId.zeroId(),
+ result.getObjectId(),
identifiedUser.get().getAccount());
try (RevWalk w = new RevWalk(repo)) {
return ListTags.createTagInfo(result, w);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/DashboardResource.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/DashboardResource.java
index 099350d..a3fd09e 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/DashboardResource.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/DashboardResource.java
@@ -17,7 +17,6 @@
import com.google.gerrit.extensions.restapi.RestResource;
import com.google.gerrit.extensions.restapi.RestView;
import com.google.inject.TypeLiteral;
-
import org.eclipse.jgit.lib.Config;
public class DashboardResource implements RestResource {
@@ -34,7 +33,8 @@
private final Config config;
private final boolean projectDefault;
- public DashboardResource(ProjectControl control,
+ public DashboardResource(
+ ProjectControl control,
String refName,
String pathName,
Config config,
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/DashboardsCollection.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/DashboardsCollection.java
index a20c51e..44d3b5c 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/DashboardsCollection.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/DashboardsCollection.java
@@ -38,7 +38,9 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
import org.eclipse.jgit.errors.AmbiguousObjectException;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.errors.IncorrectObjectTypeException;
@@ -48,21 +50,17 @@
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Repository;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-
@Singleton
-class DashboardsCollection implements
- ChildCollection<ProjectResource, DashboardResource>,
- AcceptsCreate<ProjectResource> {
+class DashboardsCollection
+ implements ChildCollection<ProjectResource, DashboardResource>, AcceptsCreate<ProjectResource> {
private final GitRepositoryManager gitManager;
private final DynamicMap<RestView<DashboardResource>> views;
private final Provider<ListDashboards> list;
private final Provider<SetDefaultDashboard.CreateDefault> createDefault;
@Inject
- DashboardsCollection(GitRepositoryManager gitManager,
+ DashboardsCollection(
+ GitRepositoryManager gitManager,
DynamicMap<RestView<DashboardResource>> views,
Provider<ListDashboards> list,
Provider<SetDefaultDashboard.CreateDefault> createDefault) {
@@ -79,8 +77,8 @@
@SuppressWarnings("unchecked")
@Override
- public RestModifyView<ProjectResource, ?> create(ProjectResource parent,
- IdString id) throws RestApiException {
+ public RestModifyView<ProjectResource, ?> create(ProjectResource parent, IdString id)
+ throws RestApiException {
if (id.toString().equals("default")) {
return createDefault.get();
}
@@ -95,8 +93,7 @@
return DashboardResource.projectDefault(myCtl);
}
- List<String> parts = Lists.newArrayList(
- Splitter.on(':').limit(2).split(id.get()));
+ List<String> parts = Lists.newArrayList(Splitter.on(':').limit(2).split(id.get()));
if (parts.size() != 2) {
throw new ResourceNotFoundException(id);
}
@@ -107,8 +104,7 @@
for (ProjectState ps : myCtl.getProjectState().tree()) {
try {
return parse(ps.controlFor(user), ref, path, myCtl);
- } catch (AmbiguousObjectException | ConfigInvalidException
- | IncorrectObjectTypeException e) {
+ } catch (AmbiguousObjectException | ConfigInvalidException | IncorrectObjectTypeException e) {
throw new ResourceNotFoundException(id);
} catch (ResourceNotFoundException e) {
continue;
@@ -117,16 +113,14 @@
throw new ResourceNotFoundException(id);
}
- private DashboardResource parse(ProjectControl ctl, String ref, String path,
- ProjectControl myCtl)
+ private DashboardResource parse(ProjectControl ctl, String ref, String path, ProjectControl myCtl)
throws ResourceNotFoundException, IOException, AmbiguousObjectException,
IncorrectObjectTypeException, ConfigInvalidException {
String id = ref + ":" + path;
if (!ref.startsWith(REFS_DASHBOARDS)) {
ref = REFS_DASHBOARDS + ref;
}
- if (!Repository.isValidRefName(ref)
- || !ctl.controlForRef(ref).canRead()) {
+ if (!Repository.isValidRefName(ref) || !ctl.controlForRef(ref).canRead()) {
throw new ResourceNotFoundException(id);
}
@@ -147,8 +141,13 @@
return views;
}
- static DashboardInfo parse(Project definingProject, String refName,
- String path, Config config, String project, boolean setDefault) {
+ static DashboardInfo parse(
+ Project definingProject,
+ String refName,
+ String path,
+ Config config,
+ String project,
+ boolean setDefault) {
DashboardInfo info = new DashboardInfo(refName, path);
info.project = project;
info.definingProject = definingProject.getName();
@@ -184,9 +183,9 @@
}
private static String defaultOf(Project proj) {
- final String defaultId = MoreObjects.firstNonNull(
- proj.getLocalDefaultDashboard(),
- Strings.nullToEmpty(proj.getDefaultDashboard()));
+ final String defaultId =
+ MoreObjects.firstNonNull(
+ proj.getLocalDefaultDashboard(), Strings.nullToEmpty(proj.getDefaultDashboard()));
if (defaultId.startsWith(REFS_DASHBOARDS)) {
return defaultId.substring(REFS_DASHBOARDS.length());
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/DeleteBranch.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/DeleteBranch.java
index e9741ef..4601bfe 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/DeleteBranch.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/DeleteBranch.java
@@ -25,20 +25,17 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.io.IOException;
@Singleton
public class DeleteBranch implements RestModifyView<BranchResource, Input> {
- public static class Input {
- }
+ public static class Input {}
private final Provider<InternalChangeQuery> queryProvider;
private final DeleteRef.Factory deleteRefFactory;
@Inject
- DeleteBranch(Provider<InternalChangeQuery> queryProvider,
- DeleteRef.Factory deleteRefFactory) {
+ DeleteBranch(Provider<InternalChangeQuery> queryProvider, DeleteRef.Factory deleteRefFactory) {
this.queryProvider = queryProvider;
this.deleteRefFactory = deleteRefFactory;
}
@@ -50,10 +47,8 @@
throw new AuthException("Cannot delete branch");
}
- if (!queryProvider.get().setLimit(1)
- .byBranchOpen(rsrc.getBranchKey()).isEmpty()) {
- throw new ResourceConflictException("branch " + rsrc.getBranchKey()
- + " has open changes");
+ if (!queryProvider.get().setLimit(1).byBranchOpen(rsrc.getBranchKey()).isEmpty()) {
+ throw new ResourceConflictException("branch " + rsrc.getBranchKey() + " has open changes");
}
deleteRefFactory.create(rsrc).ref(rsrc.getRef()).delete();
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/DeleteBranches.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/DeleteBranches.java
index 07e5032..f5e55b1 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/DeleteBranches.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/DeleteBranches.java
@@ -22,12 +22,10 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
import java.io.IOException;
@Singleton
-public class DeleteBranches
- implements RestModifyView<ProjectResource, DeleteBranchesInput> {
+public class DeleteBranches implements RestModifyView<ProjectResource, DeleteBranchesInput> {
private final DeleteRef.Factory deleteRefFactory;
@Inject
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/DeleteDashboard.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/DeleteDashboard.java
index 7702b7d..a9dd253 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/DeleteDashboard.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/DeleteDashboard.java
@@ -25,7 +25,6 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.io.IOException;
@Singleton
@@ -40,7 +39,7 @@
@Override
public Response<DashboardInfo> apply(DashboardResource resource, SetDashboard.Input input)
throws AuthException, BadRequestException, ResourceConflictException,
- ResourceNotFoundException, MethodNotAllowedException, IOException {
+ ResourceNotFoundException, MethodNotAllowedException, IOException {
if (resource.isProjectDefault()) {
SetDashboard.Input in = new SetDashboard.Input();
in.commitMessage = input != null ? input.commitMessage : null;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/DeleteRef.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/DeleteRef.java
index adff11bb..943bdc4 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/DeleteRef.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/DeleteRef.java
@@ -28,7 +28,10 @@
import com.google.inject.Provider;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
-
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.stream.Collectors;
import org.eclipse.jgit.errors.LockFailedException;
import org.eclipse.jgit.lib.BatchRefUpdate;
import org.eclipse.jgit.lib.NullProgressMonitor;
@@ -42,11 +45,6 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.stream.Collectors;
-
public class DeleteRef {
private static final Logger log = LoggerFactory.getLogger(DeleteRef.class);
@@ -67,7 +65,8 @@
}
@AssistedInject
- DeleteRef(Provider<IdentifiedUser> identifiedUser,
+ DeleteRef(
+ Provider<IdentifiedUser> identifiedUser,
GitRepositoryManager repoManager,
GitReferenceUpdated referenceUpdated,
RefValidationHelper.Factory refDeletionValidatorFactory,
@@ -97,8 +96,7 @@
return this;
}
- public void delete()
- throws OrmException, IOException, ResourceConflictException {
+ public void delete() throws OrmException, IOException, ResourceConflictException {
if (!refsToDelete.isEmpty()) {
try (Repository r = repoManager.openRepository(resource.getNameKey())) {
if (refsToDelete.size() == 1) {
@@ -110,8 +108,7 @@
}
}
- private void deleteSingleRef(Repository r)
- throws IOException, ResourceConflictException {
+ private void deleteSingleRef(Repository r) throws IOException, ResourceConflictException {
String ref = refsToDelete.get(0);
if (prefix != null && !ref.startsWith(prefix)) {
ref = prefix + ref;
@@ -119,10 +116,9 @@
RefUpdate.Result result;
RefUpdate u = r.updateRef(ref);
u.setForceUpdate(true);
- refDeletionValidator.validateRefOperation(
- ref, identifiedUser.get(), u);
+ refDeletionValidator.validateRefOperation(ref, identifiedUser.get(), u);
int remainingLockFailureCalls = MAX_LOCK_FAILURE_CALLS;
- for (;;) {
+ for (; ; ) {
try {
result = u.delete();
} catch (LockFailedException e) {
@@ -131,8 +127,7 @@
log.error("Cannot delete " + ref, e);
throw e;
}
- if (result == RefUpdate.Result.LOCK_FAILURE
- && --remainingLockFailureCalls > 0) {
+ if (result == RefUpdate.Result.LOCK_FAILURE && --remainingLockFailureCalls > 0) {
try {
Thread.sleep(SLEEP_ON_LOCK_FAILURE_MS);
} catch (InterruptedException ie) {
@@ -148,7 +143,10 @@
case NO_CHANGE:
case FAST_FORWARD:
case FORCED:
- referenceUpdated.fire(resource.getNameKey(), u, ReceiveCommand.Type.DELETE,
+ referenceUpdated.fire(
+ resource.getNameKey(),
+ u,
+ ReceiveCommand.Type.DELETE,
identifiedUser.get().getAccount());
break;
@@ -170,12 +168,13 @@
private void deleteMultipleRefs(Repository r)
throws OrmException, IOException, ResourceConflictException {
BatchRefUpdate batchUpdate = r.getRefDatabase().newBatchUpdate();
- List<String> refs = prefix == null
- ? refsToDelete
- : refsToDelete.stream().map(
- ref -> ref.startsWith(prefix)
- ? ref
- : prefix + ref).collect(Collectors.toList());
+ List<String> refs =
+ prefix == null
+ ? refsToDelete
+ : refsToDelete
+ .stream()
+ .map(ref -> ref.startsWith(prefix) ? ref : prefix + ref)
+ .collect(Collectors.toList());
for (String ref : refs) {
batchUpdate.addCommand(createDeleteCommand(resource, r, ref));
}
@@ -195,28 +194,27 @@
}
}
- private ReceiveCommand createDeleteCommand(ProjectResource project,
- Repository r, String refName)
- throws OrmException, IOException, ResourceConflictException {
+ private ReceiveCommand createDeleteCommand(ProjectResource project, Repository r, String refName)
+ throws OrmException, IOException, ResourceConflictException {
Ref ref = r.getRefDatabase().getRef(refName);
ReceiveCommand command;
if (ref == null) {
command = new ReceiveCommand(ObjectId.zeroId(), ObjectId.zeroId(), refName);
- command.setResult(Result.REJECTED_OTHER_REASON,
+ command.setResult(
+ Result.REJECTED_OTHER_REASON,
"it doesn't exist or you do not have permission to delete it");
return command;
}
- command = new ReceiveCommand(
- ref.getObjectId(), ObjectId.zeroId(), ref.getName());
+ command = new ReceiveCommand(ref.getObjectId(), ObjectId.zeroId(), ref.getName());
if (!project.getControl().controlForRef(refName).canDelete()) {
- command.setResult(Result.REJECTED_OTHER_REASON,
+ command.setResult(
+ Result.REJECTED_OTHER_REASON,
"it doesn't exist or you do not have permission to delete it");
}
if (!refName.startsWith(R_TAGS)) {
- Branch.NameKey branchKey =
- new Branch.NameKey(project.getNameKey(), ref.getName());
+ Branch.NameKey branchKey = new Branch.NameKey(project.getNameKey(), ref.getName());
if (!queryProvider.get().setLimit(1).byBranchOpen(branchKey).isEmpty()) {
command.setResult(Result.REJECTED_OTHER_REASON, "it has open changes");
}
@@ -224,18 +222,15 @@
RefUpdate u = r.updateRef(refName);
u.setForceUpdate(true);
- refDeletionValidator.validateRefOperation(
- project.getName(), identifiedUser.get(), u);
+ refDeletionValidator.validateRefOperation(project.getName(), identifiedUser.get(), u);
return command;
}
- private void appendAndLogErrorMessage(StringBuilder errorMessages,
- ReceiveCommand cmd) {
+ private void appendAndLogErrorMessage(StringBuilder errorMessages, ReceiveCommand cmd) {
String msg = null;
switch (cmd.getResult()) {
case REJECTED_CURRENT_BRANCH:
- msg = format("Cannot delete %s: it is the current branch",
- cmd.getRefName());
+ msg = format("Cannot delete %s: it is the current branch", cmd.getRefName());
break;
case REJECTED_OTHER_REASON:
msg = format("Cannot delete %s: %s", cmd.getRefName(), cmd.getMessage());
@@ -257,7 +252,6 @@
}
private void postDeletion(ProjectResource project, ReceiveCommand cmd) {
- referenceUpdated.fire(project.getNameKey(), cmd,
- identifiedUser.get().getAccount());
+ referenceUpdated.fire(project.getNameKey(), cmd, identifiedUser.get().getAccount());
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/DeleteTag.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/DeleteTag.java
index bcc433b..f26d40f 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/DeleteTag.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/DeleteTag.java
@@ -21,15 +21,13 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
import java.io.IOException;
@Singleton
public class DeleteTag implements RestModifyView<TagResource, DeleteTag.Input> {
private final DeleteRef.Factory deleteRefFactory;
- public static class Input {
- }
+ public static class Input {}
@Inject
DeleteTag(DeleteRef.Factory deleteRefFactory) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/DeleteTags.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/DeleteTags.java
index 813012b..75cf03f 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/DeleteTags.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/DeleteTags.java
@@ -24,12 +24,10 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
import java.io.IOException;
@Singleton
-public class DeleteTags
- implements RestModifyView<ProjectResource, DeleteTagsInput> {
+public class DeleteTags implements RestModifyView<ProjectResource, DeleteTagsInput> {
private final DeleteRef.Factory deleteRefFactory;
@Inject
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/FileResource.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/FileResource.java
index 82ea155..43b849f 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/FileResource.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/FileResource.java
@@ -20,24 +20,21 @@
import com.google.gerrit.extensions.restapi.RestView;
import com.google.gerrit.server.git.GitRepositoryManager;
import com.google.inject.TypeLiteral;
-
+import java.io.IOException;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevTree;
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.treewalk.TreeWalk;
-import java.io.IOException;
-
public class FileResource implements RestResource {
public static final TypeLiteral<RestView<FileResource>> FILE_KIND =
new TypeLiteral<RestView<FileResource>>() {};
- public static FileResource create(GitRepositoryManager repoManager,
- ProjectControl project, ObjectId rev, String path)
- throws ResourceNotFoundException, IOException {
- try (Repository repo =
- repoManager.openRepository(project.getProject().getNameKey());
+ public static FileResource create(
+ GitRepositoryManager repoManager, ProjectControl project, ObjectId rev, String path)
+ throws ResourceNotFoundException, IOException {
+ try (Repository repo = repoManager.openRepository(project.getProject().getNameKey());
RevWalk rw = new RevWalk(repo)) {
RevTree tree = rw.parseTree(rev);
if (TreeWalk.forPath(repo, path, tree) != null) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/FilesCollection.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/FilesCollection.java
index dcb8747..8d462a1 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/FilesCollection.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/FilesCollection.java
@@ -22,20 +22,16 @@
import com.google.gerrit.server.git.GitRepositoryManager;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
+import java.io.IOException;
import org.eclipse.jgit.lib.ObjectId;
-import java.io.IOException;
-
@Singleton
-public class FilesCollection implements
- ChildCollection<BranchResource, FileResource> {
+public class FilesCollection implements ChildCollection<BranchResource, FileResource> {
private final DynamicMap<RestView<FileResource>> views;
private final GitRepositoryManager repoManager;
@Inject
- FilesCollection(DynamicMap<RestView<FileResource>> views,
- GitRepositoryManager repoManager) {
+ FilesCollection(DynamicMap<RestView<FileResource>> views, GitRepositoryManager repoManager) {
this.views = views;
this.repoManager = repoManager;
}
@@ -48,8 +44,8 @@
@Override
public FileResource parse(BranchResource parent, IdString id)
throws ResourceNotFoundException, IOException {
- return FileResource.create(repoManager, parent.getControl(),
- ObjectId.fromString(parent.getRevision()), id.get());
+ return FileResource.create(
+ repoManager, parent.getControl(), ObjectId.fromString(parent.getRevision()), id.get());
}
@Override
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/FilesInCommitCollection.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/FilesInCommitCollection.java
index 0f44a48..807ac53 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/FilesInCommitCollection.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/FilesInCommitCollection.java
@@ -23,18 +23,16 @@
import com.google.gerrit.server.git.GitRepositoryManager;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
import java.io.IOException;
@Singleton
-public class FilesInCommitCollection implements
- ChildCollection<CommitResource, FileResource> {
+public class FilesInCommitCollection implements ChildCollection<CommitResource, FileResource> {
private final DynamicMap<RestView<FileResource>> views;
private final GitRepositoryManager repoManager;
@Inject
- FilesInCommitCollection(DynamicMap<RestView<FileResource>> views,
- GitRepositoryManager repoManager) {
+ FilesInCommitCollection(
+ DynamicMap<RestView<FileResource>> views, GitRepositoryManager repoManager) {
this.views = views;
this.repoManager = repoManager;
}
@@ -48,11 +46,9 @@
public FileResource parse(CommitResource parent, IdString id)
throws ResourceNotFoundException, IOException {
if (Patch.isMagic(id.get())) {
- return new FileResource(parent.getProject(), parent.getCommit(),
- id.get());
+ return new FileResource(parent.getProject(), parent.getCommit(), id.get());
}
- return FileResource.create(repoManager, parent.getProject(),
- parent.getCommit(), id.get());
+ return FileResource.create(repoManager, parent.getProject(), parent.getCommit(), id.get());
}
@Override
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/GarbageCollect.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/GarbageCollect.java
index 3b50129..654ce69 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/GarbageCollect.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/GarbageCollect.java
@@ -34,7 +34,6 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
@@ -43,8 +42,8 @@
@RequiresCapability(GlobalCapability.RUN_GC)
@Singleton
-public class GarbageCollect implements RestModifyView<ProjectResource, Input>,
- UiAction<ProjectResource> {
+public class GarbageCollect
+ implements RestModifyView<ProjectResource, Input>, UiAction<ProjectResource> {
public static class Input {
public boolean showProgress;
public boolean aggressive;
@@ -57,8 +56,10 @@
private final Provider<String> canonicalUrl;
@Inject
- GarbageCollect(GitRepositoryManager repoManager,
- GarbageCollection.Factory garbageCollectionFactory, WorkQueue workQueue,
+ GarbageCollect(
+ GitRepositoryManager repoManager,
+ GarbageCollection.Factory garbageCollectionFactory,
+ WorkQueue workQueue,
@CanonicalWebUrl Provider<String> canonicalUrl) {
this.workQueue = workQueue;
this.canonicalUrl = canonicalUrl;
@@ -76,42 +77,43 @@
}
private Response.Accepted applyAsync(final Project.NameKey project, final Input input) {
- Runnable job = new Runnable() {
- @Override
- public void run() {
- runGC(project, input, null);
- }
+ Runnable job =
+ new Runnable() {
+ @Override
+ public void run() {
+ runGC(project, input, null);
+ }
- @Override
- public String toString() {
- return "Run " + (input.aggressive ? "aggressive " : "")
- + "garbage collection on project " + project.get();
- }
- };
+ @Override
+ public String toString() {
+ return "Run "
+ + (input.aggressive ? "aggressive " : "")
+ + "garbage collection on project "
+ + project.get();
+ }
+ };
@SuppressWarnings("unchecked")
- WorkQueue.Task<Void> task =
- (WorkQueue.Task<Void>) workQueue.getDefaultQueue().submit(job);
+ WorkQueue.Task<Void> task = (WorkQueue.Task<Void>) workQueue.getDefaultQueue().submit(job);
- String location = canonicalUrl.get() + "a/config/server/tasks/"
- + IdGenerator.format(task.getTaskId());
+ String location =
+ canonicalUrl.get() + "a/config/server/tasks/" + IdGenerator.format(task.getTaskId());
return Response.accepted(location);
}
@SuppressWarnings("resource")
- private BinaryResult applySync(final Project.NameKey project,
- final Input input) {
+ private BinaryResult applySync(final Project.NameKey project, final Input input) {
return new BinaryResult() {
@Override
public void writeTo(OutputStream out) throws IOException {
- PrintWriter writer = new PrintWriter(
- new OutputStreamWriter(out, UTF_8)) {
- @Override
- public void println() {
- write('\n');
- }
- };
+ PrintWriter writer =
+ new PrintWriter(new OutputStreamWriter(out, UTF_8)) {
+ @Override
+ public void println() {
+ write('\n');
+ }
+ };
try {
PrintWriter progressWriter = input.showProgress ? writer : null;
GarbageCollectionResult result = runGC(project, input, progressWriter);
@@ -123,16 +125,24 @@
msg = "Error: project \"" + e.getProjectName() + "\" not found.";
break;
case GC_ALREADY_SCHEDULED:
- msg = "Error: garbage collection for project \""
- + e.getProjectName() + "\" was already scheduled.";
+ msg =
+ "Error: garbage collection for project \""
+ + e.getProjectName()
+ + "\" was already scheduled.";
break;
case GC_FAILED:
- msg = "Error: garbage collection for project \"" + e.getProjectName()
- + "\" failed.";
+ msg =
+ "Error: garbage collection for project \""
+ + e.getProjectName()
+ + "\" failed.";
break;
default:
- msg = "Error: garbage collection for project \"" + e.getProjectName()
- + "\" failed: " + e.getType() + ".";
+ msg =
+ "Error: garbage collection for project \""
+ + e.getProjectName()
+ + "\" failed: "
+ + e.getType()
+ + ".";
}
}
}
@@ -141,16 +151,13 @@
writer.flush();
}
}
- }.setContentType("text/plain")
- .setCharacterEncoding(UTF_8)
- .disableGzip();
+ }.setContentType("text/plain").setCharacterEncoding(UTF_8).disableGzip();
}
- GarbageCollectionResult runGC(Project.NameKey project,
- Input input, PrintWriter progressWriter) {
- return garbageCollectionFactory.create().run(
- Collections.singletonList(project), input.aggressive,
- progressWriter);
+ GarbageCollectionResult runGC(Project.NameKey project, Input input, PrintWriter progressWriter) {
+ return garbageCollectionFactory
+ .create()
+ .run(Collections.singletonList(project), input.aggressive, progressWriter);
}
@Override
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/GetAccess.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/GetAccess.java
index 8effe44..6d95868 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/GetAccess.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/GetAccess.java
@@ -41,24 +41,26 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.errors.ConfigInvalidException;
-import org.eclipse.jgit.errors.RepositoryNotFoundException;
-
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
+import org.eclipse.jgit.errors.ConfigInvalidException;
+import org.eclipse.jgit.errors.RepositoryNotFoundException;
@Singleton
public class GetAccess implements RestReadView<ProjectResource> {
- public static final BiMap<PermissionRule.Action,
- PermissionRuleInfo.Action> ACTION_TYPE = ImmutableBiMap.of(
- PermissionRule.Action.ALLOW, PermissionRuleInfo.Action.ALLOW,
- PermissionRule.Action.BATCH, PermissionRuleInfo.Action.BATCH,
- PermissionRule.Action.BLOCK, PermissionRuleInfo.Action.BLOCK,
- PermissionRule.Action.DENY, PermissionRuleInfo.Action.DENY,
+ public static final BiMap<PermissionRule.Action, PermissionRuleInfo.Action> ACTION_TYPE =
+ ImmutableBiMap.of(
+ PermissionRule.Action.ALLOW,
+ PermissionRuleInfo.Action.ALLOW,
+ PermissionRule.Action.BATCH,
+ PermissionRuleInfo.Action.BATCH,
+ PermissionRule.Action.BLOCK,
+ PermissionRuleInfo.Action.BLOCK,
+ PermissionRule.Action.DENY,
+ PermissionRuleInfo.Action.DENY,
PermissionRule.Action.INTERACTIVE,
PermissionRuleInfo.Action.INTERACTIVE);
@@ -72,7 +74,8 @@
private final GroupBackend groupBackend;
@Inject
- public GetAccess(Provider<CurrentUser> self,
+ public GetAccess(
+ Provider<CurrentUser> self,
GroupControl.Factory groupControlFactory,
AllProjectsName allProjectsName,
ProjectCache projectCache,
@@ -93,8 +96,7 @@
public ProjectAccessInfo apply(Project.NameKey nameKey)
throws ResourceNotFoundException, ResourceConflictException, IOException {
try {
- return this.apply(new ProjectResource(
- projectControlFactory.controlFor(nameKey, self.get())));
+ return this.apply(new ProjectResource(projectControlFactory.controlFor(nameKey, self.get())));
} catch (NoSuchProjectException e) {
throw new ResourceNotFoundException(nameKey.get());
}
@@ -121,8 +123,7 @@
projectCache.evict(config.getProject());
pc = open(projectName);
} else if (config.getRevision() != null
- && !config.getRevision().equals(
- pc.getProjectState().getConfig().getRevision())) {
+ && !config.getRevision().equals(pc.getProjectState().getConfig().getRevision())) {
projectCache.evict(config.getProject());
pc = open(projectName);
}
@@ -175,8 +176,7 @@
Boolean canSeeGroup = visibleGroups.get(group);
if (canSeeGroup == null) {
try {
- canSeeGroup = groupControlFactory.controlFor(group)
- .isVisible();
+ canSeeGroup = groupControlFactory.controlFor(group).isVisible();
} catch (NoSuchGroupException e) {
canSeeGroup = Boolean.FALSE;
}
@@ -210,8 +210,7 @@
info.revision = config.getRevision().name();
}
- ProjectState parent =
- Iterables.getFirst(pc.getProjectState().parents(), null);
+ ProjectState parent = Iterables.getFirst(pc.getProjectState().parents(), null);
if (parent != null) {
info.inheritsFrom = projectJson.format(parent.getProject());
}
@@ -223,8 +222,8 @@
}
info.isOwner = toBoolean(pc.isOwner());
- info.canUpload = toBoolean(pc.isOwner()
- || (metaConfigControl.isVisible() && metaConfigControl.canUpload()));
+ info.canUpload =
+ toBoolean(pc.isOwner() || (metaConfigControl.isVisible() && metaConfigControl.canUpload()));
info.canAdd = toBoolean(pc.canAddRefs());
info.configVisible = pc.isOwner() || metaConfigControl.isVisible();
@@ -235,12 +234,11 @@
AccessSectionInfo accessSectionInfo = new AccessSectionInfo();
accessSectionInfo.permissions = new HashMap<>();
for (Permission p : section.getPermissions()) {
- PermissionInfo pInfo = new PermissionInfo(p.getLabel(),
- p.getExclusiveGroup() ? true : null);
+ PermissionInfo pInfo = new PermissionInfo(p.getLabel(), p.getExclusiveGroup() ? true : null);
pInfo.rules = new HashMap<>();
for (PermissionRule r : p.getRules()) {
- PermissionRuleInfo info = new PermissionRuleInfo(
- ACTION_TYPE.get(r.getAction()), r.getForce());
+ PermissionRuleInfo info =
+ new PermissionRuleInfo(ACTION_TYPE.get(r.getAction()), r.getForce());
if (r.hasRange()) {
info.max = r.getMax();
info.min = r.getMin();
@@ -258,8 +256,8 @@
private ProjectControl open(Project.NameKey projectName)
throws ResourceNotFoundException, IOException {
try {
- return projectControlFactory.validateFor(projectName,
- ProjectControl.OWNER | ProjectControl.VISIBLE, self.get());
+ return projectControlFactory.validateFor(
+ projectName, ProjectControl.OWNER | ProjectControl.VISIBLE, self.get());
} catch (NoSuchProjectException e) {
throw new ResourceNotFoundException(projectName.get());
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/GetChildProject.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/GetChildProject.java
index 7737d8c..53e1baa 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/GetChildProject.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/GetChildProject.java
@@ -18,7 +18,6 @@
import com.google.gerrit.extensions.restapi.ResourceNotFoundException;
import com.google.gerrit.extensions.restapi.RestReadView;
import com.google.inject.Inject;
-
import org.kohsuke.args4j.Option;
public class GetChildProject implements RestReadView<ChildProjectResource> {
@@ -36,8 +35,7 @@
}
@Override
- public ProjectInfo apply(ChildProjectResource rsrc)
- throws ResourceNotFoundException {
+ public ProjectInfo apply(ChildProjectResource rsrc) throws ResourceNotFoundException {
if (recursive || rsrc.isDirectChild()) {
return json.format(rsrc.getChild().getProject());
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/GetCommit.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/GetCommit.java
index 63cee1f..bd4492e 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/GetCommit.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/GetCommit.java
@@ -18,10 +18,8 @@
import com.google.gerrit.extensions.restapi.RestReadView;
import com.google.gerrit.server.CommonConverters;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.revwalk.RevCommit;
-
import java.util.ArrayList;
+import org.eclipse.jgit.revwalk.RevCommit;
@Singleton
public class GetCommit implements RestReadView<CommitResource> {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/GetConfig.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/GetConfig.java
index c999119..8192e29 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/GetConfig.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/GetConfig.java
@@ -36,7 +36,8 @@
private final DynamicMap<RestView<ProjectResource>> views;
@Inject
- public GetConfig(@EnableSignedPush boolean serverEnableSignedPush,
+ public GetConfig(
+ @EnableSignedPush boolean serverEnableSignedPush,
TransferConfig config,
DynamicMap<ProjectConfigEntry> pluginConfigEntries,
PluginConfigFactory cfgFactory,
@@ -52,7 +53,13 @@
@Override
public ConfigInfo apply(ProjectResource resource) {
- return new ConfigInfoImpl(serverEnableSignedPush, resource.getControl(),
- config, pluginConfigEntries, cfgFactory, allProjects, views);
+ return new ConfigInfoImpl(
+ serverEnableSignedPush,
+ resource.getControl(),
+ config,
+ pluginConfigEntries,
+ cfgFactory,
+ allProjects,
+ views);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/GetContent.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/GetContent.java
index 23e9e30..10da990f 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/GetContent.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/GetContent.java
@@ -20,7 +20,6 @@
import com.google.gerrit.server.change.FileContentUtil;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
import java.io.IOException;
@Singleton
@@ -33,11 +32,8 @@
}
@Override
- public BinaryResult apply(FileResource rsrc)
- throws ResourceNotFoundException, IOException {
+ public BinaryResult apply(FileResource rsrc) throws ResourceNotFoundException, IOException {
return fileContentUtil.getContent(
- rsrc.getProject().getProjectState(),
- rsrc.getRev(),
- rsrc.getPath());
+ rsrc.getProject().getProjectState(), rsrc.getRev(), rsrc.getPath());
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/GetDashboard.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/GetDashboard.java
index 09555b7..1549658 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/GetDashboard.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/GetDashboard.java
@@ -26,12 +26,10 @@
import com.google.gerrit.extensions.restapi.Url;
import com.google.gerrit.server.project.DashboardsCollection.DashboardInfo;
import com.google.inject.Inject;
-
-import org.eclipse.jgit.errors.ConfigInvalidException;
-import org.kohsuke.args4j.Option;
-
import java.io.IOException;
import java.util.List;
+import org.eclipse.jgit.errors.ConfigInvalidException;
+import org.kohsuke.args4j.Option;
class GetDashboard implements RestReadView<DashboardResource> {
private final DashboardsCollection dashboards;
@@ -102,8 +100,6 @@
List<String> p = Lists.newArrayList(Splitter.on(':').limit(2).split(id));
String ref = Url.encode(p.get(0));
String path = Url.encode(p.get(1));
- return dashboards.parse(
- new ProjectResource(ctl),
- IdString.fromUrl(ref + ':' + path));
+ return dashboards.parse(new ProjectResource(ctl), IdString.fromUrl(ref + ':' + path));
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/GetHead.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/GetHead.java
index 12ca2eb..03db4f6 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/GetHead.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/GetHead.java
@@ -22,7 +22,7 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
+import java.io.IOException;
import org.eclipse.jgit.errors.IncorrectObjectTypeException;
import org.eclipse.jgit.errors.MissingObjectException;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
@@ -32,23 +32,20 @@
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;
-import java.io.IOException;
-
@Singleton
public class GetHead implements RestReadView<ProjectResource> {
private GitRepositoryManager repoManager;
private Provider<ReviewDb> db;
@Inject
- GetHead(GitRepositoryManager repoManager,
- Provider<ReviewDb> db) {
+ GetHead(GitRepositoryManager repoManager, Provider<ReviewDb> db) {
this.repoManager = repoManager;
this.db = db;
}
@Override
- public String apply(ProjectResource rsrc) throws AuthException,
- ResourceNotFoundException, IOException {
+ public String apply(ProjectResource rsrc)
+ throws AuthException, ResourceNotFoundException, IOException {
try (Repository repo = repoManager.openRepository(rsrc.getNameKey())) {
Ref head = repo.getRefDatabase().exactRef(Constants.HEAD);
if (head == null) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/GetReflog.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/GetReflog.java
index 8718a9b..5d0afea 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/GetReflog.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/GetReflog.java
@@ -23,39 +23,51 @@
import com.google.gerrit.server.args4j.TimestampHandler;
import com.google.gerrit.server.git.GitRepositoryManager;
import com.google.inject.Inject;
-
+import java.io.IOException;
+import java.sql.Timestamp;
+import java.util.ArrayList;
+import java.util.List;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
import org.eclipse.jgit.lib.ReflogEntry;
import org.eclipse.jgit.lib.ReflogReader;
import org.eclipse.jgit.lib.Repository;
import org.kohsuke.args4j.Option;
-import java.io.IOException;
-import java.sql.Timestamp;
-import java.util.ArrayList;
-import java.util.List;
-
public class GetReflog implements RestReadView<BranchResource> {
private final GitRepositoryManager repoManager;
- @Option(name = "--limit", aliases = {"-n"}, metaVar = "CNT",
- usage = "maximum number of reflog entries to list")
+ @Option(
+ name = "--limit",
+ aliases = {"-n"},
+ metaVar = "CNT",
+ usage = "maximum number of reflog entries to list"
+ )
public GetReflog setLimit(int limit) {
this.limit = limit;
return this;
}
- @Option(name = "--from", metaVar = "TIMESTAMP",
- usage = "timestamp from which the reflog entries should be listed (UTC, format: "
- + TimestampHandler.TIMESTAMP_FORMAT + ")")
+ @Option(
+ name = "--from",
+ metaVar = "TIMESTAMP",
+ usage =
+ "timestamp from which the reflog entries should be listed (UTC, format: "
+ + TimestampHandler.TIMESTAMP_FORMAT
+ + ")"
+ )
public GetReflog setFrom(Timestamp from) {
this.from = from;
return this;
}
- @Option(name = "--to", metaVar = "TIMESTAMP",
- usage = "timestamp until which the reflog entries should be listed (UTC, format: "
- + TimestampHandler.TIMESTAMP_FORMAT + ")")
+ @Option(
+ name = "--to",
+ metaVar = "TIMESTAMP",
+ usage =
+ "timestamp until which the reflog entries should be listed (UTC, format: "
+ + TimestampHandler.TIMESTAMP_FORMAT
+ + ")"
+ )
public GetReflog setTo(Timestamp to) {
this.to = to;
return this;
@@ -71,8 +83,8 @@
}
@Override
- public List<ReflogEntryInfo> apply(BranchResource rsrc) throws AuthException,
- ResourceNotFoundException, RepositoryNotFoundException, IOException {
+ public List<ReflogEntryInfo> apply(BranchResource rsrc)
+ throws AuthException, ResourceNotFoundException, RepositoryNotFoundException, IOException {
if (!rsrc.getControl().isOwner()) {
throw new AuthException("not project owner");
}
@@ -84,16 +96,12 @@
}
List<ReflogEntry> entries;
if (from == null && to == null) {
- entries =
- limit > 0 ? r.getReverseEntries(limit) : r.getReverseEntries();
+ entries = limit > 0 ? r.getReverseEntries(limit) : r.getReverseEntries();
} else {
- entries = limit > 0
- ? new ArrayList<>(limit)
- : new ArrayList<>();
+ entries = limit > 0 ? new ArrayList<>(limit) : new ArrayList<>();
for (ReflogEntry e : r.getReverseEntries()) {
Timestamp timestamp = new Timestamp(e.getWho().getWhen().getTime());
- if ((from == null || from.before(timestamp)) &&
- (to == null || to.after(timestamp))) {
+ if ((from == null || from.before(timestamp)) && (to == null || to.after(timestamp))) {
entries.add(e);
}
if (limit > 0 && entries.size() >= limit) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/GetStatistics.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/GetStatistics.java
index 723ee63..36d558c 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/GetStatistics.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/GetStatistics.java
@@ -22,15 +22,13 @@
import com.google.gerrit.server.git.GitRepositoryManager;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
+import java.io.IOException;
import org.eclipse.jgit.api.GarbageCollectCommand;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.api.errors.JGitInternalException;
import org.eclipse.jgit.lib.Repository;
-import java.io.IOException;
-
@RequiresCapability(GlobalCapability.RUN_GC)
@Singleton
public class GetStatistics implements RestReadView<ProjectResource> {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/InvalidChangeOperationException.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/InvalidChangeOperationException.java
index e5c6ba5..c09baa0 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/InvalidChangeOperationException.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/InvalidChangeOperationException.java
@@ -14,7 +14,6 @@
package com.google.gerrit.server.project;
-
/** Indicates the change operation is not currently valid. */
public class InvalidChangeOperationException extends Exception {
private static final long serialVersionUID = 1L;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/ListBranches.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/ListBranches.java
index 2da0e01..a5b6458 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/ListBranches.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/ListBranches.java
@@ -31,13 +31,6 @@
import com.google.gerrit.server.git.GitRepositoryManager;
import com.google.inject.Inject;
import com.google.inject.util.Providers;
-
-import org.eclipse.jgit.errors.RepositoryNotFoundException;
-import org.eclipse.jgit.lib.Constants;
-import org.eclipse.jgit.lib.Ref;
-import org.eclipse.jgit.lib.Repository;
-import org.kohsuke.args4j.Option;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
@@ -46,28 +39,53 @@
import java.util.List;
import java.util.Set;
import java.util.TreeMap;
+import org.eclipse.jgit.errors.RepositoryNotFoundException;
+import org.eclipse.jgit.lib.Constants;
+import org.eclipse.jgit.lib.Ref;
+import org.eclipse.jgit.lib.Repository;
+import org.kohsuke.args4j.Option;
public class ListBranches implements RestReadView<ProjectResource> {
private final GitRepositoryManager repoManager;
private final DynamicMap<RestView<BranchResource>> branchViews;
private final WebLinks webLinks;
- @Option(name = "--limit", aliases = {"-n"}, metaVar = "CNT", usage = "maximum number of branches to list")
+ @Option(
+ name = "--limit",
+ aliases = {"-n"},
+ metaVar = "CNT",
+ usage = "maximum number of branches to list"
+ )
public void setLimit(int limit) {
this.limit = limit;
}
- @Option(name = "--start", aliases = {"-s"}, metaVar = "CNT", usage = "number of branches to skip")
+ @Option(
+ name = "--start",
+ aliases = {"-s"},
+ metaVar = "CNT",
+ usage = "number of branches to skip"
+ )
public void setStart(int start) {
this.start = start;
}
- @Option(name = "--match", aliases = {"-m"}, metaVar = "MATCH", usage = "match branches substring")
+ @Option(
+ name = "--match",
+ aliases = {"-m"},
+ metaVar = "MATCH",
+ usage = "match branches substring"
+ )
public void setMatchSubstring(String matchSubstring) {
this.matchSubstring = matchSubstring;
}
- @Option(name = "--regex", aliases = {"-r"}, metaVar = "REGEX", usage = "match branches regex")
+ @Option(
+ name = "--regex",
+ aliases = {"-r"},
+ metaVar = "REGEX",
+ usage = "match branches regex"
+ )
public void setMatchRegex(String matchRegex) {
this.matchRegex = matchRegex;
}
@@ -78,7 +96,8 @@
private String matchRegex;
@Inject
- public ListBranches(GitRepositoryManager repoManager,
+ public ListBranches(
+ GitRepositoryManager repoManager,
DynamicMap<RestView<BranchResource>> branchViews,
WebLinks webLinks) {
this.repoManager = repoManager;
@@ -101,14 +120,13 @@
throws IOException, ResourceNotFoundException {
List<Ref> refs;
try (Repository db = repoManager.openRepository(rsrc.getNameKey())) {
- Collection<Ref> heads =
- db.getRefDatabase().getRefs(Constants.R_HEADS).values();
+ Collection<Ref> heads = db.getRefDatabase().getRefs(Constants.R_HEADS).values();
refs = new ArrayList<>(heads.size() + 3);
refs.addAll(heads);
- refs.addAll(db.getRefDatabase().exactRef(
- Constants.HEAD,
- RefNames.REFS_CONFIG,
- RefNames.REFS_USERS_DEFAULT).values());
+ refs.addAll(
+ db.getRefDatabase()
+ .exactRef(Constants.HEAD, RefNames.REFS_CONFIG, RefNames.REFS_USERS_DEFAULT)
+ .values());
} catch (RepositoryNotFoundException noGitRepository) {
throw new ResourceNotFoundException();
}
@@ -174,17 +192,16 @@
}
}
- private BranchInfo createBranchInfo(Ref ref, RefControl refControl,
- Set<String> targets) {
+ private BranchInfo createBranchInfo(Ref ref, RefControl refControl, Set<String> targets) {
BranchInfo info = new BranchInfo();
info.ref = ref.getName();
info.revision = ref.getObjectId() != null ? ref.getObjectId().name() : null;
- info.canDelete = !targets.contains(ref.getName()) && refControl.canDelete()
- ? true : null;
- for (UiAction.Description d : UiActions.from(
- branchViews,
- new BranchResource(refControl.getProjectControl(), info),
- Providers.of(refControl.getUser()))) {
+ info.canDelete = !targets.contains(ref.getName()) && refControl.canDelete() ? true : null;
+ for (UiAction.Description d :
+ UiActions.from(
+ branchViews,
+ new BranchResource(refControl.getProjectControl(), info),
+ Providers.of(refControl.getUser()))) {
if (info.actions == null) {
info.actions = new TreeMap<>();
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/ListChildProjects.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/ListChildProjects.java
index 0c2f9fc..c14ade6 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/ListChildProjects.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/ListChildProjects.java
@@ -20,14 +20,12 @@
import com.google.gerrit.server.CurrentUser;
import com.google.gerrit.server.config.AllProjectsName;
import com.google.inject.Inject;
-
-import org.kohsuke.args4j.Option;
-
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import org.kohsuke.args4j.Option;
public class ListChildProjects implements RestReadView<ProjectResource> {
@@ -40,9 +38,11 @@
private final ProjectNode.Factory projectNodeFactory;
@Inject
- ListChildProjects(ProjectCache projectCache,
+ ListChildProjects(
+ ProjectCache projectCache,
AllProjectsName allProjectsName,
- ProjectJson json, ProjectNode.Factory projectNodeFactory) {
+ ProjectJson json,
+ ProjectNode.Factory projectNodeFactory) {
this.projectCache = projectCache;
this.allProjects = allProjectsName;
this.json = json;
@@ -56,8 +56,7 @@
@Override
public List<ProjectInfo> apply(ProjectResource rsrc) {
if (recursive) {
- return getChildProjectsRecursively(rsrc.getNameKey(),
- rsrc.getControl().getUser());
+ return getChildProjectsRecursively(rsrc.getNameKey(), rsrc.getControl().getUser());
}
return getDirectChildProjects(rsrc.getNameKey());
}
@@ -77,8 +76,7 @@
return childProjects;
}
- private List<ProjectInfo> getChildProjectsRecursively(Project.NameKey parent,
- CurrentUser user) {
+ private List<ProjectInfo> getChildProjectsRecursively(Project.NameKey parent, CurrentUser user) {
Map<Project.NameKey, ProjectNode> projects = new HashMap<>();
for (Project.NameKey name : projectCache.all()) {
ProjectState p = projectCache.get(name);
@@ -86,8 +84,7 @@
// If we can't get it from the cache, pretend it's not present.
continue;
}
- projects.put(name, projectNodeFactory.create(p.getProject(),
- p.controlFor(user).isVisible()));
+ projects.put(name, projectNodeFactory.create(p.getProject(), p.controlFor(user).isVisible()));
}
for (ProjectNode key : projects.values()) {
ProjectNode node = projects.get(key.getParentName());
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/ListDashboards.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/ListDashboards.java
index 2546ac6..dd69e0e 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/ListDashboards.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/ListDashboards.java
@@ -22,7 +22,9 @@
import com.google.gerrit.server.git.GitRepositoryManager;
import com.google.gerrit.server.project.DashboardsCollection.DashboardInfo;
import com.google.inject.Inject;
-
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
import org.eclipse.jgit.lib.BlobBasedConfig;
@@ -35,10 +37,6 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-
class ListDashboards implements RestReadView<ProjectResource> {
private static final Logger log = LoggerFactory.getLogger(ListDashboards.class);
@@ -53,8 +51,7 @@
}
@Override
- public List<?> apply(ProjectResource resource)
- throws ResourceNotFoundException, IOException {
+ public List<?> apply(ProjectResource resource) throws ResourceNotFoundException, IOException {
ProjectControl ctl = resource.getControl();
String project = ctl.getProject().getName();
if (!inherited) {
@@ -80,16 +77,15 @@
return all;
}
- private List<DashboardInfo> scan(ProjectControl ctl, String project,
- boolean setDefault) throws ResourceNotFoundException, IOException {
+ private List<DashboardInfo> scan(ProjectControl ctl, String project, boolean setDefault)
+ throws ResourceNotFoundException, IOException {
Project.NameKey projectName = ctl.getProject().getNameKey();
try (Repository git = gitManager.openRepository(projectName);
RevWalk rw = new RevWalk(git)) {
List<DashboardInfo> all = new ArrayList<>();
for (Ref ref : git.getRefDatabase().getRefs(REFS_DASHBOARDS).values()) {
if (ctl.controlForRef(ref.getName()).canRead()) {
- all.addAll(scanDashboards(ctl.getProject(), git, rw, ref,
- project, setDefault));
+ all.addAll(scanDashboards(ctl.getProject(), git, rw, ref, project, setDefault));
}
}
return all;
@@ -98,8 +94,13 @@
}
}
- private List<DashboardInfo> scanDashboards(Project definingProject,
- Repository git, RevWalk rw, Ref ref, String project, boolean setDefault)
+ private List<DashboardInfo> scanDashboards(
+ Project definingProject,
+ Repository git,
+ RevWalk rw,
+ Ref ref,
+ String project,
+ boolean setDefault)
throws IOException {
List<DashboardInfo> list = new ArrayList<>();
try (TreeWalk tw = new TreeWalk(rw.getObjectReader())) {
@@ -108,18 +109,19 @@
while (tw.next()) {
if (tw.getFileMode(0) == FileMode.REGULAR_FILE) {
try {
- list.add(DashboardsCollection.parse(
- definingProject,
- ref.getName().substring(REFS_DASHBOARDS.length()),
- tw.getPathString(),
- new BlobBasedConfig(null, git, tw.getObjectId(0)),
- project,
- setDefault));
+ list.add(
+ DashboardsCollection.parse(
+ definingProject,
+ ref.getName().substring(REFS_DASHBOARDS.length()),
+ tw.getPathString(),
+ new BlobBasedConfig(null, git, tw.getObjectId(0)),
+ project,
+ setDefault));
} catch (ConfigInvalidException e) {
- log.warn(String.format(
- "Cannot parse dashboard %s:%s:%s: %s",
- definingProject.getName(), ref.getName(), tw.getPathString(),
- e.getMessage()));
+ log.warn(
+ String.format(
+ "Cannot parse dashboard %s:%s:%s: %s",
+ definingProject.getName(), ref.getName(), tw.getPathString(), e.getMessage()));
}
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/ListProjects.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/ListProjects.java
index 92189dd..a84fefd 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/ListProjects.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/ListProjects.java
@@ -42,15 +42,6 @@
import com.google.gerrit.server.util.TreeFormatter;
import com.google.gson.reflect.TypeToken;
import com.google.inject.Inject;
-
-import org.eclipse.jgit.errors.RepositoryNotFoundException;
-import org.eclipse.jgit.lib.Constants;
-import org.eclipse.jgit.lib.Ref;
-import org.eclipse.jgit.lib.Repository;
-import org.kohsuke.args4j.Option;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@@ -70,6 +61,13 @@
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
+import org.eclipse.jgit.errors.RepositoryNotFoundException;
+import org.eclipse.jgit.lib.Constants;
+import org.eclipse.jgit.lib.Ref;
+import org.eclipse.jgit.lib.Repository;
+import org.kohsuke.args4j.Option;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/** List projects visible to the calling user. */
public class ListProjects implements RestReadView<TopLevelResource> {
@@ -93,8 +91,8 @@
boolean matches(Repository git) throws IOException {
Ref head = git.getRefDatabase().exactRef(Constants.HEAD);
return head != null
- && head.isSymbolic()
- && RefNames.REFS_CONFIG.equals(head.getLeaf().getName());
+ && head.isSymbolic()
+ && RefNames.REFS_CONFIG.equals(head.getLeaf().getName());
}
},
ALL {
@@ -119,15 +117,22 @@
@Option(name = "--format", usage = "(deprecated) output format")
private OutputFormat format = OutputFormat.TEXT;
- @Option(name = "--show-branch", aliases = {"-b"},
- usage = "displays the sha of each project in the specified branch")
+ @Option(
+ name = "--show-branch",
+ aliases = {"-b"},
+ usage = "displays the sha of each project in the specified branch"
+ )
public void addShowBranch(String branch) {
showBranch.add(branch);
}
- @Option(name = "--tree", aliases = {"-t"}, usage =
- "displays project inheritance in a tree-like format\n"
- + "this option does not work together with the show-branch option")
+ @Option(
+ name = "--tree",
+ aliases = {"-t"},
+ usage =
+ "displays project inheritance in a tree-like format\n"
+ + "this option does not work together with the show-branch option"
+ )
public void setShowTree(boolean showTree) {
this.showTree = showTree;
}
@@ -137,7 +142,11 @@
this.type = type;
}
- @Option(name = "--description", aliases = {"-d"}, usage = "include description of project in list")
+ @Option(
+ name = "--description",
+ aliases = {"-d"},
+ usage = "include description of project in list"
+ )
public void setShowDescription(boolean showDescription) {
this.showDescription = showDescription;
}
@@ -147,22 +156,42 @@
this.all = all;
}
- @Option(name = "--limit", aliases = {"-n"}, metaVar = "CNT", usage = "maximum number of projects to list")
+ @Option(
+ name = "--limit",
+ aliases = {"-n"},
+ metaVar = "CNT",
+ usage = "maximum number of projects to list"
+ )
public void setLimit(int limit) {
this.limit = limit;
}
- @Option(name = "--start", aliases = {"-S"}, metaVar = "CNT", usage = "number of projects to skip")
+ @Option(
+ name = "--start",
+ aliases = {"-S"},
+ metaVar = "CNT",
+ usage = "number of projects to skip"
+ )
public void setStart(int start) {
this.start = start;
}
- @Option(name = "--prefix", aliases = {"-p"}, metaVar = "PREFIX", usage = "match project prefix")
+ @Option(
+ name = "--prefix",
+ aliases = {"-p"},
+ metaVar = "PREFIX",
+ usage = "match project prefix"
+ )
public void setMatchPrefix(String matchPrefix) {
this.matchPrefix = matchPrefix;
}
- @Option(name = "--match", aliases = {"-m"}, metaVar = "MATCH", usage = "match project substring")
+ @Option(
+ name = "--match",
+ aliases = {"-m"},
+ metaVar = "MATCH",
+ usage = "match project substring"
+ )
public void setMatchSubstring(String matchSubstring) {
this.matchSubstring = matchSubstring;
}
@@ -172,8 +201,11 @@
this.matchRegex = matchRegex;
}
- @Option(name = "--has-acl-for", metaVar = "GROUP", usage =
- "displays only projects on which access rights for this group are directly assigned")
+ @Option(
+ name = "--has-acl-for",
+ metaVar = "GROUP",
+ usage = "displays only projects on which access rights for this group are directly assigned"
+ )
public void setGroupUuid(AccountGroup.UUID groupUuid) {
this.groupUuid = groupUuid;
}
@@ -191,7 +223,8 @@
private AccountGroup.UUID groupUuid;
@Inject
- protected ListProjects(CurrentUser currentUser,
+ protected ListProjects(
+ CurrentUser currentUser,
ProjectCache projectCache,
GroupsCollection groupsCollection,
GroupControl.Factory groupControlFactory,
@@ -249,8 +282,8 @@
throws BadRequestException {
PrintWriter stdout = null;
if (displayOutputStream != null) {
- stdout = new PrintWriter(new BufferedWriter(
- new OutputStreamWriter(displayOutputStream, UTF_8)));
+ stdout =
+ new PrintWriter(new BufferedWriter(new OutputStreamWriter(displayOutputStream, UTF_8)));
}
int foundIndex = 0;
@@ -278,8 +311,8 @@
} catch (NoSuchGroupException ex) {
break;
}
- if (!pctl.getLocalGroups().contains(
- GroupReference.forGroup(groupsCollection.parseId(groupUuid.get())))) {
+ if (!pctl.getLocalGroups()
+ .contains(GroupReference.forGroup(groupsCollection.parseId(groupUuid.get())))) {
continue;
}
}
@@ -293,8 +326,7 @@
ProjectControl parentCtrl = parentState.controlFor(currentUser);
if (parentCtrl.isVisible() || parentCtrl.isOwner()) {
info.name = parentState.getProject().getName();
- info.description = Strings.emptyToNull(
- parentState.getProject().getDescription());
+ info.description = Strings.emptyToNull(parentState.getProject().getDescription());
info.state = parentState.getProject().getState();
} else {
rejected.add(parentState.getProject().getName());
@@ -307,8 +339,7 @@
} else {
final boolean isVisible = pctl.isVisible() || (all && pctl.isOwner());
if (showTree && !format.isJson()) {
- treeMap.put(projectName,
- projectNodeFactory.create(pctl.getProject(), isVisible));
+ treeMap.put(projectName, projectNodeFactory.create(pctl.getProject(), isVisible));
continue;
}
@@ -377,8 +408,7 @@
log.warn("Unexpected error reading " + projectName, err);
continue;
}
- List<WebLinkInfo> links =
- webLinks.getProjectLinks(projectName.get());
+ List<WebLinkInfo> links = webLinks.getProjectLinks(projectName.get());
info.webLinks = links.isEmpty() ? null : links;
}
@@ -422,8 +452,9 @@
if (stdout == null) {
return output;
} else if (format.isJson()) {
- format.newGson().toJson(
- output, new TypeToken<Map<String, ProjectInfo>>() {}.getType(), stdout);
+ format
+ .newGson()
+ .toJson(output, new TypeToken<Map<String, ProjectInfo>>() {}.getType(), stdout);
stdout.print('\n');
} else if (showTree && treeMap.size() > 0) {
printProjectTree(stdout, treeMap);
@@ -442,19 +473,20 @@
return projectCache.byName(matchPrefix);
} else if (matchSubstring != null) {
checkMatchOptions(matchPrefix == null && matchRegex == null);
- return Iterables.filter(projectCache.all(),
- p -> p.get().toLowerCase(Locale.US)
- .contains(matchSubstring.toLowerCase(Locale.US)));
+ return Iterables.filter(
+ projectCache.all(),
+ p -> p.get().toLowerCase(Locale.US).contains(matchSubstring.toLowerCase(Locale.US)));
} else if (matchRegex != null) {
checkMatchOptions(matchPrefix == null && matchSubstring == null);
RegexListSearcher<Project.NameKey> searcher;
try {
- searcher = new RegexListSearcher<Project.NameKey>(matchRegex) {
- @Override
- public String apply(Project.NameKey in) {
- return in.get();
- }
- };
+ searcher =
+ new RegexListSearcher<Project.NameKey>(matchRegex) {
+ @Override
+ public String apply(Project.NameKey in) {
+ return in.get();
+ }
+ };
} catch (IllegalArgumentException e) {
throw new BadRequestException(e.getMessage());
}
@@ -464,15 +496,14 @@
}
}
- private static void checkMatchOptions(boolean cond)
- throws BadRequestException {
+ private static void checkMatchOptions(boolean cond) throws BadRequestException {
if (!cond) {
throw new BadRequestException("specify exactly one of p/m/r");
}
}
- private void printProjectTree(final PrintWriter stdout,
- final TreeMap<Project.NameKey, ProjectNode> treeMap) {
+ private void printProjectTree(
+ final PrintWriter stdout, final TreeMap<Project.NameKey, ProjectNode> treeMap) {
final SortedSet<ProjectNode> sortedNodes = new TreeSet<>();
// Builds the inheritance tree using a list.
@@ -496,16 +527,15 @@
stdout.flush();
}
- private List<Ref> getBranchRefs(Project.NameKey projectName,
- ProjectControl projectControl) {
+ private List<Ref> getBranchRefs(Project.NameKey projectName, ProjectControl projectControl) {
Ref[] result = new Ref[showBranch.size()];
try (Repository git = repoManager.openRepository(projectName)) {
for (int i = 0; i < showBranch.size(); i++) {
Ref ref = git.findRef(showBranch.get(i));
if (ref != null
- && ref.getObjectId() != null
- && (projectControl.controlForRef(ref.getLeaf().getName()).isVisible())
- || (all && projectControl.isOwner())) {
+ && ref.getObjectId() != null
+ && (projectControl.controlForRef(ref.getLeaf().getName()).isVisible())
+ || (all && projectControl.isOwner())) {
result[i] = ref;
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/ListTags.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/ListTags.java
index 6088c54..9312e49 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/ListTags.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/ListTags.java
@@ -31,7 +31,12 @@
import com.google.gerrit.server.notedb.ChangeNotes;
import com.google.inject.Inject;
import com.google.inject.Provider;
-
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+import java.util.Map;
import org.eclipse.jgit.errors.MissingObjectException;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
import org.eclipse.jgit.lib.Constants;
@@ -43,13 +48,6 @@
import org.eclipse.jgit.revwalk.RevWalk;
import org.kohsuke.args4j.Option;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.List;
-import java.util.Map;
-
public class ListTags implements RestReadView<ProjectResource> {
private final GitRepositoryManager repoManager;
private final Provider<ReviewDb> dbProvider;
@@ -57,22 +55,42 @@
private final ChangeNotes.Factory changeNotesFactory;
@Nullable private final SearchingChangeCacheImpl changeCache;
- @Option(name = "--limit", aliases = {"-n"}, metaVar = "CNT", usage = "maximum number of tags to list")
+ @Option(
+ name = "--limit",
+ aliases = {"-n"},
+ metaVar = "CNT",
+ usage = "maximum number of tags to list"
+ )
public void setLimit(int limit) {
this.limit = limit;
}
- @Option(name = "--start", aliases = {"-s"}, metaVar = "CNT", usage = "number of tags to skip")
+ @Option(
+ name = "--start",
+ aliases = {"-s"},
+ metaVar = "CNT",
+ usage = "number of tags to skip"
+ )
public void setStart(int start) {
this.start = start;
}
- @Option(name = "--match", aliases = {"-m"}, metaVar = "MATCH", usage = "match tags substring")
+ @Option(
+ name = "--match",
+ aliases = {"-m"},
+ metaVar = "MATCH",
+ usage = "match tags substring"
+ )
public void setMatchSubstring(String matchSubstring) {
this.matchSubstring = matchSubstring;
}
- @Option(name = "--regex", aliases = {"-r"}, metaVar = "REGEX", usage = "match tags regex")
+ @Option(
+ name = "--regex",
+ aliases = {"-r"},
+ metaVar = "REGEX",
+ usage = "match tags regex"
+ )
public void setMatchRegex(String matchRegex) {
this.matchRegex = matchRegex;
}
@@ -83,7 +101,8 @@
private String matchRegex;
@Inject
- public ListTags(GitRepositoryManager repoManager,
+ public ListTags(
+ GitRepositoryManager repoManager,
Provider<ReviewDb> dbProvider,
TagCache tagCache,
ChangeNotes.Factory changeNotesFactory,
@@ -96,25 +115,27 @@
}
@Override
- public List<TagInfo> apply(ProjectResource resource) throws IOException,
- ResourceNotFoundException, BadRequestException {
+ public List<TagInfo> apply(ProjectResource resource)
+ throws IOException, ResourceNotFoundException, BadRequestException {
List<TagInfo> tags = new ArrayList<>();
try (Repository repo = getRepository(resource.getNameKey());
RevWalk rw = new RevWalk(repo)) {
- Map<String, Ref> all = visibleTags(resource.getControl(), repo,
- repo.getRefDatabase().getRefs(Constants.R_TAGS));
+ Map<String, Ref> all =
+ visibleTags(resource.getControl(), repo, repo.getRefDatabase().getRefs(Constants.R_TAGS));
for (Ref ref : all.values()) {
tags.add(createTagInfo(ref, rw));
}
}
- Collections.sort(tags, new Comparator<TagInfo>() {
- @Override
- public int compare(TagInfo a, TagInfo b) {
- return a.ref.compareTo(b.ref);
- }
- });
+ Collections.sort(
+ tags,
+ new Comparator<TagInfo>() {
+ @Override
+ public int compare(TagInfo a, TagInfo b) {
+ return a.ref.compareTo(b.ref);
+ }
+ });
return new RefFilter<TagInfo>(Constants.R_TAGS)
.start(start)
@@ -133,8 +154,9 @@
tagName = Constants.R_TAGS + tagName;
}
Ref ref = repo.getRefDatabase().exactRef(tagName);
- if (ref != null && !visibleTags(resource.getControl(), repo,
- ImmutableMap.of(ref.getName(), ref)).isEmpty()) {
+ if (ref != null
+ && !visibleTags(resource.getControl(), repo, ImmutableMap.of(ref.getName(), ref))
+ .isEmpty()) {
return createTagInfo(ref, rw);
}
}
@@ -146,20 +168,17 @@
RevObject object = rw.parseAny(ref.getObjectId());
if (object instanceof RevTag) {
// Annotated or signed tag
- RevTag tag = (RevTag)object;
+ RevTag tag = (RevTag) object;
PersonIdent tagger = tag.getTaggerIdent();
return new TagInfo(
ref.getName(),
tag.getName(),
tag.getObject().getName(),
tag.getFullMessage().trim(),
- tagger != null ?
- CommonConverters.toGitPerson(tag.getTaggerIdent()) : null);
+ tagger != null ? CommonConverters.toGitPerson(tag.getTaggerIdent()) : null);
}
// Lightweight tag
- return new TagInfo(
- ref.getName(),
- ref.getObjectId().getName());
+ return new TagInfo(ref.getName(), ref.getObjectId().getName());
}
private Repository getRepository(Project.NameKey project)
@@ -171,9 +190,10 @@
}
}
- private Map<String, Ref> visibleTags(ProjectControl control, Repository repo,
- Map<String, Ref> tags) {
- return new VisibleRefFilter(tagCache, changeNotesFactory, changeCache, repo,
- control, dbProvider.get(), false).filter(tags, true);
+ private Map<String, Ref> visibleTags(
+ ProjectControl control, Repository repo, Map<String, Ref> tags) {
+ return new VisibleRefFilter(
+ tagCache, changeNotesFactory, changeCache, repo, control, dbProvider.get(), false)
+ .filter(tags, true);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/PerRequestProjectControlCache.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/PerRequestProjectControlCache.java
index f46a881..0f71ac8 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/PerRequestProjectControlCache.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/PerRequestProjectControlCache.java
@@ -18,7 +18,6 @@
import com.google.gerrit.server.CurrentUser;
import com.google.inject.Inject;
import com.google.inject.servlet.RequestScoped;
-
import java.util.HashMap;
import java.util.Map;
@@ -30,8 +29,7 @@
private final Map<Project.NameKey, ProjectControl> controls;
@Inject
- PerRequestProjectControlCache(ProjectCache projectCache,
- CurrentUser userProvider) {
+ PerRequestProjectControlCache(ProjectCache projectCache, CurrentUser userProvider) {
this.projectCache = projectCache;
this.user = userProvider;
this.controls = new HashMap<>();
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/PermissionCollection.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/PermissionCollection.java
index bb1b20e..4bf3e47 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/PermissionCollection.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/PermissionCollection.java
@@ -31,7 +31,6 @@
import com.google.gerrit.server.CurrentUser;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
@@ -43,11 +42,10 @@
/**
* Effective permissions applied to a reference in a project.
- * <p>
- * A collection may be user specific if a matching {@link AccessSection} uses
- * "${username}" in its name. The permissions granted in that section may only
- * be granted to the username that appears in the reference name, and also only
- * if the user is a member of the relevant group.
+ *
+ * <p>A collection may be user specific if a matching {@link AccessSection} uses "${username}" in
+ * its name. The permissions granted in that section may only be granted to the username that
+ * appears in the reference name, and also only if the user is a member of the relevant group.
*/
public class PermissionCollection {
@Singleton
@@ -62,19 +60,16 @@
/**
* Get all permissions that apply to a reference.
*
- * @param matcherList collection of sections that should be considered, in
- * priority order (project specific definitions must appear before
- * inherited ones).
+ * @param matcherList collection of sections that should be considered, in priority order
+ * (project specific definitions must appear before inherited ones).
* @param ref reference being accessed.
- * @param user if the reference is a per-user reference, e.g. access
- * sections using the parameter variable "${username}" will have
- * each username inserted into them to see if they apply to the
- * reference named by {@code ref}.
- * @return map of permissions that apply to this reference, keyed by
- * permission name.
+ * @param user if the reference is a per-user reference, e.g. access sections using the
+ * parameter variable "${username}" will have each username inserted into them to see if
+ * they apply to the reference named by {@code ref}.
+ * @return map of permissions that apply to this reference, keyed by permission name.
*/
- PermissionCollection filter(Iterable<SectionMatcher> matcherList,
- String ref, CurrentUser user) {
+ PermissionCollection filter(
+ Iterable<SectionMatcher> matcherList, String ref, CurrentUser user) {
if (isRE(ref)) {
ref = RefPattern.shortestExample(ref);
} else if (ref.endsWith("/*")) {
@@ -130,8 +125,7 @@
SeenRule s = SeenRule.create(section, permission, rule);
boolean addRule;
if (rule.isBlock()) {
- addRule = !exclusivePermissionsByProject.containsEntry(project,
- permission.getName());
+ addRule = !exclusivePermissionsByProject.containsEntry(project, permission.getName());
} else {
addRule = seen.add(s) && !rule.isDeny() && !exclusivePermissionExists;
}
@@ -161,8 +155,7 @@
}
}
- return new PermissionCollection(permissions, overridden, ruleProps,
- perUser);
+ return new PermissionCollection(permissions, overridden, ruleProps, perUser);
}
}
@@ -171,7 +164,8 @@
private final Map<PermissionRule, ProjectRef> ruleProps;
private final boolean perUser;
- private PermissionCollection(Map<String, List<PermissionRule>> rules,
+ private PermissionCollection(
+ Map<String, List<PermissionRule>> rules,
Map<String, List<PermissionRule>> overridden,
Map<PermissionRule, ProjectRef> ruleProps,
boolean perUser) {
@@ -182,8 +176,8 @@
}
/**
- * @return true if a "${username}" pattern might need to be expanded to build
- * this collection, making the results user specific.
+ * @return true if a "${username}" pattern might need to be expanded to build this collection,
+ * making the results user specific.
*/
public boolean isUserSpecific() {
return perUser;
@@ -193,18 +187,16 @@
* Obtain all permission rules for a given type of permission.
*
* @param permissionName type of permission.
- * @return all rules that apply to this reference, for any group. Never null;
- * the empty list is returned when there are no rules for the requested
- * permission name.
+ * @return all rules that apply to this reference, for any group. Never null; the empty list is
+ * returned when there are no rules for the requested permission name.
*/
public List<PermissionRule> getPermission(String permissionName) {
List<PermissionRule> r = rules.get(permissionName);
- return r != null ? r : Collections.<PermissionRule> emptyList();
+ return r != null ? r : Collections.<PermissionRule>emptyList();
}
List<PermissionRule> getOverridden(String permissionName) {
- return firstNonNull(
- overridden.get(permissionName), Collections.<PermissionRule> emptyList());
+ return firstNonNull(overridden.get(permissionName), Collections.<PermissionRule>emptyList());
}
ProjectRef getRuleProps(PermissionRule rule) {
@@ -214,12 +206,11 @@
/**
* Obtain all declared permission rules that match the reference.
*
- * @return all rules. The collection will iterate a permission if it was
- * declared in the project configuration, either directly or
- * inherited. If the project owner did not use a known permission (for
- * example {@link Permission#FORGE_SERVER}, then it will not be
- * represented in the result even if {@link #getPermission(String)}
- * returns an empty list for the same permission.
+ * @return all rules. The collection will iterate a permission if it was declared in the project
+ * configuration, either directly or inherited. If the project owner did not use a known
+ * permission (for example {@link Permission#FORGE_SERVER}, then it will not be represented in
+ * the result even if {@link #getPermission(String)} returns an empty list for the same
+ * permission.
*/
public Iterable<Map.Entry<String, List<PermissionRule>>> getDeclaredPermissions() {
return rules.entrySet();
@@ -229,14 +220,16 @@
@AutoValue
abstract static class SeenRule {
public abstract String refPattern();
- public abstract String permissionName();
- @Nullable public abstract AccountGroup.UUID group();
- static SeenRule create(AccessSection section, Permission permission,
- @Nullable PermissionRule rule) {
- AccountGroup.UUID group = rule != null && rule.getGroup() != null
- ? rule.getGroup().getUUID()
- : null;
+ public abstract String permissionName();
+
+ @Nullable
+ public abstract AccountGroup.UUID group();
+
+ static SeenRule create(
+ AccessSection section, Permission permission, @Nullable PermissionRule rule) {
+ AccountGroup.UUID group =
+ rule != null && rule.getGroup() != null ? rule.getGroup().getUUID() : null;
return new AutoValue_PermissionCollection_SeenRule(
section.getName(), permission.getName(), group);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/ProjectCache.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/ProjectCache.java
index 67bdc88..65c7315 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/ProjectCache.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/ProjectCache.java
@@ -16,7 +16,6 @@
import com.google.gerrit.reviewdb.client.AccountGroup;
import com.google.gerrit.reviewdb.client.Project;
-
import java.io.IOException;
import java.util.Set;
@@ -44,8 +43,7 @@
* @throws IOException when there was an error.
* @return the cached data; null if no such project exists.
*/
- ProjectState checkedGet(Project.NameKey projectName)
- throws IOException;
+ ProjectState checkedGet(Project.NameKey projectName) throws IOException;
/** Invalidate the cached information about the given project. */
void evict(Project p);
@@ -54,8 +52,8 @@
void evict(Project.NameKey p);
/**
- * Remove information about the given project from the cache. It will no
- * longer be returned from {@link #all()}.
+ * Remove information about the given project from the cache. It will no longer be returned from
+ * {@link #all()}.
*/
void remove(Project p);
@@ -63,9 +61,8 @@
Iterable<Project.NameKey> all();
/**
- * @return estimated set of relevant groups extracted from hot project access
- * rules. If the cache is cold or too small for the entire project set
- * of the server, this set may be incomplete.
+ * @return estimated set of relevant groups extracted from hot project access rules. If the cache
+ * is cold or too small for the entire project set of the server, this set may be incomplete.
*/
Set<AccountGroup.UUID> guessRelevantGroupUUIDs();
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/ProjectCacheClock.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/ProjectCacheClock.java
index c96ebdf..00e82c4 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/ProjectCacheClock.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/ProjectCacheClock.java
@@ -19,12 +19,10 @@
import com.google.gerrit.server.config.GerritServerConfig;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.lib.Config;
-
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
+import org.eclipse.jgit.lib.Config;
/** Ticks periodically to force refresh events for {@link ProjectCacheImpl}. */
@Singleton
@@ -44,21 +42,26 @@
} else if (10 < checkFrequencyMillis) {
// Start with generation 1 (to avoid magic 0 below).
generation = 1;
- ScheduledExecutorService executor = Executors.newScheduledThreadPool(
- 1,
- new ThreadFactoryBuilder()
- .setNameFormat("ProjectCacheClock-%d")
- .setDaemon(true)
- .setPriority(Thread.MIN_PRIORITY)
- .build());
- executor.scheduleAtFixedRate(new Runnable() {
- @Override
- public void run() {
- // This is not exactly thread-safe, but is OK for our use.
- // The only thread that writes the volatile is this task.
- generation = generation + 1;
- }
- }, checkFrequencyMillis, checkFrequencyMillis, TimeUnit.MILLISECONDS);
+ ScheduledExecutorService executor =
+ Executors.newScheduledThreadPool(
+ 1,
+ new ThreadFactoryBuilder()
+ .setNameFormat("ProjectCacheClock-%d")
+ .setDaemon(true)
+ .setPriority(Thread.MIN_PRIORITY)
+ .build());
+ executor.scheduleAtFixedRate(
+ new Runnable() {
+ @Override
+ public void run() {
+ // This is not exactly thread-safe, but is OK for our use.
+ // The only thread that writes the volatile is this task.
+ generation = generation + 1;
+ }
+ },
+ checkFrequencyMillis,
+ checkFrequencyMillis,
+ TimeUnit.MILLISECONDS);
} else {
// Magic generation 0 triggers ProjectState to always
// check on each needsRefresh() request we make to it.
@@ -72,13 +75,12 @@
private static long checkFrequency(Config serverConfig) {
String freq = serverConfig.getString("cache", "projects", "checkFrequency");
- if (freq != null
- && ("disabled".equalsIgnoreCase(freq) || "off".equalsIgnoreCase(freq))) {
+ if (freq != null && ("disabled".equalsIgnoreCase(freq) || "off".equalsIgnoreCase(freq))) {
return Long.MAX_VALUE;
}
return TimeUnit.MILLISECONDS.convert(
- ConfigUtil.getTimeUnit(serverConfig,
- "cache", "projects", "checkFrequency",
- 5, TimeUnit.MINUTES), TimeUnit.MINUTES);
+ ConfigUtil.getTimeUnit(
+ serverConfig, "cache", "projects", "checkFrequency", 5, TimeUnit.MINUTES),
+ TimeUnit.MINUTES);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/ProjectCacheImpl.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/ProjectCacheImpl.java
index c2d7b7d..3ca7bd8 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/ProjectCacheImpl.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/ProjectCacheImpl.java
@@ -34,12 +34,6 @@
import com.google.inject.TypeLiteral;
import com.google.inject.internal.UniqueAnnotations;
import com.google.inject.name.Named;
-
-import org.eclipse.jgit.errors.RepositoryNotFoundException;
-import org.eclipse.jgit.lib.Repository;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.io.IOException;
import java.util.Collections;
import java.util.Iterator;
@@ -50,12 +44,15 @@
import java.util.concurrent.ExecutionException;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
+import org.eclipse.jgit.errors.RepositoryNotFoundException;
+import org.eclipse.jgit.lib.Repository;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/** Cache of project information, including access rights. */
@Singleton
public class ProjectCacheImpl implements ProjectCache {
- private static final Logger log = LoggerFactory
- .getLogger(ProjectCacheImpl.class);
+ private static final Logger log = LoggerFactory.getLogger(ProjectCacheImpl.class);
private static final String CACHE_NAME = "projects";
private static final String CACHE_LIST = "project_list";
@@ -64,20 +61,17 @@
return new CacheModule() {
@Override
protected void configure() {
- cache(CACHE_NAME, String.class, ProjectState.class)
- .loader(Loader.class);
+ cache(CACHE_NAME, String.class, ProjectState.class).loader(Loader.class);
- cache(CACHE_LIST,
- ListKey.class,
- new TypeLiteral<SortedSet<Project.NameKey>>() {})
- .maximumWeight(1)
- .loader(Lister.class);
+ cache(CACHE_LIST, ListKey.class, new TypeLiteral<SortedSet<Project.NameKey>>() {})
+ .maximumWeight(1)
+ .loader(Lister.class);
bind(ProjectCacheImpl.class);
bind(ProjectCache.class).to(ProjectCacheImpl.class);
bind(LifecycleListener.class)
- .annotatedWith(UniqueAnnotations.create())
- .to(ProjectCacheWarmer.class);
+ .annotatedWith(UniqueAnnotations.create())
+ .to(ProjectCacheWarmer.class);
}
};
}
@@ -127,7 +121,7 @@
@Override
public ProjectState get(final Project.NameKey projectName) {
- try {
+ try {
return checkedGet(projectName);
} catch (IOException e) {
return null;
@@ -135,8 +129,7 @@
}
@Override
- public ProjectState checkedGet(Project.NameKey projectName)
- throws IOException {
+ public ProjectState checkedGet(Project.NameKey projectName) throws IOException {
if (projectName == null) {
return null;
}
@@ -213,7 +206,9 @@
@Override
public Set<AccountGroup.UUID> guessRelevantGroupUUIDs() {
- return all().stream().map(n -> byName.getIfPresent(n.get()))
+ return all()
+ .stream()
+ .map(n -> byName.getIfPresent(n.get()))
.filter(Objects::nonNull)
.flatMap(p -> p.getConfig().getAllGroupUUIDs().stream())
// getAllGroupUUIDs shouldn't really return null UUIDs, but harden
@@ -252,7 +247,7 @@
next = r;
return true;
}
- itr = Collections.<Project.NameKey> emptyList().iterator();
+ itr = Collections.<Project.NameKey>emptyList().iterator();
return false;
}
@@ -306,8 +301,7 @@
static class ListKey {
static final ListKey ALL = new ListKey();
- private ListKey() {
- }
+ private ListKey() {}
}
static class Lister extends CacheLoader<ListKey, SortedSet<Project.NameKey>> {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/ProjectCacheWarmer.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/ProjectCacheWarmer.java
index 729aa9d..5e0ba28 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/ProjectCacheWarmer.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/ProjectCacheWarmer.java
@@ -20,21 +20,18 @@
import com.google.gerrit.server.config.GerritServerConfig;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.lib.Config;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
+import org.eclipse.jgit.lib.Config;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
@Singleton
public class ProjectCacheWarmer implements LifecycleListener {
- private static final Logger log =
- LoggerFactory.getLogger(ProjectCacheWarmer.class);
+ private static final Logger log = LoggerFactory.getLogger(ProjectCacheWarmer.class);
private final Config config;
private final ProjectCache cache;
@@ -50,36 +47,37 @@
int cpus = Runtime.getRuntime().availableProcessors();
if (config.getBoolean("cache", "projects", "loadOnStartup", false)) {
final ThreadPoolExecutor pool =
- new ScheduledThreadPoolExecutor(config.getInt("cache", "projects",
- "loadThreads", cpus), new ThreadFactoryBuilder().setNameFormat(
- "ProjectCacheLoader-%d").build());
+ new ScheduledThreadPoolExecutor(
+ config.getInt("cache", "projects", "loadThreads", cpus),
+ new ThreadFactoryBuilder().setNameFormat("ProjectCacheLoader-%d").build());
ExecutorService scheduler = Executors.newFixedThreadPool(1);
log.info("Loading project cache");
- scheduler.execute(new Runnable() {
- @Override
- public void run() {
- for (final Project.NameKey name : cache.all()) {
- pool.execute(new Runnable() {
- @Override
- public void run() {
- cache.get(name);
+ scheduler.execute(
+ new Runnable() {
+ @Override
+ public void run() {
+ for (final Project.NameKey name : cache.all()) {
+ pool.execute(
+ new Runnable() {
+ @Override
+ public void run() {
+ cache.get(name);
+ }
+ });
}
- });
- }
- pool.shutdown();
- try {
- pool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
- log.info("Finished loading project cache");
- } catch (InterruptedException e) {
- log.warn("Interrupted while waiting for project cache to load");
- }
- }
- });
+ pool.shutdown();
+ try {
+ pool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
+ log.info("Finished loading project cache");
+ } catch (InterruptedException e) {
+ log.warn("Interrupted while waiting for project cache to load");
+ }
+ }
+ });
}
}
@Override
- public void stop() {
- }
+ public void stop() {}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/ProjectControl.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/ProjectControl.java
index ca01630..d312951 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/ProjectControl.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/ProjectControl.java
@@ -48,14 +48,6 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.assistedinject.Assisted;
-
-import org.eclipse.jgit.lib.Ref;
-import org.eclipse.jgit.lib.Repository;
-import org.eclipse.jgit.revwalk.RevCommit;
-import org.eclipse.jgit.revwalk.RevWalk;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
@@ -65,6 +57,12 @@
import java.util.List;
import java.util.Map;
import java.util.Set;
+import org.eclipse.jgit.lib.Ref;
+import org.eclipse.jgit.lib.Repository;
+import org.eclipse.jgit.revwalk.RevCommit;
+import org.eclipse.jgit.revwalk.RevWalk;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/** Access control management for a user accessing a project's data. */
public class ProjectControl {
@@ -90,8 +88,8 @@
return p.controlFor(user);
}
- public ProjectControl validateFor(Project.NameKey nameKey, int need,
- CurrentUser user) throws NoSuchProjectException, IOException {
+ public ProjectControl validateFor(Project.NameKey nameKey, int need, CurrentUser user)
+ throws NoSuchProjectException, IOException {
final ProjectControl c = controlFor(nameKey, user);
if ((need & VISIBLE) == VISIBLE && c.isVisible()) {
return c;
@@ -111,23 +109,20 @@
userCache = uc;
}
- public ProjectControl controlFor(final Project.NameKey nameKey)
- throws NoSuchProjectException {
+ public ProjectControl controlFor(final Project.NameKey nameKey) throws NoSuchProjectException {
return userCache.get().get(nameKey);
}
- public ProjectControl validateFor(final Project.NameKey nameKey)
- throws NoSuchProjectException {
+ public ProjectControl validateFor(final Project.NameKey nameKey) throws NoSuchProjectException {
return validateFor(nameKey, VISIBLE);
}
- public ProjectControl ownerFor(final Project.NameKey nameKey)
- throws NoSuchProjectException {
+ public ProjectControl ownerFor(final Project.NameKey nameKey) throws NoSuchProjectException {
return validateFor(nameKey, OWNER);
}
- public ProjectControl validateFor(final Project.NameKey nameKey,
- final int need) throws NoSuchProjectException {
+ public ProjectControl validateFor(final Project.NameKey nameKey, final int need)
+ throws NoSuchProjectException {
final ProjectControl c = controlFor(nameKey);
if ((need & VISIBLE) == VISIBLE && c.isVisible()) {
return c;
@@ -164,7 +159,8 @@
private Boolean declaredOwner;
@Inject
- ProjectControl(@GitUploadPackGroups Set<AccountGroup.UUID> uploadGroups,
+ ProjectControl(
+ @GitUploadPackGroups Set<AccountGroup.UUID> uploadGroups,
@GitReceivePackGroups Set<AccountGroup.UUID> receiveGroups,
ProjectCache pc,
PermissionCollection.Factory permissionFilter,
@@ -197,28 +193,24 @@
return r;
}
- public ChangeControl controlFor(ReviewDb db, Change change)
- throws OrmException {
- return changeControlFactory.create(controlForRef(change.getDest()), db,
- change.getProject(), change.getId());
+ public ChangeControl controlFor(ReviewDb db, Change change) throws OrmException {
+ return changeControlFactory.create(
+ controlForRef(change.getDest()), db, change.getProject(), change.getId());
}
/**
- * Create a change control for a change that was loaded from index. This
- * method should only be used when database access is harmful and potentially
- * stale data from the index is acceptable.
+ * Create a change control for a change that was loaded from index. This method should only be
+ * used when database access is harmful and potentially stale data from the index is acceptable.
*
* @param change change loaded from secondary index
* @return change control
*/
public ChangeControl controlForIndexedChange(Change change) {
- return changeControlFactory
- .createForIndexedChange(controlForRef(change.getDest()), change);
+ return changeControlFactory.createForIndexedChange(controlForRef(change.getDest()), change);
}
public ChangeControl controlFor(ChangeNotes notes) {
- return changeControlFactory
- .create(controlForRef(notes.getChange().getDest()), notes);
+ return changeControlFactory.create(controlForRef(notes.getChange().getDest()), notes);
}
public RefControl controlForRef(Branch.NameKey ref) {
@@ -231,8 +223,7 @@
}
RefControl ctl = refControls.get(refName);
if (ctl == null) {
- PermissionCollection relevant =
- permissionFilter.filter(access(), refName, user);
+ PermissionCollection relevant = permissionFilter.filter(access(), refName, user);
ctl = new RefControl(this, refName, relevant);
refControls.put(refName, ctl);
}
@@ -260,30 +251,26 @@
/** Returns whether the project is hidden. */
public boolean isHidden() {
- return getProject().getState().equals(
- com.google.gerrit.extensions.client.ProjectState.HIDDEN);
+ return getProject().getState().equals(com.google.gerrit.extensions.client.ProjectState.HIDDEN);
}
/**
- * Returns whether the project is readable to the current user. Note
- * that the project could still be hidden.
+ * Returns whether the project is readable to the current user. Note that the project could still
+ * be hidden.
*/
public boolean isReadable() {
- return (user.isInternalUser()
- || canPerformOnAnyRef(Permission.READ));
+ return (user.isInternalUser() || canPerformOnAnyRef(Permission.READ));
}
/**
- * Returns whether the project is accessible to the current user, i.e.
- * readable and not hidden.
+ * Returns whether the project is accessible to the current user, i.e. readable and not hidden.
*/
public boolean isVisible() {
return isReadable() && !isHidden();
}
public boolean canAddRefs() {
- return (canPerformOnAnyRef(Permission.CREATE)
- || isOwnerAnyRef());
+ return (canPerformOnAnyRef(Permission.CREATE) || isOwnerAnyRef());
}
public boolean canUpload() {
@@ -291,8 +278,7 @@
AccessSection section = matcher.section;
if (section.getName().startsWith("refs/for/")) {
Permission permission = section.getPermission(Permission.PUSH);
- if (permission != null
- && controlForRef(section.getName()).canPerform(Permission.PUSH)) {
+ if (permission != null && controlForRef(section.getName()).canPerform(Permission.PUSH)) {
return true;
}
}
@@ -302,18 +288,16 @@
/** Can this user see all the refs in this projects? */
public boolean allRefsAreVisible() {
- return allRefsAreVisible(Collections.<String> emptySet());
+ return allRefsAreVisible(Collections.<String>emptySet());
}
public boolean allRefsAreVisible(Set<String> ignore) {
- return user.isInternalUser()
- || canPerformOnAllRefs(Permission.READ, ignore);
+ return user.isInternalUser() || canPerformOnAllRefs(Permission.READ, ignore);
}
/** Is this user a project owner? Ownership does not imply {@link #isVisible()} */
public boolean isOwner() {
- return (isDeclaredOwner()
- && !controlForRef("refs/*").isBlocked(Permission.OWNER))
+ return (isDeclaredOwner() && !controlForRef("refs/*").isBlocked(Permission.OWNER))
|| user.getCapabilities().canAdministrateServer();
}
@@ -327,14 +311,12 @@
/** Does this user have ownership on at least one reference name? */
public boolean isOwnerAnyRef() {
- return canPerformOnAnyRef(Permission.OWNER)
- || user.getCapabilities().canAdministrateServer();
+ return canPerformOnAnyRef(Permission.OWNER) || user.getCapabilities().canAdministrateServer();
}
/** @return true if the user can upload to at least one reference */
public Capable canPushToAtLeastOneRef() {
- if (!canPerformOnAnyRef(Permission.PUSH) &&
- !canPerformOnAnyRef(Permission.CREATE_TAG)) {
+ if (!canPerformOnAnyRef(Permission.PUSH) && !canPerformOnAnyRef(Permission.CREATE_TAG)) {
String pName = state.getProject().getName();
return new Capable("Upload denied for project '" + pName + "'");
}
@@ -352,8 +334,7 @@
return getGroups(localAccess());
}
- private static Set<GroupReference> getGroups(
- final List<SectionMatcher> sectionMatcherList) {
+ private static Set<GroupReference> getGroups(final List<SectionMatcher> sectionMatcherList) {
final Set<GroupReference> all = new HashSet<>();
for (final SectionMatcher matcher : sectionMatcherList) {
final AccessSection section = matcher.section;
@@ -367,7 +348,7 @@
}
private Capable verifyActiveContributorAgreement() {
- if (! (user.isIdentifiedUser())) {
+ if (!(user.isIdentifiedUser())) {
return new Capable("Must be logged in to verify Contributor Agreement");
}
final IdentifiedUser iUser = user.asIdentifiedUser();
@@ -378,7 +359,8 @@
groupIds = okGroupIds;
for (PermissionRule rule : ca.getAccepted()) {
- if ((rule.getAction() == Action.ALLOW) && (rule.getGroup() != null)
+ if ((rule.getAction() == Action.ALLOW)
+ && (rule.getGroup() != null)
&& (rule.getGroup().getUUID() != null)) {
groupIds.add(new AccountGroup.UUID(rule.getGroup().getUUID().get()));
}
@@ -522,45 +504,44 @@
public boolean canReadCommit(ReviewDb db, Repository repo, RevCommit commit) {
// Look for changes associated with the commit.
try {
- List<ChangeData> changes = queryProvider.get()
- .byProjectCommit(getProject().getNameKey(), commit);
+ List<ChangeData> changes =
+ queryProvider.get().byProjectCommit(getProject().getNameKey(), commit);
for (ChangeData change : changes) {
if (controlFor(db, change.change()).isVisible(db)) {
return true;
}
}
} catch (OrmException e) {
- log.error("Cannot look up change for commit " + commit.name() + " in "
- + getProject().getName(), e);
+ log.error(
+ "Cannot look up change for commit " + commit.name() + " in " + getProject().getName(), e);
}
// Scan all visible refs.
return canReadCommitFromVisibleRef(db, repo, commit);
}
- private boolean canReadCommitFromVisibleRef(ReviewDb db, Repository repo,
- RevCommit commit) {
+ private boolean canReadCommitFromVisibleRef(ReviewDb db, Repository repo, RevCommit commit) {
try (RevWalk rw = new RevWalk(repo)) {
- return isMergedIntoVisibleRef(repo, db, rw, commit,
- repo.getAllRefs().values());
+ return isMergedIntoVisibleRef(repo, db, rw, commit, repo.getAllRefs().values());
} catch (IOException e) {
- String msg = String.format(
- "Cannot verify permissions to commit object %s in repository %s",
- commit.name(), getProject().getNameKey());
+ String msg =
+ String.format(
+ "Cannot verify permissions to commit object %s in repository %s",
+ commit.name(), getProject().getNameKey());
log.error(msg, e);
return false;
}
}
- boolean isMergedIntoVisibleRef(Repository repo, ReviewDb db, RevWalk rw,
- RevCommit commit, Collection<Ref> unfilteredRefs) throws IOException {
- VisibleRefFilter filter = new VisibleRefFilter(
- tagCache, changeNotesFactory, changeCache, repo, this, db, true);
+ boolean isMergedIntoVisibleRef(
+ Repository repo, ReviewDb db, RevWalk rw, RevCommit commit, Collection<Ref> unfilteredRefs)
+ throws IOException {
+ VisibleRefFilter filter =
+ new VisibleRefFilter(tagCache, changeNotesFactory, changeCache, repo, this, db, true);
Map<String, Ref> m = Maps.newHashMapWithExpectedSize(unfilteredRefs.size());
for (Ref r : unfilteredRefs) {
m.put(r.getName(), r);
}
Map<String, Ref> refs = filter.filter(m, true);
- return !refs.isEmpty()
- && IncludedInResolver.includedInOne(repo, rw, commit, refs.values());
+ return !refs.isEmpty() && IncludedInResolver.includedInOne(repo, rw, commit, refs.values());
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/ProjectHierarchyIterator.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/ProjectHierarchyIterator.java
index 0724ce9..9d9e5bb 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/ProjectHierarchyIterator.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/ProjectHierarchyIterator.java
@@ -19,19 +19,17 @@
import com.google.common.collect.Sets;
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.server.config.AllProjectsName;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* Iterates from a project up through its parents to All-Projects.
- * <p>
- * If a cycle is detected the cycle is broken and All-Projects is visited.
+ *
+ * <p>If a cycle is detected the cycle is broken and All-Projects is visited.
*/
class ProjectHierarchyIterator implements Iterator<ProjectState> {
private static final Logger log = LoggerFactory.getLogger(ProjectHierarchyIterator.class);
@@ -41,9 +39,7 @@
private final Set<Project.NameKey> seen;
private ProjectState next;
- ProjectHierarchyIterator(ProjectCache c,
- AllProjectsName all,
- ProjectState firstResult) {
+ ProjectHierarchyIterator(ProjectCache c, AllProjectsName all, ProjectState firstResult) {
cache = c;
allProjectsName = all;
@@ -95,8 +91,8 @@
}
int idx = order.lastIndexOf(parentName.get());
order.add(parentName.get());
- log.warn("Cycle detected in projects: "
- + Joiner.on(" -> ").join(order.subList(idx, order.size())));
+ log.warn(
+ "Cycle detected in projects: " + Joiner.on(" -> ").join(order.subList(idx, order.size())));
return false;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/ProjectJson.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/ProjectJson.java
index 767e36a..b4b9c49 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/ProjectJson.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/ProjectJson.java
@@ -23,7 +23,6 @@
import com.google.gerrit.server.config.AllProjectsName;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
import java.util.List;
@Singleton
@@ -33,8 +32,7 @@
private final WebLinks webLinks;
@Inject
- ProjectJson(AllProjectsName allProjectsName,
- WebLinks webLinks) {
+ ProjectJson(AllProjectsName allProjectsName, WebLinks webLinks) {
this.allProjects = allProjectsName;
this.webLinks = webLinks;
}
@@ -51,8 +49,7 @@
info.description = Strings.emptyToNull(p.getDescription());
info.state = p.getState();
info.id = Url.encode(info.name);
- List<WebLinkInfo> links =
- webLinks.getProjectLinks(p.getName());
+ List<WebLinkInfo> links = webLinks.getProjectLinks(p.getName());
info.webLinks = links.isEmpty() ? null : links;
return info;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/ProjectNode.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/ProjectNode.java
index 9eafc4bc..403efd2 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/ProjectNode.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/ProjectNode.java
@@ -19,7 +19,6 @@
import com.google.gerrit.server.util.TreeFormatter.TreeNode;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
-
import java.util.SortedSet;
import java.util.TreeSet;
@@ -36,8 +35,10 @@
private final SortedSet<ProjectNode> children = new TreeSet<>();
@Inject
- protected ProjectNode(final AllProjectsName allProjectsName,
- @Assisted final Project project, @Assisted final boolean isVisible) {
+ protected ProjectNode(
+ final AllProjectsName allProjectsName,
+ @Assisted final Project project,
+ @Assisted final boolean isVisible) {
this.allProjectsName = allProjectsName;
this.project = project;
this.isVisible = isVisible;
@@ -46,8 +47,7 @@
/**
* Returns the project parent name.
*
- * @return Project parent name, {@code null} for the 'All-Projects' root
- * project
+ * @return Project parent name, {@code null} for the 'All-Projects' root project
*/
public Project.NameKey getParentName() {
return project.getParent(allProjectsName);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/ProjectRef.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/ProjectRef.java
index 8d3185d..be5fda0 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/ProjectRef.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/ProjectRef.java
@@ -20,6 +20,7 @@
@AutoValue
abstract class ProjectRef {
public abstract Project.NameKey project();
+
public abstract String ref();
static ProjectRef create(Project.NameKey project, String ref) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/ProjectState.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/ProjectState.java
index f4ef129..8b8745e 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/ProjectState.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/ProjectState.java
@@ -48,16 +48,8 @@
import com.google.gerrit.server.git.ProjectLevelConfig;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
-
import com.googlecode.prolog_cafe.exceptions.CompileException;
import com.googlecode.prolog_cafe.lang.PrologMachineCopy;
-
-import org.eclipse.jgit.errors.ConfigInvalidException;
-import org.eclipse.jgit.lib.Ref;
-import org.eclipse.jgit.lib.Repository;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.io.IOException;
import java.io.Reader;
import java.nio.file.Files;
@@ -73,11 +65,15 @@
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
+import org.eclipse.jgit.errors.ConfigInvalidException;
+import org.eclipse.jgit.lib.Ref;
+import org.eclipse.jgit.lib.Repository;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/** Cached information on a project. */
public class ProjectState {
- private static final Logger log =
- LoggerFactory.getLogger(ProjectState.class);
+ private static final Logger log = LoggerFactory.getLogger(ProjectState.class);
public interface Factory {
ProjectState create(ProjectConfig config);
@@ -138,9 +134,10 @@
this.commentLinks = commentLinks;
this.config = config;
this.configs = new HashMap<>();
- this.capabilities = isAllProjects
- ? capabilityFactory.create(config.getAccessSection(AccessSection.GLOBAL_CAPABILITIES))
- : null;
+ this.capabilities =
+ isAllProjects
+ ? capabilityFactory.create(config.getAccessSection(AccessSection.GLOBAL_CAPABILITIES))
+ : null;
if (isAllProjects && !Permission.canBeOnAllProjects(AccessSection.ALL, Permission.OWNER)) {
localOwners = Collections.emptySet();
@@ -190,9 +187,8 @@
}
/**
- * @return cached computation of all global capabilities. This should only be
- * invoked on the state from {@link ProjectCache#getAllProjects()}.
- * Null on any other project.
+ * @return cached computation of all global capabilities. This should only be invoked on the state
+ * from {@link ProjectCache#getAllProjects()}. Null on any other project.
*/
public CapabilityCollection getCapabilityCollection() {
return capabilities;
@@ -202,24 +198,21 @@
public PrologEnvironment newPrologEnvironment() throws CompileException {
PrologMachineCopy pmc = rulesMachine;
if (pmc == null) {
- pmc = rulesCache.loadMachine(
- getProject().getNameKey(),
- config.getRulesId());
+ pmc = rulesCache.loadMachine(getProject().getNameKey(), config.getRulesId());
rulesMachine = pmc;
}
return envFactory.create(pmc);
}
/**
- * Like {@link #newPrologEnvironment()} but instead of reading the rules.pl
- * read the provided input stream.
+ * Like {@link #newPrologEnvironment()} but instead of reading the rules.pl read the provided
+ * input stream.
*
* @param name a name of the input stream. Could be any name.
* @param in stream to read prolog rules from
* @throws CompileException
*/
- public PrologEnvironment newPrologEnvironment(String name, Reader in)
- throws CompileException {
+ public PrologEnvironment newPrologEnvironment(String name, Reader in) throws CompileException {
PrologMachineCopy pmc = rulesCache.loadMachine(name, in);
return envFactory.create(pmc);
}
@@ -260,8 +253,7 @@
sm = new ArrayList<>(fromConfig.size());
for (AccessSection section : fromConfig) {
if (isAllProjects) {
- List<Permission> copy =
- Lists.newArrayListWithCapacity(section.getPermissions().size());
+ List<Permission> copy = Lists.newArrayListWithCapacity(section.getPermissions().size());
for (Permission p : section.getPermissions()) {
if (Permission.canBeOnAllProjects(section.getName(), p.getName())) {
copy.add(p);
@@ -271,8 +263,7 @@
section.setPermissions(copy);
}
- SectionMatcher matcher = SectionMatcher.wrap(getProject().getNameKey(),
- section);
+ SectionMatcher matcher = SectionMatcher.wrap(getProject().getNameKey(), section);
if (matcher != null) {
sm.add(matcher);
}
@@ -283,9 +274,8 @@
}
/**
- * Obtain all local and inherited sections. This collection is looked up
- * dynamically and is not cached. Callers should try to cache this result
- * per-request as much as possible.
+ * Obtain all local and inherited sections. This collection is looked up dynamically and is not
+ * cached. Callers should try to cache this result per-request as much as possible.
*/
List<SectionMatcher> getAllSections() {
if (isAllProjects) {
@@ -300,10 +290,9 @@
}
/**
- * @return all {@link AccountGroup}'s to which the owner privilege for
- * 'refs/*' is assigned for this project (the local owners), if there
- * are no local owners the local owners of the nearest parent project
- * that has local owners are returned
+ * @return all {@link AccountGroup}'s to which the owner privilege for 'refs/*' is assigned for
+ * this project (the local owners), if there are no local owners the local owners of the
+ * nearest parent project that has local owners are returned
*/
public Set<AccountGroup.UUID> getOwners() {
for (ProjectState p : tree()) {
@@ -315,11 +304,10 @@
}
/**
- * @return all {@link AccountGroup}'s that are allowed to administrate the
- * complete project. This includes all groups to which the owner
- * privilege for 'refs/*' is assigned for this project (the local
- * owners) and all groups to which the owner privilege for 'refs/*' is
- * assigned for one of the parent projects (the inherited owners).
+ * @return all {@link AccountGroup}'s that are allowed to administrate the complete project. This
+ * includes all groups to which the owner privilege for 'refs/*' is assigned for this project
+ * (the local owners) and all groups to which the owner privilege for 'refs/*' is assigned for
+ * one of the parent projects (the inherited owners).
*/
public Set<AccountGroup.UUID> getAllOwners() {
Set<AccountGroup.UUID> result = new HashSet<>();
@@ -336,24 +324,21 @@
}
/**
- * @return an iterable that walks through this project and then the parents of
- * this project. Starts from this project and progresses up the
- * hierarchy to All-Projects.
+ * @return an iterable that walks through this project and then the parents of this project.
+ * Starts from this project and progresses up the hierarchy to All-Projects.
*/
public Iterable<ProjectState> tree() {
return new Iterable<ProjectState>() {
@Override
public Iterator<ProjectState> iterator() {
- return new ProjectHierarchyIterator(
- projectCache, allProjectsName,
- ProjectState.this);
+ return new ProjectHierarchyIterator(projectCache, allProjectsName, ProjectState.this);
}
};
}
/**
- * @return an iterable that walks in-order from All-Projects through the
- * project hierarchy to this project.
+ * @return an iterable that walks in-order from All-Projects through the project hierarchy to this
+ * project.
*/
public Iterable<ProjectState> treeInOrder() {
List<ProjectState> projects = Lists.newArrayList(tree());
@@ -362,9 +347,8 @@
}
/**
- * @return an iterable that walks through the parents of this project. Starts
- * from the immediate parent of this project and progresses up the
- * hierarchy to All-Projects.
+ * @return an iterable that walks through the parents of this project. Starts from the immediate
+ * parent of this project and progresses up the hierarchy to All-Projects.
*/
public FluentIterable<ProjectState> parents() {
return FluentIterable.from(tree()).skip(1);
@@ -462,8 +446,7 @@
return null;
}
- public Collection<SubscribeSection> getSubscribeSections(
- Branch.NameKey branch) {
+ public Collection<SubscribeSection> getSubscribeSections(Branch.NameKey branch) {
Collection<SubscribeSection> ret = new ArrayList<>();
for (ProjectState s : tree()) {
ret.addAll(s.getConfig().getSubscribeSections(branch));
@@ -499,7 +482,8 @@
return ThemeInfo.INHERIT;
}
try {
- return new ThemeInfo(readFile(dir.resolve(SitePaths.CSS_FILENAME)),
+ return new ThemeInfo(
+ readFile(dir.resolve(SitePaths.CSS_FILENAME)),
readFile(dir.resolve(SitePaths.HEADER_FILENAME)),
readFile(dir.resolve(SitePaths.FOOTER_FILENAME)));
} catch (IOException e) {
@@ -512,8 +496,7 @@
return Files.exists(p) ? new String(Files.readAllBytes(p), UTF_8) : null;
}
- private boolean getInheritableBoolean(
- Function<Project, InheritableBoolean> func) {
+ private boolean getInheritableBoolean(Function<Project, InheritableBoolean> func) {
for (ProjectState s : tree()) {
switch (func.apply(s.getProject())) {
case TRUE:
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/ProjectsCollection.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/ProjectsCollection.java
index 51603fc..dcb3404 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/ProjectsCollection.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/ProjectsCollection.java
@@ -28,15 +28,12 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
+import java.io.IOException;
import org.eclipse.jgit.lib.Constants;
-import java.io.IOException;
-
@Singleton
-public class ProjectsCollection implements
- RestCollection<TopLevelResource, ProjectResource>,
- AcceptsCreate<TopLevelResource> {
+public class ProjectsCollection
+ implements RestCollection<TopLevelResource, ProjectResource>, AcceptsCreate<TopLevelResource> {
private final DynamicMap<RestView<ProjectResource>> views;
private final Provider<ListProjects> list;
private final ProjectControl.GenericFactory controlFactory;
@@ -44,10 +41,12 @@
private final CreateProject.Factory createProjectFactory;
@Inject
- ProjectsCollection(DynamicMap<RestView<ProjectResource>> views,
+ ProjectsCollection(
+ DynamicMap<RestView<ProjectResource>> views,
Provider<ListProjects> list,
ProjectControl.GenericFactory controlFactory,
- CreateProject.Factory factory, Provider<CurrentUser> user) {
+ CreateProject.Factory factory,
+ Provider<CurrentUser> user) {
this.views = views;
this.list = list;
this.controlFactory = controlFactory;
@@ -75,12 +74,11 @@
*
* @param id ID of the project, can be a project name
* @return the project
- * @throws UnprocessableEntityException thrown if the project ID cannot be
- * resolved or if the project is not visible to the calling user
+ * @throws UnprocessableEntityException thrown if the project ID cannot be resolved or if the
+ * project is not visible to the calling user
* @throws IOException thrown when there is an error.
*/
- public ProjectResource parse(String id)
- throws UnprocessableEntityException, IOException {
+ public ProjectResource parse(String id) throws UnprocessableEntityException, IOException {
return parse(id, true);
}
@@ -88,34 +86,28 @@
* Parses a project ID from a request body and returns the project.
*
* @param id ID of the project, can be a project name
- * @param checkVisibility Whether to check or not that project is visible to
- * the calling user
+ * @param checkVisibility Whether to check or not that project is visible to the calling user
* @return the project
- * @throws UnprocessableEntityException thrown if the project ID cannot be
- * resolved or if the project is not visible to the calling user and
- * checkVisibility is true.
+ * @throws UnprocessableEntityException thrown if the project ID cannot be resolved or if the
+ * project is not visible to the calling user and checkVisibility is true.
* @throws IOException thrown when there is an error.
*/
public ProjectResource parse(String id, boolean checkVisibility)
throws UnprocessableEntityException, IOException {
ProjectResource rsrc = _parse(id, checkVisibility);
if (rsrc == null) {
- throw new UnprocessableEntityException(String.format(
- "Project Not Found: %s", id));
+ throw new UnprocessableEntityException(String.format("Project Not Found: %s", id));
}
return rsrc;
}
- private ProjectResource _parse(String id, boolean checkVisibility)
- throws IOException {
+ private ProjectResource _parse(String id, boolean checkVisibility) throws IOException {
if (id.endsWith(Constants.DOT_GIT_EXT)) {
id = id.substring(0, id.length() - Constants.DOT_GIT_EXT.length());
}
ProjectControl ctl;
try {
- ctl = controlFactory.controlFor(
- new Project.NameKey(id),
- user.get());
+ ctl = controlFactory.controlFor(new Project.NameKey(id), user.get());
} catch (NoSuchProjectException e) {
return null;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/PutBranch.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/PutBranch.java
index 52bbdf3..9e0db6e 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/PutBranch.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/PutBranch.java
@@ -24,9 +24,8 @@
public class PutBranch implements RestModifyView<BranchResource, BranchInput> {
@Override
- public BranchInfo apply(BranchResource rsrc, BranchInput input)
- throws ResourceConflictException {
- throw new ResourceConflictException("Branch \"" + rsrc.getBranchInfo().ref
- + "\" already exists");
+ public BranchInfo apply(BranchResource rsrc, BranchInput input) throws ResourceConflictException {
+ throw new ResourceConflictException(
+ "Branch \"" + rsrc.getBranchInfo().ref + "\" already exists");
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/PutConfig.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/PutConfig.java
index bf4cbbf..c5ded54 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/PutConfig.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/PutConfig.java
@@ -40,17 +40,15 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.errors.ConfigInvalidException;
-import org.eclipse.jgit.errors.RepositoryNotFoundException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
+import org.eclipse.jgit.errors.ConfigInvalidException;
+import org.eclipse.jgit.errors.RepositoryNotFoundException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
@Singleton
public class PutConfig implements RestModifyView<ProjectResource, ConfigInput> {
@@ -68,7 +66,8 @@
private final Provider<CurrentUser> user;
@Inject
- PutConfig(@EnableSignedPush boolean serverEnableSignedPush,
+ PutConfig(
+ @EnableSignedPush boolean serverEnableSignedPush,
Provider<MetaDataUpdate.User> metaDataUpdateFactory,
ProjectCache projectCache,
ProjectState.Factory projectStateFactory,
@@ -92,8 +91,7 @@
@Override
public ConfigInfo apply(ProjectResource rsrc, ConfigInput input)
- throws ResourceNotFoundException, BadRequestException,
- ResourceConflictException {
+ throws ResourceNotFoundException, BadRequestException, ResourceConflictException {
if (!rsrc.getControl().isOwner()) {
throw new ResourceNotFoundException(rsrc.getName());
}
@@ -101,8 +99,7 @@
}
public ConfigInfo apply(ProjectControl ctrl, ConfigInput input)
- throws ResourceNotFoundException, BadRequestException,
- ResourceConflictException {
+ throws ResourceNotFoundException, BadRequestException, ResourceConflictException {
Project.NameKey projectName = ctrl.getProject().getNameKey();
if (input == null) {
throw new BadRequestException("config is required");
@@ -158,8 +155,7 @@
}
if (input.pluginConfigValues != null) {
- setPluginConfigValues(ctrl.getProjectState(),
- projectConfig, input.pluginConfigValues);
+ setPluginConfigValues(ctrl.getProjectState(), projectConfig, input.pluginConfigValues);
}
md.setMessage("Modified project settings\n");
@@ -169,18 +165,22 @@
md.getRepository().setGitwebDescription(p.getDescription());
} catch (IOException e) {
if (e.getCause() instanceof ConfigInvalidException) {
- throw new ResourceConflictException("Cannot update " + projectName
- + ": " + e.getCause().getMessage());
+ throw new ResourceConflictException(
+ "Cannot update " + projectName + ": " + e.getCause().getMessage());
}
- log.warn(String.format("Failed to update config of project %s.",
- projectName), e);
+ log.warn(String.format("Failed to update config of project %s.", projectName), e);
throw new ResourceConflictException("Cannot update " + projectName);
}
ProjectState state = projectStateFactory.create(projectConfig);
- return new ConfigInfoImpl(serverEnableSignedPush,
- state.controlFor(user.get()), config, pluginConfigEntries,
- cfgFactory, allProjects, views);
+ return new ConfigInfoImpl(
+ serverEnableSignedPush,
+ state.controlFor(user.get()),
+ config,
+ pluginConfigEntries,
+ cfgFactory,
+ allProjects,
+ views);
} catch (RepositoryNotFoundException notFound) {
throw new ResourceNotFoundException(projectName.get());
} catch (ConfigInvalidException err) {
@@ -190,19 +190,21 @@
}
}
- private void setPluginConfigValues(ProjectState projectState,
- ProjectConfig projectConfig, Map<String, Map<String, ConfigValue>> pluginConfigValues)
+ private void setPluginConfigValues(
+ ProjectState projectState,
+ ProjectConfig projectConfig,
+ Map<String, Map<String, ConfigValue>> pluginConfigValues)
throws BadRequestException {
for (Entry<String, Map<String, ConfigValue>> e : pluginConfigValues.entrySet()) {
String pluginName = e.getKey();
PluginConfig cfg = projectConfig.getPluginConfig(pluginName);
for (Entry<String, ConfigValue> v : e.getValue().entrySet()) {
- ProjectConfigEntry projectConfigEntry =
- pluginConfigEntries.get(pluginName, v.getKey());
+ ProjectConfigEntry projectConfigEntry = pluginConfigEntries.get(pluginName, v.getKey());
if (projectConfigEntry != null) {
if (!isValidParameterName(v.getKey())) {
- log.warn(String.format(
- "Parameter name '%s' must match '^[a-zA-Z0-9]+[a-zA-Z0-9-]*$'", v.getKey()));
+ log.warn(
+ String.format(
+ "Parameter name '%s' must match '^[a-zA-Z0-9]+[a-zA-Z0-9-]*$'", v.getKey()));
continue;
}
String oldValue = cfg.getString(v.getKey());
@@ -214,8 +216,8 @@
}
if (Strings.emptyToNull(value) != null) {
if (!value.equals(oldValue)) {
- validateProjectConfigEntryIsEditable(projectConfigEntry,
- projectState, v.getKey(), pluginName);
+ validateProjectConfigEntryIsEditable(
+ projectConfigEntry, projectState, v.getKey(), pluginName);
v.setValue(projectConfigEntry.preUpdate(v.getValue()));
value = v.getValue().value;
try {
@@ -234,9 +236,13 @@
break;
case LIST:
if (!projectConfigEntry.getPermittedValues().contains(value)) {
- throw new BadRequestException(String.format(
- "The value '%s' is not permitted for parameter '%s' of plugin '"
- + pluginName + "'", value, v.getKey()));
+ throw new BadRequestException(
+ String.format(
+ "The value '%s' is not permitted for parameter '%s' of plugin '"
+ + pluginName
+ + "'",
+ value,
+ v.getKey()));
}
//$FALL-THROUGH$
case STRING:
@@ -246,45 +252,51 @@
cfg.setStringList(v.getKey(), v.getValue().values);
break;
default:
- log.warn(String.format(
- "The type '%s' of parameter '%s' is not supported.",
- projectConfigEntry.getType().name(), v.getKey()));
+ log.warn(
+ String.format(
+ "The type '%s' of parameter '%s' is not supported.",
+ projectConfigEntry.getType().name(), v.getKey()));
}
} catch (NumberFormatException ex) {
- throw new BadRequestException(String.format(
- "The value '%s' of config parameter '%s' of plugin '%s' is invalid: %s",
- v.getValue(), v.getKey(), pluginName, ex.getMessage()));
+ throw new BadRequestException(
+ String.format(
+ "The value '%s' of config parameter '%s' of plugin '%s' is invalid: %s",
+ v.getValue(), v.getKey(), pluginName, ex.getMessage()));
}
}
} else {
if (oldValue != null) {
- validateProjectConfigEntryIsEditable(projectConfigEntry,
- projectState, v.getKey(), pluginName);
+ validateProjectConfigEntryIsEditable(
+ projectConfigEntry, projectState, v.getKey(), pluginName);
cfg.unset(v.getKey());
}
}
} else {
- throw new BadRequestException(String.format(
- "The config parameter '%s' of plugin '%s' does not exist.",
- v.getKey(), pluginName));
+ throw new BadRequestException(
+ String.format(
+ "The config parameter '%s' of plugin '%s' does not exist.",
+ v.getKey(), pluginName));
}
}
}
}
private static void validateProjectConfigEntryIsEditable(
- ProjectConfigEntry projectConfigEntry, ProjectState projectState,
- String parameterName, String pluginName) throws BadRequestException {
+ ProjectConfigEntry projectConfigEntry,
+ ProjectState projectState,
+ String parameterName,
+ String pluginName)
+ throws BadRequestException {
if (!projectConfigEntry.isEditable(projectState)) {
- throw new BadRequestException(String.format(
- "Not allowed to set parameter '%s' of plugin '%s' on project '%s'.",
- parameterName, pluginName, projectState.getProject().getName()));
+ throw new BadRequestException(
+ String.format(
+ "Not allowed to set parameter '%s' of plugin '%s' on project '%s'.",
+ parameterName, pluginName, projectState.getProject().getName()));
}
}
private static boolean isValidParameterName(String name) {
- return CharMatcher.javaLetterOrDigit()
- .or(CharMatcher.is('-'))
- .matchesAllOf(name) && !name.startsWith("-");
+ return CharMatcher.javaLetterOrDigit().or(CharMatcher.is('-')).matchesAllOf(name)
+ && !name.startsWith("-");
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/PutDescription.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/PutDescription.java
index 99f0b83..78230bd 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/PutDescription.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/PutDescription.java
@@ -28,28 +28,24 @@
import com.google.gerrit.server.git.ProjectConfig;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
+import java.io.IOException;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
-import java.io.IOException;
-
@Singleton
public class PutDescription implements RestModifyView<ProjectResource, DescriptionInput> {
private final ProjectCache cache;
private final MetaDataUpdate.Server updateFactory;
@Inject
- PutDescription(ProjectCache cache,
- MetaDataUpdate.Server updateFactory) {
+ PutDescription(ProjectCache cache, MetaDataUpdate.Server updateFactory) {
this.cache = cache;
this.updateFactory = updateFactory;
}
@Override
- public Response<String> apply(ProjectResource resource,
- DescriptionInput input) throws AuthException,
- ResourceConflictException, ResourceNotFoundException, IOException {
+ public Response<String> apply(ProjectResource resource, DescriptionInput input)
+ throws AuthException, ResourceConflictException, ResourceNotFoundException, IOException {
if (input == null) {
input = new DescriptionInput(); // Delete would set description to null.
}
@@ -65,9 +61,9 @@
Project project = config.getProject();
project.setDescription(Strings.emptyToNull(input.description));
- String msg = MoreObjects.firstNonNull(
- Strings.emptyToNull(input.commitMessage),
- "Updated description.\n");
+ String msg =
+ MoreObjects.firstNonNull(
+ Strings.emptyToNull(input.commitMessage), "Updated description.\n");
if (!msg.endsWith("\n")) {
msg += "\n";
}
@@ -83,8 +79,8 @@
} catch (RepositoryNotFoundException notFound) {
throw new ResourceNotFoundException(resource.getName());
} catch (ConfigInvalidException e) {
- throw new ResourceConflictException(String.format(
- "invalid project.config: %s", e.getMessage()));
+ throw new ResourceConflictException(
+ String.format("invalid project.config: %s", e.getMessage()));
}
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/PutProject.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/PutProject.java
index fc397e1..1d2384f 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/PutProject.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/PutProject.java
@@ -25,7 +25,6 @@
@Override
public Response<?> apply(ProjectResource resource, ProjectInput input)
throws ResourceConflictException {
- throw new ResourceConflictException("Project \"" + resource.getName()
- + "\" already exists");
+ throw new ResourceConflictException("Project \"" + resource.getName() + "\" already exists");
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/PutTag.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/PutTag.java
index 1be4b0e..b8a8f6d 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/PutTag.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/PutTag.java
@@ -22,9 +22,7 @@
public class PutTag implements RestModifyView<TagResource, TagInput> {
@Override
- public TagInfo apply(TagResource resource, TagInput input)
- throws ResourceConflictException {
- throw new ResourceConflictException("Tag \"" + resource.getTagInfo().ref
- + "\" already exists");
+ public TagInfo apply(TagResource resource, TagInput input) throws ResourceConflictException {
+ throw new ResourceConflictException("Tag \"" + resource.getTagInfo().ref + "\" already exists");
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/RefControl.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/RefControl.java
index 3314309..8fabeaf 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/RefControl.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/RefControl.java
@@ -22,7 +22,14 @@
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gerrit.server.CurrentUser;
import com.google.gerrit.server.group.SystemGroupBackend;
-
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.PersonIdent;
import org.eclipse.jgit.lib.Ref;
@@ -34,16 +41,6 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-
/** Manages access control for Git references (aka branches, tags). */
public class RefControl {
private static final Logger log = LoggerFactory.getLogger(RefControl.class);
@@ -62,8 +59,7 @@
private Boolean canForgeCommitter;
private Boolean isVisible;
- RefControl(ProjectControl projectControl, String ref,
- PermissionCollection relevant) {
+ RefControl(ProjectControl projectControl, String ref, PermissionCollection relevant) {
this.projectControl = projectControl;
this.refName = ref;
this.relevant = relevant;
@@ -106,16 +102,12 @@
/** Can this user see this reference exists? */
public boolean isVisible() {
if (isVisible == null) {
- isVisible =
- (getUser().isInternalUser() || canPerform(Permission.READ))
- && canRead();
+ isVisible = (getUser().isInternalUser() || canPerform(Permission.READ)) && canRead();
}
return isVisible;
}
- /**
- * True if this reference is visible by all REGISTERED_USERS
- */
+ /** True if this reference is visible by all REGISTERED_USERS */
public boolean isVisibleByRegisteredUsers() {
List<PermissionRule> access = relevant.getPermission(Permission.READ);
List<PermissionRule> overridden = relevant.getOverridden(Permission.READ);
@@ -138,36 +130,34 @@
}
/**
- * Determines whether the user can upload a change to the ref controlled by
- * this object.
+ * Determines whether the user can upload a change to the ref controlled by this object.
*
- * @return {@code true} if the user specified can upload a change to the Git
- * ref
+ * @return {@code true} if the user specified can upload a change to the Git ref
*/
public boolean canUpload() {
- return projectControl.controlForRef("refs/for/" + getRefName())
- .canPerform(Permission.PUSH)
+ return projectControl.controlForRef("refs/for/" + getRefName()).canPerform(Permission.PUSH)
&& canWrite();
}
/** @return true if this user can add a new patch set to this ref */
public boolean canAddPatchSet() {
- return projectControl.controlForRef("refs/for/" + getRefName())
- .canPerform(Permission.ADD_PATCH_SET)
+ return projectControl
+ .controlForRef("refs/for/" + getRefName())
+ .canPerform(Permission.ADD_PATCH_SET)
&& canWrite();
}
/** @return true if this user can submit merge patch sets to this ref */
public boolean canUploadMerges() {
- return projectControl.controlForRef("refs/for/" + getRefName())
- .canPerform(Permission.PUSH_MERGE)
+ return projectControl
+ .controlForRef("refs/for/" + getRefName())
+ .canPerform(Permission.PUSH_MERGE)
&& canWrite();
}
/** @return true if this user can rebase changes on this ref */
public boolean canRebase() {
- return canPerform(Permission.REBASE)
- && canWrite();
+ return canPerform(Permission.REBASE) && canWrite();
}
/** @return true if this user can submit patch sets to this ref */
@@ -180,8 +170,7 @@
// granting of powers beyond submitting to the configuration.
return projectControl.isOwner();
}
- return canPerform(Permission.SUBMIT, isChangeOwner)
- && canWrite();
+ return canPerform(Permission.SUBMIT, isChangeOwner) && canWrite();
}
/** @return true if this user was granted submitAs to this ref */
@@ -191,8 +180,7 @@
/** @return true if the user can update the reference as a fast-forward. */
public boolean canUpdate() {
- if (RefNames.REFS_CONFIG.equals(refName)
- && !projectControl.isOwner()) {
+ if (RefNames.REFS_CONFIG.equals(refName) && !projectControl.isOwner()) {
// Pushing requires being at least project owner, in addition to push.
// Pushing configuration changes modifies the access control
// rules. Allowing this to be done by a non-project-owner opens
@@ -202,13 +190,12 @@
// On the AllProjects project the owner access right cannot be assigned,
// this why for the AllProjects project we allow administrators to push
// configuration changes if they have push without being project owner.
- if (!(projectControl.getProjectState().isAllProjects() &&
- getUser().getCapabilities().canAdministrateServer())) {
+ if (!(projectControl.getProjectState().isAllProjects()
+ && getUser().getCapabilities().canAdministrateServer())) {
return false;
}
}
- return canPerform(Permission.PUSH)
- && canWrite();
+ return canPerform(Permission.PUSH) && canWrite();
}
/** @return true if the user can rewind (force push) the reference. */
@@ -237,18 +224,15 @@
}
public boolean canWrite() {
- return getProjectControl().getProject().getState().equals(
- ProjectState.ACTIVE);
+ return getProjectControl().getProject().getState().equals(ProjectState.ACTIVE);
}
public boolean canRead() {
- return getProjectControl().getProject().getState().equals(
- ProjectState.READ_ONLY) || canWrite();
+ return getProjectControl().getProject().getState().equals(ProjectState.READ_ONLY) || canWrite();
}
private boolean canPushWithForce() {
- if (!canWrite() || (RefNames.REFS_CONFIG.equals(refName)
- && !projectControl.isOwner())) {
+ if (!canWrite() || (RefNames.REFS_CONFIG.equals(refName) && !projectControl.isOwner())) {
// Pushing requires being at least project owner, in addition to push.
// Pushing configuration changes modifies the access control
// rules. Allowing this to be done by a non-project-owner opens
@@ -325,8 +309,7 @@
}
}
- private boolean canCreateCommit(ReviewDb db, Repository repo,
- RevCommit commit) {
+ private boolean canCreateCommit(ReviewDb db, Repository repo, RevCommit commit) {
if (canUpdate()) {
// If the user has push permissions, they can create the ref regardless
// of whether they are pushing any new objects along with the create.
@@ -341,26 +324,23 @@
return false;
}
- private boolean isMergedIntoBranchOrTag(ReviewDb db, Repository repo,
- RevCommit commit) {
+ private boolean isMergedIntoBranchOrTag(ReviewDb db, Repository repo, RevCommit commit) {
try (RevWalk rw = new RevWalk(repo)) {
- List<Ref> refs = new ArrayList<>(
- repo.getRefDatabase().getRefs(Constants.R_HEADS).values());
+ List<Ref> refs = new ArrayList<>(repo.getRefDatabase().getRefs(Constants.R_HEADS).values());
refs.addAll(repo.getRefDatabase().getRefs(Constants.R_TAGS).values());
- return projectControl.isMergedIntoVisibleRef(
- repo, db, rw, commit, refs);
+ return projectControl.isMergedIntoVisibleRef(repo, db, rw, commit, refs);
} catch (IOException e) {
- String msg = String.format(
- "Cannot verify permissions to commit object %s in repository %s",
- commit.name(), projectControl.getProject().getNameKey());
+ String msg =
+ String.format(
+ "Cannot verify permissions to commit object %s in repository %s",
+ commit.name(), projectControl.getProject().getNameKey());
log.error(msg, e);
}
return false;
}
/**
- * Determines whether the user can delete the Git ref controlled by this
- * object.
+ * Determines whether the user can delete the Git ref controlled by this object.
*
* @return {@code true} if the user specified can delete a Git ref.
*/
@@ -509,21 +489,23 @@
int getAllowMin() {
return allowMin;
}
+
int getAllowMax() {
return allowMax;
}
+
int getBlockMin() {
// ALLOW wins over BLOCK on the same project
return Math.min(blockMin, allowMin - 1);
}
+
int getBlockMax() {
// ALLOW wins over BLOCK on the same project
return Math.max(blockMax, allowMax + 1);
}
}
- private PermissionRange toRange(String permissionName,
- List<PermissionRule> ruleList) {
+ private PermissionRange toRange(String permissionName, List<PermissionRule> ruleList) {
Map<ProjectRef, AllowedRange> ranges = new HashMap<>();
for (PermissionRule rule : ruleList) {
ProjectRef p = relevant.getRuleProps(rule);
@@ -565,8 +547,7 @@
return !doCanPerform(permissionName, false, true);
}
- private boolean doCanPerform(String permissionName, boolean isChangeOwner,
- boolean blockOnly) {
+ private boolean doCanPerform(String permissionName, boolean isChangeOwner, boolean blockOnly) {
List<PermissionRule> access = access(permissionName, isChangeOwner);
List<PermissionRule> overridden = relevant.getOverridden(permissionName);
Set<ProjectRef> allows = new HashSet<>();
@@ -635,8 +616,7 @@
}
/** Rules for the given permission, or the empty list. */
- private List<PermissionRule> access(String permissionName,
- boolean isChangeOwner) {
+ private List<PermissionRule> access(String permissionName, boolean isChangeOwner) {
List<PermissionRule> rules = effective.get(permissionName);
if (rules != null) {
return rules;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/RefFilter.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/RefFilter.java
index 63fb595..a789a7b 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/RefFilter.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/RefFilter.java
@@ -19,10 +19,8 @@
import com.google.common.collect.FluentIterable;
import com.google.gerrit.extensions.api.projects.RefInfo;
import com.google.gerrit.extensions.restapi.BadRequestException;
-
import dk.brics.automaton.RegExp;
import dk.brics.automaton.RunAutomaton;
-
import java.util.List;
import java.util.Locale;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/RefPattern.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/RefPattern.java
index 8c850fb..72face2 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/RefPattern.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/RefPattern.java
@@ -21,28 +21,26 @@
import com.google.gerrit.common.data.AccessSection;
import com.google.gerrit.common.data.RefConfigSection;
import com.google.gerrit.common.errors.InvalidNameException;
-
import dk.brics.automaton.RegExp;
-
-import org.eclipse.jgit.lib.Repository;
-
import java.util.concurrent.ExecutionException;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
+import org.eclipse.jgit.lib.Repository;
public class RefPattern {
public static final String USERID_SHARDED = "shardeduserid";
public static final String USERNAME = "username";
- private static final LoadingCache<String, String> exampleCache = CacheBuilder
- .newBuilder()
- .maximumSize(4000)
- .build(new CacheLoader<String, String>() {
- @Override
- public String load(String refPattern) {
- return example(refPattern);
- }
- });
+ private static final LoadingCache<String, String> exampleCache =
+ CacheBuilder.newBuilder()
+ .maximumSize(4000)
+ .build(
+ new CacheLoader<String, String>() {
+ @Override
+ public String load(String refPattern) {
+ return example(refPattern);
+ }
+ });
public static String shortestExample(String refPattern) {
if (isRE(refPattern)) {
@@ -65,8 +63,7 @@
// Repository.isValidRefName() if not combined with star [*].
// To get around this, we substitute the \0 with an arbitrary
// accepted character.
- return toRegExp(refPattern).toAutomaton().getShortestExample(true)
- .replace('\0', '-');
+ return toRegExp(refPattern).toAutomaton().getShortestExample(true).replace('\0', '-');
}
public static boolean isRE(String refPattern) {
@@ -80,8 +77,7 @@
return new RegExp(refPattern, RegExp.NONE);
}
- public static void validate(String refPattern)
- throws InvalidNameException {
+ public static void validate(String refPattern) throws InvalidNameException {
if (refPattern.startsWith(RefConfigSection.REGEX_PREFIX)) {
if (!Repository.isValidRefName(shortestExample(refPattern))) {
throw new InvalidNameException(refPattern);
@@ -99,8 +95,7 @@
validateRegExp(refPattern);
}
- public static void validateRegExp(String refPattern)
- throws InvalidNameException {
+ public static void validateRegExp(String refPattern) throws InvalidNameException {
try {
refPattern = refPattern.replace("${" + USERID_SHARDED + "}", "");
refPattern = refPattern.replace("${" + USERNAME + "}", "");
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/RefPatternMatcher.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/RefPatternMatcher.java
index fe87b6b..63da731 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/RefPatternMatcher.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/RefPatternMatcher.java
@@ -23,9 +23,7 @@
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.reviewdb.client.RefNames;
import com.google.gerrit.server.CurrentUser;
-
import dk.brics.automaton.Automaton;
-
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
@@ -99,11 +97,11 @@
// allows the pattern prefix to be clipped, saving time on
// evaluation.
String replacement = ":PLACEHOLDER:";
- Map<String, String> params = ImmutableMap.of(
- RefPattern.USERID_SHARDED, replacement,
- RefPattern.USERNAME, replacement);
- Automaton am =
- RefPattern.toRegExp(template.replace(params)).toAutomaton();
+ Map<String, String> params =
+ ImmutableMap.of(
+ RefPattern.USERID_SHARDED, replacement,
+ RefPattern.USERNAME, replacement);
+ Automaton am = RefPattern.toRegExp(template.replace(params)).toAutomaton();
String rePrefix = am.getCommonPrefix();
prefix = rePrefix.substring(0, rePrefix.indexOf(replacement));
} else {
@@ -125,9 +123,7 @@
u = username;
}
- Account.Id accountId = user.isIdentifiedUser()
- ? user.getAccountId()
- : null;
+ Account.Id accountId = user.isIdentifiedUser() ? user.getAccountId() : null;
RefPatternMatcher next = getMatcher(expand(template, u, accountId));
if (next != null && next.match(expand(ref, u, accountId), user)) {
return true;
@@ -163,8 +159,8 @@
return parameterizedRef;
}
- private String expand(ParameterizedString parameterizedRef, String userName,
- Account.Id accountId) {
+ private String expand(
+ ParameterizedString parameterizedRef, String userName, Account.Id accountId) {
Map<String, String> params = new HashMap<>();
params.put(RefPattern.USERNAME, userName);
if (accountId != null) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/RefResource.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/RefResource.java
index 9300d43..124439f 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/RefResource.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/RefResource.java
@@ -20,13 +20,9 @@
super(control);
}
- /**
- * @return the ref's name
- */
+ /** @return the ref's name */
public abstract String getRef();
- /**
- * @return the ref's revision
- */
+ /** @return the ref's revision */
public abstract String getRevision();
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/RefUtil.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/RefUtil.java
index 680bba1..8a7e5f1 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/RefUtil.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/RefUtil.java
@@ -21,7 +21,8 @@
import com.google.gerrit.extensions.restapi.BadRequestException;
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.reviewdb.client.RefNames;
-
+import java.io.IOException;
+import java.util.Collections;
import org.eclipse.jgit.errors.IncorrectObjectTypeException;
import org.eclipse.jgit.errors.MissingObjectException;
import org.eclipse.jgit.errors.RevisionSyntaxException;
@@ -35,14 +36,11 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.util.Collections;
-
public class RefUtil {
private static final Logger log = LoggerFactory.getLogger(RefUtil.class);
- public static ObjectId parseBaseRevision(Repository repo,
- Project.NameKey projectName, String baseRevision)
+ public static ObjectId parseBaseRevision(
+ Repository repo, Project.NameKey projectName, String baseRevision)
throws InvalidRevisionException {
try {
ObjectId revid = repo.resolve(baseRevision);
@@ -51,8 +49,8 @@
}
return revid;
} catch (IOException err) {
- log.error("Cannot resolve \"" + baseRevision + "\" in project \""
- + projectName.get() + "\"", err);
+ log.error(
+ "Cannot resolve \"" + baseRevision + "\" in project \"" + projectName.get() + "\"", err);
throw new InvalidRevisionException();
} catch (RevisionSyntaxException err) {
log.error("Invalid revision syntax \"" + baseRevision + "\"", err);
@@ -70,9 +68,9 @@
throw new InvalidRevisionException();
}
RefDatabase refDb = repo.getRefDatabase();
- Iterable<Ref> refs = Iterables.concat(
- refDb.getRefs(Constants.R_HEADS).values(),
- refDb.getRefs(Constants.R_TAGS).values());
+ Iterable<Ref> refs =
+ Iterables.concat(
+ refDb.getRefs(Constants.R_HEADS).values(), refDb.getRefs(Constants.R_TAGS).values());
Ref rc = refDb.exactRef(RefNames.REFS_CONFIG);
if (rc != null) {
refs = Iterables.concat(refs, Collections.singleton(rc));
@@ -89,8 +87,9 @@
} catch (IncorrectObjectTypeException | MissingObjectException err) {
throw new InvalidRevisionException();
} catch (IOException err) {
- log.error("Repository \"" + repo.getDirectory()
- + "\" may be corrupt; suggest running git fsck", err);
+ log.error(
+ "Repository \"" + repo.getDirectory() + "\" may be corrupt; suggest running git fsck",
+ err);
throw new InvalidRevisionException();
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/RefValidationHelper.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/RefValidationHelper.java
index 6e2fd5d..0a5980c 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/RefValidationHelper.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/RefValidationHelper.java
@@ -21,7 +21,6 @@
import com.google.gerrit.server.validators.ValidationException;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
-
import org.eclipse.jgit.lib.RefUpdate;
import org.eclipse.jgit.transport.ReceiveCommand.Type;
@@ -34,14 +33,14 @@
private final Type operationType;
@Inject
- RefValidationHelper(RefOperationValidators.Factory refValidatorsFactory,
- @Assisted Type operationType) {
+ RefValidationHelper(
+ RefOperationValidators.Factory refValidatorsFactory, @Assisted Type operationType) {
this.refValidatorsFactory = refValidatorsFactory;
this.operationType = operationType;
}
- public void validateRefOperation(String projectName, IdentifiedUser user,
- RefUpdate update) throws ResourceConflictException {
+ public void validateRefOperation(String projectName, IdentifiedUser user, RefUpdate update)
+ throws ResourceConflictException {
RefOperationValidators refValidators =
refValidatorsFactory.create(
new Project(new Project.NameKey(projectName)),
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/RepositoryStatistics.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/RepositoryStatistics.java
index de045b7..3cb4bac 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/RepositoryStatistics.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/RepositoryStatistics.java
@@ -15,7 +15,6 @@
package com.google.gerrit.server.project;
import com.google.common.base.CaseFormat;
-
import java.util.Map.Entry;
import java.util.Properties;
import java.util.TreeMap;
@@ -25,8 +24,9 @@
RepositoryStatistics(Properties p) {
for (Entry<Object, Object> e : p.entrySet()) {
- put(CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE,
- e.getKey().toString()), e.getValue());
+ put(
+ CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, e.getKey().toString()),
+ e.getValue());
}
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/SectionMatcher.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/SectionMatcher.java
index 478357a..65b17bb 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/SectionMatcher.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/SectionMatcher.java
@@ -20,9 +20,9 @@
/**
* Matches an AccessSection against a reference name.
- * <p>
- * These matchers are "compiled" versions of the AccessSection name, supporting
- * faster selection of which sections are relevant to any given input reference.
+ *
+ * <p>These matchers are "compiled" versions of the AccessSection name, supporting faster selection
+ * of which sections are relevant to any given input reference.
*/
class SectionMatcher extends RefPatternMatcher {
static SectionMatcher wrap(Project.NameKey project, AccessSection section) {
@@ -37,8 +37,7 @@
final AccessSection section;
final RefPatternMatcher matcher;
- SectionMatcher(Project.NameKey project, AccessSection section,
- RefPatternMatcher matcher) {
+ SectionMatcher(Project.NameKey project, AccessSection section, RefPatternMatcher matcher) {
this.project = project;
this.section = section;
this.matcher = matcher;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/SectionSortCache.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/SectionSortCache.java
index 7b6b5c8..a02941e 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/SectionSortCache.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/SectionSortCache.java
@@ -24,20 +24,17 @@
import com.google.inject.Module;
import com.google.inject.Singleton;
import com.google.inject.name.Named;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.util.ArrayList;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.List;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/** Caches the order AccessSections should be sorted for evaluation. */
@Singleton
public class SectionSortCache {
- private static final Logger log =
- LoggerFactory.getLogger(SectionSortCache.class);
+ private static final Logger log = LoggerFactory.getLogger(SectionSortCache.class);
private static final String CACHE_NAME = "permission_sort";
@@ -108,8 +105,8 @@
return sections.toArray(new AccessSection[sections.size()]);
}
- private static boolean isIdentityTransform(List<AccessSection> sections,
- IdentityHashMap<AccessSection, Integer> srcMap) {
+ private static boolean isIdentityTransform(
+ List<AccessSection> sections, IdentityHashMap<AccessSection, Integer> srcMap) {
for (int i = 0; i < sections.size(); i++) {
if (i != srcMap.get(sections.get(i))) {
return false;
@@ -121,7 +118,9 @@
@AutoValue
abstract static class EntryKey {
public abstract String ref();
+
public abstract List<String> patterns();
+
public abstract int cachedHashCode();
static EntryKey create(String refName, List<AccessSection> sections) {
@@ -132,8 +131,7 @@
patterns.add(n);
hc = hc * 31 + n.hashCode();
}
- return new AutoValue_SectionSortCache_EntryKey(
- refName, ImmutableList.copyOf(patterns), hc);
+ return new AutoValue_SectionSortCache_EntryKey(refName, ImmutableList.copyOf(patterns), hc);
}
@Override
@@ -145,9 +143,9 @@
static final class EntryVal {
/**
* Maps the input index to the output index.
- * <p>
- * For {@code x == order[y]} the expression means move the item at
- * source position {@code x} to the output position {@code y}.
+ *
+ * <p>For {@code x == order[y]} the expression means move the item at source position {@code x}
+ * to the output position {@code y}.
*/
final int[] order;
@@ -155,6 +153,4 @@
this.order = order;
}
}
-
-
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/SetAccess.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/SetAccess.java
index 33e24ac..b36a09d 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/SetAccess.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/SetAccess.java
@@ -44,18 +44,15 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.errors.ConfigInvalidException;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
+import org.eclipse.jgit.errors.ConfigInvalidException;
@Singleton
-public class SetAccess implements
- RestModifyView<ProjectResource, ProjectAccessInput> {
+public class SetAccess implements RestModifyView<ProjectResource, ProjectAccessInput> {
protected final GroupBackend groupBackend;
private final GroupsCollection groupsCollection;
private final Provider<MetaDataUpdate.User> metaDataUpdateFactory;
@@ -66,7 +63,8 @@
private final Provider<IdentifiedUser> identifiedUser;
@Inject
- private SetAccess(GroupBackend groupBackend,
+ private SetAccess(
+ GroupBackend groupBackend,
Provider<MetaDataUpdate.User> metaDataUpdateFactory,
AllProjectsName allProjects,
Provider<SetParent> setParent,
@@ -85,11 +83,9 @@
}
@Override
- public ProjectAccessInfo apply(ProjectResource rsrc,
- ProjectAccessInput input)
- throws ResourceNotFoundException, ResourceConflictException,
- IOException, AuthException, BadRequestException,
- UnprocessableEntityException{
+ public ProjectAccessInfo apply(ProjectResource rsrc, ProjectAccessInput input)
+ throws ResourceNotFoundException, ResourceConflictException, IOException, AuthException,
+ BadRequestException, UnprocessableEntityException {
List<AccessSection> removals = getAccessSections(input.remove);
List<AccessSection> additions = getAccessSections(input.add);
MetaDataUpdate.User metaDataUpdateUser = metaDataUpdateFactory.get();
@@ -97,29 +93,27 @@
ProjectControl projectControl = rsrc.getControl();
ProjectConfig config;
- Project.NameKey newParentProjectName = input.parent == null ?
- null : new Project.NameKey(input.parent);
+ Project.NameKey newParentProjectName =
+ input.parent == null ? null : new Project.NameKey(input.parent);
try (MetaDataUpdate md = metaDataUpdateUser.create(rsrc.getNameKey())) {
config = ProjectConfig.read(md);
// Perform removal checks
for (AccessSection section : removals) {
- boolean isGlobalCapabilities =
- AccessSection.GLOBAL_CAPABILITIES.equals(section.getName());
+ boolean isGlobalCapabilities = AccessSection.GLOBAL_CAPABILITIES.equals(section.getName());
if (isGlobalCapabilities) {
checkGlobalCapabilityPermissions(config.getName());
} else if (!projectControl.controlForRef(section.getName()).isOwner()) {
- throw new AuthException("You are not allowed to edit permissions"
- + "for ref: " + section.getName());
+ throw new AuthException(
+ "You are not allowed to edit permissions" + "for ref: " + section.getName());
}
}
// Perform addition checks
for (AccessSection section : additions) {
String name = section.getName();
- boolean isGlobalCapabilities =
- AccessSection.GLOBAL_CAPABILITIES.equals(name);
+ boolean isGlobalCapabilities = AccessSection.GLOBAL_CAPABILITIES.equals(name);
if (isGlobalCapabilities) {
checkGlobalCapabilityPermissions(config.getName());
@@ -128,18 +122,16 @@
throw new BadRequestException("invalid section name");
}
if (!projectControl.controlForRef(name).isOwner()) {
- throw new AuthException("You are not allowed to edit permissions"
- + "for ref: " + name);
+ throw new AuthException("You are not allowed to edit permissions" + "for ref: " + name);
}
RefPattern.validate(name);
}
// Check all permissions for soundness
for (Permission p : section.getPermissions()) {
- if (isGlobalCapabilities
- && !GlobalCapability.isCapability(p.getName())) {
- throw new BadRequestException("Cannot add non-global capability "
- + p.getName() + " to global capabilities");
+ if (isGlobalCapabilities && !GlobalCapability.isCapability(p.getName())) {
+ throw new BadRequestException(
+ "Cannot add non-global capability " + p.getName() + " to global capabilities");
}
}
}
@@ -164,16 +156,14 @@
// Apply additions
for (AccessSection section : additions) {
- AccessSection currentAccessSection =
- config.getAccessSection(section.getName());
+ AccessSection currentAccessSection = config.getAccessSection(section.getName());
if (currentAccessSection == null) {
// Add AccessSection
config.replace(section);
} else {
for (Permission p : section.getPermissions()) {
- Permission currentPermission =
- currentAccessSection.getPermission(p.getName());
+ Permission currentPermission = currentAccessSection.getPermission(p.getName());
if (currentPermission == null) {
// Add Permission
currentAccessSection.addPermission(p);
@@ -187,14 +177,16 @@
}
}
- if (newParentProjectName != null &&
- !config.getProject().getNameKey().equals(allProjects) &&
- !config.getProject().getParent(allProjects)
- .equals(newParentProjectName)) {
+ if (newParentProjectName != null
+ && !config.getProject().getNameKey().equals(allProjects)
+ && !config.getProject().getParent(allProjects).equals(newParentProjectName)) {
try {
- setParent.get().validateParentUpdate(projectControl,
- MoreObjects.firstNonNull(newParentProjectName, allProjects).get(),
- true);
+ setParent
+ .get()
+ .validateParentUpdate(
+ projectControl,
+ MoreObjects.firstNonNull(newParentProjectName, allProjects).get(),
+ true);
} catch (UnprocessableEntityException e) {
throw new ResourceConflictException(e.getMessage(), e);
}
@@ -221,25 +213,22 @@
return getAccess.apply(rsrc.getNameKey());
}
- private List<AccessSection> getAccessSections(
- Map<String, AccessSectionInfo> sectionInfos)
+ private List<AccessSection> getAccessSections(Map<String, AccessSectionInfo> sectionInfos)
throws UnprocessableEntityException {
if (sectionInfos == null) {
return Collections.emptyList();
}
List<AccessSection> sections = new ArrayList<>(sectionInfos.size());
- for (Map.Entry<String, AccessSectionInfo> entry :
- sectionInfos.entrySet()) {
+ for (Map.Entry<String, AccessSectionInfo> entry : sectionInfos.entrySet()) {
AccessSection accessSection = new AccessSection(entry.getKey());
if (entry.getValue().permissions == null) {
continue;
}
- for (Map.Entry<String, PermissionInfo> permissionEntry : entry
- .getValue().permissions
- .entrySet()) {
+ for (Map.Entry<String, PermissionInfo> permissionEntry :
+ entry.getValue().permissions.entrySet()) {
Permission p = new Permission(permissionEntry.getKey());
if (permissionEntry.getValue().exclusive != null) {
p.setExclusiveGroup(permissionEntry.getValue().exclusive);
@@ -252,14 +241,12 @@
permissionEntry.getValue().rules.entrySet()) {
PermissionRuleInfo pri = permissionRuleInfoEntry.getValue();
- GroupDescription.Basic group = groupsCollection
- .parseId(permissionRuleInfoEntry.getKey());
+ GroupDescription.Basic group = groupsCollection.parseId(permissionRuleInfoEntry.getKey());
if (group == null) {
throw new UnprocessableEntityException(
- permissionRuleInfoEntry.getKey() + " is not a valid group ID");
+ permissionRuleInfoEntry.getKey() + " is not a valid group ID");
}
- PermissionRule r = new PermissionRule(
- GroupReference.forGroup(group));
+ PermissionRule r = new PermissionRule(GroupReference.forGroup(group));
if (pri != null) {
if (pri.max != null) {
r.setMax(pri.max);
@@ -282,16 +269,16 @@
}
private void checkGlobalCapabilityPermissions(Project.NameKey projectName)
- throws BadRequestException, AuthException {
+ throws BadRequestException, AuthException {
if (!allProjects.equals(projectName)) {
- throw new BadRequestException("Cannot edit global capabilities "
- + "for projects other than " + allProjects.get());
+ throw new BadRequestException(
+ "Cannot edit global capabilities " + "for projects other than " + allProjects.get());
}
if (!identifiedUser.get().getCapabilities().canAdministrateServer()) {
- throw new AuthException("Editing global capabilities "
- + "requires " + GlobalCapability.ADMINISTRATE_SERVER);
+ throw new AuthException(
+ "Editing global capabilities " + "requires " + GlobalCapability.ADMINISTRATE_SERVER);
}
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/SetDashboard.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/SetDashboard.java
index 594763e..332ea76 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/SetDashboard.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/SetDashboard.java
@@ -27,14 +27,12 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.io.IOException;
@Singleton
class SetDashboard implements RestModifyView<DashboardResource, Input> {
static class Input {
- @DefaultInput
- String id;
+ @DefaultInput String id;
String commitMessage;
}
@@ -48,7 +46,7 @@
@Override
public Response<DashboardInfo> apply(DashboardResource resource, Input input)
throws AuthException, BadRequestException, ResourceConflictException,
- MethodNotAllowedException, ResourceNotFoundException, IOException {
+ MethodNotAllowedException, ResourceNotFoundException, IOException {
if (resource.isProjectDefault()) {
return defaultSetter.get().apply(resource, input);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/SetDefaultDashboard.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/SetDefaultDashboard.java
index 641c3a7..be93296 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/SetDefaultDashboard.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/SetDefaultDashboard.java
@@ -30,13 +30,11 @@
import com.google.gerrit.server.project.SetDashboard.Input;
import com.google.inject.Inject;
import com.google.inject.Provider;
-
+import java.io.IOException;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
import org.kohsuke.args4j.Option;
-import java.io.IOException;
-
class SetDefaultDashboard implements RestModifyView<DashboardResource, Input> {
private final ProjectCache cache;
private final MetaDataUpdate.Server updateFactory;
@@ -47,7 +45,8 @@
private boolean inherited;
@Inject
- SetDefaultDashboard(ProjectCache cache,
+ SetDefaultDashboard(
+ ProjectCache cache,
MetaDataUpdate.Server updateFactory,
DashboardsCollection dashboards,
Provider<GetDashboard> get) {
@@ -60,7 +59,7 @@
@Override
public Response<DashboardInfo> apply(DashboardResource resource, Input input)
throws AuthException, BadRequestException, ResourceConflictException,
- ResourceNotFoundException, IOException {
+ ResourceNotFoundException, IOException {
if (input == null) {
input = new Input(); // Delete would set input to null.
}
@@ -74,9 +73,7 @@
DashboardResource target = null;
if (input.id != null) {
try {
- target = dashboards.parse(
- new ProjectResource(ctl),
- IdString.fromUrl(input.id));
+ target = dashboards.parse(new ProjectResource(ctl), IdString.fromUrl(input.id));
} catch (ResourceNotFoundException e) {
throw new BadRequestException("dashboard " + input.id + " not found");
} catch (ConfigInvalidException e) {
@@ -93,11 +90,12 @@
project.setLocalDefaultDashboard(input.id);
}
- String msg = MoreObjects.firstNonNull(
- Strings.emptyToNull(input.commitMessage),
- input.id == null
- ? "Removed default dashboard.\n"
- : String.format("Changed default dashboard to %s.\n", input.id));
+ String msg =
+ MoreObjects.firstNonNull(
+ Strings.emptyToNull(input.commitMessage),
+ input.id == null
+ ? "Removed default dashboard.\n"
+ : String.format("Changed default dashboard to %s.\n", input.id));
if (!msg.endsWith("\n")) {
msg += "\n";
}
@@ -115,13 +113,12 @@
} catch (RepositoryNotFoundException notFound) {
throw new ResourceNotFoundException(ctl.getProject().getName());
} catch (ConfigInvalidException e) {
- throw new ResourceConflictException(String.format(
- "invalid project.config: %s", e.getMessage()));
+ throw new ResourceConflictException(
+ String.format("invalid project.config: %s", e.getMessage()));
}
}
- static class CreateDefault implements
- RestModifyView<ProjectResource, SetDashboard.Input> {
+ static class CreateDefault implements RestModifyView<ProjectResource, SetDashboard.Input> {
private final Provider<SetDefaultDashboard> setDefault;
@Option(name = "--inherited", usage = "set dashboard inherited by children")
@@ -135,11 +132,10 @@
@Override
public Response<DashboardInfo> apply(ProjectResource resource, Input input)
throws AuthException, BadRequestException, ResourceConflictException,
- ResourceNotFoundException, IOException {
+ ResourceNotFoundException, IOException {
SetDefaultDashboard set = setDefault.get();
set.inherited = inherited;
- return set.apply(
- DashboardResource.projectDefault(resource.getControl()), input);
+ return set.apply(DashboardResource.projectDefault(resource.getControl()), input);
}
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/SetHead.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/SetHead.java
index 442447f..6c45bc3 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/SetHead.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/SetHead.java
@@ -32,7 +32,8 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
+import java.io.IOException;
+import java.util.Map;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.Ref;
@@ -41,16 +42,12 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.util.Map;
-
@Singleton
public class SetHead implements RestModifyView<ProjectResource, Input> {
private static final Logger log = LoggerFactory.getLogger(SetHead.class);
public static class Input {
- @DefaultInput
- public String ref;
+ @DefaultInput public String ref;
}
private final GitRepositoryManager repoManager;
@@ -58,7 +55,8 @@
private final DynamicSet<HeadUpdatedListener> headUpdatedListeners;
@Inject
- SetHead(GitRepositoryManager repoManager,
+ SetHead(
+ GitRepositoryManager repoManager,
Provider<IdentifiedUser> identifiedUser,
DynamicSet<HeadUpdatedListener> headUpdatedListeners) {
this.repoManager = repoManager;
@@ -67,9 +65,9 @@
}
@Override
- public String apply(final ProjectResource rsrc, Input input) throws AuthException,
- ResourceNotFoundException, BadRequestException,
- UnprocessableEntityException, IOException {
+ public String apply(final ProjectResource rsrc, Input input)
+ throws AuthException, ResourceNotFoundException, BadRequestException,
+ UnprocessableEntityException, IOException {
if (!rsrc.getControl().isOwner()) {
throw new AuthException("restricted to project owner");
}
@@ -79,11 +77,9 @@
String ref = RefNames.fullName(input.ref);
try (Repository repo = repoManager.openRepository(rsrc.getNameKey())) {
- Map<String, Ref> cur =
- repo.getRefDatabase().exactRef(Constants.HEAD, ref);
+ Map<String, Ref> cur = repo.getRefDatabase().exactRef(Constants.HEAD, ref);
if (!cur.containsKey(ref)) {
- throw new UnprocessableEntityException(String.format(
- "Ref Not Found: %s", ref));
+ throw new UnprocessableEntityException(String.format("Ref Not Found: %s", ref));
}
final String oldHead = cur.get(Constants.HEAD).getTarget().getName();
@@ -130,8 +126,7 @@
}
}
- static class Event extends AbstractNoNotifyEvent
- implements HeadUpdatedListener.Event {
+ static class Event extends AbstractNoNotifyEvent implements HeadUpdatedListener.Event {
private final Project.NameKey nameKey;
private final String oldHead;
private final String newHead;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/SetParent.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/SetParent.java
index cc215d2..f8d649b 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/SetParent.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/SetParent.java
@@ -33,17 +33,14 @@
import com.google.gerrit.server.project.SetParent.Input;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
+import java.io.IOException;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
-import java.io.IOException;
-
@Singleton
public class SetParent implements RestModifyView<ProjectResource, Input> {
public static class Input {
- @DefaultInput
- public String parent;
+ @DefaultInput public String parent;
public String commitMessage;
}
@@ -52,27 +49,25 @@
private final AllProjectsName allProjects;
@Inject
- SetParent(ProjectCache cache,
- MetaDataUpdate.Server updateFactory,
- AllProjectsName allProjects) {
+ SetParent(ProjectCache cache, MetaDataUpdate.Server updateFactory, AllProjectsName allProjects) {
this.cache = cache;
this.updateFactory = updateFactory;
this.allProjects = allProjects;
}
@Override
- public String apply(ProjectResource rsrc, Input input) throws AuthException,
- ResourceConflictException, ResourceNotFoundException,
- UnprocessableEntityException, IOException {
+ public String apply(ProjectResource rsrc, Input input)
+ throws AuthException, ResourceConflictException, ResourceNotFoundException,
+ UnprocessableEntityException, IOException {
return apply(rsrc, input, true);
}
public String apply(ProjectResource rsrc, Input input, boolean checkIfAdmin)
- throws AuthException, ResourceConflictException,
- ResourceNotFoundException, UnprocessableEntityException, IOException {
+ throws AuthException, ResourceConflictException, ResourceNotFoundException,
+ UnprocessableEntityException, IOException {
ProjectControl ctl = rsrc.getControl();
- String parentName = MoreObjects.firstNonNull(
- Strings.emptyToNull(input.parent), allProjects.get());
+ String parentName =
+ MoreObjects.firstNonNull(Strings.emptyToNull(input.parent), allProjects.get());
validateParentUpdate(ctl, parentName, checkIfAdmin);
try (MetaDataUpdate md = updateFactory.create(rsrc.getNameKey())) {
ProjectConfig config = ProjectConfig.read(md);
@@ -81,8 +76,7 @@
String msg = Strings.emptyToNull(input.commitMessage);
if (msg == null) {
- msg = String.format(
- "Changed parent to %s.\n", parentName);
+ msg = String.format("Changed parent to %s.\n", parentName);
} else if (!msg.endsWith("\n")) {
msg += "\n";
}
@@ -97,39 +91,40 @@
} catch (RepositoryNotFoundException notFound) {
throw new ResourceNotFoundException(rsrc.getName());
} catch (ConfigInvalidException e) {
- throw new ResourceConflictException(String.format(
- "invalid project.config: %s", e.getMessage()));
+ throw new ResourceConflictException(
+ String.format("invalid project.config: %s", e.getMessage()));
}
}
- public void validateParentUpdate(final ProjectControl ctl, String newParent,
- boolean checkIfAdmin) throws AuthException, ResourceConflictException,
- UnprocessableEntityException {
+ public void validateParentUpdate(final ProjectControl ctl, String newParent, boolean checkIfAdmin)
+ throws AuthException, ResourceConflictException, UnprocessableEntityException {
IdentifiedUser user = ctl.getUser().asIdentifiedUser();
if (checkIfAdmin && !user.getCapabilities().canAdministrateServer()) {
throw new AuthException("not administrator");
}
if (ctl.getProject().getNameKey().equals(allProjects)) {
- throw new ResourceConflictException("cannot set parent of "
- + allProjects.get());
+ throw new ResourceConflictException("cannot set parent of " + allProjects.get());
}
newParent = Strings.emptyToNull(newParent);
if (newParent != null) {
ProjectState parent = cache.get(new Project.NameKey(newParent));
if (parent == null) {
- throw new UnprocessableEntityException("parent project " + newParent
- + " not found");
+ throw new UnprocessableEntityException("parent project " + newParent + " not found");
}
- if (Iterables.tryFind(parent.tree(), p -> {
- return p.getProject().getNameKey()
- .equals(ctl.getProject().getNameKey());
- }).isPresent()) {
- throw new ResourceConflictException("cycle exists between "
- + ctl.getProject().getName() + " and "
- + parent.getProject().getName());
+ if (Iterables.tryFind(
+ parent.tree(),
+ p -> {
+ return p.getProject().getNameKey().equals(ctl.getProject().getNameKey());
+ })
+ .isPresent()) {
+ throw new ResourceConflictException(
+ "cycle exists between "
+ + ctl.getProject().getName()
+ + " and "
+ + parent.getProject().getName());
}
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/SubmitRuleEvaluator.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/SubmitRuleEvaluator.java
index 48cd7ee..e6ad352 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/SubmitRuleEvaluator.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/SubmitRuleEvaluator.java
@@ -29,7 +29,6 @@
import com.google.gerrit.server.CurrentUser;
import com.google.gerrit.server.query.change.ChangeData;
import com.google.gwtorm.server.OrmException;
-
import com.googlecode.prolog_cafe.exceptions.CompileException;
import com.googlecode.prolog_cafe.exceptions.ReductionLimitException;
import com.googlecode.prolog_cafe.lang.IntegerTerm;
@@ -39,26 +38,21 @@
import com.googlecode.prolog_cafe.lang.SymbolTerm;
import com.googlecode.prolog_cafe.lang.Term;
import com.googlecode.prolog_cafe.lang.VariableTerm;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
- * Evaluates a submit-like Prolog rule found in the rules.pl file of the current
- * project and filters the results through rules found in the parent projects,
- * all the way up to All-Projects.
+ * Evaluates a submit-like Prolog rule found in the rules.pl file of the current project and filters
+ * the results through rules found in the parent projects, all the way up to All-Projects.
*/
public class SubmitRuleEvaluator {
- private static final Logger log = LoggerFactory
- .getLogger(SubmitRuleEvaluator.class);
+ private static final Logger log = LoggerFactory.getLogger(SubmitRuleEvaluator.class);
- private static final String DEFAULT_MSG =
- "Error evaluating project rules, check server log";
+ private static final String DEFAULT_MSG = "Error evaluating project rules, check server log";
public static List<SubmitRecord> defaultRuleError() {
return createRuleError(DEFAULT_MSG);
@@ -76,15 +70,14 @@
}
/**
- * Exception thrown when the label term of a submit record
- * unexpectedly didn't contain a user term.
+ * Exception thrown when the label term of a submit record unexpectedly didn't contain a user
+ * term.
*/
private static class UserTermExpected extends Exception {
private static final long serialVersionUID = 1L;
UserTermExpected(SubmitRecord.Label label) {
- super(String.format("A label with the status %s must contain a user.",
- label.toString()));
+ super(String.format("A label with the status %s must contain a user.", label.toString()));
}
}
@@ -105,10 +98,10 @@
}
/**
- * @return immutable snapshot of options configured so far. If neither {@link
- * #getSubmitRule()} nor {@link #getSubmitType()} have been called yet,
- * state within this instance is still mutable, so may change before
- * evaluation. The instance's options are frozen at evaluation time.
+ * @return immutable snapshot of options configured so far. If neither {@link #getSubmitRule()}
+ * nor {@link #getSubmitType()} have been called yet, state within this instance is still
+ * mutable, so may change before evaluation. The instance's options are frozen at evaluation
+ * time.
*/
public SubmitRuleOptions getOptions() {
if (opts != null) {
@@ -128,22 +121,23 @@
}
/**
- * @param ps patch set of the change to evaluate. If not set, the current
- * patch set will be loaded from {@link #evaluate()} or {@link
- * #getSubmitType}.
+ * @param ps patch set of the change to evaluate. If not set, the current patch set will be loaded
+ * from {@link #evaluate()} or {@link #getSubmitType}.
* @return this
*/
public SubmitRuleEvaluator setPatchSet(PatchSet ps) {
- checkArgument(ps.getId().getParentKey().equals(cd.getId()),
- "Patch set %s does not match change %s", ps.getId(), cd.getId());
+ checkArgument(
+ ps.getId().getParentKey().equals(cd.getId()),
+ "Patch set %s does not match change %s",
+ ps.getId(),
+ cd.getId());
patchSet = ps;
return this;
}
/**
- * @param fast if true assume reviewers are permitted to use label values
- * currently stored on the change. Fast mode bypasses some reviewer
- * permission checks.
+ * @param fast if true assume reviewers are permitted to use label values currently stored on the
+ * change. Fast mode bypasses some reviewer permission checks.
* @return this
*/
public SubmitRuleEvaluator setFastEvalLabels(boolean fast) {
@@ -193,8 +187,8 @@
}
/**
- * @param log whether to log error messages in addition to returning error
- * records. If true, error record messages will be less descriptive.
+ * @param log whether to log error messages in addition to returning error records. If true, error
+ * record messages will be less descriptive.
*/
public SubmitRuleEvaluator setLogErrors(boolean log) {
logErrors = log;
@@ -209,8 +203,8 @@
/**
* Evaluate the submit rules.
*
- * @return List of {@link SubmitRecord} objects returned from the evaluated
- * rules, including any errors.
+ * @return List of {@link SubmitRecord} objects returned from the evaluated rules, including any
+ * errors.
*/
public List<SubmitRecord> evaluate() {
initOptions();
@@ -224,8 +218,8 @@
try {
initPatchSet();
} catch (OrmException e) {
- return ruleError("Error looking up patch set "
- + control.getChange().currentPatchSetId(), e);
+ return ruleError(
+ "Error looking up patch set " + control.getChange().currentPatchSetId(), e);
}
if (c.getStatus() == Change.Status.DRAFT || patchSet.isDraft()) {
return cannotSubmitDraft();
@@ -234,9 +228,13 @@
List<Term> results;
try {
- results = evaluateImpl("locate_submit_rule", "can_submit",
- "locate_submit_filter", "filter_submit_results",
- control.getUser());
+ results =
+ evaluateImpl(
+ "locate_submit_rule",
+ "can_submit",
+ "locate_submit_filter",
+ "filter_submit_results",
+ control.getUser());
} catch (RuleEvalException e) {
return ruleError(e.getMessage(), e);
}
@@ -246,9 +244,10 @@
// at least one result informing the caller of the labels that are
// required for this change to be submittable. Each label will indicate
// whether or not that is actually possible given the permissions.
- return ruleError(String.format("Submit rule '%s' for change %s of %s has "
- + "no solution.", getSubmitRuleName(), cd.getId(),
- getProjectName()));
+ return ruleError(
+ String.format(
+ "Submit rule '%s' for change %s of %s has " + "no solution.",
+ getSubmitRuleName(), cd.getId(), getProjectName()));
}
return resultsToSubmitRecord(getSubmitRule(), results);
@@ -264,9 +263,8 @@
}
return createRuleError("Cannot submit draft changes");
} catch (OrmException err) {
- PatchSet.Id psId = patchSet != null
- ? patchSet.getId()
- : control.getChange().currentPatchSetId();
+ PatchSet.Id psId =
+ patchSet != null ? patchSet.getId() : control.getChange().currentPatchSetId();
String msg = "Cannot check visibility of patch set " + psId;
log.error(msg, err);
return createRuleError(msg);
@@ -276,13 +274,12 @@
/**
* Convert the results from Prolog Cafe's format to Gerrit's common format.
*
- * can_submit/1 terminates when an ok(P) record is found. Therefore walk
- * the results backwards, using only that ok(P) record if it exists. This
- * skips partial results that occur early in the output. Later after the loop
- * the out collection is reversed to restore it to the original ordering.
+ * <p>can_submit/1 terminates when an ok(P) record is found. Therefore walk the results backwards,
+ * using only that ok(P) record if it exists. This skips partial results that occur early in the
+ * output. Later after the loop the out collection is reversed to restore it to the original
+ * ordering.
*/
- private List<SubmitRecord> resultsToSubmitRecord(
- Term submitRule, List<Term> results) {
+ private List<SubmitRecord> resultsToSubmitRecord(Term submitRule, List<Term> results) {
List<SubmitRecord> out = new ArrayList<>(results.size());
for (int resultIdx = results.size() - 1; 0 <= resultIdx; resultIdx--) {
Term submitRecord = results.get(resultIdx);
@@ -363,9 +360,14 @@
}
private List<SubmitRecord> invalidResult(Term rule, Term record, String reason) {
- return ruleError(String.format("Submit rule %s for change %s of %s output "
- + "invalid result: %s%s", rule, cd.getId(), getProjectName(), record,
- (reason == null ? "" : ". Reason: " + reason)));
+ return ruleError(
+ String.format(
+ "Submit rule %s for change %s of %s output " + "invalid result: %s%s",
+ rule,
+ cd.getId(),
+ getProjectName(),
+ record,
+ (reason == null ? "" : ". Reason: " + reason)));
}
private List<SubmitRecord> invalidResult(Term rule, Term record) {
@@ -398,19 +400,16 @@
try {
initPatchSet();
} catch (OrmException e) {
- return typeError("Error looking up patch set "
- + control.getChange().currentPatchSetId(), e);
+ return typeError("Error looking up patch set " + control.getChange().currentPatchSetId(), e);
}
try {
if (control.getChange().getStatus() == Change.Status.DRAFT
&& !control.isDraftVisible(cd.db(), cd)) {
- return SubmitTypeRecord.error(
- "Patch set " + patchSet.getId() + " not found");
+ return SubmitTypeRecord.error("Patch set " + patchSet.getId() + " not found");
}
if (patchSet.isDraft() && !control.isDraftVisible(cd.db(), cd)) {
- return SubmitTypeRecord.error(
- "Patch set " + patchSet.getId() + " not found");
+ return SubmitTypeRecord.error("Patch set " + patchSet.getId() + " not found");
}
} catch (OrmException err) {
String msg = "Cannot read patch set " + patchSet.getId();
@@ -420,37 +419,57 @@
List<Term> results;
try {
- results = evaluateImpl("locate_submit_type", "get_submit_type",
- "locate_submit_type_filter", "filter_submit_type_results",
- // Do not include current user in submit type evaluation. This is used
- // for mergeability checks, which are stored persistently and so must
- // have a consistent view of the submit type.
- null);
+ results =
+ evaluateImpl(
+ "locate_submit_type",
+ "get_submit_type",
+ "locate_submit_type_filter",
+ "filter_submit_type_results",
+ // Do not include current user in submit type evaluation. This is used
+ // for mergeability checks, which are stored persistently and so must
+ // have a consistent view of the submit type.
+ null);
} catch (RuleEvalException e) {
return typeError(e.getMessage(), e);
}
if (results.isEmpty()) {
// Should never occur for a well written rule
- return typeError("Submit rule '" + getSubmitRuleName() + "' for change "
- + cd.getId() + " of " + getProjectName() + " has no solution.");
+ return typeError(
+ "Submit rule '"
+ + getSubmitRuleName()
+ + "' for change "
+ + cd.getId()
+ + " of "
+ + getProjectName()
+ + " has no solution.");
}
Term typeTerm = results.get(0);
if (!(typeTerm instanceof SymbolTerm)) {
- return typeError("Submit rule '" + getSubmitRuleName() + "' for change "
- + cd.getId() + " of " + getProjectName()
- + " did not return a symbol.");
+ return typeError(
+ "Submit rule '"
+ + getSubmitRuleName()
+ + "' for change "
+ + cd.getId()
+ + " of "
+ + getProjectName()
+ + " did not return a symbol.");
}
String typeName = ((SymbolTerm) typeTerm).name();
try {
- return SubmitTypeRecord.OK(
- SubmitType.valueOf(typeName.toUpperCase()));
+ return SubmitTypeRecord.OK(SubmitType.valueOf(typeName.toUpperCase()));
} catch (IllegalArgumentException e) {
- return typeError("Submit type rule " + getSubmitRule() + " for change "
- + cd.getId() + " of " + getProjectName() + " output invalid result: "
- + typeName);
+ return typeError(
+ "Submit type rule "
+ + getSubmitRule()
+ + " for change "
+ + cd.getId()
+ + " of "
+ + getProjectName()
+ + " output invalid result: "
+ + typeName);
}
}
@@ -475,7 +494,8 @@
String userRuleWrapperName,
String filterRuleLocatorName,
String filterRuleWrapperName,
- CurrentUser user) throws RuleEvalException {
+ CurrentUser user)
+ throws RuleEvalException {
PrologEnvironment env = getPrologEnvironment(user);
try {
Term sr = env.once("gerrit", userRuleLocatorName, new VariableTerm());
@@ -485,31 +505,31 @@
List<Term> results = new ArrayList<>();
try {
- for (Term[] template : env.all("gerrit", userRuleWrapperName, sr,
- new VariableTerm())) {
+ for (Term[] template : env.all("gerrit", userRuleWrapperName, sr, new VariableTerm())) {
results.add(template[1]);
}
} catch (ReductionLimitException err) {
- throw new RuleEvalException(String.format(
- "%s on change %d of %s",
- err.getMessage(), cd.getId().get(), getProjectName()));
+ throw new RuleEvalException(
+ String.format(
+ "%s on change %d of %s", err.getMessage(), cd.getId().get(), getProjectName()));
} catch (RuntimeException err) {
- throw new RuleEvalException(String.format(
- "Exception calling %s on change %d of %s",
- sr, cd.getId().get(), getProjectName()), err);
+ throw new RuleEvalException(
+ String.format(
+ "Exception calling %s on change %d of %s", sr, cd.getId().get(), getProjectName()),
+ err);
} finally {
reductionsConsumed = env.getReductions();
}
Term resultsTerm = toListTerm(results);
if (!opts.skipFilters()) {
- resultsTerm = runSubmitFilters(
- resultsTerm, env, filterRuleLocatorName, filterRuleWrapperName);
+ resultsTerm =
+ runSubmitFilters(resultsTerm, env, filterRuleLocatorName, filterRuleWrapperName);
}
List<Term> r;
if (resultsTerm instanceof ListTerm) {
r = new ArrayList<>();
- for (Term t = resultsTerm; t instanceof ListTerm;) {
+ for (Term t = resultsTerm; t instanceof ListTerm; ) {
ListTerm l = (ListTerm) t;
r.add(l.car().dereference());
t = l.cdr().dereference();
@@ -524,23 +544,19 @@
}
}
- private PrologEnvironment getPrologEnvironment(CurrentUser user)
- throws RuleEvalException {
+ private PrologEnvironment getPrologEnvironment(CurrentUser user) throws RuleEvalException {
ProjectState projectState = control.getProjectControl().getProjectState();
PrologEnvironment env;
try {
if (opts.rule() == null) {
env = projectState.newPrologEnvironment();
} else {
- env = projectState.newPrologEnvironment(
- "stdin", new StringReader(opts.rule()));
+ env = projectState.newPrologEnvironment("stdin", new StringReader(opts.rule()));
}
} catch (CompileException err) {
String msg;
if (opts.rule() == null && control.getProjectControl().isOwner()) {
- msg = String.format(
- "Cannot load rules.pl for %s: %s",
- getProjectName(), err.getMessage());
+ msg = String.format("Cannot load rules.pl for %s: %s", getProjectName(), err.getMessage());
} else if (opts.rule() != null) {
msg = err.getMessage();
} else {
@@ -557,8 +573,11 @@
return env;
}
- private Term runSubmitFilters(Term results, PrologEnvironment env,
- String filterRuleLocatorName, String filterRuleWrapperName)
+ private Term runSubmitFilters(
+ Term results,
+ PrologEnvironment env,
+ String filterRuleLocatorName,
+ String filterRuleWrapperName)
throws RuleEvalException {
ProjectState projectState = control.getProjectControl().getProjectState();
PrologEnvironment childEnv = env;
@@ -567,30 +586,32 @@
try {
parentEnv = parentState.newPrologEnvironment();
} catch (CompileException err) {
- throw new RuleEvalException("Cannot consult rules.pl for "
- + parentState.getProject().getName(), err);
+ throw new RuleEvalException(
+ "Cannot consult rules.pl for " + parentState.getProject().getName(), err);
}
parentEnv.copyStoredValues(childEnv);
- Term filterRule =
- parentEnv.once("gerrit", filterRuleLocatorName, new VariableTerm());
+ Term filterRule = parentEnv.once("gerrit", filterRuleLocatorName, new VariableTerm());
try {
if (opts.fastEvalLabels()) {
env.once("gerrit", "assume_range_from_label");
}
Term[] template =
- parentEnv.once("gerrit", filterRuleWrapperName, filterRule,
- results, new VariableTerm());
+ parentEnv.once(
+ "gerrit", filterRuleWrapperName, filterRule, results, new VariableTerm());
results = template[2];
} catch (ReductionLimitException err) {
- throw new RuleEvalException(String.format(
- "%s on change %d of %s",
- err.getMessage(), cd.getId().get(), parentState.getProject().getName()));
+ throw new RuleEvalException(
+ String.format(
+ "%s on change %d of %s",
+ err.getMessage(), cd.getId().get(), parentState.getProject().getName()));
} catch (RuntimeException err) {
- throw new RuleEvalException(String.format(
- "Exception calling %s on change %d of %s",
- filterRule, cd.getId().get(), parentState.getProject().getName()), err);
+ throw new RuleEvalException(
+ String.format(
+ "Exception calling %s on change %d of %s",
+ filterRule, cd.getId().get(), parentState.getProject().getName()),
+ err);
} finally {
reductionsConsumed += env.getReductions();
}
@@ -607,8 +628,7 @@
return list;
}
- private void appliedBy(SubmitRecord.Label label, Term status)
- throws UserTermExpected {
+ private void appliedBy(SubmitRecord.Label label, Term status) throws UserTermExpected {
if (status instanceof StructureTerm && status.arity() == 1) {
Term who = status.arg(0);
if (isUser(who)) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/SubmitRuleOptions.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/SubmitRuleOptions.java
index 97155ac..6d6aaad 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/SubmitRuleOptions.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/SubmitRuleOptions.java
@@ -19,10 +19,9 @@
/**
* Stable identifier for options passed to a particular submit rule evaluator.
- * <p>
- * Used to test whether it is ok to reuse a cached list of submit records. Does
- * not include a change or patch set ID; callers are responsible for checking
- * those on their own.
+ *
+ * <p>Used to test whether it is ok to reuse a cached list of submit records. Does not include a
+ * change or patch set ID; callers are responsible for checking those on their own.
*/
@AutoValue
public abstract class SubmitRuleOptions {
@@ -40,17 +39,26 @@
}
public abstract boolean fastEvalLabels();
+
public abstract boolean allowDraft();
+
public abstract boolean allowClosed();
+
public abstract boolean skipFilters();
- @Nullable public abstract String rule();
+
+ @Nullable
+ public abstract String rule();
@AutoValue.Builder
public abstract static class Builder {
public abstract SubmitRuleOptions.Builder fastEvalLabels(boolean fastEvalLabels);
+
public abstract SubmitRuleOptions.Builder allowDraft(boolean allowDraft);
+
public abstract SubmitRuleOptions.Builder allowClosed(boolean allowClosed);
+
public abstract SubmitRuleOptions.Builder skipFilters(boolean skipFilters);
+
public abstract SubmitRuleOptions.Builder rule(@Nullable String rule);
public abstract SubmitRuleOptions build();
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/SuggestParentCandidates.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/SuggestParentCandidates.java
index a6717d5..9d3005c 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/SuggestParentCandidates.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/SuggestParentCandidates.java
@@ -18,7 +18,6 @@
import com.google.gerrit.server.config.AllProjectsName;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
@@ -32,8 +31,10 @@
private final AllProjectsName allProject;
@Inject
- SuggestParentCandidates(final ProjectControl.Factory projectControlFactory,
- final ProjectCache projectCache, final AllProjectsName allProject) {
+ SuggestParentCandidates(
+ final ProjectControl.Factory projectControlFactory,
+ final ProjectCache projectCache,
+ final AllProjectsName allProject) {
this.projectControlFactory = projectControlFactory;
this.projectCache = projectCache;
this.allProject = allProject;
@@ -49,12 +50,14 @@
}
public List<Project> getProjects() throws NoSuchProjectException {
- Set<Project> projects = new TreeSet<>(new Comparator<Project>() {
- @Override
- public int compare(Project o1, Project o2) {
- return o1.getName().compareTo(o2.getName());
- }
- });
+ Set<Project> projects =
+ new TreeSet<>(
+ new Comparator<Project>() {
+ @Override
+ public int compare(Project o1, Project o2) {
+ return o1.getName().compareTo(o2.getName());
+ }
+ });
for (Project.NameKey p : projectCache.all()) {
try {
final ProjectControl control = projectControlFactory.controlFor(p);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/project/TagsCollection.java b/gerrit-server/src/main/java/com/google/gerrit/server/project/TagsCollection.java
index b324fe0..82afce4 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/project/TagsCollection.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/project/TagsCollection.java
@@ -23,21 +23,20 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.io.IOException;
@Singleton
-public class TagsCollection implements
- ChildCollection<ProjectResource, TagResource>,
- AcceptsCreate<ProjectResource> {
+public class TagsCollection
+ implements ChildCollection<ProjectResource, TagResource>, AcceptsCreate<ProjectResource> {
private final DynamicMap<RestView<TagResource>> views;
private final Provider<ListTags> list;
private final CreateTag.Factory createTagFactory;
@Inject
- public TagsCollection(DynamicMap<RestView<TagResource>> views,
- Provider<ListTags> list,
- CreateTag.Factory createTagFactory) {
+ public TagsCollection(
+ DynamicMap<RestView<TagResource>> views,
+ Provider<ListTags> list,
+ CreateTag.Factory createTagFactory) {
this.views = views;
this.list = list;
this.createTagFactory = createTagFactory;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/AndPredicate.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/AndPredicate.java
index 899e789..7e03355 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/AndPredicate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/AndPredicate.java
@@ -17,7 +17,6 @@
import static com.google.common.base.Preconditions.checkState;
import com.google.gwtorm.server.OrmException;
-
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
@@ -85,8 +84,11 @@
@Override
public boolean match(final T object) throws OrmException {
for (Predicate<T> c : children) {
- checkState(c.isMatchable(), "match invoked, but child predicate %s "
- + "doesn't implement %s", c, Matchable.class.getName());
+ checkState(
+ c.isMatchable(),
+ "match invoked, but child predicate %s " + "doesn't implement %s",
+ c,
+ Matchable.class.getName());
if (!c.asMatchable().match(object)) {
return false;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/AndSource.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/AndSource.java
index 4acd2ba..dcd8a66 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/AndSource.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/AndSource.java
@@ -24,7 +24,6 @@
import com.google.gwtorm.server.OrmException;
import com.google.gwtorm.server.OrmRuntimeException;
import com.google.gwtorm.server.ResultSet;
-
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
@@ -43,18 +42,18 @@
this(that, null, 0);
}
- public AndSource(Predicate<T> that,
- IsVisibleToPredicate<T> isVisibleToPredicate) {
+ public AndSource(Predicate<T> that, IsVisibleToPredicate<T> isVisibleToPredicate) {
this(that, isVisibleToPredicate, 0);
}
- public AndSource(Predicate<T> that,
- IsVisibleToPredicate<T> isVisibleToPredicate, int start) {
+ public AndSource(Predicate<T> that, IsVisibleToPredicate<T> isVisibleToPredicate, int start) {
this(ImmutableList.of(that), isVisibleToPredicate, start);
}
- public AndSource(Collection<? extends Predicate<T>> that,
- IsVisibleToPredicate<T> isVisibleToPredicate, int start) {
+ public AndSource(
+ Collection<? extends Predicate<T>> that,
+ IsVisibleToPredicate<T> isVisibleToPredicate,
+ int start) {
super(that);
checkArgument(start >= 0, "negative start: %s", start);
this.isVisibleToPredicate = isVisibleToPredicate;
@@ -186,9 +185,7 @@
cmp = a.estimateCost() - b.estimateCost();
}
- if (cmp == 0
- && a instanceof DataSource
- && b instanceof DataSource) {
+ if (cmp == 0 && a instanceof DataSource && b instanceof DataSource) {
DataSource<?> as = (DataSource<?>) a;
DataSource<?> bs = (DataSource<?>) b;
cmp = as.getCardinality() - bs.getCardinality();
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/IntPredicate.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/IntPredicate.java
index d336bb5..6627687 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/IntPredicate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/IntPredicate.java
@@ -44,8 +44,7 @@
}
if (getClass() == other.getClass()) {
final IntPredicate<?> p = (IntPredicate<?>) other;
- return getOperator().equals(p.getOperator())
- && intValue() == p.intValue();
+ return getOperator().equals(p.getOperator()) && intValue() == p.intValue();
}
return false;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/InternalQuery.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/InternalQuery.java
index e98211e..87772d2 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/InternalQuery.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/InternalQuery.java
@@ -21,17 +21,15 @@
import com.google.gerrit.server.index.IndexConfig;
import com.google.gerrit.server.index.Schema;
import com.google.gwtorm.server.OrmException;
-
import java.util.List;
import java.util.Set;
/**
* Execute a single query over a secondary index, for use by Gerrit internals.
- * <p>
- * By default, visibility of returned entities is not enforced (unlike in {@link
- * QueryProcessor}). The methods in this class are not typically used by
- * user-facing paths, but rather by internal callers that need to process all
- * matching results.
+ *
+ * <p>By default, visibility of returned entities is not enforced (unlike in {@link
+ * QueryProcessor}). The methods in this class are not typically used by user-facing paths, but
+ * rather by internal callers that need to process all matching results.
*/
public class InternalQuery<T> {
private final QueryProcessor<T> queryProcessor;
@@ -39,9 +37,10 @@
protected final IndexConfig indexConfig;
- protected InternalQuery(QueryProcessor<T> queryProcessor,
+ protected InternalQuery(
+ QueryProcessor<T> queryProcessor,
IndexCollection<?, T, ? extends Index<?, T>> indexes,
- IndexConfig indexConfig) {
+ IndexConfig indexConfig) {
this.queryProcessor = queryProcessor.enforceVisibility(false);
this.indexes = indexes;
this.indexConfig = indexConfig;
@@ -63,7 +62,7 @@
}
public InternalQuery<T> noFields() {
- queryProcessor.setRequestedFields(ImmutableSet.<String> of());
+ queryProcessor.setRequestedFields(ImmutableSet.<String>of());
return this;
}
@@ -77,18 +76,17 @@
/**
* Run multiple queries in parallel.
- * <p>
- * If a limit was specified using {@link #setLimit(int)}, that limit is
- * applied to each query independently.
+ *
+ * <p>If a limit was specified using {@link #setLimit(int)}, that limit is applied to each query
+ * independently.
*
* @param queries list of queries.
- * @return results of the queries, one list of results per input query, in the
- * same order as the input.
+ * @return results of the queries, one list of results per input query, in the same order as the
+ * input.
*/
public List<List<T>> query(List<Predicate<T>> queries) throws OrmException {
try {
- return Lists.transform(
- queryProcessor.query(queries), QueryResult::entities);
+ return Lists.transform(queryProcessor.query(queries), QueryResult::entities);
} catch (QueryParseException e) {
throw new OrmException(e);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/IsVisibleToPredicate.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/IsVisibleToPredicate.java
index 87de6bd..9295eb9 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/IsVisibleToPredicate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/IsVisibleToPredicate.java
@@ -17,8 +17,7 @@
import com.google.gerrit.server.CurrentUser;
import com.google.gerrit.server.query.change.SingleGroupUser;
-public abstract class IsVisibleToPredicate<T> extends OperatorPredicate<T>
- implements Matchable<T> {
+public abstract class IsVisibleToPredicate<T> extends OperatorPredicate<T> implements Matchable<T> {
public IsVisibleToPredicate(String name, String value) {
super(name, value);
}
@@ -28,8 +27,7 @@
return user.getAccountId().toString();
}
if (user instanceof SingleGroupUser) {
- return "group:" + user.getEffectiveGroups()
- .getKnownGroups().iterator().next().toString();
+ return "group:" + user.getEffectiveGroups().getKnownGroups().iterator().next().toString();
}
return user.toString();
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/NotPredicate.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/NotPredicate.java
index 8ffba72..530dfb9 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/NotPredicate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/NotPredicate.java
@@ -17,7 +17,6 @@
import static com.google.common.base.Preconditions.checkState;
import com.google.gwtorm.server.OrmException;
-
import java.util.Collection;
import java.util.Collections;
import java.util.List;
@@ -66,8 +65,11 @@
@Override
public boolean match(final T object) throws OrmException {
- checkState(that.isMatchable(), "match invoked, but child predicate %s "
- + "doesn't implement %s", that, Matchable.class.getName());
+ checkState(
+ that.isMatchable(),
+ "match invoked, but child predicate %s " + "doesn't implement %s",
+ that,
+ Matchable.class.getName());
return !that.asMatchable().match(object);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/OperatorPredicate.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/OperatorPredicate.java
index 2cb70af..96a30ee 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/OperatorPredicate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/OperatorPredicate.java
@@ -16,7 +16,6 @@
import java.util.Collection;
-
/** Predicate to filter a field by matching value. */
public abstract class OperatorPredicate<T> extends Predicate<T> {
private final String name;
@@ -55,8 +54,7 @@
}
if (getClass() == other.getClass()) {
final OperatorPredicate<?> p = (OperatorPredicate<?>) other;
- return getOperator().equals(p.getOperator())
- && getValue().equals(p.getValue());
+ return getOperator().equals(p.getOperator()) && getValue().equals(p.getValue());
}
return false;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/OrPredicate.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/OrPredicate.java
index ad15286..1dd46f9 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/OrPredicate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/OrPredicate.java
@@ -17,7 +17,6 @@
import static com.google.common.base.Preconditions.checkState;
import com.google.gwtorm.server.OrmException;
-
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
@@ -85,8 +84,11 @@
@Override
public boolean match(final T object) throws OrmException {
for (final Predicate<T> c : children) {
- checkState(c.isMatchable(), "match invoked, but child predicate %s "
- + "doesn't implement %s", c, Matchable.class.getName());
+ checkState(
+ c.isMatchable(),
+ "match invoked, but child predicate %s " + "doesn't implement %s",
+ c,
+ Matchable.class.getName());
if (c.asMatchable().match(object)) {
return true;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/Predicate.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/Predicate.java
index 3a38da6..aabc066 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/Predicate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/Predicate.java
@@ -17,29 +17,25 @@
import static com.google.common.base.Preconditions.checkState;
import com.google.common.collect.Iterables;
-
import java.util.Collection;
import java.util.Collections;
import java.util.List;
/**
* An abstract predicate tree for any form of query.
- * <p>
- * Implementations should be immutable, such that the meaning of a predicate
- * never changes once constructed. They should ensure their immutable promise by
- * defensively copying any structures which might be modified externally, but
- * was passed into the object's constructor.
- * <p>
- * However, implementations <i>may</i> retain non-thread-safe caches internally,
- * to speed up evaluation operations within the context of one thread's
- * evaluation of the predicate. As a result, callers should assume predicates
- * are not thread-safe, but that two predicate graphs produce the same results
- * given the same inputs if they are {@link #equals(Object)}.
- * <p>
- * Predicates should support deep inspection whenever possible, so that generic
- * algorithms can be written to operate against them. Predicates which contain
- * other predicates should override {@link #getChildren()} to return the list of
- * children nested within the predicate.
+ *
+ * <p>Implementations should be immutable, such that the meaning of a predicate never changes once
+ * constructed. They should ensure their immutable promise by defensively copying any structures
+ * which might be modified externally, but was passed into the object's constructor.
+ *
+ * <p>However, implementations <i>may</i> retain non-thread-safe caches internally, to speed up
+ * evaluation operations within the context of one thread's evaluation of the predicate. As a
+ * result, callers should assume predicates are not thread-safe, but that two predicate graphs
+ * produce the same results given the same inputs if they are {@link #equals(Object)}.
+ *
+ * <p>Predicates should support deep inspection whenever possible, so that generic algorithms can be
+ * written to operate against them. Predicates which contain other predicates should override {@link
+ * #getChildren()} to return the list of children nested within the predicate.
*
* @param <T> type of object the predicate can evaluate in memory.
*/
@@ -60,8 +56,7 @@
}
/** Combine the passed predicates into a single AND node. */
- public static <T> Predicate<T> and(
- final Collection<? extends Predicate<T>> that) {
+ public static <T> Predicate<T> and(final Collection<? extends Predicate<T>> that) {
if (that.size() == 1) {
return Iterables.getOnlyElement(that);
}
@@ -78,8 +73,7 @@
}
/** Combine the passed predicates into a single OR node. */
- public static <T> Predicate<T> or(
- final Collection<? extends Predicate<T>> that) {
+ public static <T> Predicate<T> or(final Collection<? extends Predicate<T>> that) {
if (that.size() == 1) {
return Iterables.getOnlyElement(that);
}
@@ -141,8 +135,7 @@
private static class Any<T> extends Predicate<T> implements Matchable<T> {
private static final Any<Object> INSTANCE = new Any<>();
- private Any() {
- }
+ private Any() {}
@Override
public Predicate<T> copy(Collection<? extends Predicate<T>> children) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/QueryBuilder.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/QueryBuilder.java
index 644ed63..1009ce6 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/QueryBuilder.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/QueryBuilder.java
@@ -25,8 +25,6 @@
import static com.google.gerrit.server.query.QueryParser.OR;
import static com.google.gerrit.server.query.QueryParser.SINGLE_WORD;
-import org.antlr.runtime.tree.Tree;
-
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -38,14 +36,14 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import org.antlr.runtime.tree.Tree;
/**
* Base class to support writing parsers for query languages.
- * <p>
- * Subclasses may document their supported query operators by declaring public
- * methods that perform the query conversion into a {@link Predicate}. For
- * example, to support "is:starred", "is:unread", and nothing else, a subclass
- * may write:
+ *
+ * <p>Subclasses may document their supported query operators by declaring public methods that
+ * perform the query conversion into a {@link Predicate}. For example, to support "is:starred",
+ * "is:unread", and nothing else, a subclass may write:
*
* <pre>
* @Operator
@@ -59,16 +57,15 @@
* throw new IllegalArgumentException();
* }
* </pre>
- * <p>
- * The available operator methods are discovered at runtime via reflection.
- * Method names (after being converted to lowercase), correspond to operators in
- * the query language, method string values correspond to the operator argument.
- * Methods must be declared {@code public}, returning {@link Predicate},
- * accepting one {@link String}, and annotated with the {@link Operator}
+ *
+ * <p>The available operator methods are discovered at runtime via reflection. Method names (after
+ * being converted to lowercase), correspond to operators in the query language, method string
+ * values correspond to the operator argument. Methods must be declared {@code public}, returning
+ * {@link Predicate}, accepting one {@link String}, and annotated with the {@link Operator}
* annotation.
- * <p>
- * Subclasses may also declare a handler for values which appear without
- * operator by overriding {@link #defaultField(String)}.
+ *
+ * <p>Subclasses may also declare a handler for values which appear without operator by overriding
+ * {@link #defaultField(String)}.
*
* @param <T> type of object the predicates can evaluate in memory.
*/
@@ -81,14 +78,13 @@
/**
* Defines the operators known by a QueryBuilder.
*
- * This class is thread-safe and may be reused or cached.
+ * <p>This class is thread-safe and may be reused or cached.
*
* @param <T> type of object the predicates can evaluate in memory.
* @param <Q> type of the query builder subclass.
*/
public static class Definition<T, Q extends QueryBuilder<T>> {
- private final Map<String, OperatorFactory<T, Q>> opFactories =
- new HashMap<>();
+ private final Map<String, OperatorFactory<T, Q>> opFactories = new HashMap<>();
public Definition(Class<Q> clazz) {
// Guess at the supported operators by scanning methods.
@@ -142,12 +138,12 @@
* @param p the predicate to find.
* @param clazz type of the predicate instance.
* @param name name of the operator.
- * @return the first instance of a predicate having the given type, as found
- * by a depth-first search.
+ * @return the first instance of a predicate having the given type, as found by a depth-first
+ * search.
*/
@SuppressWarnings("unchecked")
- public static <T, P extends OperatorPredicate<T>> P find(Predicate<T> p,
- Class<P> clazz, String name) {
+ public static <T, P extends OperatorPredicate<T>> P find(
+ Predicate<T> p, Class<P> clazz, String name) {
if (p instanceof OperatorPredicate
&& ((OperatorPredicate<?>) p).getOperator().equals(name)
&& clazz.isAssignableFrom(p.getClass())) {
@@ -180,10 +176,9 @@
*
* @param query the query string.
* @return predicate representing the user query.
- * @throws QueryParseException the query string is invalid and cannot be
- * parsed by this parser. This may be due to a syntax error, may be
- * due to an operator not being supported, or due to an invalid value
- * being passed to a recognized operator.
+ * @throws QueryParseException the query string is invalid and cannot be parsed by this parser.
+ * This may be due to a syntax error, may be due to an operator not being supported, or due to
+ * an invalid value being passed to a recognized operator.
*/
public Predicate<T> parse(final String query) throws QueryParseException {
return toPredicate(QueryParser.parse(query));
@@ -193,16 +188,12 @@
* Parse multiple user-supplied query strings into a list of predicates.
*
* @param queries the query strings.
- * @return predicates representing the user query, in the same order as the
- * input.
- * @throws QueryParseException one of the query strings is invalid and cannot
- * be parsed by this parser. This may be due to a syntax error, may be
- * due to an operator not being supported, or due to an invalid value
- * being passed to a recognized operator.
- *
+ * @return predicates representing the user query, in the same order as the input.
+ * @throws QueryParseException one of the query strings is invalid and cannot be parsed by this
+ * parser. This may be due to a syntax error, may be due to an operator not being supported,
+ * or due to an invalid value being passed to a recognized operator.
*/
- public List<Predicate<T>> parse(final List<String> queries)
- throws QueryParseException {
+ public List<Predicate<T>> parse(final List<String> queries) throws QueryParseException {
List<Predicate<T>> predicates = new ArrayList<>(queries.size());
for (String query : queries) {
predicates.add(parse(query));
@@ -210,8 +201,8 @@
return predicates;
}
- private Predicate<T> toPredicate(final Tree r) throws QueryParseException,
- IllegalArgumentException {
+ private Predicate<T> toPredicate(final Tree r)
+ throws QueryParseException, IllegalArgumentException {
switch (r.getType()) {
case AND:
return and(children(r));
@@ -231,24 +222,24 @@
}
}
- private Predicate<T> operator(final String name, final Tree val)
- throws QueryParseException {
+ private Predicate<T> operator(final String name, final Tree val) throws QueryParseException {
switch (val.getType()) {
- // Expand multiple values, "foo:(a b c)", as though they were written
- // out with the longer form, "foo:a foo:b foo:c".
- //
+ // Expand multiple values, "foo:(a b c)", as though they were written
+ // out with the longer form, "foo:a foo:b foo:c".
+ //
case AND:
- case OR: {
- List<Predicate<T>> p = new ArrayList<>(val.getChildCount());
- for (int i = 0; i < val.getChildCount(); i++) {
- final Tree c = val.getChild(i);
- if (c.getType() != DEFAULT_FIELD) {
- throw error("Nested operator not expected: " + c);
+ case OR:
+ {
+ List<Predicate<T>> p = new ArrayList<>(val.getChildCount());
+ for (int i = 0; i < val.getChildCount(); i++) {
+ final Tree c = val.getChild(i);
+ if (c.getType() != DEFAULT_FIELD) {
+ throw error("Nested operator not expected: " + c);
+ }
+ p.add(operator(name, onlyChildOf(c)));
}
- p.add(operator(name, onlyChildOf(c)));
+ return val.getType() == AND ? and(p) : or(p);
}
- return val.getType() == AND ? and(p) : or(p);
- }
case SINGLE_WORD:
case EXACT_PHRASE:
@@ -263,8 +254,7 @@
}
@SuppressWarnings("unchecked")
- private Predicate<T> operator(final String name, final String value)
- throws QueryParseException {
+ private Predicate<T> operator(final String name, final String value) throws QueryParseException {
@SuppressWarnings("rawtypes")
OperatorFactory f = opFactories.get(name);
if (f == null) {
@@ -289,23 +279,22 @@
/**
* Handle a value present outside of an operator.
- * <p>
- * This default implementation always throws an "Unsupported query: " message
- * containing the input text. Subclasses may override this method to perform
- * do-what-i-mean guesses based on the input string.
+ *
+ * <p>This default implementation always throws an "Unsupported query: " message containing the
+ * input text. Subclasses may override this method to perform do-what-i-mean guesses based on the
+ * input string.
*
* @param value the value supplied by itself in the query.
* @return predicate representing this value.
* @throws QueryParseException the parser does not recognize this value.
*/
- protected Predicate<T> defaultField(final String value)
- throws QueryParseException {
+ protected Predicate<T> defaultField(final String value) throws QueryParseException {
throw error("Unsupported query:" + value);
}
@SuppressWarnings("unchecked")
- private Predicate<T>[] children(final Tree r) throws QueryParseException,
- IllegalArgumentException {
+ private Predicate<T>[] children(final Tree r)
+ throws QueryParseException, IllegalArgumentException {
final Predicate<T>[] p = new Predicate[r.getChildCount()];
for (int i = 0; i < p.length; i++) {
p[i] = toPredicate(r.getChild(i));
@@ -331,8 +320,7 @@
/** Denotes a method which is a query operator. */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
- protected @interface Operator {
- }
+ protected @interface Operator {}
private static class ReflectionFactory<T, Q extends QueryBuilder<T>>
implements OperatorFactory<T, Q> {
@@ -346,8 +334,7 @@
@SuppressWarnings("unchecked")
@Override
- public Predicate<T> create(Q builder, String value)
- throws QueryParseException {
+ public Predicate<T> create(Q builder, String value) throws QueryParseException {
try {
return (Predicate<T>) method.invoke(builder, value);
} catch (RuntimeException | IllegalAccessException e) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/QueryProcessor.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/QueryProcessor.java
index a0f66db..b5ea361 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/QueryProcessor.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/QueryProcessor.java
@@ -36,7 +36,6 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
@@ -50,11 +49,14 @@
@Inject
Metrics(MetricMaker metricMaker) {
Field<String> index = Field.ofString("index", "index name");
- executionTime = metricMaker.newTimer("query/query_latency",
- new Description("Successful query latency,"
- + " accumulated over the life of the process").setCumulative()
+ executionTime =
+ metricMaker.newTimer(
+ "query/query_latency",
+ new Description(
+ "Successful query latency," + " accumulated over the life of the process")
+ .setCumulative()
.setUnit(Description.Units.MILLISECONDS),
- index);
+ index);
}
}
@@ -117,8 +119,7 @@
* @param query the query.
* @return results of the query.
*/
- public QueryResult<T> query(Predicate<T> query)
- throws OrmException, QueryParseException {
+ public QueryResult<T> query(Predicate<T> query) throws OrmException, QueryParseException {
return query(ImmutableList.of(query)).get(0);
}
@@ -126,8 +127,8 @@
* Perform multiple queries in parallel.
*
* @param queries list of queries.
- * @return results of the queries, one QueryResult per input query, in the
- * same order as the input.
+ * @return results of the queries, one QueryResult per input query, in the same order as the
+ * input.
*/
public List<QueryResult<T>> query(List<Predicate<T>> queries)
throws OrmException, QueryParseException {
@@ -143,8 +144,7 @@
}
}
- private List<QueryResult<T>> query(List<String> queryStrings,
- List<Predicate<T>> queries)
+ private List<QueryResult<T>> query(List<String> queryStrings, List<Predicate<T>> queries)
throws OrmException, QueryParseException {
long startNanos = System.nanoTime();
@@ -170,8 +170,7 @@
// Always bump limit by 1, even if this results in exceeding the permitted
// max for this user. The only way to see if there are more entities is to
// ask for one more result from the query.
- QueryOptions opts =
- createOptions(indexConfig, start, limit + 1, getRequestedFields());
+ QueryOptions opts = createOptions(indexConfig, start, limit + 1, getRequestedFields());
Predicate<T> pred = rewriter.rewrite(q, opts);
if (enforceVisibility) {
pred = enforceVisibility(pred);
@@ -191,27 +190,28 @@
List<QueryResult<T>> out = new ArrayList<>(cnt);
for (int i = 0; i < cnt; i++) {
- out.add(QueryResult.create(
- queryStrings != null ? queryStrings.get(i) : null,
- predicates.get(i),
- limits.get(i),
- matches.get(i).toList()));
+ out.add(
+ QueryResult.create(
+ queryStrings != null ? queryStrings.get(i) : null,
+ predicates.get(i),
+ limits.get(i),
+ matches.get(i).toList()));
}
// only measure successful queries
- metrics.executionTime.record(schemaDef.getName(),
- System.nanoTime() - startNanos, TimeUnit.NANOSECONDS);
+ metrics.executionTime.record(
+ schemaDef.getName(), System.nanoTime() - startNanos, TimeUnit.NANOSECONDS);
return out;
}
- protected QueryOptions createOptions(IndexConfig indexConfig, int start,
- int limit, Set<String> requestedFields) {
+ protected QueryOptions createOptions(
+ IndexConfig indexConfig, int start, int limit, Set<String> requestedFields) {
return QueryOptions.create(indexConfig, start, limit, requestedFields);
}
/**
- * Invoked after the query was rewritten. Subclasses must overwrite this
- * method to filter out results that are not visible to the calling user.
+ * Invoked after the query was rewritten. Subclasses must overwrite this method to filter out
+ * results that are not visible to the calling user.
*
* @param pred the query
* @return the modified query
@@ -223,9 +223,7 @@
return requestedFields;
}
Index<?, T> index = indexes.getSearchIndex();
- return index != null
- ? index.getSchema().getStoredFields().keySet()
- : ImmutableSet.<String> of();
+ return index != null ? index.getSchema().getStoredFields().keySet() : ImmutableSet.<String>of();
}
public boolean isDisabled() {
@@ -234,9 +232,7 @@
private int getPermittedLimit() {
if (enforceVisibility) {
- return userProvider.get().getCapabilities()
- .getRange(GlobalCapability.QUERY_LIMIT)
- .getMax();
+ return userProvider.get().getCapabilities().getRange(GlobalCapability.QUERY_LIMIT).getMax();
}
return Integer.MAX_VALUE;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/QueryResult.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/QueryResult.java
index b35bde3..f86eb707 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/QueryResult.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/QueryResult.java
@@ -16,14 +16,13 @@
import com.google.auto.value.AutoValue;
import com.google.gerrit.common.Nullable;
-
import java.util.List;
/** Results of a query over entities. */
@AutoValue
public abstract class QueryResult<T> {
- static <T> QueryResult<T> create(@Nullable String query,
- Predicate<T> predicate, int limit, List<T> entites) {
+ static <T> QueryResult<T> create(
+ @Nullable String query, Predicate<T> predicate, int limit, List<T> entites) {
boolean more;
if (entites.size() > limit) {
more = true;
@@ -34,25 +33,19 @@
return new AutoValue_QueryResult<>(query, predicate, entites, more);
}
- /**
- * @return the original query string, or null if the query was created
- * programmatically.
- */
- @Nullable public abstract String query();
+ /** @return the original query string, or null if the query was created programmatically. */
+ @Nullable
+ public abstract String query();
- /**
- * @return the predicate after all rewriting and other modification by the
- * query subsystem.
- */
+ /** @return the predicate after all rewriting and other modification by the query subsystem. */
public abstract Predicate<T> predicate();
/** @return the query results. */
public abstract List<T> entities();
/**
- * @return whether the query could be retried with
- * {@link QueryProcessor#setStart(int)} to produce more results. Never
- * true if {@link #entities()} is empty.
+ * @return whether the query could be retried with {@link QueryProcessor#setStart(int)} to produce
+ * more results. Never true if {@link #entities()} is empty.
*/
public abstract boolean more();
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/account/AccountIsVisibleToPredicate.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/account/AccountIsVisibleToPredicate.java
index 0d6f5ce..0a74647 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/account/AccountIsVisibleToPredicate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/account/AccountIsVisibleToPredicate.java
@@ -19,13 +19,11 @@
import com.google.gerrit.server.query.IsVisibleToPredicate;
import com.google.gwtorm.server.OrmException;
-public class AccountIsVisibleToPredicate
- extends IsVisibleToPredicate<AccountState> {
+public class AccountIsVisibleToPredicate extends IsVisibleToPredicate<AccountState> {
private final AccountControl accountControl;
AccountIsVisibleToPredicate(AccountControl accountControl) {
- super(AccountQueryBuilder.FIELD_VISIBLETO,
- describe(accountControl.getUser()));
+ super(AccountQueryBuilder.FIELD_VISIBLETO, describe(accountControl.getUser()));
this.accountControl = accountControl;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/account/AccountPredicates.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/account/AccountPredicates.java
index 9a9ec5d..796539b 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/account/AccountPredicates.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/account/AccountPredicates.java
@@ -24,13 +24,11 @@
import com.google.gerrit.server.index.account.AccountField;
import com.google.gerrit.server.query.Predicate;
import com.google.gerrit.server.query.QueryBuilder;
-
import java.util.List;
public class AccountPredicates {
public static boolean hasActive(Predicate<AccountState> p) {
- return QueryBuilder.find(p, AccountPredicate.class,
- AccountField.ACTIVE.getName()) != null;
+ return QueryBuilder.find(p, AccountPredicate.class, AccountField.ACTIVE.getName()) != null;
}
static Predicate<AccountState> defaultPredicate(String query) {
@@ -48,18 +46,18 @@
}
public static Predicate<AccountState> id(Account.Id accountId) {
- return new AccountPredicate(AccountField.ID,
- AccountQueryBuilder.FIELD_ACCOUNT, accountId.toString());
+ return new AccountPredicate(
+ AccountField.ID, AccountQueryBuilder.FIELD_ACCOUNT, accountId.toString());
}
static Predicate<AccountState> email(String email) {
- return new AccountPredicate(AccountField.EMAIL,
- AccountQueryBuilder.FIELD_EMAIL, email.toLowerCase());
+ return new AccountPredicate(
+ AccountField.EMAIL, AccountQueryBuilder.FIELD_EMAIL, email.toLowerCase());
}
static Predicate<AccountState> equalsName(String name) {
- return new AccountPredicate(AccountField.NAME_PART,
- AccountQueryBuilder.FIELD_NAME, name.toLowerCase());
+ return new AccountPredicate(
+ AccountField.NAME_PART, AccountQueryBuilder.FIELD_NAME, name.toLowerCase());
}
static Predicate<AccountState> externalId(String externalId) {
@@ -79,8 +77,8 @@
}
static Predicate<AccountState> username(String username) {
- return new AccountPredicate(AccountField.USERNAME,
- AccountQueryBuilder.FIELD_USERNAME, username.toLowerCase());
+ return new AccountPredicate(
+ AccountField.USERNAME, AccountQueryBuilder.FIELD_USERNAME, username.toLowerCase());
}
static Predicate<AccountState> watchedProject(Project.NameKey project) {
@@ -97,6 +95,5 @@
}
}
- private AccountPredicates() {
- }
+ private AccountPredicates() {}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/account/AccountQueryBuilder.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/account/AccountQueryBuilder.java
index 1c945e3..5ae6a67 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/account/AccountQueryBuilder.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/account/AccountQueryBuilder.java
@@ -30,9 +30,7 @@
import com.google.inject.Provider;
import com.google.inject.ProvisionException;
-/**
- * Parses a query string meant to be applied to account objects.
- */
+/** Parses a query string meant to be applied to account objects. */
public class AccountQueryBuilder extends QueryBuilder<AccountState> {
public static final String FIELD_ACCOUNT = "account";
public static final String FIELD_EMAIL = "email";
@@ -98,8 +96,7 @@
}
@Operator
- public Predicate<AccountState> limit(String query)
- throws QueryParseException {
+ public Predicate<AccountState> limit(String query) throws QueryParseException {
Integer limit = Ints.tryParse(query);
if (limit == null) {
throw error("Invalid limit: " + query);
@@ -120,14 +117,12 @@
public Predicate<AccountState> defaultQuery(String query) {
return Predicate.and(
Lists.transform(
- Splitter.on(' ').omitEmptyStrings().splitToList(query),
- this::defaultField));
+ Splitter.on(' ').omitEmptyStrings().splitToList(query), this::defaultField));
}
@Override
protected Predicate<AccountState> defaultField(String query) {
- Predicate<AccountState> defaultPredicate =
- AccountPredicates.defaultPredicate(query);
+ Predicate<AccountState> defaultPredicate = AccountPredicates.defaultPredicate(query);
if ("self".equalsIgnoreCase(query)) {
try {
return Predicate.or(defaultPredicate, AccountPredicates.id(self()));
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/account/AccountQueryProcessor.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/account/AccountQueryProcessor.java
index 48d0897..d984e6d 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/account/AccountQueryProcessor.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/account/AccountQueryProcessor.java
@@ -42,21 +42,27 @@
}
@Inject
- protected AccountQueryProcessor(Provider<CurrentUser> userProvider,
+ protected AccountQueryProcessor(
+ Provider<CurrentUser> userProvider,
Metrics metrics,
IndexConfig indexConfig,
AccountIndexCollection indexes,
AccountIndexRewriter rewriter,
AccountControl.Factory accountControlFactory) {
- super(userProvider, metrics, AccountSchemaDefinitions.INSTANCE, indexConfig,
- indexes, rewriter, FIELD_LIMIT);
+ super(
+ userProvider,
+ metrics,
+ AccountSchemaDefinitions.INSTANCE,
+ indexConfig,
+ indexes,
+ rewriter,
+ FIELD_LIMIT);
this.accountControlFactory = accountControlFactory;
}
@Override
- protected Predicate<AccountState> enforceVisibility(
- Predicate<AccountState> pred) {
- return new AndSource<>(pred,
- new AccountIsVisibleToPredicate(accountControlFactory.get()), start);
+ protected Predicate<AccountState> enforceVisibility(Predicate<AccountState> pred) {
+ return new AndSource<>(
+ pred, new AccountIsVisibleToPredicate(accountControlFactory.get()), start);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/account/InternalAccountQuery.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/account/InternalAccountQuery.java
index 7bc3144..1c336d4 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/account/InternalAccountQuery.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/account/InternalAccountQuery.java
@@ -23,19 +23,17 @@
import com.google.gerrit.server.query.InternalQuery;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
-
+import java.util.List;
+import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.util.List;
-import java.util.Set;
-
public class InternalAccountQuery extends InternalQuery<AccountState> {
- private static final Logger log =
- LoggerFactory.getLogger(InternalAccountQuery.class);
+ private static final Logger log = LoggerFactory.getLogger(InternalAccountQuery.class);
@Inject
- InternalAccountQuery(AccountQueryProcessor queryProcessor,
+ InternalAccountQuery(
+ AccountQueryProcessor queryProcessor,
AccountIndexCollection indexes,
IndexConfig indexConfig) {
super(queryProcessor, indexes, indexConfig);
@@ -65,13 +63,11 @@
return this;
}
- public List<AccountState> byDefault(String query)
- throws OrmException {
+ public List<AccountState> byDefault(String query) throws OrmException {
return query(AccountPredicates.defaultPredicate(query));
}
- public List<AccountState> byExternalId(String externalId)
- throws OrmException {
+ public List<AccountState> byExternalId(String externalId) throws OrmException {
return query(AccountPredicates.externalId(externalId));
}
@@ -81,23 +77,19 @@
return accountStates.get(0);
} else if (accountStates.size() > 0) {
StringBuilder msg = new StringBuilder();
- msg.append("Ambiguous external ID ")
- .append(externalId)
- .append("for accounts: ");
- Joiner.on(", ").appendTo(msg,
- Lists.transform(accountStates, AccountState.ACCOUNT_ID_FUNCTION));
+ msg.append("Ambiguous external ID ").append(externalId).append("for accounts: ");
+ Joiner.on(", ")
+ .appendTo(msg, Lists.transform(accountStates, AccountState.ACCOUNT_ID_FUNCTION));
log.warn(msg.toString());
}
return null;
}
- public List<AccountState> byFullName(String fullName)
- throws OrmException {
+ public List<AccountState> byFullName(String fullName) throws OrmException {
return query(AccountPredicates.fullName(fullName));
}
- public List<AccountState> byWatchedProject(Project.NameKey project)
- throws OrmException {
+ public List<AccountState> byWatchedProject(Project.NameKey project) throws OrmException {
return query(AccountPredicates.watchedProject(project));
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/AfterPredicate.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/AfterPredicate.java
index 477bf16..7d51217 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/AfterPredicate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/AfterPredicate.java
@@ -17,7 +17,6 @@
import com.google.gerrit.server.index.change.ChangeField;
import com.google.gerrit.server.query.QueryParseException;
import com.google.gwtorm.server.OrmException;
-
import java.util.Date;
public class AfterPredicate extends TimestampRangeChangePredicate {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/AgePredicate.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/AgePredicate.java
index fd6cbee..0cd76bb 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/AgePredicate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/AgePredicate.java
@@ -22,7 +22,6 @@
import com.google.gerrit.server.config.ConfigUtil;
import com.google.gerrit.server.index.change.ChangeField;
import com.google.gwtorm.server.OrmException;
-
import java.sql.Timestamp;
public class AgePredicate extends TimestampRangeChangePredicate {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/AndChangeSource.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/AndChangeSource.java
index bd7daed..b0fcfd1 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/AndChangeSource.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/AndChangeSource.java
@@ -19,31 +19,31 @@
import com.google.gerrit.server.query.Predicate;
import com.google.gwtorm.server.OrmException;
import com.google.gwtorm.server.OrmRuntimeException;
-
import java.util.Collection;
import java.util.List;
-public class AndChangeSource extends AndSource<ChangeData>
- implements ChangeDataSource {
+public class AndChangeSource extends AndSource<ChangeData> implements ChangeDataSource {
public AndChangeSource(Collection<Predicate<ChangeData>> that) {
super(that);
}
- public AndChangeSource(Predicate<ChangeData> that,
- IsVisibleToPredicate<ChangeData> isVisibleToPredicate, int start) {
+ public AndChangeSource(
+ Predicate<ChangeData> that,
+ IsVisibleToPredicate<ChangeData> isVisibleToPredicate,
+ int start) {
super(that, isVisibleToPredicate, start);
}
@Override
public boolean hasChange() {
- return source != null && source instanceof ChangeDataSource
+ return source != null
+ && source instanceof ChangeDataSource
&& ((ChangeDataSource) source).hasChange();
}
@Override
- protected List<ChangeData> transformBuffer(List<ChangeData> buffer)
- throws OrmRuntimeException {
+ protected List<ChangeData> transformBuffer(List<ChangeData> buffer) throws OrmRuntimeException {
if (!hasChange()) {
try {
ChangeData.ensureChangeLoaded(buffer);
@@ -57,8 +57,7 @@
@Override
public int compare(Predicate<ChangeData> a, Predicate<ChangeData> b) {
int cmp = super.compare(a, b);
- if (cmp == 0 && a instanceof ChangeDataSource
- && b instanceof ChangeDataSource) {
+ if (cmp == 0 && a instanceof ChangeDataSource && b instanceof ChangeDataSource) {
ChangeDataSource as = (ChangeDataSource) a;
ChangeDataSource bs = (ChangeDataSource) b;
cmp = (as.hasChange() ? 0 : 1) - (bs.hasChange() ? 0 : 1);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/AuthorPredicate.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/AuthorPredicate.java
index ebaaab9..6a760db 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/AuthorPredicate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/AuthorPredicate.java
@@ -27,8 +27,7 @@
@Override
public boolean match(ChangeData object) throws OrmException {
- return ChangeField.getAuthorParts(object).contains(
- getValue().toLowerCase());
+ return ChangeField.getAuthorParts(object).contains(getValue().toLowerCase());
}
@Override
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/BeforePredicate.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/BeforePredicate.java
index f36a1631..9e443c9 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/BeforePredicate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/BeforePredicate.java
@@ -17,7 +17,6 @@
import com.google.gerrit.server.index.change.ChangeField;
import com.google.gerrit.server.query.QueryParseException;
import com.google.gwtorm.server.OrmException;
-
import java.util.Date;
public class BeforePredicate extends TimestampRangeChangePredicate {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ChangeData.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ChangeData.java
index 98f6cb5..3fc719b 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ChangeData.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ChangeData.java
@@ -69,18 +69,6 @@
import com.google.gwtorm.server.ResultSet;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
-
-import org.eclipse.jgit.errors.IncorrectObjectTypeException;
-import org.eclipse.jgit.errors.MissingObjectException;
-import org.eclipse.jgit.errors.RepositoryNotFoundException;
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.lib.PersonIdent;
-import org.eclipse.jgit.lib.Ref;
-import org.eclipse.jgit.lib.Repository;
-import org.eclipse.jgit.revwalk.FooterLine;
-import org.eclipse.jgit.revwalk.RevCommit;
-import org.eclipse.jgit.revwalk.RevWalk;
-
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
@@ -94,12 +82,21 @@
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
+import org.eclipse.jgit.errors.IncorrectObjectTypeException;
+import org.eclipse.jgit.errors.MissingObjectException;
+import org.eclipse.jgit.errors.RepositoryNotFoundException;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.lib.PersonIdent;
+import org.eclipse.jgit.lib.Ref;
+import org.eclipse.jgit.lib.Repository;
+import org.eclipse.jgit.revwalk.FooterLine;
+import org.eclipse.jgit.revwalk.RevCommit;
+import org.eclipse.jgit.revwalk.RevWalk;
public class ChangeData {
private static final int BATCH_SIZE = 50;
- public static List<Change> asChanges(List<ChangeData> changeDatas)
- throws OrmException {
+ public static List<Change> asChanges(List<ChangeData> changeDatas) throws OrmException {
List<Change> result = new ArrayList<>(changeDatas.size());
for (ChangeData cd : changeDatas) {
result.add(cd.change());
@@ -108,12 +105,10 @@
}
public static Map<Change.Id, ChangeData> asMap(List<ChangeData> changes) {
- return changes.stream().collect(
- Collectors.toMap(ChangeData::getId, cd -> cd));
+ return changes.stream().collect(Collectors.toMap(ChangeData::getId, cd -> cd));
}
- public static void ensureChangeLoaded(Iterable<ChangeData> changes)
- throws OrmException {
+ public static void ensureChangeLoaded(Iterable<ChangeData> changes) throws OrmException {
ChangeData first = Iterables.getFirst(changes, null);
if (first == null) {
return;
@@ -133,14 +128,12 @@
if (missing.isEmpty()) {
return;
}
- for (ChangeNotes notes : first.notesFactory.create(
- first.db, missing.keySet())) {
+ for (ChangeNotes notes : first.notesFactory.create(first.db, missing.keySet())) {
missing.get(notes.getChangeId()).change = notes.getChange();
}
}
- public static void ensureAllPatchSetsLoaded(Iterable<ChangeData> changes)
- throws OrmException {
+ public static void ensureAllPatchSetsLoaded(Iterable<ChangeData> changes) throws OrmException {
ChangeData first = Iterables.getFirst(changes, null);
if (first == null) {
return;
@@ -170,8 +163,7 @@
}
}
- public static void ensureCurrentPatchSetLoaded(Iterable<ChangeData> changes)
- throws OrmException {
+ public static void ensureCurrentPatchSetLoaded(Iterable<ChangeData> changes) throws OrmException {
ChangeData first = Iterables.getFirst(changes, null);
if (first == null) {
return;
@@ -228,8 +220,7 @@
}
}
- public static void ensureMessagesLoaded(Iterable<ChangeData> changes)
- throws OrmException {
+ public static void ensureMessagesLoaded(Iterable<ChangeData> changes) throws OrmException {
ChangeData first = Iterables.getFirst(changes, null);
if (first == null) {
return;
@@ -260,8 +251,8 @@
}
}
- public static void ensureReviewedByLoadedForOpenChanges(
- Iterable<ChangeData> changes) throws OrmException {
+ public static void ensureReviewedByLoadedForOpenChanges(Iterable<ChangeData> changes)
+ throws OrmException {
List<ChangeData> pending = new ArrayList<>();
for (ChangeData cd : changes) {
if (cd.reviewedBy == null && cd.change().getStatus().isOpen()) {
@@ -280,8 +271,11 @@
public interface Factory {
ChangeData create(ReviewDb db, Project.NameKey project, Change.Id id);
+
ChangeData create(ReviewDb db, Change c);
+
ChangeData create(ReviewDb db, ChangeNotes cn);
+
ChangeData create(ReviewDb db, ChangeControl c);
// TODO(dborowitz): Remove when deleting index schemas <27.
@@ -290,17 +284,19 @@
/**
* Create an instance for testing only.
- * <p>
- * Attempting to lazy load data will fail with NPEs. Callers may consider
- * manually setting fields that can be set.
+ *
+ * <p>Attempting to lazy load data will fail with NPEs. Callers may consider manually setting
+ * fields that can be set.
*
* @param id change ID
* @return instance for testing.
*/
- public static ChangeData createForTest(Project.NameKey project, Change.Id id,
- int currentPatchSetId) {
- ChangeData cd = new ChangeData(null, null, null, null, null, null, null,
- null, null, null, null, null, null, null, null, project, id);
+ public static ChangeData createForTest(
+ Project.NameKey project, Change.Id id, int currentPatchSetId) {
+ ChangeData cd =
+ new ChangeData(
+ null, null, null, null, null, null, null, null, null, null, null, null, null, null,
+ null, project, id);
cd.currentPatchSet = new PatchSet(new PatchSet.Id(id, currentPatchSetId));
return cd;
}
@@ -322,8 +318,8 @@
private final MergeabilityCache mergeabilityCache;
private final StarredChangesUtil starredChangesUtil;
private final Change.Id legacyId;
- private final Map<SubmitRuleOptions, List<SubmitRecord>>
- submitRecords = Maps.newLinkedHashMapWithExpectedSize(1);
+ private final Map<SubmitRuleOptions, List<SubmitRecord>> submitRecords =
+ Maps.newLinkedHashMapWithExpectedSize(1);
private Project.NameKey project;
private Change change;
@@ -348,8 +344,7 @@
private Map<Account.Id, Ref> editsByUser;
private Set<Account.Id> reviewedBy;
private Map<Account.Id, Ref> draftsByUser;
- @Deprecated
- private Set<Account.Id> starredByUser;
+ @Deprecated private Set<Account.Id> starredByUser;
private ImmutableListMultimap<Account.Id, String> stars;
private ImmutableMap<Account.Id, StarRef> starRefs;
private ReviewerSet reviewers;
@@ -533,7 +528,8 @@
@Nullable StarredChangesUtil starredChangesUtil,
@Assisted ReviewDb db,
@Assisted Change.Id id) {
- checkState(!notesMigration.readChanges(),
+ checkState(
+ !notesMigration.readChanges(),
"do not call createOnlyWhenNoteDbDisabled when NoteDb is enabled");
this.db = db;
this.repoManager = repoManager;
@@ -655,8 +651,7 @@
if (ps == null) {
return Optional.empty();
}
- return getPatchList(c, ps).map(
- p -> new ChangedLines(p.getInsertions(), p.getDeletions()));
+ return getPatchList(c, ps).map(p -> new ChangedLines(p.getInsertions(), p.getDeletions()));
}
public Optional<ChangedLines> changedLines() throws OrmException {
@@ -683,8 +678,9 @@
public Project.NameKey project() throws OrmException {
if (project == null) {
- checkState(!notesMigration.readChanges(), "should not have created "
- + " ChangeData without a project when NoteDb is enabled");
+ checkState(
+ !notesMigration.readChanges(),
+ "should not have created " + " ChangeData without a project when NoteDb is enabled");
project = change().getProject();
}
return project;
@@ -702,8 +698,7 @@
if (changeControl == null) {
Change c = change();
try {
- changeControl = changeControlFactory.controlFor(
- db, c, userFactory.create(c.getOwner()));
+ changeControl = changeControlFactory.controlFor(db, c, userFactory.create(c.getOwner()));
} catch (NoSuchChangeException e) {
throw new OrmException(e);
}
@@ -717,15 +712,13 @@
if (sameUser(user, oldUser)) {
return changeControl;
}
- throw new IllegalStateException(
- "user already specified: " + changeControl.getUser());
+ throw new IllegalStateException("user already specified: " + changeControl.getUser());
}
try {
if (change != null) {
changeControl = changeControlFactory.controlFor(db, change, user);
} else {
- changeControl =
- changeControlFactory.controlFor(db, project(), legacyId, user);
+ changeControl = changeControlFactory.controlFor(db, project(), legacyId, user);
}
} catch (NoSuchChangeException e) {
throw new OrmException(e);
@@ -799,8 +792,7 @@
return currentPatchSet;
}
- public List<PatchSetApproval> currentApprovals()
- throws OrmException {
+ public List<PatchSetApproval> currentApprovals() throws OrmException {
if (currentApprovals == null) {
if (!lazyLoad) {
return Collections.emptyList();
@@ -810,8 +802,9 @@
currentApprovals = Collections.emptyList();
} else {
try {
- currentApprovals = ImmutableList.copyOf(approvalsUtil.byPatchSet(
- db, changeControl(), c.currentPatchSetId()));
+ currentApprovals =
+ ImmutableList.copyOf(
+ approvalsUtil.byPatchSet(db, changeControl(), c.currentPatchSetId()));
} catch (OrmException e) {
if (e.getCause() instanceof NoSuchChangeException) {
currentApprovals = Collections.emptyList();
@@ -864,9 +857,9 @@
return committer;
}
- private boolean loadCommitData() throws OrmException,
- RepositoryNotFoundException, IOException, MissingObjectException,
- IncorrectObjectTypeException {
+ private boolean loadCommitData()
+ throws OrmException, RepositoryNotFoundException, IOException, MissingObjectException,
+ IncorrectObjectTypeException {
PatchSet ps = currentPatchSet();
if (ps == null) {
return false;
@@ -899,13 +892,14 @@
* @throws OrmException an error occurred reading the database.
*/
public Collection<PatchSet> visiblePatchSets() throws OrmException {
- Predicate<? super PatchSet> predicate = ps -> {
- try {
- return changeControl().isPatchVisible(ps, db);
- } catch (OrmException e) {
- return false;
- }
- };
+ Predicate<? super PatchSet> predicate =
+ ps -> {
+ try {
+ return changeControl().isPatchVisible(ps, db);
+ } catch (OrmException e) {
+ return false;
+ }
+ };
return patchSets().stream().filter(predicate).collect(toList());
}
@@ -931,12 +925,11 @@
}
/**
- * @return all patch set approvals for the change, keyed by ID, ordered by
- * timestamp within each patch set.
+ * @return all patch set approvals for the change, keyed by ID, ordered by timestamp within each
+ * patch set.
* @throws OrmException an error occurred reading the database.
*/
- public ListMultimap<PatchSet.Id, PatchSetApproval> approvals()
- throws OrmException {
+ public ListMultimap<PatchSet.Id, PatchSetApproval> approvals() throws OrmException {
if (allApprovals == null) {
if (!lazyLoad) {
return ImmutableListMultimap.of();
@@ -950,11 +943,8 @@
* @return The submit ('SUBM') approval label
* @throws OrmException an error occurred reading the database.
*/
- public Optional<PatchSetApproval> getSubmitApproval()
- throws OrmException {
- return currentApprovals().stream()
- .filter(PatchSetApproval::isLegacySubmit)
- .findFirst();
+ public Optional<PatchSetApproval> getSubmitApproval() throws OrmException {
+ return currentApprovals().stream().filter(PatchSetApproval::isLegacySubmit).findFirst();
}
public ReviewerSet reviewers() throws OrmException {
@@ -993,8 +983,7 @@
return reviewerUpdates;
}
- public Collection<Comment> publishedComments()
- throws OrmException {
+ public Collection<Comment> publishedComments() throws OrmException {
if (publishedComments == null) {
if (!lazyLoad) {
return Collections.emptyList();
@@ -1004,8 +993,7 @@
return publishedComments;
}
- public List<ChangeMessage> messages()
- throws OrmException {
+ public List<ChangeMessage> messages() throws OrmException {
if (messages == null) {
if (!lazyLoad) {
return Collections.emptyList();
@@ -1015,29 +1003,24 @@
return messages;
}
- public List<SubmitRecord> submitRecords(
- SubmitRuleOptions options) throws OrmException {
+ public List<SubmitRecord> submitRecords(SubmitRuleOptions options) throws OrmException {
List<SubmitRecord> records = submitRecords.get(options);
if (records == null) {
if (!lazyLoad) {
return Collections.emptyList();
}
- records = new SubmitRuleEvaluator(this)
- .setOptions(options)
- .evaluate();
+ records = new SubmitRuleEvaluator(this).setOptions(options).evaluate();
submitRecords.put(options, records);
}
return records;
}
@Nullable
- public List<SubmitRecord> getSubmitRecords(
- SubmitRuleOptions options) {
+ public List<SubmitRecord> getSubmitRecords(SubmitRuleOptions options) {
return submitRecords.get(options);
}
- public void setSubmitRecords(SubmitRuleOptions options,
- List<SubmitRecord> records) {
+ public void setSubmitRecords(SubmitRuleOptions options, List<SubmitRecord> records) {
submitRecords.put(options, records);
}
@@ -1084,12 +1067,16 @@
// No need to log, as SubmitRuleEvaluator already did it for us.
return false;
}
- String mergeStrategy = mergeUtilFactory
- .create(projectCache.get(project()))
- .mergeStrategyName();
- mergeable = mergeabilityCache.get(
- ObjectId.fromString(ps.getRevision().get()),
- ref, str.type, mergeStrategy, c.getDest(), repo);
+ String mergeStrategy =
+ mergeUtilFactory.create(projectCache.get(project())).mergeStrategyName();
+ mergeable =
+ mergeabilityCache.get(
+ ObjectId.fromString(ps.getRevision().get()),
+ ref,
+ str.type,
+ mergeStrategy,
+ c.getDest(),
+ repo);
} catch (IOException e) {
throw new OrmException(e);
}
@@ -1114,8 +1101,8 @@
editsByUser = new HashMap<>();
Change.Id id = checkNotNull(change.getId());
try (Repository repo = repoManager.openRepository(project())) {
- for (Map.Entry<String, Ref> e
- : repo.getRefDatabase().getRefs(RefNames.REFS_USERS).entrySet()) {
+ for (Map.Entry<String, Ref> e :
+ repo.getRefDatabase().getRefs(RefNames.REFS_USERS).entrySet()) {
if (id.equals(Change.Id.fromEditRefPart(e.getKey()))) {
editsByUser.put(Account.Id.fromRefPart(e.getKey()), e.getValue());
}
@@ -1217,8 +1204,8 @@
if (!lazyLoad) {
return Collections.emptySet();
}
- starredByUser = checkNotNull(starredChangesUtil).byChange(
- legacyId, StarredChangesUtil.DEFAULT_LABEL);
+ starredByUser =
+ checkNotNull(starredChangesUtil).byChange(legacyId, StarredChangesUtil.DEFAULT_LABEL);
}
return starredByUser;
}
@@ -1233,8 +1220,7 @@
if (!lazyLoad) {
return ImmutableListMultimap.of();
}
- ImmutableListMultimap.Builder<Account.Id, String> b =
- ImmutableListMultimap.builder();
+ ImmutableListMultimap.Builder<Account.Id, String> b = ImmutableListMultimap.builder();
for (Map.Entry<Account.Id, StarRef> e : starRefs().entrySet()) {
b.putAll(e.getKey(), e.getValue().labels());
}
@@ -1260,11 +1246,11 @@
@AutoValue
abstract static class ReviewedByEvent {
private static ReviewedByEvent create(ChangeMessage msg) {
- return new AutoValue_ChangeData_ReviewedByEvent(
- msg.getAuthor(), msg.getWrittenOn());
+ return new AutoValue_ChangeData_ReviewedByEvent(msg.getAuthor(), msg.getWrittenOn());
}
public abstract Account.Id author();
+
public abstract Timestamp ts();
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ChangeIndexPredicate.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ChangeIndexPredicate.java
index 80951fd..0604f8b 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ChangeIndexPredicate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ChangeIndexPredicate.java
@@ -24,8 +24,7 @@
super(def, value);
}
- protected ChangeIndexPredicate(FieldDef<ChangeData, ?> def, String name,
- String value) {
+ protected ChangeIndexPredicate(FieldDef<ChangeData, ?> def, String name, String value) {
super(def, name, value);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ChangeIsVisibleToPredicate.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ChangeIsVisibleToPredicate.java
index 88499ec..8db62a7 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ChangeIsVisibleToPredicate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ChangeIsVisibleToPredicate.java
@@ -30,9 +30,11 @@
private final ChangeControl.GenericFactory changeControl;
private final CurrentUser user;
- ChangeIsVisibleToPredicate(Provider<ReviewDb> db,
+ ChangeIsVisibleToPredicate(
+ Provider<ReviewDb> db,
ChangeNotes.Factory notesFactory,
- ChangeControl.GenericFactory changeControlFactory, CurrentUser user) {
+ ChangeControl.GenericFactory changeControlFactory,
+ CurrentUser user) {
super(ChangeQueryBuilder.FIELD_VISIBLETO, describe(user));
this.db = db;
this.notesFactory = notesFactory;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ChangeOperatorPredicate.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ChangeOperatorPredicate.java
index 6bec598..242592e 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ChangeOperatorPredicate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ChangeOperatorPredicate.java
@@ -17,8 +17,8 @@
import com.google.gerrit.server.query.Matchable;
import com.google.gerrit.server.query.OperatorPredicate;
-public abstract class ChangeOperatorPredicate extends
- OperatorPredicate<ChangeData> implements Matchable<ChangeData> {
+public abstract class ChangeOperatorPredicate extends OperatorPredicate<ChangeData>
+ implements Matchable<ChangeData> {
protected ChangeOperatorPredicate(String name, String value) {
super(name, value);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ChangeQueryBuilder.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ChangeQueryBuilder.java
index 73951c4..2af5cd8 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ChangeQueryBuilder.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ChangeQueryBuilder.java
@@ -74,12 +74,6 @@
import com.google.inject.Provider;
import com.google.inject.ProvisionException;
import com.google.inject.util.Providers;
-
-import org.eclipse.jgit.errors.ConfigInvalidException;
-import org.eclipse.jgit.errors.RepositoryNotFoundException;
-import org.eclipse.jgit.lib.Config;
-import org.eclipse.jgit.lib.Repository;
-
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
@@ -89,40 +83,35 @@
import java.util.Optional;
import java.util.Set;
import java.util.regex.Pattern;
+import org.eclipse.jgit.errors.ConfigInvalidException;
+import org.eclipse.jgit.errors.RepositoryNotFoundException;
+import org.eclipse.jgit.lib.Config;
+import org.eclipse.jgit.lib.Repository;
-/**
- * Parses a query string meant to be applied to change objects.
- */
+/** Parses a query string meant to be applied to change objects. */
public class ChangeQueryBuilder extends QueryBuilder<ChangeData> {
- public interface ChangeOperatorFactory
- extends OperatorFactory<ChangeData, ChangeQueryBuilder> {
- }
+ public interface ChangeOperatorFactory extends OperatorFactory<ChangeData, ChangeQueryBuilder> {}
/**
- * Converts a operand (operator value) passed to an operator into a
- * {@link Predicate}.
+ * Converts a operand (operator value) passed to an operator into a {@link Predicate}.
*
- * Register a ChangeOperandFactory in a config Module like this (note, for
- * an example we are using the has predicate, when other predicate plugin
- * operands are created they can be registered in a similar manner):
+ * <p>Register a ChangeOperandFactory in a config Module like this (note, for an example we are
+ * using the has predicate, when other predicate plugin operands are created they can be
+ * registered in a similar manner):
*
- * bind(ChangeHasOperandFactory.class)
- * .annotatedWith(Exports.named("your has operand"))
- * .to(YourClass.class);
- *
+ * <p>bind(ChangeHasOperandFactory.class) .annotatedWith(Exports.named("your has operand"))
+ * .to(YourClass.class);
*/
private interface ChangeOperandFactory {
- Predicate<ChangeData> create(ChangeQueryBuilder builder)
- throws QueryParseException;
+ Predicate<ChangeData> create(ChangeQueryBuilder builder) throws QueryParseException;
}
- public interface ChangeHasOperandFactory extends ChangeOperandFactory {
- }
+ public interface ChangeHasOperandFactory extends ChangeOperandFactory {}
private static final Pattern PAT_LEGACY_ID = Pattern.compile("^[1-9][0-9]*$");
private static final Pattern PAT_CHANGE_ID = Pattern.compile(CHANGE_ID_PATTERN);
- private static final Pattern DEF_CHANGE = Pattern.compile(
- "^(?:[1-9][0-9]*|(?:[^~]+~[^~]+~)?[iI][0-9a-f]{4,}.*)$");
+ private static final Pattern DEF_CHANGE =
+ Pattern.compile("^(?:[1-9][0-9]*|(?:[^~]+~[^~]+~)?[iI][0-9a-f]{4,}.*)$");
// NOTE: As new search operations are added, please keep the
// SearchSuggestOracle up to date.
@@ -217,7 +206,8 @@
@Inject
@VisibleForTesting
- public Arguments(Provider<ReviewDb> db,
+ public Arguments(
+ Provider<ReviewDb> db,
Provider<InternalChangeQuery> queryProvider,
ChangeIndexRewriter rewriter,
DynamicMap<ChangeOperatorFactory> opFactories,
@@ -247,13 +237,36 @@
StarredChangesUtil starredChangesUtil,
AccountCache accountCache,
@GerritServerConfig Config cfg) {
- this(db, queryProvider, rewriter, opFactories, hasOperands, userFactory,
- self, capabilityControlFactory, changeControlGenericFactory, notesFactory,
- changeDataFactory, fillArgs, commentsUtil, accountResolver, groupBackend,
- allProjectsName, allUsersName, patchListCache, repoManager, projectCache,
- listChildProjects, submitDryRun, conflictsCache, trackingFooters,
- indexes != null ? indexes.getSearchIndex() : null, indexConfig, listMembers,
- starredChangesUtil, accountCache,
+ this(
+ db,
+ queryProvider,
+ rewriter,
+ opFactories,
+ hasOperands,
+ userFactory,
+ self,
+ capabilityControlFactory,
+ changeControlGenericFactory,
+ notesFactory,
+ changeDataFactory,
+ fillArgs,
+ commentsUtil,
+ accountResolver,
+ groupBackend,
+ allProjectsName,
+ allUsersName,
+ patchListCache,
+ repoManager,
+ projectCache,
+ listChildProjects,
+ submitDryRun,
+ conflictsCache,
+ trackingFooters,
+ indexes != null ? indexes.getSearchIndex() : null,
+ indexConfig,
+ listMembers,
+ starredChangesUtil,
+ accountCache,
cfg == null ? true : cfg.getBoolean("change", "allowDrafts", true));
}
@@ -288,47 +301,70 @@
StarredChangesUtil starredChangesUtil,
AccountCache accountCache,
boolean allowsDrafts) {
- this.db = db;
- this.queryProvider = queryProvider;
- this.rewriter = rewriter;
- this.opFactories = opFactories;
- this.userFactory = userFactory;
- this.self = self;
- this.capabilityControlFactory = capabilityControlFactory;
- this.notesFactory = notesFactory;
- this.changeControlGenericFactory = changeControlGenericFactory;
- this.changeDataFactory = changeDataFactory;
- this.fillArgs = fillArgs;
- this.commentsUtil = commentsUtil;
- this.accountResolver = accountResolver;
- this.groupBackend = groupBackend;
- this.allProjectsName = allProjectsName;
- this.allUsersName = allUsersName;
- this.patchListCache = patchListCache;
- this.repoManager = repoManager;
- this.projectCache = projectCache;
- this.listChildProjects = listChildProjects;
- this.submitDryRun = submitDryRun;
- this.conflictsCache = conflictsCache;
- this.trackingFooters = trackingFooters;
- this.index = index;
- this.indexConfig = indexConfig;
- this.listMembers = listMembers;
- this.starredChangesUtil = starredChangesUtil;
- this.accountCache = accountCache;
- this.allowsDrafts = allowsDrafts;
- this.hasOperands = hasOperands;
+ this.db = db;
+ this.queryProvider = queryProvider;
+ this.rewriter = rewriter;
+ this.opFactories = opFactories;
+ this.userFactory = userFactory;
+ this.self = self;
+ this.capabilityControlFactory = capabilityControlFactory;
+ this.notesFactory = notesFactory;
+ this.changeControlGenericFactory = changeControlGenericFactory;
+ this.changeDataFactory = changeDataFactory;
+ this.fillArgs = fillArgs;
+ this.commentsUtil = commentsUtil;
+ this.accountResolver = accountResolver;
+ this.groupBackend = groupBackend;
+ this.allProjectsName = allProjectsName;
+ this.allUsersName = allUsersName;
+ this.patchListCache = patchListCache;
+ this.repoManager = repoManager;
+ this.projectCache = projectCache;
+ this.listChildProjects = listChildProjects;
+ this.submitDryRun = submitDryRun;
+ this.conflictsCache = conflictsCache;
+ this.trackingFooters = trackingFooters;
+ this.index = index;
+ this.indexConfig = indexConfig;
+ this.listMembers = listMembers;
+ this.starredChangesUtil = starredChangesUtil;
+ this.accountCache = accountCache;
+ this.allowsDrafts = allowsDrafts;
+ this.hasOperands = hasOperands;
}
Arguments asUser(CurrentUser otherUser) {
- return new Arguments(db, queryProvider, rewriter, opFactories,
- hasOperands, userFactory, Providers.of(otherUser),
- capabilityControlFactory, changeControlGenericFactory, notesFactory,
- changeDataFactory, fillArgs, commentsUtil, accountResolver,
- groupBackend, allProjectsName, allUsersName, patchListCache,
- repoManager, projectCache, listChildProjects, submitDryRun,
- conflictsCache, trackingFooters, index, indexConfig, listMembers,
- starredChangesUtil, accountCache, allowsDrafts);
+ return new Arguments(
+ db,
+ queryProvider,
+ rewriter,
+ opFactories,
+ hasOperands,
+ userFactory,
+ Providers.of(otherUser),
+ capabilityControlFactory,
+ changeControlGenericFactory,
+ notesFactory,
+ changeDataFactory,
+ fillArgs,
+ commentsUtil,
+ accountResolver,
+ groupBackend,
+ allProjectsName,
+ allUsersName,
+ patchListCache,
+ repoManager,
+ projectCache,
+ listChildProjects,
+ submitDryRun,
+ conflictsCache,
+ trackingFooters,
+ index,
+ indexConfig,
+ listMembers,
+ starredChangesUtil,
+ accountCache,
+ allowsDrafts);
}
Arguments asUser(Account.Id otherId) {
@@ -379,8 +415,7 @@
@VisibleForTesting
protected ChangeQueryBuilder(
- Definition<ChangeData, ? extends QueryBuilder<ChangeData>> def,
- Arguments args) {
+ Definition<ChangeData, ? extends QueryBuilder<ChangeData>> def, Arguments args) {
super(def);
this.args = args;
}
@@ -449,8 +484,7 @@
}
@Operator
- public Predicate<ChangeData> status(String statusName)
- throws QueryParseException {
+ public Predicate<ChangeData> status(String statusName) throws QueryParseException {
if ("reviewed".equalsIgnoreCase(statusName)) {
return IsReviewedPredicate.create();
}
@@ -548,8 +582,7 @@
}
@Operator
- public Predicate<ChangeData> conflicts(String value) throws OrmException,
- QueryParseException {
+ public Predicate<ChangeData> conflicts(String value) throws OrmException, QueryParseException {
return new ConflictsPredicate(args, value, parseChange(value));
}
@@ -573,8 +606,7 @@
@Operator
public Predicate<ChangeData> parentproject(String name) {
- return new ParentProjectPredicate(args.projectCache, args.listChildProjects,
- args.self, name);
+ return new ParentProjectPredicate(args.projectCache, args.listChildProjects, args.self, name);
}
@Operator
@@ -636,8 +668,7 @@
}
@Operator
- public Predicate<ChangeData> label(String name) throws QueryParseException,
- OrmException {
+ public Predicate<ChangeData> label(String name) throws QueryParseException, OrmException {
Set<Account.Id> accounts = null;
AccountGroup.UUID group = null;
@@ -651,7 +682,7 @@
// label:Code-Review+2,owner
// label:Code-Review+2,user=owner
String[] splitReviewer = name.split(",", 2);
- name = splitReviewer[0]; // remove all but the vote piece, e.g.'CodeReview=1'
+ name = splitReviewer[0]; // remove all but the vote piece, e.g.'CodeReview=1'
if (splitReviewer.length == 2) {
// process the user/group piece
@@ -667,15 +698,13 @@
} else if (pair.getKey().equalsIgnoreCase(ARG_ID_GROUP)) {
group = parseGroup(pair.getValue()).getUUID();
} else {
- throw new QueryParseException(
- "Invalid argument identifier '" + pair.getKey() + "'");
+ throw new QueryParseException("Invalid argument identifier '" + pair.getKey() + "'");
}
}
for (String value : lblArgs.positional) {
- if (accounts != null || group != null) {
- throw new QueryParseException("more than one user/group specified (" +
- value + ")");
+ if (accounts != null || group != null) {
+ throw new QueryParseException("more than one user/group specified (" + value + ")");
}
try {
if (value.equals(ARG_ID_OWNER)) {
@@ -698,7 +727,11 @@
// expand a group predicate into multiple user predicates
if (group != null) {
Set<Account.Id> allMembers =
- args.listMembers.get().setRecursive(true).apply(group).stream()
+ args.listMembers
+ .get()
+ .setRecursive(true)
+ .apply(group)
+ .stream()
.map(a -> new Account.Id(a._accountId))
.collect(toSet());
int maxLimit = args.indexConfig.maxLimit();
@@ -716,13 +749,12 @@
if (args.getSchema().hasField(ChangeField.SUBMIT_RECORD) && eq > 0) {
String statusName = name.substring(eq + 1).toUpperCase();
if (!isInt(statusName)) {
- SubmitRecord.Label.Status status = Enums.getIfPresent(
- SubmitRecord.Label.Status.class, statusName).orNull();
+ SubmitRecord.Label.Status status =
+ Enums.getIfPresent(SubmitRecord.Label.Status.class, statusName).orNull();
if (status == null) {
throw error("Invalid label status " + statusName + " in " + name);
}
- return SubmitRecordPredicate.create(
- name.substring(0, eq), status, accounts);
+ return SubmitRecordPredicate.create(name.substring(0, eq), status, accounts);
}
}
@@ -750,8 +782,7 @@
}
@Operator
- public Predicate<ChangeData> starredby(String who)
- throws QueryParseException, OrmException {
+ public Predicate<ChangeData> starredby(String who) throws QueryParseException, OrmException {
return starredby(parseAccount(who));
}
@@ -768,8 +799,7 @@
}
@Operator
- public Predicate<ChangeData> watchedby(String who)
- throws QueryParseException, OrmException {
+ public Predicate<ChangeData> watchedby(String who) throws QueryParseException, OrmException {
Set<Account.Id> m = parseAccount(who);
List<IsWatchedByPredicate> p = Lists.newArrayListWithCapacity(m.size());
@@ -793,8 +823,7 @@
}
@Operator
- public Predicate<ChangeData> draftby(String who) throws QueryParseException,
- OrmException {
+ public Predicate<ChangeData> draftby(String who) throws QueryParseException, OrmException {
Set<Account.Id> m = parseAccount(who);
List<Predicate<ChangeData>> p = Lists.newArrayListWithCapacity(m.size());
for (Account.Id id : m) {
@@ -808,8 +837,7 @@
}
@Operator
- public Predicate<ChangeData> visibleto(String who)
- throws QueryParseException, OrmException {
+ public Predicate<ChangeData> visibleto(String who) throws QueryParseException, OrmException {
if ("self".equals(who)) {
return is_visible();
}
@@ -837,8 +865,8 @@
}
public Predicate<ChangeData> visibleto(CurrentUser user) {
- return new ChangeIsVisibleToPredicate(args.db, args.notesFactory,
- args.changeControlGenericFactory, user);
+ return new ChangeIsVisibleToPredicate(
+ args.db, args.notesFactory, args.changeControlGenericFactory, user);
}
public Predicate<ChangeData> is_visible() throws QueryParseException {
@@ -846,14 +874,12 @@
}
@Operator
- public Predicate<ChangeData> o(String who)
- throws QueryParseException, OrmException {
+ public Predicate<ChangeData> o(String who) throws QueryParseException, OrmException {
return owner(who);
}
@Operator
- public Predicate<ChangeData> owner(String who) throws QueryParseException,
- OrmException {
+ public Predicate<ChangeData> owner(String who) throws QueryParseException, OrmException {
return owner(parseAccount(who));
}
@@ -866,8 +892,7 @@
}
@Operator
- public Predicate<ChangeData> assignee(String who) throws QueryParseException,
- OrmException {
+ public Predicate<ChangeData> assignee(String who) throws QueryParseException, OrmException {
return assignee(parseAccount(who));
}
@@ -880,8 +905,7 @@
}
@Operator
- public Predicate<ChangeData> ownerin(String group)
- throws QueryParseException {
+ public Predicate<ChangeData> ownerin(String group) throws QueryParseException {
GroupReference g = GroupBackends.findBestSuggestion(args.groupBackend, group);
if (g == null) {
throw error("Group " + group + " not found");
@@ -890,14 +914,12 @@
}
@Operator
- public Predicate<ChangeData> r(String who)
- throws QueryParseException, OrmException {
+ public Predicate<ChangeData> r(String who) throws QueryParseException, OrmException {
return reviewer(who);
}
@Operator
- public Predicate<ChangeData> reviewer(String who)
- throws QueryParseException, OrmException {
+ public Predicate<ChangeData> reviewer(String who) throws QueryParseException, OrmException {
Set<Account.Id> m = parseAccount(who);
List<Predicate<ChangeData>> p = Lists.newArrayListWithCapacity(m.size());
for (Account.Id id : m) {
@@ -907,8 +929,7 @@
}
@Operator
- public Predicate<ChangeData> reviewerin(String group)
- throws QueryParseException {
+ public Predicate<ChangeData> reviewerin(String group) throws QueryParseException {
GroupReference g = GroupBackends.findBestSuggestion(args.groupBackend, group);
if (g == null) {
throw error("Group " + group + " not found");
@@ -936,32 +957,27 @@
}
@Operator
- public Predicate<ChangeData> added(String value)
- throws QueryParseException {
+ public Predicate<ChangeData> added(String value) throws QueryParseException {
return new AddedPredicate(value);
}
@Operator
- public Predicate<ChangeData> deleted(String value)
- throws QueryParseException {
+ public Predicate<ChangeData> deleted(String value) throws QueryParseException {
return new DeletedPredicate(value);
}
@Operator
- public Predicate<ChangeData> size(String value)
- throws QueryParseException {
+ public Predicate<ChangeData> size(String value) throws QueryParseException {
return delta(value);
}
@Operator
- public Predicate<ChangeData> delta(String value)
- throws QueryParseException {
+ public Predicate<ChangeData> delta(String value) throws QueryParseException {
return new DeltaPredicate(value);
}
@Operator
- public Predicate<ChangeData> commentby(String who)
- throws QueryParseException, OrmException {
+ public Predicate<ChangeData> commentby(String who) throws QueryParseException, OrmException {
return commentby(parseAccount(who));
}
@@ -974,8 +990,7 @@
}
@Operator
- public Predicate<ChangeData> from(String who)
- throws QueryParseException, OrmException {
+ public Predicate<ChangeData> from(String who) throws QueryParseException, OrmException {
Set<Account.Id> ownerIds = parseAccount(who);
return Predicate.or(owner(ownerIds), commentby(ownerIds));
}
@@ -990,8 +1005,8 @@
return parse(query);
}
} catch (RepositoryNotFoundException e) {
- throw new QueryParseException("Unknown named query (no " +
- args.allUsersName + " repo): " + name, e);
+ throw new QueryParseException(
+ "Unknown named query (no " + args.allUsersName + " repo): " + name, e);
} catch (IOException | ConfigInvalidException e) {
throw new QueryParseException("Error parsing named query: " + name, e);
}
@@ -999,26 +1014,22 @@
}
@Operator
- public Predicate<ChangeData> reviewedby(String who)
- throws QueryParseException, OrmException {
+ public Predicate<ChangeData> reviewedby(String who) throws QueryParseException, OrmException {
return IsReviewedPredicate.create(parseAccount(who));
}
@Operator
- public Predicate<ChangeData> destination(String name)
- throws QueryParseException {
+ public Predicate<ChangeData> destination(String name) throws QueryParseException {
try (Repository git = args.repoManager.openRepository(args.allUsersName)) {
- VersionedAccountDestinations d =
- VersionedAccountDestinations.forUser(self());
+ VersionedAccountDestinations d = VersionedAccountDestinations.forUser(self());
d.load(git);
- Set<Branch.NameKey> destinations =
- d.getDestinationList().getDestinations(name);
+ Set<Branch.NameKey> destinations = d.getDestinationList().getDestinations(name);
if (destinations != null) {
return new DestinationPredicate(destinations, name);
}
} catch (RepositoryNotFoundException e) {
- throw new QueryParseException("Unknown named destination (no " +
- args.allUsersName + " repo): " + name, e);
+ throw new QueryParseException(
+ "Unknown named destination (no " + args.allUsersName + " repo): " + name, e);
} catch (IOException | ConfigInvalidException e) {
throw new QueryParseException("Error parsing named destination: " + name, e);
}
@@ -1036,10 +1047,9 @@
}
@Operator
- public Predicate<ChangeData> submittable(String str)
- throws QueryParseException {
- SubmitRecord.Status status = Enums.getIfPresent(
- SubmitRecord.Status.class, str.toUpperCase()).orNull();
+ public Predicate<ChangeData> submittable(String str) throws QueryParseException {
+ SubmitRecord.Status status =
+ Enums.getIfPresent(SubmitRecord.Status.class, str.toUpperCase()).orNull();
if (status == null) {
throw error("invalid value for submittable:" + str);
}
@@ -1092,8 +1102,7 @@
return Predicate.or(predicates);
}
- private Set<Account.Id> parseAccount(String who)
- throws QueryParseException, OrmException {
+ private Set<Account.Id> parseAccount(String who) throws QueryParseException, OrmException {
if ("self".equals(who)) {
return Collections.singleton(self());
}
@@ -1105,22 +1114,18 @@
}
private GroupReference parseGroup(String group) throws QueryParseException {
- GroupReference g = GroupBackends.findBestSuggestion(args.groupBackend,
- group);
+ GroupReference g = GroupBackends.findBestSuggestion(args.groupBackend, group);
if (g == null) {
throw error("Group " + group + " not found");
}
return g;
}
- private List<Change> parseChange(String value) throws OrmException,
- QueryParseException {
+ private List<Change> parseChange(String value) throws OrmException, QueryParseException {
if (PAT_LEGACY_ID.matcher(value).matches()) {
- return asChanges(
- args.queryProvider.get().byLegacyChangeId(Change.Id.parse(value)));
+ return asChanges(args.queryProvider.get().byLegacyChangeId(Change.Id.parse(value)));
} else if (PAT_CHANGE_ID.matcher(value).matches()) {
- List<Change> changes =
- asChanges(args.queryProvider.get().byKeyPrefix(parseChangeId(value)));
+ List<Change> changes = asChanges(args.queryProvider.get().byKeyPrefix(parseChangeId(value)));
if (changes.isEmpty()) {
throw error("Change " + value + " not found");
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ChangeQueryProcessor.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ChangeQueryProcessor.java
index 0ff5ac7..91a37d5 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ChangeQueryProcessor.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ChangeQueryProcessor.java
@@ -32,7 +32,6 @@
import com.google.gerrit.server.query.QueryProcessor;
import com.google.inject.Inject;
import com.google.inject.Provider;
-
import java.util.Set;
public class ChangeQueryProcessor extends QueryProcessor<ChangeData> {
@@ -48,7 +47,8 @@
}
@Inject
- ChangeQueryProcessor(Provider<CurrentUser> userProvider,
+ ChangeQueryProcessor(
+ Provider<CurrentUser> userProvider,
Metrics metrics,
IndexConfig indexConfig,
ChangeIndexCollection indexes,
@@ -56,8 +56,14 @@
Provider<ReviewDb> db,
ChangeControl.GenericFactory changeControlFactory,
ChangeNotes.Factory notesFactory) {
- super(userProvider, metrics, ChangeSchemaDefinitions.INSTANCE, indexConfig, indexes,
- rewriter, FIELD_LIMIT);
+ super(
+ userProvider,
+ metrics,
+ ChangeSchemaDefinitions.INSTANCE,
+ indexConfig,
+ indexes,
+ rewriter,
+ FIELD_LIMIT);
this.db = db;
this.changeControlFactory = changeControlFactory;
this.notesFactory = notesFactory;
@@ -70,16 +76,16 @@
}
@Override
- protected QueryOptions createOptions(IndexConfig indexConfig, int start,
- int limit, Set<String> requestedFields) {
- return IndexedChangeQuery.createOptions(indexConfig, start, limit,
- requestedFields);
+ protected QueryOptions createOptions(
+ IndexConfig indexConfig, int start, int limit, Set<String> requestedFields) {
+ return IndexedChangeQuery.createOptions(indexConfig, start, limit, requestedFields);
}
@Override
- protected Predicate<ChangeData> enforceVisibility(
- Predicate<ChangeData> pred) {
- return new AndChangeSource(pred, new ChangeIsVisibleToPredicate(db,
- notesFactory, changeControlFactory, userProvider.get()), start);
+ protected Predicate<ChangeData> enforceVisibility(Predicate<ChangeData> pred) {
+ return new AndChangeSource(
+ pred,
+ new ChangeIsVisibleToPredicate(db, notesFactory, changeControlFactory, userProvider.get()),
+ start);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ChangeRegexPredicate.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ChangeRegexPredicate.java
index 747d72d..f421985 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ChangeRegexPredicate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ChangeRegexPredicate.java
@@ -24,8 +24,7 @@
super(def, value);
}
- protected ChangeRegexPredicate(FieldDef<ChangeData, ?> def, String name,
- String value) {
+ protected ChangeRegexPredicate(FieldDef<ChangeData, ?> def, String name, String value) {
super(def, name, value);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ChangeStatusPredicate.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ChangeStatusPredicate.java
index 1ae8591..9c16777 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ChangeStatusPredicate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ChangeStatusPredicate.java
@@ -20,7 +20,6 @@
import com.google.gerrit.server.query.Predicate;
import com.google.gerrit.server.query.QueryParseException;
import com.google.gwtorm.server.OrmException;
-
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@@ -29,12 +28,12 @@
/**
* Predicate for a {@link Status}.
- * <p>
- * The actual name of this operator can differ, it usually comes as {@code
- * status:} but may also be {@code is:} to help do-what-i-meanery for end-users
- * searching for changes. Either operator name has the same meaning.
- * <p>
- * Status names are looked up by prefix case-insensitively.
+ *
+ * <p>The actual name of this operator can differ, it usually comes as {@code status:} but may also
+ * be {@code is:} to help do-what-i-meanery for end-users searching for changes. Either operator
+ * name has the same meaning.
+ *
+ * <p>Status names are looked up by prefix case-insensitively.
*/
public final class ChangeStatusPredicate extends ChangeIndexPredicate {
private static final TreeMap<String, Predicate<ChangeData>> PREDICATES;
@@ -64,15 +63,12 @@
return status.name().toLowerCase();
}
- public static Predicate<ChangeData> parse(String value)
- throws QueryParseException {
+ public static Predicate<ChangeData> parse(String value) throws QueryParseException {
String lower = value.toLowerCase();
- NavigableMap<String, Predicate<ChangeData>> head =
- PREDICATES.tailMap(lower, true);
+ NavigableMap<String, Predicate<ChangeData>> head = PREDICATES.tailMap(lower, true);
if (!head.isEmpty()) {
// Assume no statuses share a common prefix so we can only walk one entry.
- Map.Entry<String, Predicate<ChangeData>> e =
- head.entrySet().iterator().next();
+ Map.Entry<String, Predicate<ChangeData>> e = head.entrySet().iterator().next();
if (e.getKey().startsWith(lower)) {
return e.getValue();
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/CommentByPredicate.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/CommentByPredicate.java
index 1cb6333..668c6f2 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/CommentByPredicate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/CommentByPredicate.java
@@ -19,7 +19,6 @@
import com.google.gerrit.reviewdb.client.Comment;
import com.google.gerrit.server.index.change.ChangeField;
import com.google.gwtorm.server.OrmException;
-
import java.util.Objects;
class CommentByPredicate extends ChangeIndexPredicate {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/CommentPredicate.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/CommentPredicate.java
index b351740..4779a16 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/CommentPredicate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/CommentPredicate.java
@@ -32,10 +32,8 @@
@Override
public boolean match(ChangeData object) throws OrmException {
try {
- Predicate<ChangeData> p = Predicate.and(
- new LegacyChangeIdPredicate(object.getId()), this);
- for (ChangeData cData
- : index.getSource(p, IndexedChangeQuery.oneResult()).read()) {
+ Predicate<ChangeData> p = Predicate.and(new LegacyChangeIdPredicate(object.getId()), this);
+ for (ChangeData cData : index.getSource(p, IndexedChangeQuery.oneResult()).read()) {
if (cData.getId().equals(object.getId())) {
return true;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/CommitPredicate.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/CommitPredicate.java
index aa3dde3..1188d5d 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/CommitPredicate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/CommitPredicate.java
@@ -48,8 +48,7 @@
private boolean equals(PatchSet p, String id) {
boolean exact = getField() == EXACT_COMMIT;
String rev = p.getRevision() != null ? p.getRevision().get() : null;
- return (exact && id.equals(rev))
- || (!exact && rev != null && rev.startsWith(id));
+ return (exact && id.equals(rev)) || (!exact && rev != null && rev.startsWith(id));
}
@Override
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/CommitterPredicate.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/CommitterPredicate.java
index 06f5379..8e13e20 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/CommitterPredicate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/CommitterPredicate.java
@@ -27,8 +27,7 @@
@Override
public boolean match(ChangeData object) throws OrmException {
- return ChangeField.getCommitterParts(object).contains(
- getValue().toLowerCase());
+ return ChangeField.getCommitterParts(object).contains(getValue().toLowerCase());
}
@Override
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ConflictKey.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ConflictKey.java
index 3b3d986..0101ffe 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ConflictKey.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ConflictKey.java
@@ -15,11 +15,9 @@
package com.google.gerrit.server.query.change;
import com.google.gerrit.extensions.client.SubmitType;
-
-import org.eclipse.jgit.lib.ObjectId;
-
import java.io.Serializable;
import java.util.Objects;
+import org.eclipse.jgit.lib.ObjectId;
public class ConflictKey implements Serializable {
private static final long serialVersionUID = 2L;
@@ -29,10 +27,9 @@
private final SubmitType submitType;
private final boolean contentMerge;
- public ConflictKey(ObjectId commit, ObjectId otherCommit,
- SubmitType submitType, boolean contentMerge) {
- if (SubmitType.FAST_FORWARD_ONLY.equals(submitType)
- || commit.compareTo(otherCommit) < 0) {
+ public ConflictKey(
+ ObjectId commit, ObjectId otherCommit, SubmitType submitType, boolean contentMerge) {
+ if (SubmitType.FAST_FORWARD_ONLY.equals(submitType) || commit.compareTo(otherCommit) < 0) {
this.commit = commit;
this.otherCommit = otherCommit;
} else {
@@ -64,7 +61,7 @@
if (!(o instanceof ConflictKey)) {
return false;
}
- ConflictKey other = (ConflictKey)o;
+ ConflictKey other = (ConflictKey) o;
return commit.equals(other.commit)
&& otherCommit.equals(other.otherCommit)
&& submitType.equals(other.submitType)
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ConflictsCacheImpl.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ConflictsCacheImpl.java
index 8cca00d..1185677 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ConflictsCacheImpl.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ConflictsCacheImpl.java
@@ -29,8 +29,7 @@
return new CacheModule() {
@Override
protected void configure() {
- persist(NAME, ConflictKey.class, Boolean.class)
- .maximumWeight(37400);
+ persist(NAME, ConflictKey.class, Boolean.class).maximumWeight(37400);
bind(ConflictsCache.class).to(ConflictsCacheImpl.class);
}
};
@@ -39,8 +38,7 @@
private final Cache<ConflictKey, Boolean> conflictsCache;
@Inject
- public ConflictsCacheImpl(
- @Named(NAME) Cache<ConflictKey, Boolean> conflictsCache) {
+ public ConflictsCacheImpl(@Named(NAME) Cache<ConflictKey, Boolean> conflictsCache) {
this.conflictsCache = conflictsCache;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ConflictsPredicate.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ConflictsPredicate.java
index 26dbe23..9b11e8b 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ConflictsPredicate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ConflictsPredicate.java
@@ -31,7 +31,11 @@
import com.google.gerrit.server.query.change.ChangeQueryBuilder.Arguments;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Provider;
-
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
@@ -41,16 +45,9 @@
import org.eclipse.jgit.treewalk.TreeWalk;
import org.eclipse.jgit.treewalk.filter.TreeFilter;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
class ConflictsPredicate extends OrPredicate<ChangeData> {
// UI code may depend on this string, so use caution when changing.
- private static final String TOO_MANY_FILES =
- "too many files to find conflicts";
+ private static final String TOO_MANY_FILES = "too many files to find conflicts";
private final String value;
@@ -60,17 +57,16 @@
this.value = value;
}
- private static List<Predicate<ChangeData>> predicates(final Arguments args,
- String value, List<Change> changes)
+ private static List<Predicate<ChangeData>> predicates(
+ final Arguments args, String value, List<Change> changes)
throws QueryParseException, OrmException {
int indexTerms = 0;
- List<Predicate<ChangeData>> changePredicates =
- Lists.newArrayListWithCapacity(changes.size());
+ List<Predicate<ChangeData>> changePredicates = Lists.newArrayListWithCapacity(changes.size());
final Provider<ReviewDb> db = args.db;
for (final Change c : changes) {
- final ChangeDataCache changeDataCache = new ChangeDataCache(
- c, db, args.changeDataFactory, args.projectCache);
+ final ChangeDataCache changeDataCache =
+ new ChangeDataCache(c, db, args.changeDataFactory, args.projectCache);
List<String> files = listFiles(c, args, changeDataCache);
indexTerms += 3 + files.size();
if (indexTerms > args.indexConfig.maxTerms()) {
@@ -82,94 +78,90 @@
throw new QueryParseException(TOO_MANY_FILES);
}
- List<Predicate<ChangeData>> filePredicates =
- Lists.newArrayListWithCapacity(files.size());
+ List<Predicate<ChangeData>> filePredicates = Lists.newArrayListWithCapacity(files.size());
for (String file : files) {
- filePredicates.add(
- new EqualsPathPredicate(ChangeQueryBuilder.FIELD_PATH, file));
+ filePredicates.add(new EqualsPathPredicate(ChangeQueryBuilder.FIELD_PATH, file));
}
- List<Predicate<ChangeData>> predicatesForOneChange =
- Lists.newArrayListWithCapacity(5);
+ List<Predicate<ChangeData>> predicatesForOneChange = Lists.newArrayListWithCapacity(5);
+ predicatesForOneChange.add(not(new LegacyChangeIdPredicate(c.getId())));
+ predicatesForOneChange.add(new ProjectPredicate(c.getProject().get()));
+ predicatesForOneChange.add(new RefPredicate(c.getDest().get()));
+
+ predicatesForOneChange.add(or(or(filePredicates), new IsMergePredicate(args, value)));
+
predicatesForOneChange.add(
- not(new LegacyChangeIdPredicate(c.getId())));
- predicatesForOneChange.add(
- new ProjectPredicate(c.getProject().get()));
- predicatesForOneChange.add(
- new RefPredicate(c.getDest().get()));
+ new ChangeOperatorPredicate(ChangeQueryBuilder.FIELD_CONFLICTS, value) {
- predicatesForOneChange.add(or(or(filePredicates),
- new IsMergePredicate(args, value)));
-
- predicatesForOneChange.add(new ChangeOperatorPredicate(
- ChangeQueryBuilder.FIELD_CONFLICTS, value) {
-
- @Override
- public boolean match(ChangeData object) throws OrmException {
- Change otherChange = object.change();
- if (otherChange == null) {
- return false;
- }
- if (!otherChange.getDest().equals(c.getDest())) {
- return false;
- }
- SubmitTypeRecord str = object.submitTypeRecord();
- if (!str.isOk()) {
- return false;
- }
- ObjectId other = ObjectId.fromString(
- object.currentPatchSet().getRevision().get());
- ConflictKey conflictsKey =
- new ConflictKey(changeDataCache.getTestAgainst(), other, str.type,
- changeDataCache.getProjectState().isUseContentMerge());
- Boolean conflicts = args.conflictsCache.getIfPresent(conflictsKey);
- if (conflicts != null) {
- return conflicts;
- }
- try (Repository repo =
- args.repoManager.openRepository(otherChange.getProject());
- CodeReviewRevWalk rw = CodeReviewCommit.newRevWalk(repo)) {
- conflicts = !args.submitDryRun.run(
- str.type, repo, rw, otherChange.getDest(),
- changeDataCache.getTestAgainst(), other,
- getAlreadyAccepted(repo, rw));
- args.conflictsCache.put(conflictsKey, conflicts);
- return conflicts;
- } catch (IntegrationException | NoSuchProjectException
- | IOException e) {
- throw new IllegalStateException(e);
- }
- }
-
- @Override
- public int getCost() {
- return 5;
- }
-
- private Set<RevCommit> getAlreadyAccepted(Repository repo, RevWalk rw)
- throws IntegrationException {
- try {
- Set<RevCommit> accepted = new HashSet<>();
- SubmitDryRun.addCommits(
- changeDataCache.getAlreadyAccepted(repo), rw, accepted);
- ObjectId tip = changeDataCache.getTestAgainst();
- if (tip != null) {
- accepted.add(rw.parseCommit(tip));
+ @Override
+ public boolean match(ChangeData object) throws OrmException {
+ Change otherChange = object.change();
+ if (otherChange == null) {
+ return false;
+ }
+ if (!otherChange.getDest().equals(c.getDest())) {
+ return false;
+ }
+ SubmitTypeRecord str = object.submitTypeRecord();
+ if (!str.isOk()) {
+ return false;
+ }
+ ObjectId other = ObjectId.fromString(object.currentPatchSet().getRevision().get());
+ ConflictKey conflictsKey =
+ new ConflictKey(
+ changeDataCache.getTestAgainst(),
+ other,
+ str.type,
+ changeDataCache.getProjectState().isUseContentMerge());
+ Boolean conflicts = args.conflictsCache.getIfPresent(conflictsKey);
+ if (conflicts != null) {
+ return conflicts;
+ }
+ try (Repository repo = args.repoManager.openRepository(otherChange.getProject());
+ CodeReviewRevWalk rw = CodeReviewCommit.newRevWalk(repo)) {
+ conflicts =
+ !args.submitDryRun.run(
+ str.type,
+ repo,
+ rw,
+ otherChange.getDest(),
+ changeDataCache.getTestAgainst(),
+ other,
+ getAlreadyAccepted(repo, rw));
+ args.conflictsCache.put(conflictsKey, conflicts);
+ return conflicts;
+ } catch (IntegrationException | NoSuchProjectException | IOException e) {
+ throw new IllegalStateException(e);
+ }
}
- return accepted;
- } catch (OrmException | IOException e) {
- throw new IntegrationException(
- "Failed to determine already accepted commits.", e);
- }
- }
- });
+
+ @Override
+ public int getCost() {
+ return 5;
+ }
+
+ private Set<RevCommit> getAlreadyAccepted(Repository repo, RevWalk rw)
+ throws IntegrationException {
+ try {
+ Set<RevCommit> accepted = new HashSet<>();
+ SubmitDryRun.addCommits(changeDataCache.getAlreadyAccepted(repo), rw, accepted);
+ ObjectId tip = changeDataCache.getTestAgainst();
+ if (tip != null) {
+ accepted.add(rw.parseCommit(tip));
+ }
+ return accepted;
+ } catch (OrmException | IOException e) {
+ throw new IntegrationException("Failed to determine already accepted commits.", e);
+ }
+ }
+ });
changePredicates.add(and(predicatesForOneChange));
}
return changePredicates;
}
- private static List<String> listFiles(Change c, Arguments args,
- ChangeDataCache changeDataCache) throws OrmException {
+ private static List<String> listFiles(Change c, Arguments args, ChangeDataCache changeDataCache)
+ throws OrmException {
try (Repository repo = args.repoManager.openRepository(c.getProject());
RevWalk rw = new RevWalk(repo)) {
RevCommit ps = rw.parseCommit(changeDataCache.getTestAgainst());
@@ -218,20 +210,22 @@
private ProjectState projectState;
private Iterable<ObjectId> alreadyAccepted;
- ChangeDataCache(Change change, Provider<ReviewDb> db,
- ChangeData.Factory changeDataFactory, ProjectCache projectCache) {
+ ChangeDataCache(
+ Change change,
+ Provider<ReviewDb> db,
+ ChangeData.Factory changeDataFactory,
+ ProjectCache projectCache) {
this.change = change;
this.db = db;
this.changeDataFactory = changeDataFactory;
this.projectCache = projectCache;
}
- ObjectId getTestAgainst()
- throws OrmException {
+ ObjectId getTestAgainst() throws OrmException {
if (testAgainst == null) {
- testAgainst = ObjectId.fromString(
- changeDataFactory.create(db.get(), change)
- .currentPatchSet().getRevision().get());
+ testAgainst =
+ ObjectId.fromString(
+ changeDataFactory.create(db.get(), change).currentPatchSet().getRevision().get());
}
return testAgainst;
}
@@ -240,8 +234,7 @@
if (projectState == null) {
projectState = projectCache.get(change.getProject());
if (projectState == null) {
- throw new IllegalStateException(
- new NoSuchProjectException(change.getProject()));
+ throw new IllegalStateException(new NoSuchProjectException(change.getProject()));
}
}
return projectState;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/DestinationPredicate.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/DestinationPredicate.java
index 7e573dc..809e7a1 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/DestinationPredicate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/DestinationPredicate.java
@@ -17,7 +17,6 @@
import com.google.gerrit.reviewdb.client.Branch;
import com.google.gerrit.reviewdb.client.Change;
import com.google.gwtorm.server.OrmException;
-
import java.util.Set;
class DestinationPredicate extends ChangeOperatorPredicate {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/EqualsFilePredicate.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/EqualsFilePredicate.java
index 6877761..fb6c56b 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/EqualsFilePredicate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/EqualsFilePredicate.java
@@ -21,8 +21,7 @@
class EqualsFilePredicate extends ChangeIndexPredicate {
static Predicate<ChangeData> create(Arguments args, String value) {
- Predicate<ChangeData> eqPath =
- new EqualsPathPredicate(ChangeQueryBuilder.FIELD_FILE, value);
+ Predicate<ChangeData> eqPath = new EqualsPathPredicate(ChangeQueryBuilder.FIELD_FILE, value);
if (!args.getSchema().hasField(ChangeField.FILE_PART)) {
return eqPath;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/EqualsLabelPredicate.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/EqualsLabelPredicate.java
index 0adf78f..1189e87 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/EqualsLabelPredicate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/EqualsLabelPredicate.java
@@ -41,8 +41,7 @@
private final Account.Id account;
private final AccountGroup.UUID group;
- EqualsLabelPredicate(LabelPredicate.Args args, String label, int expVal,
- Account.Id account) {
+ EqualsLabelPredicate(LabelPredicate.Args args, String label, int expVal, Account.Id account) {
super(args.field, ChangeField.formatLabel(label, expVal, account));
this.ccFactory = args.ccFactory;
this.projectCache = args.projectCache;
@@ -105,16 +104,15 @@
return null;
}
- private boolean match(Change change, int value, Account.Id approver,
- LabelType type) throws OrmException {
+ private boolean match(Change change, int value, Account.Id approver, LabelType type)
+ throws OrmException {
int psVal = value;
if (psVal == expVal) {
// Double check the value is still permitted for the user.
//
IdentifiedUser reviewer = userFactory.create(approver);
try {
- ChangeControl cc =
- ccFactory.controlFor(dbProvider.get(), change, reviewer);
+ ChangeControl cc = ccFactory.controlFor(dbProvider.get(), change, reviewer);
if (!cc.isVisible(dbProvider.get())) {
// The user can't see the change anymore.
//
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/EqualsPathPredicate.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/EqualsPathPredicate.java
index 5edd06c..9d841f3 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/EqualsPathPredicate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/EqualsPathPredicate.java
@@ -16,7 +16,6 @@
import com.google.gerrit.server.index.change.ChangeField;
import com.google.gwtorm.server.OrmException;
-
import java.util.Collections;
import java.util.List;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/GroupPredicate.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/GroupPredicate.java
index 9e9bc8d..54e1c97 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/GroupPredicate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/GroupPredicate.java
@@ -17,7 +17,6 @@
import com.google.gerrit.reviewdb.client.PatchSet;
import com.google.gerrit.server.index.change.ChangeField;
import com.google.gwtorm.server.OrmException;
-
import java.util.List;
class GroupPredicate extends ChangeIndexPredicate {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/HashtagPredicate.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/HashtagPredicate.java
index 185a539..4fd4156 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/HashtagPredicate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/HashtagPredicate.java
@@ -38,4 +38,3 @@
return 1;
}
}
-
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/IntegerRangeChangePredicate.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/IntegerRangeChangePredicate.java
index a272fbb..d4f5620 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/IntegerRangeChangePredicate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/IntegerRangeChangePredicate.java
@@ -19,11 +19,11 @@
import com.google.gerrit.server.query.Matchable;
import com.google.gerrit.server.query.QueryParseException;
-public abstract class IntegerRangeChangePredicate
- extends IntegerRangePredicate<ChangeData> implements Matchable<ChangeData> {
+public abstract class IntegerRangeChangePredicate extends IntegerRangePredicate<ChangeData>
+ implements Matchable<ChangeData> {
- protected IntegerRangeChangePredicate(FieldDef<ChangeData, Integer> type,
- String value) throws QueryParseException {
+ protected IntegerRangeChangePredicate(FieldDef<ChangeData, Integer> type, String value)
+ throws QueryParseException {
super(type, value);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/InternalChangeQuery.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/InternalChangeQuery.java
index 0bd1800..fa2f5fe 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/InternalChangeQuery.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/InternalChangeQuery.java
@@ -36,17 +36,15 @@
import com.google.gerrit.server.query.Predicate;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
-
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.lib.Ref;
-import org.eclipse.jgit.lib.Repository;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.lib.Ref;
+import org.eclipse.jgit.lib.Repository;
public class InternalChangeQuery extends InternalQuery<ChangeData> {
private static Predicate<ChangeData> ref(Branch.NameKey branch) {
@@ -73,7 +71,8 @@
private final ChangeNotes.Factory notesFactory;
@Inject
- InternalChangeQuery(ChangeQueryProcessor queryProcessor,
+ InternalChangeQuery(
+ ChangeQueryProcessor queryProcessor,
ChangeIndexCollection indexes,
IndexConfig indexConfig,
ChangeData.Factory changeDataFactory,
@@ -119,8 +118,7 @@
return query(new LegacyChangeIdPredicate(id));
}
- public List<ChangeData> byLegacyChangeIds(Collection<Change.Id> ids)
- throws OrmException {
+ public List<ChangeData> byLegacyChangeIds(Collection<Change.Id> ids) throws OrmException {
List<Predicate<ChangeData>> preds = new ArrayList<>(ids.size());
for (Change.Id id : ids) {
preds.add(new LegacyChangeIdPredicate(id));
@@ -128,46 +126,41 @@
return query(or(preds));
}
- public List<ChangeData> byBranchKey(Branch.NameKey branch, Change.Key key)
- throws OrmException {
- return query(and(
- ref(branch),
- project(branch.getParentKey()),
- change(key)));
+ public List<ChangeData> byBranchKey(Branch.NameKey branch, Change.Key key) throws OrmException {
+ return query(and(ref(branch), project(branch.getParentKey()), change(key)));
}
- public List<ChangeData> byProject(Project.NameKey project)
- throws OrmException {
+ public List<ChangeData> byProject(Project.NameKey project) throws OrmException {
return query(project(project));
}
- public List<ChangeData> byBranchOpen(Branch.NameKey branch)
- throws OrmException {
- return query(and(
- ref(branch),
- project(branch.getParentKey()),
- open()));
+ public List<ChangeData> byBranchOpen(Branch.NameKey branch) throws OrmException {
+ return query(and(ref(branch), project(branch.getParentKey()), open()));
}
- public List<ChangeData> byBranchNew(Branch.NameKey branch)
- throws OrmException {
- return query(and(
- ref(branch),
- project(branch.getParentKey()),
- status(Change.Status.NEW)));
+ public List<ChangeData> byBranchNew(Branch.NameKey branch) throws OrmException {
+ return query(and(ref(branch), project(branch.getParentKey()), status(Change.Status.NEW)));
}
- public Iterable<ChangeData> byCommitsOnBranchNotMerged(Repository repo,
- ReviewDb db, Branch.NameKey branch, Collection<String> hashes)
+ public Iterable<ChangeData> byCommitsOnBranchNotMerged(
+ Repository repo, ReviewDb db, Branch.NameKey branch, Collection<String> hashes)
throws OrmException, IOException {
- return byCommitsOnBranchNotMerged(repo, db, branch, hashes,
+ return byCommitsOnBranchNotMerged(
+ repo,
+ db,
+ branch,
+ hashes,
// Account for all commit predicates plus ref, project, status.
indexConfig.maxTerms() - 3);
}
@VisibleForTesting
- Iterable<ChangeData> byCommitsOnBranchNotMerged(Repository repo, ReviewDb db,
- Branch.NameKey branch, Collection<String> hashes, int indexLimit)
+ Iterable<ChangeData> byCommitsOnBranchNotMerged(
+ Repository repo,
+ ReviewDb db,
+ Branch.NameKey branch,
+ Collection<String> hashes,
+ int indexLimit)
throws OrmException, IOException {
if (hashes.size() > indexLimit) {
return byCommitsOnBranchNotMergedFromDatabase(repo, db, branch, hashes);
@@ -176,12 +169,11 @@
}
private Iterable<ChangeData> byCommitsOnBranchNotMergedFromDatabase(
- Repository repo, final ReviewDb db, final Branch.NameKey branch,
- Collection<String> hashes) throws OrmException, IOException {
+ Repository repo, final ReviewDb db, final Branch.NameKey branch, Collection<String> hashes)
+ throws OrmException, IOException {
Set<Change.Id> changeIds = Sets.newHashSetWithExpectedSize(hashes.size());
String lastPrefix = null;
- for (Ref ref :
- repo.getRefDatabase().getRefs(RefNames.REFS_CHANGES).values()) {
+ for (Ref ref : repo.getRefDatabase().getRefs(RefNames.REFS_CHANGES).values()) {
String r = ref.getName();
if ((lastPrefix != null && r.startsWith(lastPrefix))
|| !hashes.contains(ref.getObjectId().name())) {
@@ -196,23 +188,26 @@
}
}
- List<ChangeNotes> notes = notesFactory.create(
- db, branch.getParentKey(), changeIds,
- cn -> {
- Change c = cn.getChange();
- return c.getDest().equals(branch)
- && c.getStatus() != Change.Status.MERGED;
- });
+ List<ChangeNotes> notes =
+ notesFactory.create(
+ db,
+ branch.getParentKey(),
+ changeIds,
+ cn -> {
+ Change c = cn.getChange();
+ return c.getDest().equals(branch) && c.getStatus() != Change.Status.MERGED;
+ });
return Lists.transform(notes, n -> changeDataFactory.create(db, n));
}
private Iterable<ChangeData> byCommitsOnBranchNotMergedFromIndex(
Branch.NameKey branch, Collection<String> hashes) throws OrmException {
- return query(and(
- ref(branch),
- project(branch.getParentKey()),
- not(status(Change.Status.MERGED)),
- or(commits(hashes))));
+ return query(
+ and(
+ ref(branch),
+ project(branch.getParentKey()),
+ not(status(Change.Status.MERGED)),
+ or(commits(hashes))));
}
private static List<Predicate<ChangeData>> commits(Collection<String> hashes) {
@@ -223,13 +218,11 @@
return commits;
}
- public List<ChangeData> byProjectOpen(Project.NameKey project)
- throws OrmException {
+ public List<ChangeData> byProjectOpen(Project.NameKey project) throws OrmException {
return query(and(project(project), open()));
}
- public List<ChangeData> byTopicOpen(String topic)
- throws OrmException {
+ public List<ChangeData> byTopicOpen(String topic) throws OrmException {
return query(and(new ExactTopicPredicate(topic), open()));
}
@@ -241,33 +234,29 @@
return query(commit(hash));
}
- public List<ChangeData> byProjectCommit(Project.NameKey project,
- ObjectId id) throws OrmException {
+ public List<ChangeData> byProjectCommit(Project.NameKey project, ObjectId id)
+ throws OrmException {
return byProjectCommit(project, id.name());
}
- public List<ChangeData> byProjectCommit(Project.NameKey project,
- String hash) throws OrmException {
+ public List<ChangeData> byProjectCommit(Project.NameKey project, String hash)
+ throws OrmException {
return query(and(project(project), commit(hash)));
}
- public List<ChangeData> byProjectCommits(Project.NameKey project,
- List<String> hashes) throws OrmException {
+ public List<ChangeData> byProjectCommits(Project.NameKey project, List<String> hashes)
+ throws OrmException {
int n = indexConfig.maxTerms() - 1;
checkArgument(hashes.size() <= n, "cannot exceed %s commits", n);
return query(and(project(project), or(commits(hashes))));
}
- public List<ChangeData> byBranchCommit(String project, String branch,
- String hash) throws OrmException {
- return query(and(
- new ProjectPredicate(project),
- new RefPredicate(branch),
- commit(hash)));
+ public List<ChangeData> byBranchCommit(String project, String branch, String hash)
+ throws OrmException {
+ return query(and(new ProjectPredicate(project), new RefPredicate(branch), commit(hash)));
}
- public List<ChangeData> byBranchCommit(Branch.NameKey branch, String hash)
- throws OrmException {
+ public List<ChangeData> byBranchCommit(Branch.NameKey branch, String hash) throws OrmException {
return byBranchCommit(branch.getParentKey().get(), branch.get(), hash);
}
@@ -278,8 +267,8 @@
return query(new SubmissionIdPredicate(cs));
}
- public List<ChangeData> byProjectGroups(Project.NameKey project,
- Collection<String> groups) throws OrmException {
+ public List<ChangeData> byProjectGroups(Project.NameKey project, Collection<String> groups)
+ throws OrmException {
List<GroupPredicate> groupPredicates = new ArrayList<>(groups.size());
for (String g : groups) {
groupPredicates.add(new GroupPredicate(g));
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/IsMergePredicate.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/IsMergePredicate.java
index 376ad84..820c605 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/IsMergePredicate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/IsMergePredicate.java
@@ -17,14 +17,12 @@
import com.google.gerrit.server.git.CodeReviewCommit;
import com.google.gerrit.server.query.change.ChangeQueryBuilder.Arguments;
import com.google.gwtorm.server.OrmException;
-
+import java.io.IOException;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;
-import java.io.IOException;
-
public class IsMergePredicate extends ChangeOperatorPredicate {
private final Arguments args;
@@ -35,10 +33,8 @@
@Override
public boolean match(ChangeData cd) throws OrmException {
- ObjectId id = ObjectId.fromString(
- cd.currentPatchSet().getRevision().get());
- try (Repository repo =
- args.repoManager.openRepository(cd.change().getProject());
+ ObjectId id = ObjectId.fromString(cd.currentPatchSet().getRevision().get());
+ try (Repository repo = args.repoManager.openRepository(cd.change().getProject());
RevWalk rw = CodeReviewCommit.newRevWalk(repo)) {
RevCommit commit = rw.parseCommit(id);
return commit.getParentCount() > 1;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/IsReviewedPredicate.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/IsReviewedPredicate.java
index 24fcd6b..3295f1c 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/IsReviewedPredicate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/IsReviewedPredicate.java
@@ -20,15 +20,13 @@
import com.google.gerrit.server.index.change.ChangeField;
import com.google.gerrit.server.query.Predicate;
import com.google.gwtorm.server.OrmException;
-
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
class IsReviewedPredicate extends ChangeIndexPredicate {
- private static final Account.Id NOT_REVIEWED =
- new Account.Id(ChangeField.NOT_REVIEWED);
+ private static final Account.Id NOT_REVIEWED = new Account.Id(ChangeField.NOT_REVIEWED);
static Predicate<ChangeData> create() {
return Predicate.not(new IsReviewedPredicate(NOT_REVIEWED));
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/IsWatchedByPredicate.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/IsWatchedByPredicate.java
index 0b7a2f0..dda834b 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/IsWatchedByPredicate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/IsWatchedByPredicate.java
@@ -21,7 +21,6 @@
import com.google.gerrit.server.query.Predicate;
import com.google.gerrit.server.query.QueryBuilder;
import com.google.gerrit.server.query.QueryParseException;
-
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
@@ -37,15 +36,14 @@
private final CurrentUser user;
- IsWatchedByPredicate(ChangeQueryBuilder.Arguments args,
- boolean checkIsVisible) throws QueryParseException {
+ IsWatchedByPredicate(ChangeQueryBuilder.Arguments args, boolean checkIsVisible)
+ throws QueryParseException {
super(filters(args, checkIsVisible));
this.user = args.getUser();
}
private static List<Predicate<ChangeData>> filters(
- ChangeQueryBuilder.Arguments args,
- boolean checkIsVisible) throws QueryParseException {
+ ChangeQueryBuilder.Arguments args, boolean checkIsVisible) throws QueryParseException {
List<Predicate<ChangeData>> r = new ArrayList<>();
ChangeQueryBuilder builder = new ChangeQueryBuilder(args);
for (ProjectWatchKey w : getWatches(args)) {
@@ -58,7 +56,7 @@
// will never match and return null. Yes this test
// prevents you from having a filter that matches what
// another user is filtering on. :-)
- continue;
+ continue;
}
} catch (QueryParseException e) {
continue;
@@ -91,14 +89,13 @@
}
}
- private static Collection<ProjectWatchKey> getWatches(
- ChangeQueryBuilder.Arguments args) throws QueryParseException {
+ private static Collection<ProjectWatchKey> getWatches(ChangeQueryBuilder.Arguments args)
+ throws QueryParseException {
CurrentUser user = args.getUser();
if (user.isIdentifiedUser()) {
- return args.accountCache.get(args.getUser().getAccountId())
- .getProjectWatches().keySet();
+ return args.accountCache.get(args.getUser().getAccountId()).getProjectWatches().keySet();
}
- return Collections.<ProjectWatchKey> emptySet();
+ return Collections.<ProjectWatchKey>emptySet();
}
private static List<Predicate<ChangeData>> none() {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/LabelPredicate.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/LabelPredicate.java
index 9bed4b5..2fbaa1e 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/LabelPredicate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/LabelPredicate.java
@@ -29,7 +29,6 @@
import com.google.gerrit.server.util.RangeUtil;
import com.google.gerrit.server.util.RangeUtil.Range;
import com.google.inject.Provider;
-
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
@@ -82,12 +81,22 @@
private final String value;
@SuppressWarnings("deprecation")
- LabelPredicate(ChangeQueryBuilder.Arguments a, String value,
- Set<Account.Id> accounts, AccountGroup.UUID group) {
- super(predicates(new Args(
- a.getSchema().getField(ChangeField.LABEL2, ChangeField.LABEL).get(),
- a.projectCache, a.changeControlGenericFactory, a.userFactory, a.db,
- value, accounts, group)));
+ LabelPredicate(
+ ChangeQueryBuilder.Arguments a,
+ String value,
+ Set<Account.Id> accounts,
+ AccountGroup.UUID group) {
+ super(
+ predicates(
+ new Args(
+ a.getSchema().getField(ChangeField.LABEL2, ChangeField.LABEL).get(),
+ a.projectCache,
+ a.changeControlGenericFactory,
+ a.userFactory,
+ a.db,
+ value,
+ accounts,
+ group)));
this.value = value;
}
@@ -116,27 +125,22 @@
range = new Range(v, 1, 1);
}
} else {
- range = RangeUtil.getRange(
- parsed.label,
- parsed.test,
- parsed.expVal,
- -MAX_LABEL_VALUE,
- MAX_LABEL_VALUE);
+ range =
+ RangeUtil.getRange(
+ parsed.label, parsed.test, parsed.expVal, -MAX_LABEL_VALUE, MAX_LABEL_VALUE);
}
String prefix = range.prefix;
int min = range.min;
int max = range.max;
- List<Predicate<ChangeData>> r =
- Lists.newArrayListWithCapacity(max - min + 1);
+ List<Predicate<ChangeData>> r = Lists.newArrayListWithCapacity(max - min + 1);
for (int i = min; i <= max; i++) {
r.add(onePredicate(args, prefix, i));
}
return r;
}
- private static Predicate<ChangeData> onePredicate(Args args, String label,
- int expVal) {
+ private static Predicate<ChangeData> onePredicate(Args args, String label, int expVal) {
if (expVal != 0) {
return equalsLabelPredicate(args, label, expVal);
}
@@ -144,8 +148,7 @@
}
private static Predicate<ChangeData> noLabelQuery(Args args, String label) {
- List<Predicate<ChangeData>> r =
- Lists.newArrayListWithCapacity(2 * MAX_LABEL_VALUE);
+ List<Predicate<ChangeData>> r = Lists.newArrayListWithCapacity(2 * MAX_LABEL_VALUE);
for (int i = 1; i <= MAX_LABEL_VALUE; i++) {
r.add(equalsLabelPredicate(args, label, i));
r.add(equalsLabelPredicate(args, label, -i));
@@ -153,8 +156,7 @@
return not(or(r));
}
- private static Predicate<ChangeData> equalsLabelPredicate(Args args,
- String label, int expVal) {
+ private static Predicate<ChangeData> equalsLabelPredicate(Args args, String label, int expVal) {
if (args.accounts == null || args.accounts.isEmpty()) {
return new EqualsLabelPredicate(args, label, expVal, null);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/MessagePredicate.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/MessagePredicate.java
index 722a8ad..9e525c2 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/MessagePredicate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/MessagePredicate.java
@@ -21,10 +21,7 @@
import com.google.gerrit.server.query.QueryParseException;
import com.google.gwtorm.server.OrmException;
-/**
- * Predicate to match changes that contains specified text in commit messages
- * body.
- */
+/** Predicate to match changes that contains specified text in commit messages body. */
class MessagePredicate extends ChangeIndexPredicate {
private final ChangeIndex index;
@@ -36,10 +33,8 @@
@Override
public boolean match(ChangeData object) throws OrmException {
try {
- Predicate<ChangeData> p = Predicate.and(
- new LegacyChangeIdPredicate(object.getId()), this);
- for (ChangeData cData
- : index.getSource(p, IndexedChangeQuery.oneResult()).read()) {
+ Predicate<ChangeData> p = Predicate.and(new LegacyChangeIdPredicate(object.getId()), this);
+ for (ChangeData cData : index.getSource(p, IndexedChangeQuery.oneResult()).read()) {
if (cData.getId().equals(object.getId())) {
return true;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/OrSource.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/OrSource.java
index 28aef5e..90c2fb3 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/OrSource.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/OrSource.java
@@ -20,7 +20,6 @@
import com.google.gwtorm.server.ListResultSet;
import com.google.gwtorm.server.OrmException;
import com.google.gwtorm.server.ResultSet;
-
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
@@ -57,8 +56,7 @@
@Override
public boolean hasChange() {
for (Predicate<ChangeData> p : getChildren()) {
- if (!(p instanceof ChangeDataSource)
- || !((ChangeDataSource) p).hasChange()) {
+ if (!(p instanceof ChangeDataSource) || !((ChangeDataSource) p).hasChange()) {
return false;
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/OutputStreamQuery.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/OutputStreamQuery.java
index 5e08ee3..cd98087 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/OutputStreamQuery.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/OutputStreamQuery.java
@@ -36,15 +36,6 @@
import com.google.gson.Gson;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
-
-import org.eclipse.jgit.lib.Repository;
-import org.eclipse.jgit.revwalk.RevWalk;
-import org.eclipse.jgit.util.io.DisabledOutputStream;
-import org.joda.time.format.DateTimeFormat;
-import org.joda.time.format.DateTimeFormatter;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
@@ -57,20 +48,23 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import org.eclipse.jgit.lib.Repository;
+import org.eclipse.jgit.revwalk.RevWalk;
+import org.eclipse.jgit.util.io.DisabledOutputStream;
+import org.joda.time.format.DateTimeFormat;
+import org.joda.time.format.DateTimeFormatter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
-/**
- * Change query implementation that outputs to a stream in the style of an SSH
- * command.
- */
+/** Change query implementation that outputs to a stream in the style of an SSH command. */
public class OutputStreamQuery {
- private static final Logger log =
- LoggerFactory.getLogger(OutputStreamQuery.class);
+ private static final Logger log = LoggerFactory.getLogger(OutputStreamQuery.class);
- private static final DateTimeFormatter dtf =
- DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss zzz");
+ private static final DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss zzz");
public enum OutputFormat {
- TEXT, JSON
+ TEXT,
+ JSON
}
private final ReviewDb db;
@@ -179,9 +173,10 @@
}
public void query(String queryString) throws IOException {
- out = new PrintWriter( //
- new BufferedWriter( //
- new OutputStreamWriter(outputStream, UTF_8)));
+ out =
+ new PrintWriter( //
+ new BufferedWriter( //
+ new OutputStreamWriter(outputStream, UTF_8)));
try {
if (queryProcessor.isDisabled()) {
ErrorMessage m = new ErrorMessage();
@@ -196,8 +191,7 @@
Map<Project.NameKey, Repository> repos = new HashMap<>();
Map<Project.NameKey, RevWalk> revWalks = new HashMap<>();
- QueryResult<ChangeData> results =
- queryProcessor.query(queryBuilder.parse(queryString));
+ QueryResult<ChangeData> results = queryProcessor.query(queryBuilder.parse(queryString));
try {
for (ChangeData d : results.entities()) {
show(buildChangeAttribute(d, repos, revWalks));
@@ -208,8 +202,7 @@
stats.rowCount = results.entities().size();
stats.moreChanges = results.more();
- stats.runTimeMilliseconds =
- TimeUtil.nowMs() - stats.runTimeMilliseconds;
+ stats.runTimeMilliseconds = TimeUtil.nowMs() - stats.runTimeMilliseconds;
show(stats);
} catch (OrmException err) {
log.error("Cannot execute query: " + queryString, err);
@@ -232,9 +225,8 @@
}
}
- private ChangeAttribute buildChangeAttribute(ChangeData d,
- Map<Project.NameKey, Repository> repos,
- Map<Project.NameKey, RevWalk> revWalks)
+ private ChangeAttribute buildChangeAttribute(
+ ChangeData d, Map<Project.NameKey, Repository> repos, Map<Project.NameKey, RevWalk> revWalks)
throws OrmException, IOException {
ChangeControl cc = d.changeControl().forUser(user);
@@ -243,8 +235,7 @@
eventFactory.extend(c, d.change());
if (!trackingFooters.isEmpty()) {
- eventFactory.addTrackingIds(c,
- trackingFooters.extract(d.commitFooters()));
+ eventFactory.addTrackingIds(c, trackingFooters.extract(d.commitFooters()));
}
if (includeAllReviewers) {
@@ -252,10 +243,8 @@
}
if (includeSubmitRecords) {
- eventFactory.addSubmitRecords(c, new SubmitRuleEvaluator(d)
- .setAllowClosed(true)
- .setAllowDraft(true)
- .evaluate());
+ eventFactory.addSubmitRecords(
+ c, new SubmitRuleEvaluator(d).setAllowClosed(true).setAllowDraft(true).evaluate());
}
if (includeCommitMessage) {
@@ -276,26 +265,28 @@
}
if (includePatchSets) {
- eventFactory.addPatchSets(db, rw, c, d.visiblePatchSets(),
+ eventFactory.addPatchSets(
+ db,
+ rw,
+ c,
+ d.visiblePatchSets(),
includeApprovals ? d.approvals().asMap() : null,
- includeFiles, d.change(), labelTypes);
+ includeFiles,
+ d.change(),
+ labelTypes);
}
if (includeCurrentPatchSet) {
PatchSet current = d.currentPatchSet();
if (current != null && cc.isPatchVisible(current, d.db())) {
- c.currentPatchSet =
- eventFactory.asPatchSetAttribute(db, rw, d.change(), current);
- eventFactory.addApprovals(c.currentPatchSet,
- d.currentApprovals(), labelTypes);
+ c.currentPatchSet = eventFactory.asPatchSetAttribute(db, rw, d.change(), current);
+ eventFactory.addApprovals(c.currentPatchSet, d.currentApprovals(), labelTypes);
if (includeFiles) {
- eventFactory.addPatchSetFileNames(c.currentPatchSet,
- d.change(), d.currentPatchSet());
+ eventFactory.addPatchSetFileNames(c.currentPatchSet, d.change(), d.currentPatchSet());
}
if (includeComments) {
- eventFactory.addPatchSetComments(c.currentPatchSet,
- d.publishedComments());
+ eventFactory.addPatchSetComments(c.currentPatchSet, d.publishedComments());
}
}
}
@@ -303,9 +294,15 @@
if (includeComments) {
eventFactory.addComments(c, d.messages());
if (includePatchSets) {
- eventFactory.addPatchSets(db, rw, c, d.visiblePatchSets(),
+ eventFactory.addPatchSets(
+ db,
+ rw,
+ c,
+ d.visiblePatchSets(),
includeApprovals ? d.approvals().asMap() : null,
- includeFiles, d.change(), labelTypes);
+ includeFiles,
+ d.change(),
+ labelTypes);
for (PatchSetAttribute attribute : c.patchSets) {
eventFactory.addPatchSetComments(attribute, d.publishedComments());
}
@@ -319,8 +316,7 @@
return c;
}
- private static void closeAll(Iterable<RevWalk> revWalks,
- Iterable<Repository> repos) {
+ private static void closeAll(Iterable<RevWalk> revWalks, Iterable<Repository> repos) {
if (repos != null) {
for (Repository repo : repos) {
repo.close();
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/OwnerinPredicate.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/OwnerinPredicate.java
index 72327ba..f3239af 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/OwnerinPredicate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/OwnerinPredicate.java
@@ -23,8 +23,7 @@
private final IdentifiedUser.GenericFactory userFactory;
private final AccountGroup.UUID uuid;
- OwnerinPredicate(IdentifiedUser.GenericFactory userFactory,
- AccountGroup.UUID uuid) {
+ OwnerinPredicate(IdentifiedUser.GenericFactory userFactory, AccountGroup.UUID uuid) {
super(ChangeQueryBuilder.FIELD_OWNERIN, uuid.toString());
this.userFactory = userFactory;
this.uuid = uuid;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ParentProjectPredicate.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ParentProjectPredicate.java
index 0cd6978..d3a3f20 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ParentProjectPredicate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ParentProjectPredicate.java
@@ -24,7 +24,6 @@
import com.google.gerrit.server.query.OrPredicate;
import com.google.gerrit.server.query.Predicate;
import com.google.inject.Provider;
-
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@@ -32,8 +31,10 @@
class ParentProjectPredicate extends OrPredicate<ChangeData> {
private final String value;
- ParentProjectPredicate(ProjectCache projectCache,
- Provider<ListChildProjects> listChildProjects, Provider<CurrentUser> self,
+ ParentProjectPredicate(
+ ProjectCache projectCache,
+ Provider<ListChildProjects> listChildProjects,
+ Provider<CurrentUser> self,
String value) {
super(predicates(projectCache, listChildProjects, self, value));
this.value = value;
@@ -42,7 +43,8 @@
private static List<Predicate<ChangeData>> predicates(
ProjectCache projectCache,
Provider<ListChildProjects> listChildProjects,
- Provider<CurrentUser> self, String value) {
+ Provider<CurrentUser> self,
+ String value) {
ProjectState projectState = projectCache.get(new Project.NameKey(value));
if (projectState == null) {
return Collections.emptyList();
@@ -52,8 +54,7 @@
r.add(new ProjectPredicate(projectState.getProject().getName()));
ListChildProjects children = listChildProjects.get();
children.setRecursive(true);
- for (ProjectInfo p : children.apply(new ProjectResource(
- projectState.controlFor(self.get())))) {
+ for (ProjectInfo p : children.apply(new ProjectResource(projectState.controlFor(self.get())))) {
r.add(new ProjectPredicate(p.name));
}
return r;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/PredicateArgs.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/PredicateArgs.java
index 2fd0177..1fbc1aa 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/PredicateArgs.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/PredicateArgs.java
@@ -15,7 +15,6 @@
package com.google.gerrit.server.query.change;
import com.google.gerrit.server.query.QueryParseException;
-
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@@ -23,12 +22,11 @@
/**
* This class is used to extract comma separated values in a predicate.
- * <p>
- * If tags for the values are present (e.g. "branch=jb_2.3,vote=approved") then
- * the args are placed in a map that maps tag to value (e.g., "branch" to "jb_2.3").
- * If no tag is present (e.g. "jb_2.3,approved") then the args are placed into a
- * positional list. Args may be mixed so some may appear in the map and others
- * in the positional list (e.g. "vote=approved,jb_2.3).
+ *
+ * <p>If tags for the values are present (e.g. "branch=jb_2.3,vote=approved") then the args are
+ * placed in a map that maps tag to value (e.g., "branch" to "jb_2.3"). If no tag is present (e.g.
+ * "jb_2.3,approved") then the args are placed into a positional list. Args may be mixed so some may
+ * appear in the map and others in the positional list (e.g. "vote=approved,jb_2.3).
*/
public class PredicateArgs {
public List<String> positional;
@@ -36,9 +34,9 @@
/**
* Parses query arguments into {@link #keyValue} and/or {@link #positional}..
- * <p>
- * Labels for these arguments should be kept in ChangeQueryBuilder
- * as {@code ARG_ID_[argument name]}.
+ *
+ * <p>Labels for these arguments should be kept in ChangeQueryBuilder as {@code ARG_ID_[argument
+ * name]}.
*
* @param args arguments to be parsed
* @throws QueryParseException
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/QueryChanges.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/QueryChanges.java
index 62ca0e0..7eccf45 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/QueryChanges.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/QueryChanges.java
@@ -31,15 +31,13 @@
import com.google.gerrit.server.query.QueryResult;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
-
-import org.kohsuke.args4j.Option;
-
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
+import org.kohsuke.args4j.Option;
public class QueryChanges implements RestReadView<TopLevelResource> {
private final ChangeJson.Factory json;
@@ -47,10 +45,20 @@
private final ChangeQueryProcessor imp;
private EnumSet<ListChangesOption> options;
- @Option(name = "--query", aliases = {"-q"}, metaVar = "QUERY", usage = "Query string")
+ @Option(
+ name = "--query",
+ aliases = {"-q"},
+ metaVar = "QUERY",
+ usage = "Query string"
+ )
private List<String> queries;
- @Option(name = "--limit", aliases = {"-n"}, metaVar = "CNT", usage = "Maximum number of results to return")
+ @Option(
+ name = "--limit",
+ aliases = {"-n"},
+ metaVar = "CNT",
+ usage = "Maximum number of results to return"
+ )
public void setLimit(int limit) {
imp.setLimit(limit);
}
@@ -65,15 +73,18 @@
options.addAll(ListChangesOption.fromBits(Integer.parseInt(hex, 16)));
}
- @Option(name = "--start", aliases = {"-S"}, metaVar = "CNT", usage = "Number of changes to skip")
+ @Option(
+ name = "--start",
+ aliases = {"-S"},
+ metaVar = "CNT",
+ usage = "Number of changes to skip"
+ )
public void setStart(int start) {
imp.setStart(start);
}
@Inject
- QueryChanges(ChangeJson.Factory json,
- ChangeQueryBuilder qb,
- ChangeQueryProcessor qp) {
+ QueryChanges(ChangeJson.Factory json, ChangeQueryBuilder qb, ChangeQueryProcessor qp) {
this.json = json;
this.qb = qb;
this.imp = qp;
@@ -100,8 +111,8 @@
out = query();
} catch (QueryParseException e) {
// This is a hack to detect an operator that requires authentication.
- Pattern p = Pattern.compile(
- "^Error in operator (.*:self|is:watched|is:owner|is:reviewer|has:.*)$");
+ Pattern p =
+ Pattern.compile("^Error in operator (.*:self|is:watched|is:owner|is:reviewer|has:.*)$");
Matcher m = p.matcher(e.getMessage());
if (m.matches()) {
String op = m.group(1);
@@ -112,8 +123,7 @@
return out.size() == 1 ? out.get(0) : out;
}
- private List<List<ChangeInfo>> query()
- throws OrmException, QueryParseException {
+ private List<List<ChangeInfo>> query() throws OrmException, QueryParseException {
if (imp.isDisabled()) {
throw new QueryParseException("query disabled");
}
@@ -129,12 +139,11 @@
List<QueryResult<ChangeData>> results = imp.query(qb.parse(queries));
boolean requireLazyLoad =
containsAnyOf(options, ImmutableSet.of(DETAILED_LABELS, LABELS))
- && !qb.getArgs().getSchema()
- .hasField(ChangeField.STORED_SUBMIT_RECORD_LENIENT);
- List<List<ChangeInfo>> res = json.create(options)
- .lazyLoad(requireLazyLoad
- || containsAnyOf(options, ChangeJson.REQUIRE_LAZY_LOAD))
- .formatQueryResults(results);
+ && !qb.getArgs().getSchema().hasField(ChangeField.STORED_SUBMIT_RECORD_LENIENT);
+ List<List<ChangeInfo>> res =
+ json.create(options)
+ .lazyLoad(requireLazyLoad || containsAnyOf(options, ChangeJson.REQUIRE_LAZY_LOAD))
+ .formatQueryResults(results);
for (int n = 0; n < cnt; n++) {
List<ChangeInfo> info = res.get(n);
if (results.get(n).more()) {
@@ -145,8 +154,7 @@
}
private static boolean containsAnyOf(
- EnumSet<ListChangesOption> set,
- ImmutableSet<ListChangesOption> toFind) {
+ EnumSet<ListChangesOption> set, ImmutableSet<ListChangesOption> toFind) {
return !Sets.intersection(toFind, set).isEmpty();
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/RegexPathPredicate.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/RegexPathPredicate.java
index 67efd69..5b9774c 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/RegexPathPredicate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/RegexPathPredicate.java
@@ -17,7 +17,6 @@
import com.google.gerrit.server.index.change.ChangeField;
import com.google.gerrit.server.util.RegexListSearcher;
import com.google.gwtorm.server.OrmException;
-
import java.util.List;
class RegexPathPredicate extends ChangeRegexPredicate {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/RegexProjectPredicate.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/RegexProjectPredicate.java
index 007566e..1284e88 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/RegexProjectPredicate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/RegexProjectPredicate.java
@@ -18,7 +18,6 @@
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.server.index.change.ChangeField;
import com.google.gwtorm.server.OrmException;
-
import dk.brics.automaton.RegExp;
import dk.brics.automaton.RunAutomaton;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/RegexRefPredicate.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/RegexRefPredicate.java
index c6d1577..671d4cc 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/RegexRefPredicate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/RegexRefPredicate.java
@@ -17,7 +17,6 @@
import com.google.gerrit.reviewdb.client.Change;
import com.google.gerrit.server.index.change.ChangeField;
import com.google.gwtorm.server.OrmException;
-
import dk.brics.automaton.RegExp;
import dk.brics.automaton.RunAutomaton;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/RegexTopicPredicate.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/RegexTopicPredicate.java
index 2d65670..9df78a0 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/RegexTopicPredicate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/RegexTopicPredicate.java
@@ -18,7 +18,6 @@
import com.google.gerrit.reviewdb.client.Change;
import com.google.gwtorm.server.OrmException;
-
import dk.brics.automaton.RegExp;
import dk.brics.automaton.RunAutomaton;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ReviewerPredicate.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ReviewerPredicate.java
index 53834a9..4a11d28 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ReviewerPredicate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ReviewerPredicate.java
@@ -21,7 +21,6 @@
import com.google.gerrit.server.query.Predicate;
import com.google.gerrit.server.query.change.ChangeQueryBuilder.Arguments;
import com.google.gwtorm.server.OrmException;
-
import java.util.ArrayList;
import java.util.List;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ReviewerinPredicate.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ReviewerinPredicate.java
index 34c10e3..63e7859 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ReviewerinPredicate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ReviewerinPredicate.java
@@ -23,8 +23,7 @@
private final IdentifiedUser.GenericFactory userFactory;
private final AccountGroup.UUID uuid;
- ReviewerinPredicate(IdentifiedUser.GenericFactory userFactory,
- AccountGroup.UUID uuid) {
+ ReviewerinPredicate(IdentifiedUser.GenericFactory userFactory, AccountGroup.UUID uuid) {
super(ChangeQueryBuilder.FIELD_REVIEWERIN, uuid.toString());
this.userFactory = userFactory;
this.uuid = uuid;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/SingleGroupUser.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/SingleGroupUser.java
index 33b338c..2661b8b 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/SingleGroupUser.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/SingleGroupUser.java
@@ -19,20 +19,19 @@
import com.google.gerrit.server.account.CapabilityControl;
import com.google.gerrit.server.account.GroupMembership;
import com.google.gerrit.server.account.ListGroupMembership;
-
import java.util.Collections;
import java.util.Set;
public final class SingleGroupUser extends CurrentUser {
private final GroupMembership groups;
- public SingleGroupUser(CapabilityControl.Factory capabilityControlFactory,
- AccountGroup.UUID groupId) {
+ public SingleGroupUser(
+ CapabilityControl.Factory capabilityControlFactory, AccountGroup.UUID groupId) {
this(capabilityControlFactory, Collections.singleton(groupId));
}
- public SingleGroupUser(CapabilityControl.Factory capabilityControlFactory,
- Set<AccountGroup.UUID> groups) {
+ public SingleGroupUser(
+ CapabilityControl.Factory capabilityControlFactory, Set<AccountGroup.UUID> groups) {
super(capabilityControlFactory);
this.groups = new ListGroupMembership(groups);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/StarPredicate.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/StarPredicate.java
index a31254f..98965bf 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/StarPredicate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/StarPredicate.java
@@ -24,8 +24,7 @@
private final String label;
StarPredicate(Account.Id accountId, String label) {
- super(ChangeField.STAR,
- StarredChangesUtil.StarField.create(accountId, label).toString());
+ super(ChangeField.STAR, StarredChangesUtil.StarField.create(accountId, label).toString());
this.accountId = accountId;
this.label = label;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/SubmitRecordPredicate.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/SubmitRecordPredicate.java
index ec3c56f..5b01ea2 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/SubmitRecordPredicate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/SubmitRecordPredicate.java
@@ -21,20 +21,19 @@
import com.google.gerrit.server.index.change.ChangeField;
import com.google.gerrit.server.query.Predicate;
import com.google.gwtorm.server.OrmException;
-
import java.util.Set;
class SubmitRecordPredicate extends ChangeIndexPredicate {
- static Predicate<ChangeData> create(String label,
- SubmitRecord.Label.Status status, Set<Account.Id> accounts) {
+ static Predicate<ChangeData> create(
+ String label, SubmitRecord.Label.Status status, Set<Account.Id> accounts) {
String lowerLabel = label.toLowerCase();
if (accounts == null || accounts.isEmpty()) {
return new SubmitRecordPredicate(status.name() + ',' + lowerLabel);
}
return Predicate.or(
- accounts.stream()
- .map(a -> new SubmitRecordPredicate(
- status.name() + ',' + lowerLabel + ',' + a.get()))
+ accounts
+ .stream()
+ .map(a -> new SubmitRecordPredicate(status.name() + ',' + lowerLabel + ',' + a.get()))
.collect(toList()));
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/SubmittablePredicate.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/SubmittablePredicate.java
index 8782cfd..0812c6a 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/SubmittablePredicate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/SubmittablePredicate.java
@@ -28,7 +28,8 @@
@Override
public boolean match(ChangeData cd) throws OrmException {
- return cd.submitRecords(ChangeField.SUBMIT_RULE_OPTIONS_STRICT).stream()
+ return cd.submitRecords(ChangeField.SUBMIT_RULE_OPTIONS_STRICT)
+ .stream()
.anyMatch(r -> r.status == status);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/TimestampRangeChangePredicate.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/TimestampRangeChangePredicate.java
index 9242d9d..f0ac127 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/TimestampRangeChangePredicate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/TimestampRangeChangePredicate.java
@@ -17,13 +17,12 @@
import com.google.gerrit.server.index.FieldDef;
import com.google.gerrit.server.index.TimestampRangePredicate;
import com.google.gerrit.server.query.Matchable;
-
import java.sql.Timestamp;
-public abstract class TimestampRangeChangePredicate extends
- TimestampRangePredicate<ChangeData> implements Matchable<ChangeData> {
- protected TimestampRangeChangePredicate(FieldDef<ChangeData, Timestamp> def,
- String name, String value) {
+public abstract class TimestampRangeChangePredicate extends TimestampRangePredicate<ChangeData>
+ implements Matchable<ChangeData> {
+ protected TimestampRangeChangePredicate(
+ FieldDef<ChangeData, Timestamp> def, String name, String value) {
super(def, name, value);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/TrackingIdPredicate.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/TrackingIdPredicate.java
index e9be4cd..afaea5c 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/TrackingIdPredicate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/TrackingIdPredicate.java
@@ -18,14 +18,12 @@
import com.google.gerrit.server.config.TrackingFooters;
import com.google.gerrit.server.index.change.ChangeField;
import com.google.gwtorm.server.OrmException;
-
+import java.io.IOException;
+import java.util.List;
import org.eclipse.jgit.revwalk.FooterLine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.util.List;
-
class TrackingIdPredicate extends ChangeIndexPredicate {
private static final Logger log = LoggerFactory.getLogger(TrackingIdPredicate.class);
@@ -42,8 +40,8 @@
if (c != null) {
try {
List<FooterLine> footers = object.commitFooters();
- return footers != null && trackingFooters.extract(
- object.commitFooters()).values().contains(getValue());
+ return footers != null
+ && trackingFooters.extract(object.commitFooters()).values().contains(getValue());
} catch (IOException e) {
log.warn("Cannot extract footers from " + c.getChangeId(), e);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/group/GroupIsVisibleToPredicate.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/group/GroupIsVisibleToPredicate.java
index 939ece6..8f72945 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/group/GroupIsVisibleToPredicate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/group/GroupIsVisibleToPredicate.java
@@ -22,13 +22,11 @@
import com.google.gerrit.server.query.account.AccountQueryBuilder;
import com.google.gwtorm.server.OrmException;
-public class GroupIsVisibleToPredicate
- extends IsVisibleToPredicate<AccountGroup> {
+public class GroupIsVisibleToPredicate extends IsVisibleToPredicate<AccountGroup> {
private final GroupControl.GenericFactory groupControlFactory;
private final CurrentUser user;
- GroupIsVisibleToPredicate(GroupControl.GenericFactory groupControlFactory,
- CurrentUser user) {
+ GroupIsVisibleToPredicate(GroupControl.GenericFactory groupControlFactory, CurrentUser user) {
super(AccountQueryBuilder.FIELD_VISIBLETO, describe(user));
this.groupControlFactory = groupControlFactory;
this.user = user;
@@ -37,8 +35,7 @@
@Override
public boolean match(AccountGroup group) throws OrmException {
try {
- return groupControlFactory.controlFor(user, group.getGroupUUID())
- .isVisible();
+ return groupControlFactory.controlFor(user, group.getGroupUUID()).isVisible();
} catch (NoSuchGroupException e) {
// Ignored
return false;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/group/GroupPredicates.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/group/GroupPredicates.java
index 16f7e42..d0751a9 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/group/GroupPredicates.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/group/GroupPredicates.java
@@ -21,7 +21,6 @@
import com.google.gerrit.server.index.IndexPredicate;
import com.google.gerrit.server.index.group.GroupField;
import com.google.gerrit.server.query.Predicate;
-
import java.util.List;
import java.util.Locale;
@@ -40,28 +39,26 @@
}
public static Predicate<AccountGroup> uuid(AccountGroup.UUID uuid) {
- return new GroupPredicate(GroupField.UUID,
- GroupQueryBuilder.FIELD_UUID, uuid.get());
+ return new GroupPredicate(GroupField.UUID, GroupQueryBuilder.FIELD_UUID, uuid.get());
}
public static Predicate<AccountGroup> description(String description) {
- return new GroupPredicate(GroupField.DESCRIPTION,
- GroupQueryBuilder.FIELD_DESCRIPTION, description);
+ return new GroupPredicate(
+ GroupField.DESCRIPTION, GroupQueryBuilder.FIELD_DESCRIPTION, description);
}
public static Predicate<AccountGroup> inname(String name) {
- return new GroupPredicate(GroupField.NAME_PART,
- GroupQueryBuilder.FIELD_INNAME, name.toLowerCase(Locale.US));
+ return new GroupPredicate(
+ GroupField.NAME_PART, GroupQueryBuilder.FIELD_INNAME, name.toLowerCase(Locale.US));
}
public static Predicate<AccountGroup> name(String name) {
- return new GroupPredicate(GroupField.NAME,
- GroupQueryBuilder.FIELD_NAME, name.toLowerCase(Locale.US));
+ return new GroupPredicate(
+ GroupField.NAME, GroupQueryBuilder.FIELD_NAME, name.toLowerCase(Locale.US));
}
public static Predicate<AccountGroup> owner(String owner) {
- return new GroupPredicate(GroupField.OWNER_UUID,
- GroupQueryBuilder.FIELD_OWNER, owner);
+ return new GroupPredicate(GroupField.OWNER_UUID, GroupQueryBuilder.FIELD_OWNER, owner);
}
public static Predicate<AccountGroup> isVisibleToAll() {
@@ -78,6 +75,5 @@
}
}
- private GroupPredicates() {
- }
+ private GroupPredicates() {}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/group/GroupQueryBuilder.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/group/GroupQueryBuilder.java
index 9105b99..f9093e1 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/group/GroupQueryBuilder.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/group/GroupQueryBuilder.java
@@ -23,9 +23,7 @@
import com.google.gerrit.server.query.QueryParseException;
import com.google.inject.Inject;
-/**
- * Parses a query string meant to be applied to group objects.
- */
+/** Parses a query string meant to be applied to group objects. */
public class GroupQueryBuilder extends QueryBuilder<AccountGroup> {
public static final String FIELD_UUID = "uuid";
public static final String FIELD_DESCRIPTION = "description";
@@ -48,8 +46,7 @@
}
@Operator
- public Predicate<AccountGroup> description(String description)
- throws QueryParseException {
+ public Predicate<AccountGroup> description(String description) throws QueryParseException {
if (Strings.isNullOrEmpty(description)) {
throw error("description operator requires a value");
}
@@ -89,13 +86,11 @@
}
@Operator
- public Predicate<AccountGroup> limit(String query)
- throws QueryParseException {
+ public Predicate<AccountGroup> limit(String query) throws QueryParseException {
Integer limit = Ints.tryParse(query);
if (limit == null) {
throw error("Invalid limit: " + query);
}
return new LimitPredicate<>(FIELD_LIMIT, limit);
}
-
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/group/GroupQueryProcessor.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/group/GroupQueryProcessor.java
index f7a94b4..1cfab20 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/group/GroupQueryProcessor.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/group/GroupQueryProcessor.java
@@ -42,22 +42,27 @@
}
@Inject
- protected GroupQueryProcessor(Provider<CurrentUser> userProvider,
+ protected GroupQueryProcessor(
+ Provider<CurrentUser> userProvider,
Metrics metrics,
IndexConfig indexConfig,
GroupIndexCollection indexes,
GroupIndexRewriter rewriter,
GroupControl.GenericFactory groupControlFactory) {
- super(userProvider, metrics, GroupSchemaDefinitions.INSTANCE, indexConfig,
- indexes, rewriter, FIELD_LIMIT);
+ super(
+ userProvider,
+ metrics,
+ GroupSchemaDefinitions.INSTANCE,
+ indexConfig,
+ indexes,
+ rewriter,
+ FIELD_LIMIT);
this.groupControlFactory = groupControlFactory;
}
@Override
- protected Predicate<AccountGroup> enforceVisibility(
- Predicate<AccountGroup> pred) {
- return new AndSource<>(pred,
- new GroupIsVisibleToPredicate(groupControlFactory, userProvider.get()),
- start);
+ protected Predicate<AccountGroup> enforceVisibility(Predicate<AccountGroup> pred) {
+ return new AndSource<>(
+ pred, new GroupIsVisibleToPredicate(groupControlFactory, userProvider.get()), start);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/AclUtil.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/AclUtil.java
index 2f49f9e..97b4e51 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/AclUtil.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/AclUtil.java
@@ -22,18 +22,26 @@
import com.google.gerrit.server.git.ProjectConfig;
public class AclUtil {
- public static void grant(ProjectConfig config, AccessSection section,
- String permission, GroupReference... groupList) {
+ public static void grant(
+ ProjectConfig config, AccessSection section, String permission, GroupReference... groupList) {
grant(config, section, permission, false, groupList);
}
- public static void grant(ProjectConfig config, AccessSection section,
- String permission, boolean force, GroupReference... groupList) {
+ public static void grant(
+ ProjectConfig config,
+ AccessSection section,
+ String permission,
+ boolean force,
+ GroupReference... groupList) {
grant(config, section, permission, force, null, groupList);
}
- public static void grant(ProjectConfig config, AccessSection section,
- String permission, boolean force, Boolean exclusive,
+ public static void grant(
+ ProjectConfig config,
+ AccessSection section,
+ String permission,
+ boolean force,
+ Boolean exclusive,
GroupReference... groupList) {
Permission p = section.getPermission(permission, true);
if (exclusive != null) {
@@ -48,9 +56,13 @@
}
}
- public static void grant(ProjectConfig config,
- AccessSection section, LabelType type,
- int min, int max, GroupReference... groupList) {
+ public static void grant(
+ ProjectConfig config,
+ AccessSection section,
+ LabelType type,
+ int min,
+ int max,
+ GroupReference... groupList) {
String name = Permission.LABEL + type.getName();
Permission p = section.getPermission(name, true);
for (GroupReference group : groupList) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/AllProjectsCreator.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/AllProjectsCreator.java
index a5c7d75..3f1d32c 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/AllProjectsCreator.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/AllProjectsCreator.java
@@ -43,7 +43,7 @@
import com.google.gerrit.server.git.ProjectConfig;
import com.google.gerrit.server.group.SystemGroupBackend;
import com.google.inject.Inject;
-
+import java.io.IOException;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
import org.eclipse.jgit.lib.Constants;
@@ -51,8 +51,6 @@
import org.eclipse.jgit.lib.RefUpdate;
import org.eclipse.jgit.lib.Repository;
-import java.io.IOException;
-
/** Creates the {@code All-Projects} repository and initial ACLs. */
public class AllProjectsCreator {
private final GitRepositoryManager mgr;
@@ -113,17 +111,15 @@
}
}
- private void initAllProjects(Repository git)
- throws IOException, ConfigInvalidException {
- try (MetaDataUpdate md = new MetaDataUpdate(
- GitReferenceUpdated.DISABLED,
- allProjectsName,
- git)) {
+ private void initAllProjects(Repository git) throws IOException, ConfigInvalidException {
+ try (MetaDataUpdate md =
+ new MetaDataUpdate(GitReferenceUpdated.DISABLED, allProjectsName, git)) {
md.getCommitBuilder().setAuthor(serverUser);
md.getCommitBuilder().setCommitter(serverUser);
- md.setMessage(MoreObjects.firstNonNull(
- Strings.emptyToNull(message),
- "Initialized Gerrit Code Review " + Version.getVersion()));
+ md.setMessage(
+ MoreObjects.firstNonNull(
+ Strings.emptyToNull(message),
+ "Initialized Gerrit Code Review " + Version.getVersion()));
ProjectConfig config = ProjectConfig.read(md);
Project p = config.getProject();
@@ -185,12 +181,15 @@
}
public static LabelType initCodeReviewLabel(ProjectConfig c) {
- LabelType type = new LabelType("Code-Review", ImmutableList.of(
- new LabelValue((short) 2, "Looks good to me, approved"),
- new LabelValue((short) 1, "Looks good to me, but someone else must approve"),
- new LabelValue((short) 0, "No score"),
- new LabelValue((short) -1, "I would prefer this is not merged as is"),
- new LabelValue((short) -2, "This shall not be merged")));
+ LabelType type =
+ new LabelType(
+ "Code-Review",
+ ImmutableList.of(
+ new LabelValue((short) 2, "Looks good to me, approved"),
+ new LabelValue((short) 1, "Looks good to me, but someone else must approve"),
+ new LabelValue((short) 0, "No score"),
+ new LabelValue((short) -1, "I would prefer this is not merged as is"),
+ new LabelValue((short) -2, "This shall not be merged")));
type.setCopyMinScore(true);
type.setCopyAllScoresOnTrivialRebase(true);
c.getLabelSections().put(type.getName(), type);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/AllUsersCreator.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/AllUsersCreator.java
index 626d258..b524ecc 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/AllUsersCreator.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/AllUsersCreator.java
@@ -33,14 +33,12 @@
import com.google.gerrit.server.group.SystemGroupBackend;
import com.google.gerrit.server.project.RefPattern;
import com.google.inject.Inject;
-
+import java.io.IOException;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
import org.eclipse.jgit.lib.PersonIdent;
import org.eclipse.jgit.lib.Repository;
-import java.io.IOException;
-
/** Creates the {@code All-Users} repository. */
public class AllUsersCreator {
private final GitRepositoryManager mgr;
@@ -80,12 +78,8 @@
}
}
- private void initAllUsers(Repository git)
- throws IOException, ConfigInvalidException {
- try (MetaDataUpdate md = new MetaDataUpdate(
- GitReferenceUpdated.DISABLED,
- allUsersName,
- git)) {
+ private void initAllUsers(Repository git) throws IOException, ConfigInvalidException {
+ try (MetaDataUpdate md = new MetaDataUpdate(GitReferenceUpdated.DISABLED, allUsersName, git)) {
md.getCommitBuilder().setAuthor(serverUser);
md.getCommitBuilder().setCommitter(serverUser);
md.setMessage("Initialized Gerrit Code Review " + Version.getVersion());
@@ -94,8 +88,9 @@
Project project = config.getProject();
project.setDescription("Individual user settings and preferences.");
- AccessSection users = config.getAccessSection(
- RefNames.REFS_USERS + "${" + RefPattern.USERID_SHARDED + "}", true);
+ AccessSection users =
+ config.getAccessSection(
+ RefNames.REFS_USERS + "${" + RefPattern.USERID_SHARDED + "}", true);
LabelType cr = AllProjectsCreator.initCodeReviewLabel(config);
grant(config, users, Permission.READ, false, true, registered);
grant(config, users, Permission.PUSH, false, true, registered);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/BaseDataSourceType.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/BaseDataSourceType.java
index bf87ee0..4b3a570 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/BaseDataSourceType.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/BaseDataSourceType.java
@@ -15,7 +15,6 @@
package com.google.gerrit.server.schema;
import com.google.gerrit.reviewdb.server.ReviewDb;
-
import java.io.IOException;
import java.io.InputStream;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/DB2.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/DB2.java
index 4f0b63f..9b8b736 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/DB2.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/DB2.java
@@ -20,7 +20,6 @@
import com.google.gerrit.server.config.ConfigSection;
import com.google.gerrit.server.config.GerritServerConfig;
import com.google.inject.Inject;
-
import org.eclipse.jgit.lib.Config;
public class DB2 extends BaseDataSourceType {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/DataSourceProvider.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/DataSourceProvider.java
index 69f4ba5..170a5fa 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/DataSourceProvider.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/DataSourceProvider.java
@@ -33,21 +33,17 @@
import com.google.inject.Provider;
import com.google.inject.ProvisionException;
import com.google.inject.Singleton;
-
-import org.apache.commons.dbcp.BasicDataSource;
-import org.eclipse.jgit.lib.Config;
-
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.Properties;
-
import javax.sql.DataSource;
+import org.apache.commons.dbcp.BasicDataSource;
+import org.eclipse.jgit.lib.Config;
/** Provides access to the DataSource. */
@Singleton
-public class DataSourceProvider implements Provider<DataSource>,
- LifecycleListener {
+public class DataSourceProvider implements Provider<DataSource>, LifecycleListener {
private final Config cfg;
private final MetricMaker metrics;
private final Context ctx;
@@ -56,7 +52,8 @@
private DataSource ds;
@Inject
- protected DataSourceProvider(@GerritServerConfig Config cfg,
+ protected DataSourceProvider(
+ @GerritServerConfig Config cfg,
MetricMaker metrics,
ThreadSettingsConfig threadSettingsConfig,
Context ctx,
@@ -77,8 +74,7 @@
}
@Override
- public void start() {
- }
+ public void start() {}
@Override
public synchronized void stop() {
@@ -92,11 +88,11 @@
}
public enum Context {
- SINGLE_USER, MULTI_USER
+ SINGLE_USER,
+ MULTI_USER
}
- private DataSource open(final Config cfg, final Context context,
- final DataSourceType dst) {
+ private DataSource open(final Config cfg, final Context context, final DataSourceType dst) {
ConfigSection dbs = new ConfigSection(cfg, "database");
String driver = dbs.optional("driver");
if (Strings.isNullOrEmpty(driver)) {
@@ -132,16 +128,20 @@
int poolLimit = threadSettingsConfig.getDatabasePoolLimit();
ds.setMaxActive(poolLimit);
ds.setMinIdle(cfg.getInt("database", "poolminidle", 4));
- ds.setMaxIdle(
- cfg.getInt("database", "poolmaxidle", Math.min(poolLimit, 16)));
- ds.setMaxWait(ConfigUtil.getTimeUnit(cfg, "database", null,
- "poolmaxwait", MILLISECONDS.convert(30, SECONDS), MILLISECONDS));
+ ds.setMaxIdle(cfg.getInt("database", "poolmaxidle", Math.min(poolLimit, 16)));
+ ds.setMaxWait(
+ ConfigUtil.getTimeUnit(
+ cfg,
+ "database",
+ null,
+ "poolmaxwait",
+ MILLISECONDS.convert(30, SECONDS),
+ MILLISECONDS));
ds.setInitialSize(ds.getMinIdle());
ds.setValidationQuery(dst.getValidationQuery());
ds.setValidationQueryTimeout(5);
exportPoolMetrics(ds);
return intercept(interceptor, ds);
-
}
// Don't use the connection pool.
//
@@ -162,22 +162,23 @@
}
private void exportPoolMetrics(final BasicDataSource pool) {
- final CallbackMetric1<Boolean, Integer> cnt = metrics.newCallbackMetric(
- "sql/connection_pool/connections",
- Integer.class,
- new Description("SQL database connections")
- .setGauge()
- .setUnit("connections"),
- Field.ofBoolean("active"));
- metrics.newTrigger(cnt, new Runnable() {
- @Override
- public void run() {
- synchronized (pool) {
- cnt.set(true, pool.getNumActive());
- cnt.set(false, pool.getNumIdle());
- }
- }
- });
+ final CallbackMetric1<Boolean, Integer> cnt =
+ metrics.newCallbackMetric(
+ "sql/connection_pool/connections",
+ Integer.class,
+ new Description("SQL database connections").setGauge().setUnit("connections"),
+ Field.ofBoolean("active"));
+ metrics.newTrigger(
+ cnt,
+ new Runnable() {
+ @Override
+ public void run() {
+ synchronized (pool) {
+ cnt.set(true, pool.getNumActive());
+ cnt.set(false, pool.getNumIdle());
+ }
+ }
+ });
}
private DataSource intercept(String interceptor, DataSource ds) {
@@ -186,12 +187,15 @@
}
try {
Constructor<?> c = Class.forName(interceptor).getConstructor();
- DataSourceInterceptor datasourceInterceptor =
- (DataSourceInterceptor) c.newInstance();
+ DataSourceInterceptor datasourceInterceptor = (DataSourceInterceptor) c.newInstance();
return datasourceInterceptor.intercept("reviewDb", ds);
- } catch (ClassNotFoundException | SecurityException | NoSuchMethodException
- | IllegalArgumentException | InstantiationException
- | IllegalAccessException | InvocationTargetException e) {
+ } catch (ClassNotFoundException
+ | SecurityException
+ | NoSuchMethodException
+ | IllegalArgumentException
+ | InstantiationException
+ | IllegalAccessException
+ | InvocationTargetException e) {
throw new ProvisionException("Cannot intercept datasource", e);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/DataSourceType.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/DataSourceType.java
index ee8ce81..cbdcf0f 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/DataSourceType.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/DataSourceType.java
@@ -16,7 +16,6 @@
import java.io.IOException;
-
/** Abstraction of a supported database platform */
public interface DataSourceType {
@@ -29,8 +28,8 @@
boolean usePool();
/**
- * Return a ScriptRunner that runs the index script. Must not return
- * {@code null}, but may return a ScriptRunner that does nothing.
+ * Return a ScriptRunner that runs the index script. Must not return {@code null}, but may return
+ * a ScriptRunner that does nothing.
*
* @throws IOException
*/
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/DatabaseModule.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/DatabaseModule.java
index a2046b5..38a7751 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/DatabaseModule.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/DatabaseModule.java
@@ -31,13 +31,10 @@
protected void configure() {
TypeLiteral<SchemaFactory<ReviewDb>> schemaFactory =
new TypeLiteral<SchemaFactory<ReviewDb>>() {};
- TypeLiteral<Database<ReviewDb>> database =
- new TypeLiteral<Database<ReviewDb>>() {};
+ TypeLiteral<Database<ReviewDb>> database = new TypeLiteral<Database<ReviewDb>>() {};
bind(schemaFactory).to(NotesMigrationSchemaFactory.class);
- bind(Key.get(schemaFactory, ReviewDbFactory.class))
- .to(database)
- .in(SINGLETON);
+ bind(Key.get(schemaFactory, ReviewDbFactory.class)).to(database).in(SINGLETON);
bind(database).toProvider(ReviewDbDatabaseProvider.class);
bind(ChangeBundleReader.class).to(GwtormChangeBundleReader.class);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Derby.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Derby.java
index f98e83b..9fb761d 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Derby.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Derby.java
@@ -17,7 +17,6 @@
import com.google.gerrit.server.config.GerritServerConfig;
import com.google.gerrit.server.config.SitePaths;
import com.google.inject.Inject;
-
import org.eclipse.jgit.lib.Config;
class Derby extends BaseDataSourceType {
@@ -26,8 +25,7 @@
private final SitePaths site;
@Inject
- Derby(@GerritServerConfig Config cfg,
- SitePaths site) {
+ Derby(@GerritServerConfig Config cfg, SitePaths site) {
super("org.apache.derby.jdbc.EmbeddedDriver");
this.cfg = cfg;
this.site = site;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/H2.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/H2.java
index 7d64437..3cffdb1 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/H2.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/H2.java
@@ -17,10 +17,8 @@
import com.google.gerrit.server.config.GerritServerConfig;
import com.google.gerrit.server.config.SitePaths;
import com.google.inject.Inject;
-
-import org.eclipse.jgit.lib.Config;
-
import java.nio.file.Path;
+import org.eclipse.jgit.lib.Config;
class H2 extends BaseDataSourceType {
@@ -44,10 +42,7 @@
}
public static String createUrl(Path path) {
- return new StringBuilder()
- .append("jdbc:h2:")
- .append(path.toUri().toString())
- .toString();
+ return new StringBuilder().append("jdbc:h2:").append(path.toUri().toString()).toString();
}
public static String appendUrlOptions(Config cfg, String url) {
@@ -58,8 +53,7 @@
if (h2CacheSize >= 0) {
// H2 CACHE_SIZE is always given in KB
- urlBuilder.append(";CACHE_SIZE=")
- .append(h2CacheSize / 1024);
+ urlBuilder.append(";CACHE_SIZE=").append(h2CacheSize / 1024);
}
if (h2AutoServer) {
urlBuilder.append(";AUTO_SERVER=TRUE");
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/H2AccountPatchReviewStore.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/H2AccountPatchReviewStore.java
index b952d63..abe221c 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/H2AccountPatchReviewStore.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/H2AccountPatchReviewStore.java
@@ -28,11 +28,6 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.lib.Config;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
@@ -42,18 +37,18 @@
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
+import org.eclipse.jgit.lib.Config;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
@Singleton
-public class H2AccountPatchReviewStore
- implements AccountPatchReviewStore, LifecycleListener {
- private static final Logger log =
- LoggerFactory.getLogger(H2AccountPatchReviewStore.class);
+public class H2AccountPatchReviewStore implements AccountPatchReviewStore, LifecycleListener {
+ private static final Logger log = LoggerFactory.getLogger(H2AccountPatchReviewStore.class);
public static class Module extends LifecycleModule {
@Override
protected void configure() {
- DynamicItem.bind(binder(), AccountPatchReviewStore.class)
- .to(H2AccountPatchReviewStore.class);
+ DynamicItem.bind(binder(), AccountPatchReviewStore.class).to(H2AccountPatchReviewStore.class);
listener().to(H2AccountPatchReviewStore.class);
}
}
@@ -63,8 +58,7 @@
@Override
protected void configure() {
H2AccountPatchReviewStore inMemoryStore = new H2AccountPatchReviewStore();
- DynamicItem.bind(binder(), AccountPatchReviewStore.class)
- .toInstance(inMemoryStore);
+ DynamicItem.bind(binder(), AccountPatchReviewStore.class).toInstance(inMemoryStore);
listener().toInstance(inMemoryStore);
}
}
@@ -72,8 +66,7 @@
private final String url;
@Inject
- H2AccountPatchReviewStore(@GerritServerConfig Config cfg,
- SitePaths sitePaths) {
+ H2AccountPatchReviewStore(@GerritServerConfig Config cfg, SitePaths sitePaths) {
this.url = H2.appendUrlOptions(cfg, getUrl(sitePaths));
}
@@ -82,8 +75,8 @@
}
/**
- * Creates an in-memory H2 database to store the reviewed flags.
- * This should be used for tests only.
+ * Creates an in-memory H2 database to store the reviewed flags. This should be used for tests
+ * only.
*/
@VisibleForTesting
private H2AccountPatchReviewStore() {
@@ -105,14 +98,15 @@
public static void createTableIfNotExists(String url) throws OrmException {
try (Connection con = DriverManager.getConnection(url);
Statement stmt = con.createStatement()) {
- stmt.executeUpdate("CREATE TABLE IF NOT EXISTS ACCOUNT_PATCH_REVIEWS ("
- + "ACCOUNT_ID INTEGER DEFAULT 0 NOT NULL, "
- + "CHANGE_ID INTEGER DEFAULT 0 NOT NULL, "
- + "PATCH_SET_ID INTEGER DEFAULT 0 NOT NULL, "
- + "FILE_NAME VARCHAR(255) DEFAULT '' NOT NULL, "
- + "CONSTRAINT PRIMARY_KEY_ACCOUNT_PATCH_REVIEWS "
- + "PRIMARY KEY (ACCOUNT_ID, CHANGE_ID, PATCH_SET_ID, FILE_NAME)"
- + ")");
+ stmt.executeUpdate(
+ "CREATE TABLE IF NOT EXISTS ACCOUNT_PATCH_REVIEWS ("
+ + "ACCOUNT_ID INTEGER DEFAULT 0 NOT NULL, "
+ + "CHANGE_ID INTEGER DEFAULT 0 NOT NULL, "
+ + "PATCH_SET_ID INTEGER DEFAULT 0 NOT NULL, "
+ + "FILE_NAME VARCHAR(255) DEFAULT '' NOT NULL, "
+ + "CONSTRAINT PRIMARY_KEY_ACCOUNT_PATCH_REVIEWS "
+ + "PRIMARY KEY (ACCOUNT_ID, CHANGE_ID, PATCH_SET_ID, FILE_NAME)"
+ + ")");
} catch (SQLException e) {
throw convertError("create", e);
}
@@ -128,17 +122,17 @@
}
@Override
- public void stop() {
- }
+ public void stop() {}
@Override
- public boolean markReviewed(PatchSet.Id psId, Account.Id accountId,
- String path) throws OrmException {
+ public boolean markReviewed(PatchSet.Id psId, Account.Id accountId, String path)
+ throws OrmException {
try (Connection con = DriverManager.getConnection(url);
PreparedStatement stmt =
- con.prepareStatement("INSERT INTO ACCOUNT_PATCH_REVIEWS "
- + "(ACCOUNT_ID, CHANGE_ID, PATCH_SET_ID, FILE_NAME) VALUES "
- + "(?, ?, ?, ?)")) {
+ con.prepareStatement(
+ "INSERT INTO ACCOUNT_PATCH_REVIEWS "
+ + "(ACCOUNT_ID, CHANGE_ID, PATCH_SET_ID, FILE_NAME) VALUES "
+ + "(?, ?, ?, ?)")) {
stmt.setInt(1, accountId.get());
stmt.setInt(2, psId.getParentKey().get());
stmt.setInt(3, psId.get());
@@ -155,17 +149,18 @@
}
@Override
- public void markReviewed(PatchSet.Id psId, Account.Id accountId,
- Collection<String> paths) throws OrmException {
+ public void markReviewed(PatchSet.Id psId, Account.Id accountId, Collection<String> paths)
+ throws OrmException {
if (paths == null || paths.isEmpty()) {
return;
}
try (Connection con = DriverManager.getConnection(url);
PreparedStatement stmt =
- con.prepareStatement("INSERT INTO ACCOUNT_PATCH_REVIEWS "
- + "(ACCOUNT_ID, CHANGE_ID, PATCH_SET_ID, FILE_NAME) VALUES "
- + "(?, ?, ?, ?)")) {
+ con.prepareStatement(
+ "INSERT INTO ACCOUNT_PATCH_REVIEWS "
+ + "(ACCOUNT_ID, CHANGE_ID, PATCH_SET_ID, FILE_NAME) VALUES "
+ + "(?, ?, ?, ?)")) {
for (String path : paths) {
stmt.setInt(1, accountId.get());
stmt.setInt(2, psId.getParentKey().get());
@@ -188,9 +183,10 @@
throws OrmException {
try (Connection con = DriverManager.getConnection(url);
PreparedStatement stmt =
- con.prepareStatement("DELETE FROM ACCOUNT_PATCH_REVIEWS "
- + "WHERE ACCOUNT_ID = ? AND CHANGE_ID + ? AND "
- + "PATCH_SET_ID = ? AND FILE_NAME = ?")) {
+ con.prepareStatement(
+ "DELETE FROM ACCOUNT_PATCH_REVIEWS "
+ + "WHERE ACCOUNT_ID = ? AND CHANGE_ID + ? AND "
+ + "PATCH_SET_ID = ? AND FILE_NAME = ?")) {
stmt.setInt(1, accountId.get());
stmt.setInt(2, psId.getParentKey().get());
stmt.setInt(3, psId.get());
@@ -205,8 +201,9 @@
public void clearReviewed(PatchSet.Id psId) throws OrmException {
try (Connection con = DriverManager.getConnection(url);
PreparedStatement stmt =
- con.prepareStatement("DELETE FROM ACCOUNT_PATCH_REVIEWS "
- + "WHERE CHANGE_ID + ? AND PATCH_SET_ID = ?")) {
+ con.prepareStatement(
+ "DELETE FROM ACCOUNT_PATCH_REVIEWS "
+ + "WHERE CHANGE_ID + ? AND PATCH_SET_ID = ?")) {
stmt.setInt(1, psId.getParentKey().get());
stmt.setInt(2, psId.get());
stmt.executeUpdate();
@@ -220,8 +217,9 @@
throws OrmException {
try (Connection con = DriverManager.getConnection(url);
PreparedStatement stmt =
- con.prepareStatement("SELECT FILE_NAME FROM ACCOUNT_PATCH_REVIEWS "
- + "WHERE ACCOUNT_ID = ? AND CHANGE_ID = ? AND PATCH_SET_ID = ?")) {
+ con.prepareStatement(
+ "SELECT FILE_NAME FROM ACCOUNT_PATCH_REVIEWS "
+ + "WHERE ACCOUNT_ID = ? AND CHANGE_ID = ? AND PATCH_SET_ID = ?")) {
stmt.setInt(1, accountId.get());
stmt.setInt(2, psId.getParentKey().get());
stmt.setInt(3, psId.get());
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/HANA.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/HANA.java
index 44f1f0c..26c94e0 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/HANA.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/HANA.java
@@ -20,10 +20,8 @@
import com.google.gerrit.server.config.ConfigSection;
import com.google.gerrit.server.config.GerritServerConfig;
import com.google.inject.Inject;
-
-import org.eclipse.jgit.lib.Config;
-
import java.io.IOException;
+import org.eclipse.jgit.lib.Config;
class HANA extends BaseDataSourceType {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/JDBC.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/JDBC.java
index 7cdf93e..a1df850 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/JDBC.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/JDBC.java
@@ -17,7 +17,6 @@
import com.google.gerrit.server.config.ConfigUtil;
import com.google.gerrit.server.config.GerritServerConfig;
import com.google.inject.Inject;
-
import org.eclipse.jgit.lib.Config;
class JDBC extends BaseDataSourceType {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/MaxDb.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/MaxDb.java
index 9a09746..ca5a60d 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/MaxDb.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/MaxDb.java
@@ -19,10 +19,8 @@
import com.google.gerrit.server.config.ConfigSection;
import com.google.gerrit.server.config.GerritServerConfig;
import com.google.inject.Inject;
-
-import org.eclipse.jgit.lib.Config;
-
import java.io.IOException;
+import org.eclipse.jgit.lib.Config;
class MaxDb extends BaseDataSourceType {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/MySql.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/MySql.java
index 0b345e8..fc8e176 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/MySql.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/MySql.java
@@ -20,7 +20,6 @@
import com.google.gerrit.server.config.ConfigSection;
import com.google.gerrit.server.config.GerritServerConfig;
import com.google.inject.Inject;
-
import org.eclipse.jgit.lib.Config;
class MySql extends BaseDataSourceType {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/NotesMigrationSchemaFactory.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/NotesMigrationSchemaFactory.java
index f38ddfa..2e4065a 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/NotesMigrationSchemaFactory.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/NotesMigrationSchemaFactory.java
@@ -29,8 +29,7 @@
@Inject
NotesMigrationSchemaFactory(
- @ReviewDbFactory SchemaFactory<ReviewDb> delegate,
- NotesMigration migration) {
+ @ReviewDbFactory SchemaFactory<ReviewDb> delegate, NotesMigration migration) {
this.delegate = delegate;
this.migration = migration;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Oracle.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Oracle.java
index e7d3390..e86f788 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Oracle.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Oracle.java
@@ -20,7 +20,6 @@
import com.google.gerrit.server.config.ConfigSection;
import com.google.gerrit.server.config.GerritServerConfig;
import com.google.inject.Inject;
-
import org.eclipse.jgit.lib.Config;
public class Oracle extends BaseDataSourceType {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/PostgreSQL.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/PostgreSQL.java
index 3e3509e..23e7625 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/PostgreSQL.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/PostgreSQL.java
@@ -20,10 +20,8 @@
import com.google.gerrit.server.config.ConfigSection;
import com.google.gerrit.server.config.GerritServerConfig;
import com.google.inject.Inject;
-
-import org.eclipse.jgit.lib.Config;
-
import java.io.IOException;
+import org.eclipse.jgit.lib.Config;
class PostgreSQL extends BaseDataSourceType {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/ProjectConfigSchemaUpdate.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/ProjectConfigSchemaUpdate.java
index 504767c..67d11a8 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/ProjectConfigSchemaUpdate.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/ProjectConfigSchemaUpdate.java
@@ -23,16 +23,14 @@
import com.google.gerrit.server.git.ProjectConfig;
import com.google.gerrit.server.git.VersionedMetaData;
import com.google.gwtorm.server.OrmException;
-
-import org.eclipse.jgit.errors.ConfigInvalidException;
-import org.eclipse.jgit.lib.CommitBuilder;
-import org.eclipse.jgit.lib.Config;
-import org.eclipse.jgit.lib.PersonIdent;
-
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
+import org.eclipse.jgit.errors.ConfigInvalidException;
+import org.eclipse.jgit.lib.CommitBuilder;
+import org.eclipse.jgit.lib.Config;
+import org.eclipse.jgit.lib.PersonIdent;
public class ProjectConfigSchemaUpdate extends VersionedMetaData {
@@ -67,7 +65,8 @@
if (names.contains(name)) {
List<String> values =
Arrays.stream(config.getStringList(ACCESS, subsection, name))
- .map(r -> {
+ .map(
+ r -> {
PermissionRule rule = PermissionRule.fromString(r, false);
if (rule.getForce()) {
rule.setForce(false);
@@ -82,14 +81,12 @@
}
@Override
- protected boolean onSave(CommitBuilder commit)
- throws IOException, ConfigInvalidException {
+ protected boolean onSave(CommitBuilder commit) throws IOException, ConfigInvalidException {
saveConfig(ProjectConfig.PROJECT_CONFIG, config);
return true;
}
- public void save(PersonIdent personIdent, String commitMessage)
- throws OrmException {
+ public void save(PersonIdent personIdent, String commitMessage) throws OrmException {
if (!updated) {
return;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/ReviewDbDatabaseProvider.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/ReviewDbDatabaseProvider.java
index 9ceaf1c..0fbaeca 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/ReviewDbDatabaseProvider.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/ReviewDbDatabaseProvider.java
@@ -21,7 +21,6 @@
import com.google.inject.Provider;
import com.google.inject.ProvisionException;
import com.google.inject.name.Named;
-
import javax.sql.DataSource;
/** Provides the {@code Database<ReviewDb>} database handle. */
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/ReviewDbFactory.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/ReviewDbFactory.java
index 3a63360..86f5d06 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/ReviewDbFactory.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/ReviewDbFactory.java
@@ -17,19 +17,15 @@
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import com.google.inject.BindingAnnotation;
-
import java.lang.annotation.Retention;
/**
- * Marker on {@link com.google.gwtorm.server.SchemaFactory} implementation
- * that talks to the underlying traditional {@link
- * com.google.gerrit.reviewdb.server.ReviewDb} database.
- * <p>
- * During the migration to NoteDb, the actual {@code ReviewDb} will be a wrapper
- * with certain tables enabled/disabled; this marker goes on the low-level
- * implementation that has all tables.
+ * Marker on {@link com.google.gwtorm.server.SchemaFactory} implementation that talks to the
+ * underlying traditional {@link com.google.gerrit.reviewdb.server.ReviewDb} database.
+ *
+ * <p>During the migration to NoteDb, the actual {@code ReviewDb} will be a wrapper with certain
+ * tables enabled/disabled; this marker goes on the low-level implementation that has all tables.
*/
@Retention(RUNTIME)
@BindingAnnotation
-public @interface ReviewDbFactory {
-}
+public @interface ReviewDbFactory {}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/SchemaCreator.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/SchemaCreator.java
index 7caea42..62d0f42 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/SchemaCreator.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/SchemaCreator.java
@@ -30,19 +30,15 @@
import com.google.gwtorm.jdbc.JdbcSchema;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
-
-import org.eclipse.jgit.errors.ConfigInvalidException;
-import org.eclipse.jgit.lib.PersonIdent;
-
import java.io.IOException;
import java.nio.file.Path;
import java.util.Collections;
+import org.eclipse.jgit.errors.ConfigInvalidException;
+import org.eclipse.jgit.lib.PersonIdent;
/** Creates the current database schema and populates initial code rows. */
public class SchemaCreator {
- @SitePath
- private final
- Path site_path;
+ @SitePath private final Path site_path;
private final AllProjectsCreator allProjectsCreator;
private final AllUsersCreator allUsersCreator;
@@ -54,7 +50,8 @@
private AccountGroup batch;
@Inject
- public SchemaCreator(SitePaths site,
+ public SchemaCreator(
+ SitePaths site,
AllProjectsCreator ap,
AllUsersCreator auc,
@GerritPersonIdent PersonIdent au,
@@ -63,7 +60,8 @@
this(site.site_path, ap, auc, au, dst, ic);
}
- public SchemaCreator(@SitePath Path site,
+ public SchemaCreator(
+ @SitePath Path site,
AllProjectsCreator ap,
AllUsersCreator auc,
@GerritPersonIdent PersonIdent au,
@@ -77,8 +75,7 @@
indexCollection = ic;
}
- public void create(final ReviewDb db) throws OrmException, IOException,
- ConfigInvalidException {
+ public void create(final ReviewDb db) throws OrmException, IOException, ConfigInvalidException {
final JdbcSchema jdbc = (JdbcSchema) db;
try (JdbcExecutor e = new JdbcExecutor(jdbc)) {
jdbc.updateSchema(e);
@@ -91,30 +88,25 @@
createDefaultGroups(db);
initSystemConfig(db);
allProjectsCreator
- .setAdministrators(GroupReference.forGroup(admin))
- .setBatchUsers(GroupReference.forGroup(batch))
- .create();
- allUsersCreator
- .setAdministrators(GroupReference.forGroup(admin))
- .create();
+ .setAdministrators(GroupReference.forGroup(admin))
+ .setBatchUsers(GroupReference.forGroup(batch))
+ .create();
+ allUsersCreator.setAdministrators(GroupReference.forGroup(admin)).create();
dataSourceType.getIndexScript().run(db);
}
- private void createDefaultGroups(ReviewDb db)
- throws OrmException, IOException {
+ private void createDefaultGroups(ReviewDb db) throws OrmException, IOException {
admin = newGroup(db, "Administrators", null);
admin.setDescription("Gerrit Site Administrators");
db.accountGroups().insert(Collections.singleton(admin));
- db.accountGroupNames()
- .insert(Collections.singleton(new AccountGroupName(admin)));
+ db.accountGroupNames().insert(Collections.singleton(new AccountGroupName(admin)));
index(admin);
batch = newGroup(db, "Non-Interactive Users", null);
batch.setDescription("Users who perform batch actions on Gerrit");
batch.setOwnerGroupUUID(admin.getGroupUUID());
db.accountGroups().insert(Collections.singleton(batch));
- db.accountGroupNames()
- .insert(Collections.singleton(new AccountGroupName(batch)));
+ db.accountGroupNames().insert(Collections.singleton(new AccountGroupName(batch)));
index(batch);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/SchemaModule.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/SchemaModule.java
index f23dabf..9ce19fe 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/SchemaModule.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/SchemaModule.java
@@ -27,29 +27,27 @@
import com.google.gerrit.server.config.AnonymousCowardNameProvider;
import com.google.gerrit.server.config.GerritServerId;
import com.google.gerrit.server.config.GerritServerIdProvider;
-
import org.eclipse.jgit.lib.PersonIdent;
/** Validate the schema and connect to Git. */
public class SchemaModule extends FactoryModule {
@Override
protected void configure() {
- bind(PersonIdent.class).annotatedWith(GerritPersonIdent.class)
- .toProvider(GerritPersonIdentProvider.class);
+ bind(PersonIdent.class)
+ .annotatedWith(GerritPersonIdent.class)
+ .toProvider(GerritPersonIdentProvider.class);
- bind(AllProjectsName.class)
- .toProvider(AllProjectsNameProvider.class)
- .in(SINGLETON);
+ bind(AllProjectsName.class).toProvider(AllProjectsNameProvider.class).in(SINGLETON);
- bind(AllUsersName.class)
- .toProvider(AllUsersNameProvider.class)
- .in(SINGLETON);
+ bind(AllUsersName.class).toProvider(AllUsersNameProvider.class).in(SINGLETON);
- bind(String.class).annotatedWith(AnonymousCowardName.class).toProvider(
- AnonymousCowardNameProvider.class);
+ bind(String.class)
+ .annotatedWith(AnonymousCowardName.class)
+ .toProvider(AnonymousCowardNameProvider.class);
- bind(String.class).annotatedWith(GerritServerId.class)
- .toProvider(GerritServerIdProvider.class)
- .in(SINGLETON);
+ bind(String.class)
+ .annotatedWith(GerritServerId.class)
+ .toProvider(GerritServerIdProvider.class)
+ .in(SINGLETON);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/SchemaUpdater.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/SchemaUpdater.java
index fe14c52..374b233 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/SchemaUpdater.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/SchemaUpdater.java
@@ -35,13 +35,11 @@
import com.google.inject.Key;
import com.google.inject.Provider;
import com.google.inject.Stage;
-
-import org.eclipse.jgit.errors.ConfigInvalidException;
-import org.eclipse.jgit.lib.PersonIdent;
-
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collections;
+import org.eclipse.jgit.errors.ConfigInvalidException;
+import org.eclipse.jgit.lib.PersonIdent;
/** Creates or updates the current database schema. */
public class SchemaUpdater {
@@ -51,10 +49,8 @@
private final Provider<SchemaVersion> updater;
@Inject
- SchemaUpdater(SchemaFactory<ReviewDb> schema,
- SitePaths site,
- SchemaCreator creator,
- Injector parent) {
+ SchemaUpdater(
+ SchemaFactory<ReviewDb> schema, SitePaths site, SchemaCreator creator, Injector parent) {
this.schema = schema;
this.site = site;
this.creator = creator;
@@ -65,34 +61,38 @@
// Use DEVELOPMENT mode to allow lazy initialization of the
// graph. This avoids touching ancient schema versions that
// are behind this installation's current version.
- return Guice.createInjector(Stage.DEVELOPMENT, new AbstractModule() {
- @Override
- protected void configure() {
- bind(SchemaVersion.class).to(SchemaVersion.C);
+ return Guice.createInjector(
+ Stage.DEVELOPMENT,
+ new AbstractModule() {
+ @Override
+ protected void configure() {
+ bind(SchemaVersion.class).to(SchemaVersion.C);
- for (Key<?> k : new Key<?>[]{
- Key.get(PersonIdent.class, GerritPersonIdent.class),
- Key.get(String.class, AnonymousCowardName.class),
- }) {
- rebind(parent, k);
- }
+ for (Key<?> k :
+ new Key<?>[] {
+ Key.get(PersonIdent.class, GerritPersonIdent.class),
+ Key.get(String.class, AnonymousCowardName.class),
+ }) {
+ rebind(parent, k);
+ }
- for (Class<?> c : new Class<?>[] {
- AllProjectsName.class,
- AllUsersCreator.class,
- AllUsersName.class,
- GitRepositoryManager.class,
- SitePaths.class,
- SystemGroupBackend.class,
- }) {
- rebind(parent, Key.get(c));
- }
- }
+ for (Class<?> c :
+ new Class<?>[] {
+ AllProjectsName.class,
+ AllUsersCreator.class,
+ AllUsersName.class,
+ GitRepositoryManager.class,
+ SitePaths.class,
+ SystemGroupBackend.class,
+ }) {
+ rebind(parent, Key.get(c));
+ }
+ }
- private <T> void rebind(Injector parent, Key<T> c) {
- bind(c).toProvider(parent.getProvider(c));
- }
- });
+ private <T> void rebind(Injector parent, Key<T> c) {
+ bind(c).toProvider(parent.getProvider(c));
+ }
+ });
}
public void update(final UpdateUI ui) throws OrmException {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/SchemaVersion.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/SchemaVersion.java
index 2c81c56..e2d16d8 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/SchemaVersion.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/SchemaVersion.java
@@ -24,7 +24,6 @@
import com.google.gwtorm.server.OrmException;
import com.google.gwtorm.server.StatementExecutor;
import com.google.inject.Provider;
-
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
@@ -74,8 +73,12 @@
if (curr.versionNbr == versionNbr) {
// Nothing to do, we are at the correct schema.
} else if (curr.versionNbr > versionNbr) {
- throw new OrmException("Cannot downgrade database schema from version "
- + curr.versionNbr + " to " + versionNbr + ".");
+ throw new OrmException(
+ "Cannot downgrade database schema from version "
+ + curr.versionNbr
+ + " to "
+ + versionNbr
+ + ".");
} else {
upgradeFrom(ui, curr, db);
}
@@ -90,17 +93,18 @@
JdbcSchema s = (JdbcSchema) db;
final List<String> pruneList = new ArrayList<>();
- s.pruneSchema(new StatementExecutor() {
- @Override
- public void execute(String sql) {
- pruneList.add(sql);
- }
+ s.pruneSchema(
+ new StatementExecutor() {
+ @Override
+ public void execute(String sql) {
+ pruneList.add(sql);
+ }
- @Override
- public void close() {
- // Do nothing.
- }
- });
+ @Override
+ public void close() {
+ // Do nothing.
+ }
+ });
try (JdbcExecutor e = new JdbcExecutor(s)) {
if (!pruneList.isEmpty()) {
@@ -118,8 +122,8 @@
return r;
}
- private void updateSchema(List<SchemaVersion> pending, UpdateUI ui,
- ReviewDb db) throws OrmException, SQLException {
+ private void updateSchema(List<SchemaVersion> pending, UpdateUI ui, ReviewDb db)
+ throws OrmException, SQLException {
for (SchemaVersion v : pending) {
ui.message(String.format("Upgrading schema to %d ...", v.getVersionNbr()));
v.preUpdateSchema(db);
@@ -138,45 +142,39 @@
* @throws OrmException if a Gerrit-specific exception occurred.
* @throws SQLException if an underlying SQL exception occurred.
*/
- protected void preUpdateSchema(ReviewDb db) throws OrmException, SQLException {
- }
+ protected void preUpdateSchema(ReviewDb db) throws OrmException, SQLException {}
- private void migrateData(List<SchemaVersion> pending, UpdateUI ui,
- CurrentSchemaVersion curr, ReviewDb db) throws OrmException, SQLException {
+ private void migrateData(
+ List<SchemaVersion> pending, UpdateUI ui, CurrentSchemaVersion curr, ReviewDb db)
+ throws OrmException, SQLException {
for (SchemaVersion v : pending) {
Stopwatch sw = Stopwatch.createStarted();
- ui.message(String.format(
- "Migrating data to schema %d ...",
- v.getVersionNbr()));
+ ui.message(String.format("Migrating data to schema %d ...", v.getVersionNbr()));
v.migrateData(db, ui);
v.finish(curr, db);
- ui.message(String.format("\t> Done (%.3f s)",
- sw.elapsed(TimeUnit.MILLISECONDS) / 1000d));
+ ui.message(String.format("\t> Done (%.3f s)", sw.elapsed(TimeUnit.MILLISECONDS) / 1000d));
}
}
/**
- * Invoked between updateSchema (adds new columns/tables) and pruneSchema
- * (removes deleted columns/tables).
+ * Invoked between updateSchema (adds new columns/tables) and pruneSchema (removes deleted
+ * columns/tables).
*
* @param db open database handle.
* @param ui interface for interacting with the user.
* @throws OrmException if a Gerrit-specific exception occurred.
* @throws SQLException if an underlying SQL exception occurred.
*/
- protected void migrateData(ReviewDb db, UpdateUI ui) throws OrmException, SQLException {
- }
+ protected void migrateData(ReviewDb db, UpdateUI ui) throws OrmException, SQLException {}
/** Mark the current schema version. */
- protected void finish(CurrentSchemaVersion curr, ReviewDb db)
- throws OrmException {
+ protected void finish(CurrentSchemaVersion curr, ReviewDb db) throws OrmException {
curr.versionNbr = versionNbr;
db.schemaVersion().update(Collections.singleton(curr));
}
/** Rename an existing table. */
- protected static void renameTable(ReviewDb db, String from, String to)
- throws OrmException {
+ protected static void renameTable(ReviewDb db, String from, String to) throws OrmException {
JdbcSchema s = (JdbcSchema) db;
try (JdbcExecutor e = new JdbcExecutor(s)) {
s.renameTable(e, from, to);
@@ -205,8 +203,7 @@
}
/** Open a new prepared statement. */
- protected static PreparedStatement prepareStatement(ReviewDb db, String sql)
- throws SQLException {
+ protected static PreparedStatement prepareStatement(ReviewDb db, String sql) throws SQLException {
return ((JdbcSchema) db).getConnection().prepareStatement(sql);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/SchemaVersionCheck.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/SchemaVersionCheck.java
index 245e94d..2f3d09f 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/SchemaVersionCheck.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/SchemaVersionCheck.java
@@ -27,7 +27,7 @@
/** Validates the current schema version. */
public class SchemaVersionCheck implements LifecycleListener {
- public static Module module () {
+ public static Module module() {
return new LifecycleModule() {
@Override
protected void configure() {
@@ -40,8 +40,7 @@
private final SitePaths site;
@Inject
- public SchemaVersionCheck(SchemaFactory<ReviewDb> schemaFactory,
- SitePaths site) {
+ public SchemaVersionCheck(SchemaFactory<ReviewDb> schemaFactory, SitePaths site) {
this.schema = schemaFactory;
this.site = site;
}
@@ -53,21 +52,30 @@
final int expectedVer = SchemaVersion.getBinaryVersion();
if (currentVer == null) {
- throw new ProvisionException("Schema not yet initialized."
- + " Run init to initialize the schema:\n"
- + "$ java -jar gerrit.war init -d "
- + site.site_path.toAbsolutePath());
+ throw new ProvisionException(
+ "Schema not yet initialized."
+ + " Run init to initialize the schema:\n"
+ + "$ java -jar gerrit.war init -d "
+ + site.site_path.toAbsolutePath());
}
if (currentVer.versionNbr < expectedVer) {
- throw new ProvisionException("Unsupported schema version "
- + currentVer.versionNbr + "; expected schema version " + expectedVer
- + ". Run init to upgrade:\n"
- + "$ java -jar " + site.gerrit_war.toAbsolutePath() + " init -d "
- + site.site_path.toAbsolutePath());
+ throw new ProvisionException(
+ "Unsupported schema version "
+ + currentVer.versionNbr
+ + "; expected schema version "
+ + expectedVer
+ + ". Run init to upgrade:\n"
+ + "$ java -jar "
+ + site.gerrit_war.toAbsolutePath()
+ + " init -d "
+ + site.site_path.toAbsolutePath());
} else if (currentVer.versionNbr > expectedVer) {
- throw new ProvisionException("Unsupported schema version "
- + currentVer.versionNbr + "; expected schema version " + expectedVer
- + ". Downgrade is not supported.");
+ throw new ProvisionException(
+ "Unsupported schema version "
+ + currentVer.versionNbr
+ + "; expected schema version "
+ + expectedVer
+ + ". Downgrade is not supported.");
}
} catch (OrmException e) {
throw new ProvisionException("Cannot read schema_version", e);
@@ -75,8 +83,7 @@
}
@Override
- public void stop() {
- }
+ public void stop() {}
private CurrentSchemaVersion getSchemaVersion(final ReviewDb db) {
try {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_101.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_101.java
index 4ef0d96..ccbb2de 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_101.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_101.java
@@ -27,7 +27,6 @@
import com.google.gwtorm.server.StatementExecutor;
import com.google.inject.Inject;
import com.google.inject.Provider;
-
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
@@ -55,8 +54,7 @@
}
@Override
- protected void migrateData(ReviewDb db, UpdateUI ui)
- throws OrmException, SQLException {
+ protected void migrateData(ReviewDb db, UpdateUI ui) throws OrmException, SQLException {
conn = ((JdbcSchema) db).getConnection();
dialect = ((JdbcSchema) db).getDialect();
Map<String, PrimaryKey> corrections = findPKUpdates();
@@ -78,8 +76,7 @@
}
}
- private Map<String, PrimaryKey> findPKUpdates()
- throws OrmException, SQLException {
+ private Map<String, PrimaryKey> findPKUpdates() throws OrmException, SQLException {
Map<String, PrimaryKey> corrections = new TreeMap<>();
DatabaseMetaData meta = conn.getMetaData();
JavaSchemaModel jsm = new JavaSchemaModel(ReviewDb.class);
@@ -104,8 +101,7 @@
return pk;
}
- private PrimaryKey dbTablePK(DatabaseMetaData meta, String tableName)
- throws SQLException {
+ private PrimaryKey dbTablePK(DatabaseMetaData meta, String tableName) throws SQLException {
if (meta.storesUpperCaseIdentifiers()) {
tableName = tableName.toUpperCase();
} else if (meta.storesLowerCaseIdentifiers()) {
@@ -130,21 +126,19 @@
}
}
- private void recreatePK(StatementExecutor executor, String tableName,
- PrimaryKey pk, UpdateUI ui) throws OrmException {
+ private void recreatePK(StatementExecutor executor, String tableName, PrimaryKey pk, UpdateUI ui)
+ throws OrmException {
if (pk.oldNameInDb == null) {
- ui.message(String.format(
- "warning: primary key for table %s didn't exist ... ", tableName));
+ ui.message(String.format("warning: primary key for table %s didn't exist ... ", tableName));
} else {
if (dialect instanceof DialectPostgreSQL) {
// postgresql doesn't support the ALTER TABLE foo DROP PRIMARY KEY form
- executor.execute("ALTER TABLE " + tableName + " DROP CONSTRAINT "
- + pk.oldNameInDb);
+ executor.execute("ALTER TABLE " + tableName + " DROP CONSTRAINT " + pk.oldNameInDb);
} else {
executor.execute("ALTER TABLE " + tableName + " DROP PRIMARY KEY");
}
}
- executor.execute("ALTER TABLE " + tableName
- + " ADD PRIMARY KEY(" + Joiner.on(",").join(pk.cols) + ")");
+ executor.execute(
+ "ALTER TABLE " + tableName + " ADD PRIMARY KEY(" + Joiner.on(",").join(pk.cols) + ")");
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_102.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_102.java
index bcb3e1a..1c1aa55 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_102.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_102.java
@@ -22,7 +22,6 @@
import com.google.gwtorm.server.StatementExecutor;
import com.google.inject.Inject;
import com.google.inject.Provider;
-
import java.sql.SQLException;
import java.util.Set;
import java.util.regex.Pattern;
@@ -34,8 +33,7 @@
}
@Override
- protected void migrateData(ReviewDb db, UpdateUI ui)
- throws OrmException, SQLException {
+ protected void migrateData(ReviewDb db, UpdateUI ui) throws OrmException, SQLException {
JdbcSchema schema = (JdbcSchema) db;
SqlDialect dialect = schema.getDialect();
try (StatementExecutor e = newExecutor(db)) {
@@ -43,11 +41,9 @@
// See "Delete SQL index support" commit for more details:
// d4ae3a16d5e1464574bd04f429a63eb9c02b3b43
Pattern pattern =
- Pattern.compile("^changes_(allOpen|allClosed|byBranchClosed)$",
- Pattern.CASE_INSENSITIVE);
+ Pattern.compile("^changes_(allOpen|allClosed|byBranchClosed)$", Pattern.CASE_INSENSITIVE);
String table = "changes";
- Set<String> listIndexes = dialect.listIndexes(
- schema.getConnection(), table);
+ Set<String> listIndexes = dialect.listIndexes(schema.getConnection(), table);
for (String index : listIndexes) {
if (pattern.matcher(index).matches()) {
dialect.dropIndex(e, table, index);
@@ -56,12 +52,18 @@
dialect.dropIndex(e, table, "changes_byProjectOpen");
if (dialect instanceof DialectPostgreSQL) {
- e.execute("CREATE INDEX changes_byProjectOpen"
- + " ON " + table + " (dest_project_name, last_updated_on)"
- + " WHERE open = 'Y'");
+ e.execute(
+ "CREATE INDEX changes_byProjectOpen"
+ + " ON "
+ + table
+ + " (dest_project_name, last_updated_on)"
+ + " WHERE open = 'Y'");
} else {
- e.execute("CREATE INDEX changes_byProjectOpen"
- + " ON " + table + " (open, dest_project_name, last_updated_on)");
+ e.execute(
+ "CREATE INDEX changes_byProjectOpen"
+ + " ON "
+ + table
+ + " (open, dest_project_name, last_updated_on)");
}
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_105.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_105.java
index 74f0cf5..78ecdbd 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_105.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_105.java
@@ -23,7 +23,6 @@
import com.google.gwtorm.server.StatementExecutor;
import com.google.inject.Inject;
import com.google.inject.Provider;
-
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
@@ -38,8 +37,7 @@
}
@Override
- protected void migrateData(ReviewDb db, UpdateUI ui)
- throws SQLException, OrmException {
+ protected void migrateData(ReviewDb db, UpdateUI ui) throws SQLException, OrmException {
JdbcSchema schema = (JdbcSchema) db;
SqlDialect dialect = schema.getDialect();
@@ -65,25 +63,24 @@
}
}
- private Set<String> listChangesIndexes(JdbcSchema schema)
- throws SQLException {
+ private Set<String> listChangesIndexes(JdbcSchema schema) throws SQLException {
// List of all changes indexes ever created or dropped, found with the
// following command:
// find g* -name \*.sql | xargs git log -i -p -S' index changes_' | grep -io ' index changes_\w*' | cut -d' ' -f3 | tr A-Z a-z | sort -u
// Used rather than listIndexes as we're not sure whether it might include
// primary key indexes.
- Set<String> allChanges = ImmutableSet.of(
- "changes_allclosed",
- "changes_allopen",
- "changes_bybranchclosed",
- "changes_byownerclosed",
- "changes_byowneropen",
- "changes_byproject",
- "changes_byprojectopen",
- "changes_key",
- "changes_submitted");
+ Set<String> allChanges =
+ ImmutableSet.of(
+ "changes_allclosed",
+ "changes_allopen",
+ "changes_bybranchclosed",
+ "changes_byownerclosed",
+ "changes_byowneropen",
+ "changes_byproject",
+ "changes_byprojectopen",
+ "changes_key",
+ "changes_submitted");
return Sets.intersection(
- schema.getDialect().listIndexes(schema.getConnection(), TABLE),
- allChanges);
+ schema.getDialect().listIndexes(schema.getConnection(), TABLE), allChanges);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_106.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_106.java
index 838706e..294c96d 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_106.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_106.java
@@ -25,11 +25,6 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
-
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.lib.PersonIdent;
-import org.eclipse.jgit.lib.Repository;
-
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
@@ -41,6 +36,9 @@
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.lib.PersonIdent;
+import org.eclipse.jgit.lib.Repository;
public class Schema_106 extends SchemaVersion {
// we can use multiple threads per CPU as we can expect that threads will be
@@ -50,7 +48,8 @@
private final PersonIdent serverUser;
@Inject
- Schema_106(Provider<Schema_105> prior,
+ Schema_106(
+ Provider<Schema_105> prior,
GitRepositoryManager repoManager,
@GerritPersonIdent PersonIdent serverUser) {
super(prior);
@@ -68,8 +67,7 @@
SortedSet<Project.NameKey> repoList = repoManager.list();
ui.message("done");
- ui.message(String.format("creating reflog files for %s branches ...",
- RefNames.REFS_CONFIG));
+ ui.message(String.format("creating reflog files for %s branches ...", RefNames.REFS_CONFIG));
ExecutorService executorPool = createExecutor(ui, repoList.size());
List<Future<Void>> futures = new ArrayList<>();
@@ -90,9 +88,10 @@
}
ui.message("done");
} catch (InterruptedException ex) {
- String msg = String.format(
+ String msg =
+ String.format(
"Migration step 106 was interrupted. "
- + "Reflog created in %d of %d repositories only.",
+ + "Reflog created in %d of %d repositories only.",
countDone(futures), repoList.size());
ui.message(msg);
}
@@ -126,21 +125,18 @@
@Override
public Void call() throws IOException {
try (Repository repo = repoManager.openRepository(project)) {
- File metaConfigLog =
- new File(repo.getDirectory(), "logs/" + RefNames.REFS_CONFIG);
+ File metaConfigLog = new File(repo.getDirectory(), "logs/" + RefNames.REFS_CONFIG);
if (metaConfigLog.exists()) {
return null;
}
- if (!metaConfigLog.getParentFile().mkdirs()
- || !metaConfigLog.createNewFile()) {
+ if (!metaConfigLog.getParentFile().mkdirs() || !metaConfigLog.createNewFile()) {
throw new IOException();
}
ObjectId metaConfigId = repo.resolve(RefNames.REFS_CONFIG);
if (metaConfigId != null) {
- try (PrintWriter writer =
- new PrintWriter(metaConfigLog, UTF_8.name())) {
+ try (PrintWriter writer = new PrintWriter(metaConfigLog, UTF_8.name())) {
writer.print(ObjectId.zeroId().name());
writer.print(" ");
writer.print(metaConfigId.name());
@@ -153,10 +149,10 @@
}
return null;
} catch (IOException e) {
- throw new IOException(String.format(
- "ERROR: Failed to create reflog file for the"
- + " %s branch in repository %s", RefNames.REFS_CONFIG,
- project.get()));
+ throw new IOException(
+ String.format(
+ "ERROR: Failed to create reflog file for the" + " %s branch in repository %s",
+ RefNames.REFS_CONFIG, project.get()));
}
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_107.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_107.java
index c2c2305..dd8868f 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_107.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_107.java
@@ -18,7 +18,6 @@
import com.google.gwtorm.jdbc.JdbcSchema;
import com.google.inject.Inject;
import com.google.inject.Provider;
-
import java.sql.SQLException;
import java.sql.Statement;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_108.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_108.java
index d568cba..dc88f8d 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_108.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_108.java
@@ -33,7 +33,11 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
-
+import java.io.IOException;
+import java.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import java.util.SortedSet;
import org.eclipse.jgit.errors.MissingObjectException;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.ObjectId;
@@ -45,18 +49,11 @@
import org.eclipse.jgit.revwalk.RevSort;
import org.eclipse.jgit.revwalk.RevWalk;
-import java.io.IOException;
-import java.util.Collection;
-import java.util.Map;
-import java.util.Set;
-import java.util.SortedSet;
-
public class Schema_108 extends SchemaVersion {
private final GitRepositoryManager repoManager;
@Inject
- Schema_108(Provider<Schema_107> prior,
- GitRepositoryManager repoManager) {
+ Schema_108(Provider<Schema_107> prior, GitRepositoryManager repoManager) {
super(prior);
this.repoManager = repoManager;
}
@@ -64,14 +61,12 @@
@Override
protected void migrateData(ReviewDb db, UpdateUI ui) throws OrmException {
ui.message("Listing all changes ...");
- SetMultimap<Project.NameKey, Change.Id> openByProject =
- getOpenChangesByProject(db, ui);
+ SetMultimap<Project.NameKey, Change.Id> openByProject = getOpenChangesByProject(db, ui);
ui.message("done");
ui.message("Updating groups for open changes ...");
int i = 0;
- for (Map.Entry<Project.NameKey, Collection<Change.Id>> e
- : openByProject.asMap().entrySet()) {
+ for (Map.Entry<Project.NameKey, Collection<Change.Id>> e : openByProject.asMap().entrySet()) {
try (Repository repo = repoManager.openRepository(e.getKey());
RevWalk rw = new RevWalk(repo)) {
updateProjectGroups(db, repo, rw, (Set<Change.Id>) e.getValue(), ui);
@@ -85,8 +80,9 @@
ui.message("done");
}
- private void updateProjectGroups(ReviewDb db, Repository repo, RevWalk rw,
- Set<Change.Id> changes, UpdateUI ui) throws OrmException, IOException {
+ private void updateProjectGroups(
+ ReviewDb db, Repository repo, RevWalk rw, Set<Change.Id> changes, UpdateUI ui)
+ throws OrmException, IOException {
// Match sorting in ReceiveCommits.
rw.reset();
rw.sort(RevSort.TOPO);
@@ -121,8 +117,7 @@
}
}
- GroupCollector collector =
- GroupCollector.createForSchemaUpgradeOnly(changeRefsBySha, db);
+ GroupCollector collector = GroupCollector.createForSchemaUpgradeOnly(changeRefsBySha, db);
RevCommit c;
while ((c = rw.next()) != null) {
collector.visit(c);
@@ -131,12 +126,12 @@
updateGroups(db, collector, patchSetsBySha);
}
- private static void updateGroups(ReviewDb db, GroupCollector collector,
- ListMultimap<ObjectId, PatchSet.Id> patchSetsBySha) throws OrmException {
+ private static void updateGroups(
+ ReviewDb db, GroupCollector collector, ListMultimap<ObjectId, PatchSet.Id> patchSetsBySha)
+ throws OrmException {
Map<PatchSet.Id, PatchSet> patchSets =
db.patchSets().toMap(db.patchSets().get(patchSetsBySha.values()));
- for (Map.Entry<ObjectId, Collection<String>> e
- : collector.getGroups().asMap().entrySet()) {
+ for (Map.Entry<ObjectId, Collection<String>> e : collector.getGroups().asMap().entrySet()) {
for (PatchSet.Id psId : patchSetsBySha.get(e.getKey())) {
PatchSet ps = patchSets.get(psId);
if (ps != null) {
@@ -148,8 +143,8 @@
db.patchSets().update(patchSets.values());
}
- private SetMultimap<Project.NameKey, Change.Id> getOpenChangesByProject(
- ReviewDb db, UpdateUI ui) throws OrmException {
+ private SetMultimap<Project.NameKey, Change.Id> getOpenChangesByProject(ReviewDb db, UpdateUI ui)
+ throws OrmException {
SortedSet<NameKey> projects = repoManager.list();
SortedSet<NameKey> nonExistentProjects = Sets.newTreeSet();
SetMultimap<Project.NameKey, Change.Id> openByProject =
@@ -174,8 +169,9 @@
if (!nonExistentProjects.isEmpty()) {
ui.message("Detected open changes referring to the following non-existent projects:");
ui.message(Joiner.on(", ").join(nonExistentProjects));
- ui.message("It is highly recommended to remove\n"
- + "the obsolete open changes, comments and patch-sets from your DB.\n");
+ ui.message(
+ "It is highly recommended to remove\n"
+ + "the obsolete open changes, comments and patch-sets from your DB.\n");
}
return openByProject;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_115.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_115.java
index 26cd3e1..3c6a50e 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_115.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_115.java
@@ -35,14 +35,6 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
-
-import org.eclipse.jgit.errors.ConfigInvalidException;
-import org.eclipse.jgit.lib.BatchRefUpdate;
-import org.eclipse.jgit.lib.NullProgressMonitor;
-import org.eclipse.jgit.lib.PersonIdent;
-import org.eclipse.jgit.lib.Repository;
-import org.eclipse.jgit.revwalk.RevWalk;
-
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
@@ -52,6 +44,12 @@
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
+import org.eclipse.jgit.errors.ConfigInvalidException;
+import org.eclipse.jgit.lib.BatchRefUpdate;
+import org.eclipse.jgit.lib.NullProgressMonitor;
+import org.eclipse.jgit.lib.PersonIdent;
+import org.eclipse.jgit.lib.Repository;
+import org.eclipse.jgit.revwalk.RevWalk;
public class Schema_115 extends SchemaVersion {
private final GitRepositoryManager mgr;
@@ -59,7 +57,8 @@
private final PersonIdent serverUser;
@Inject
- Schema_115(Provider<Schema_114> prior,
+ Schema_115(
+ Provider<Schema_114> prior,
GitRepositoryManager mgr,
AllUsersName allUsersName,
@GerritPersonIdent PersonIdent serverUser) {
@@ -70,80 +69,78 @@
}
@Override
- protected void migrateData(ReviewDb db, UpdateUI ui)
- throws OrmException, SQLException {
+ protected void migrateData(ReviewDb db, UpdateUI ui) throws OrmException, SQLException {
Map<Account.Id, DiffPreferencesInfo> imports = new HashMap<>();
try (Statement stmt = ((JdbcSchema) db).getConnection().createStatement();
- ResultSet rs = stmt.executeQuery(
- "SELECT * FROM account_diff_preferences")) {
- Set<String> availableColumns = getColumns(rs);
- while (rs.next()) {
- Account.Id accountId = new Account.Id(rs.getInt("id"));
- DiffPreferencesInfo prefs = new DiffPreferencesInfo();
- if (availableColumns.contains("context")) {
- prefs.context = (int)rs.getShort("context");
- }
- if (availableColumns.contains("expand_all_comments")) {
- prefs.expandAllComments = toBoolean(rs.getString("expand_all_comments"));
- }
- if (availableColumns.contains("hide_line_numbers")) {
- prefs.hideLineNumbers = toBoolean(rs.getString("hide_line_numbers"));
- }
- if (availableColumns.contains("hide_top_menu")) {
- prefs.hideTopMenu = toBoolean(rs.getString("hide_top_menu"));
- }
- if (availableColumns.contains("ignore_whitespace")) {
- // Enum with char as value
- prefs.ignoreWhitespace = toWhitespace(rs.getString("ignore_whitespace"));
- }
- if (availableColumns.contains("intraline_difference")) {
- prefs.intralineDifference = toBoolean(rs.getString("intraline_difference"));
- }
- if (availableColumns.contains("line_length")) {
- prefs.lineLength = rs.getInt("line_length");
- }
- if (availableColumns.contains("manual_review")) {
- prefs.manualReview = toBoolean(rs.getString("manual_review"));
- }
- if (availableColumns.contains("render_entire_file")) {
- prefs.renderEntireFile = toBoolean(rs.getString("render_entire_file"));
- }
- if (availableColumns.contains("retain_header")) {
- prefs.retainHeader = toBoolean(rs.getString("retain_header"));
- }
- if (availableColumns.contains("show_line_endings")) {
- prefs.showLineEndings = toBoolean(rs.getString("show_line_endings"));
- }
- if (availableColumns.contains("show_tabs")) {
- prefs.showTabs = toBoolean(rs.getString("show_tabs"));
- }
- if (availableColumns.contains("show_whitespace_errors")) {
- prefs.showWhitespaceErrors = toBoolean(rs.getString("show_whitespace_errors"));
- }
- if (availableColumns.contains("skip_deleted")) {
- prefs.skipDeleted = toBoolean(rs.getString("skip_deleted"));
- }
- if (availableColumns.contains("skip_uncommented")) {
- prefs.skipUncommented = toBoolean(rs.getString("skip_uncommented"));
- }
- if (availableColumns.contains("syntax_highlighting")) {
- prefs.syntaxHighlighting = toBoolean(rs.getString("syntax_highlighting"));
- }
- if (availableColumns.contains("tab_size")) {
- prefs.tabSize = rs.getInt("tab_size");
- }
- if (availableColumns.contains("theme")) {
- // Enum with name as values; can be null
- prefs.theme = toTheme(rs.getString("theme"));
- }
- if (availableColumns.contains("hide_empty_pane")) {
- prefs.hideEmptyPane = toBoolean(rs.getString("hide_empty_pane"));
- }
- if (availableColumns.contains("auto_hide_diff_table_header")) {
- prefs.autoHideDiffTableHeader = toBoolean(rs.getString("auto_hide_diff_table_header"));
- }
- imports.put(accountId, prefs);
+ ResultSet rs = stmt.executeQuery("SELECT * FROM account_diff_preferences")) {
+ Set<String> availableColumns = getColumns(rs);
+ while (rs.next()) {
+ Account.Id accountId = new Account.Id(rs.getInt("id"));
+ DiffPreferencesInfo prefs = new DiffPreferencesInfo();
+ if (availableColumns.contains("context")) {
+ prefs.context = (int) rs.getShort("context");
}
+ if (availableColumns.contains("expand_all_comments")) {
+ prefs.expandAllComments = toBoolean(rs.getString("expand_all_comments"));
+ }
+ if (availableColumns.contains("hide_line_numbers")) {
+ prefs.hideLineNumbers = toBoolean(rs.getString("hide_line_numbers"));
+ }
+ if (availableColumns.contains("hide_top_menu")) {
+ prefs.hideTopMenu = toBoolean(rs.getString("hide_top_menu"));
+ }
+ if (availableColumns.contains("ignore_whitespace")) {
+ // Enum with char as value
+ prefs.ignoreWhitespace = toWhitespace(rs.getString("ignore_whitespace"));
+ }
+ if (availableColumns.contains("intraline_difference")) {
+ prefs.intralineDifference = toBoolean(rs.getString("intraline_difference"));
+ }
+ if (availableColumns.contains("line_length")) {
+ prefs.lineLength = rs.getInt("line_length");
+ }
+ if (availableColumns.contains("manual_review")) {
+ prefs.manualReview = toBoolean(rs.getString("manual_review"));
+ }
+ if (availableColumns.contains("render_entire_file")) {
+ prefs.renderEntireFile = toBoolean(rs.getString("render_entire_file"));
+ }
+ if (availableColumns.contains("retain_header")) {
+ prefs.retainHeader = toBoolean(rs.getString("retain_header"));
+ }
+ if (availableColumns.contains("show_line_endings")) {
+ prefs.showLineEndings = toBoolean(rs.getString("show_line_endings"));
+ }
+ if (availableColumns.contains("show_tabs")) {
+ prefs.showTabs = toBoolean(rs.getString("show_tabs"));
+ }
+ if (availableColumns.contains("show_whitespace_errors")) {
+ prefs.showWhitespaceErrors = toBoolean(rs.getString("show_whitespace_errors"));
+ }
+ if (availableColumns.contains("skip_deleted")) {
+ prefs.skipDeleted = toBoolean(rs.getString("skip_deleted"));
+ }
+ if (availableColumns.contains("skip_uncommented")) {
+ prefs.skipUncommented = toBoolean(rs.getString("skip_uncommented"));
+ }
+ if (availableColumns.contains("syntax_highlighting")) {
+ prefs.syntaxHighlighting = toBoolean(rs.getString("syntax_highlighting"));
+ }
+ if (availableColumns.contains("tab_size")) {
+ prefs.tabSize = rs.getInt("tab_size");
+ }
+ if (availableColumns.contains("theme")) {
+ // Enum with name as values; can be null
+ prefs.theme = toTheme(rs.getString("theme"));
+ }
+ if (availableColumns.contains("hide_empty_pane")) {
+ prefs.hideEmptyPane = toBoolean(rs.getString("hide_empty_pane"));
+ }
+ if (availableColumns.contains("auto_hide_diff_table_header")) {
+ prefs.autoHideDiffTableHeader = toBoolean(rs.getString("auto_hide_diff_table_header"));
+ }
+ imports.put(accountId, prefs);
+ }
}
if (imports.isEmpty()) {
@@ -154,15 +151,18 @@
RevWalk rw = new RevWalk(git)) {
BatchRefUpdate bru = git.getRefDatabase().newBatchUpdate();
for (Map.Entry<Account.Id, DiffPreferencesInfo> e : imports.entrySet()) {
- try (MetaDataUpdate md = new MetaDataUpdate(GitReferenceUpdated.DISABLED,
- allUsersName, git, bru)) {
+ try (MetaDataUpdate md =
+ new MetaDataUpdate(GitReferenceUpdated.DISABLED, allUsersName, git, bru)) {
md.getCommitBuilder().setAuthor(serverUser);
md.getCommitBuilder().setCommitter(serverUser);
- VersionedAccountPreferences p =
- VersionedAccountPreferences.forUser(e.getKey());
+ VersionedAccountPreferences p = VersionedAccountPreferences.forUser(e.getKey());
p.load(md);
- storeSection(p.getConfig(), UserConfigSections.DIFF, null,
- e.getValue(), DiffPreferencesInfo.defaults());
+ storeSection(
+ p.getConfig(),
+ UserConfigSections.DIFF,
+ null,
+ e.getValue(),
+ DiffPreferencesInfo.defaults());
p.commit(md);
}
}
@@ -197,8 +197,7 @@
}
Whitespace r = PatchListKey.WHITESPACE_TYPES.inverse().get(v.charAt(0));
if (r == null) {
- throw new IllegalArgumentException("Cannot find Whitespace type for: "
- + v);
+ throw new IllegalArgumentException("Cannot find Whitespace type for: " + v);
}
return r;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_117.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_117.java
index 6176aeb..35e6c8a 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_117.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_117.java
@@ -19,7 +19,6 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
-
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
@@ -32,21 +31,18 @@
}
@Override
- protected void preUpdateSchema(ReviewDb db)
- throws OrmException, SQLException {
+ protected void preUpdateSchema(ReviewDb db) throws OrmException, SQLException {
JdbcSchema schema = (JdbcSchema) db;
Connection connection = schema.getConnection();
String tableName = "patch_sets";
String oldColumnName = "push_certficate";
String newColumnName = "push_certificate";
- Set<String> columns =
- schema.getDialect().listColumns(connection, tableName);
+ Set<String> columns = schema.getDialect().listColumns(connection, tableName);
if (columns.contains(oldColumnName)) {
renameColumn(db, tableName, oldColumnName, newColumnName);
}
try (Statement stmt = schema.getConnection().createStatement()) {
- stmt.execute(
- "ALTER TABLE " + tableName + " MODIFY " + newColumnName + " clob");
+ stmt.execute("ALTER TABLE " + tableName + " MODIFY " + newColumnName + " clob");
} catch (SQLException e) {
// Ignore. Type may have already been modified manually.
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_119.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_119.java
index cd42e75..0081baa 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_119.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_119.java
@@ -44,14 +44,6 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
-
-import org.eclipse.jgit.errors.ConfigInvalidException;
-import org.eclipse.jgit.lib.BatchRefUpdate;
-import org.eclipse.jgit.lib.NullProgressMonitor;
-import org.eclipse.jgit.lib.PersonIdent;
-import org.eclipse.jgit.lib.Repository;
-import org.eclipse.jgit.revwalk.RevWalk;
-
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
@@ -60,10 +52,16 @@
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
+import org.eclipse.jgit.errors.ConfigInvalidException;
+import org.eclipse.jgit.lib.BatchRefUpdate;
+import org.eclipse.jgit.lib.NullProgressMonitor;
+import org.eclipse.jgit.lib.PersonIdent;
+import org.eclipse.jgit.lib.Repository;
+import org.eclipse.jgit.revwalk.RevWalk;
public class Schema_119 extends SchemaVersion {
private static final Map<String, String> LEGACY_DISPLAYNAME_MAP =
- ImmutableMap.<String, String> of(
+ ImmutableMap.<String, String>of(
"ANON_GIT", ANON_GIT,
"ANON_HTTP", ANON_HTTP,
"HTTP", HTTP,
@@ -75,7 +73,8 @@
private final PersonIdent serverUser;
@Inject
- Schema_119(Provider<Schema_118> prior,
+ Schema_119(
+ Provider<Schema_118> prior,
GitRepositoryManager mgr,
AllUsersName allUsersName,
@GerritPersonIdent PersonIdent serverUser) {
@@ -86,60 +85,56 @@
}
@Override
- protected void migrateData(ReviewDb db, UpdateUI ui)
- throws OrmException, SQLException {
+ protected void migrateData(ReviewDb db, UpdateUI ui) throws OrmException, SQLException {
JdbcSchema schema = (JdbcSchema) db;
Connection connection = schema.getConnection();
String tableName = "accounts";
String emailStrategy = "email_strategy";
- Set<String> columns =
- schema.getDialect().listColumns(connection, tableName);
+ Set<String> columns = schema.getDialect().listColumns(connection, tableName);
Map<Account.Id, GeneralPreferencesInfo> imports = new HashMap<>();
try (Statement stmt = ((JdbcSchema) db).getConnection().createStatement();
- ResultSet rs = stmt.executeQuery(
- "select "
- + "account_id, "
- + "maximum_page_size, "
- + "show_site_header, "
- + "use_flash_clipboard, "
- + "download_url, "
- + "download_command, "
- + (columns.contains(emailStrategy)
- ? emailStrategy + ", "
- : "copy_self_on_email, ")
- + "date_format, "
- + "time_format, "
- + "relative_date_in_change_table, "
- + "diff_view, "
- + "size_bar_in_change_table, "
- + "legacycid_in_change_table, "
- + "review_category_strategy, "
- + "mute_common_path_prefixes "
- + "from " + tableName)) {
- while (rs.next()) {
- GeneralPreferencesInfo p =
- new GeneralPreferencesInfo();
- Account.Id accountId = new Account.Id(rs.getInt(1));
- p.changesPerPage = (int)rs.getShort(2);
- p.showSiteHeader = toBoolean(rs.getString(3));
- p.useFlashClipboard = toBoolean(rs.getString(4));
- p.downloadScheme = convertToModernNames(rs.getString(5));
- p.downloadCommand = toDownloadCommand(rs.getString(6));
- p.emailStrategy = toEmailStrategy(rs.getString(7),
- columns.contains(emailStrategy));
- p.dateFormat = toDateFormat(rs.getString(8));
- p.timeFormat = toTimeFormat(rs.getString(9));
- p.relativeDateInChangeTable = toBoolean(rs.getString(10));
- p.diffView = toDiffView(rs.getString(11));
- p.sizeBarInChangeTable = toBoolean(rs.getString(12));
- p.legacycidInChangeTable = toBoolean(rs.getString(13));
- p.reviewCategoryStrategy =
- toReviewCategoryStrategy(rs.getString(14));
- p.muteCommonPathPrefixes = toBoolean(rs.getString(15));
- p.defaultBaseForMerges =
- GeneralPreferencesInfo.defaults().defaultBaseForMerges;
- imports.put(accountId, p);
- }
+ ResultSet rs =
+ stmt.executeQuery(
+ "select "
+ + "account_id, "
+ + "maximum_page_size, "
+ + "show_site_header, "
+ + "use_flash_clipboard, "
+ + "download_url, "
+ + "download_command, "
+ + (columns.contains(emailStrategy)
+ ? emailStrategy + ", "
+ : "copy_self_on_email, ")
+ + "date_format, "
+ + "time_format, "
+ + "relative_date_in_change_table, "
+ + "diff_view, "
+ + "size_bar_in_change_table, "
+ + "legacycid_in_change_table, "
+ + "review_category_strategy, "
+ + "mute_common_path_prefixes "
+ + "from "
+ + tableName)) {
+ while (rs.next()) {
+ GeneralPreferencesInfo p = new GeneralPreferencesInfo();
+ Account.Id accountId = new Account.Id(rs.getInt(1));
+ p.changesPerPage = (int) rs.getShort(2);
+ p.showSiteHeader = toBoolean(rs.getString(3));
+ p.useFlashClipboard = toBoolean(rs.getString(4));
+ p.downloadScheme = convertToModernNames(rs.getString(5));
+ p.downloadCommand = toDownloadCommand(rs.getString(6));
+ p.emailStrategy = toEmailStrategy(rs.getString(7), columns.contains(emailStrategy));
+ p.dateFormat = toDateFormat(rs.getString(8));
+ p.timeFormat = toTimeFormat(rs.getString(9));
+ p.relativeDateInChangeTable = toBoolean(rs.getString(10));
+ p.diffView = toDiffView(rs.getString(11));
+ p.sizeBarInChangeTable = toBoolean(rs.getString(12));
+ p.legacycidInChangeTable = toBoolean(rs.getString(13));
+ p.reviewCategoryStrategy = toReviewCategoryStrategy(rs.getString(14));
+ p.muteCommonPathPrefixes = toBoolean(rs.getString(15));
+ p.defaultBaseForMerges = GeneralPreferencesInfo.defaults().defaultBaseForMerges;
+ imports.put(accountId, p);
+ }
}
if (imports.isEmpty()) {
@@ -149,17 +144,19 @@
try (Repository git = mgr.openRepository(allUsersName);
RevWalk rw = new RevWalk(git)) {
BatchRefUpdate bru = git.getRefDatabase().newBatchUpdate();
- for (Map.Entry<Account.Id, GeneralPreferencesInfo> e
- : imports.entrySet()) {
- try (MetaDataUpdate md = new MetaDataUpdate(GitReferenceUpdated.DISABLED,
- allUsersName, git, bru)) {
+ for (Map.Entry<Account.Id, GeneralPreferencesInfo> e : imports.entrySet()) {
+ try (MetaDataUpdate md =
+ new MetaDataUpdate(GitReferenceUpdated.DISABLED, allUsersName, git, bru)) {
md.getCommitBuilder().setAuthor(serverUser);
md.getCommitBuilder().setCommitter(serverUser);
- VersionedAccountPreferences p =
- VersionedAccountPreferences.forUser(e.getKey());
+ VersionedAccountPreferences p = VersionedAccountPreferences.forUser(e.getKey());
p.load(md);
- storeSection(p.getConfig(), UserConfigSections.GENERAL, null,
- e.getValue(), GeneralPreferencesInfo.defaults());
+ storeSection(
+ p.getConfig(),
+ UserConfigSections.GENERAL,
+ null,
+ e.getValue(),
+ GeneralPreferencesInfo.defaults());
p.commit(md);
}
}
@@ -204,8 +201,8 @@
return DiffView.valueOf(v);
}
- private static EmailStrategy toEmailStrategy(String v,
- boolean emailStrategyColumnExists) throws OrmException {
+ private static EmailStrategy toEmailStrategy(String v, boolean emailStrategyColumnExists)
+ throws OrmException {
if (v == null) {
return EmailStrategy.ENABLED;
}
@@ -219,8 +216,7 @@
// EMAIL_STRATEGY='CC_ON_OWN_COMMENTS' WHERE (COPY_SELF_ON_EMAIL='Y')
return EmailStrategy.CC_ON_OWN_COMMENTS;
} else {
- throw new OrmException(
- "invalid value in accounts.copy_self_on_email: " + v);
+ throw new OrmException("invalid value in accounts.copy_self_on_email: " + v);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_120.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_120.java
index fc1b0cd..072fc62 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_120.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_120.java
@@ -27,7 +27,10 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
-
+import java.io.IOException;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.lib.BatchRefUpdate;
import org.eclipse.jgit.lib.NullProgressMonitor;
@@ -36,18 +39,14 @@
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.transport.RefSpec;
-import java.io.IOException;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Statement;
-
public class Schema_120 extends SchemaVersion {
private final GitRepositoryManager mgr;
private final PersonIdent serverUser;
@Inject
- Schema_120(Provider<Schema_119> prior,
+ Schema_120(
+ Provider<Schema_119> prior,
GitRepositoryManager mgr,
@GerritPersonIdent PersonIdent serverUser) {
super(prior);
@@ -55,13 +54,13 @@
this.serverUser = serverUser;
}
- private void allowSubmoduleSubscription(Branch.NameKey subbranch,
- Branch.NameKey superBranch) throws OrmException {
+ private void allowSubmoduleSubscription(Branch.NameKey subbranch, Branch.NameKey superBranch)
+ throws OrmException {
try (Repository git = mgr.openRepository(subbranch.getParentKey());
RevWalk rw = new RevWalk(git)) {
BatchRefUpdate bru = git.getRefDatabase().newBatchUpdate();
- try (MetaDataUpdate md = new MetaDataUpdate(GitReferenceUpdated.DISABLED,
- subbranch.getParentKey(), git, bru)) {
+ try (MetaDataUpdate md =
+ new MetaDataUpdate(GitReferenceUpdated.DISABLED, subbranch.getParentKey(), git, bru)) {
md.getCommitBuilder().setAuthor(serverUser);
md.getCommitBuilder().setCommitter(serverUser);
md.setMessage("Added superproject subscription during upgrade");
@@ -94,25 +93,24 @@
}
@Override
- protected void migrateData(ReviewDb db, UpdateUI ui)
- throws OrmException, SQLException {
+ protected void migrateData(ReviewDb db, UpdateUI ui) throws OrmException, SQLException {
ui.message("Generating Superproject subscriptions table to submodule ACLs");
try (Statement stmt = ((JdbcSchema) db).getConnection().createStatement();
- ResultSet rs = stmt.executeQuery("SELECT "
- + "super_project_project_name, "
- + "super_project_branch_name, "
- + "submodule_project_name, "
- + "submodule_branch_name "
- + "FROM submodule_subscriptions")) {
+ ResultSet rs =
+ stmt.executeQuery(
+ "SELECT "
+ + "super_project_project_name, "
+ + "super_project_branch_name, "
+ + "submodule_project_name, "
+ + "submodule_branch_name "
+ + "FROM submodule_subscriptions")) {
while (rs.next()) {
Project.NameKey superproject = new Project.NameKey(rs.getString(1));
- Branch.NameKey superbranch = new Branch.NameKey(superproject,
- rs.getString(2));
+ Branch.NameKey superbranch = new Branch.NameKey(superproject, rs.getString(2));
Project.NameKey submodule = new Project.NameKey(rs.getString(3));
- Branch.NameKey subbranch = new Branch.NameKey(submodule,
- rs.getString(4));
+ Branch.NameKey subbranch = new Branch.NameKey(submodule, rs.getString(4));
allowSubmoduleSubscription(subbranch, superbranch);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_123.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_123.java
index 95c0257..5a0c61d 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_123.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_123.java
@@ -27,7 +27,11 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
-
+import java.io.IOException;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.Map;
import org.eclipse.jgit.lib.BatchRefUpdate;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Repository;
@@ -35,36 +39,25 @@
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.transport.ReceiveCommand;
-import java.io.IOException;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Statement;
-import java.util.Map;
-
public class Schema_123 extends SchemaVersion {
private final GitRepositoryManager repoManager;
private final AllUsersName allUsersName;
@Inject
- Schema_123(Provider<Schema_122> prior,
- GitRepositoryManager repoManager,
- AllUsersName allUsersName) {
+ Schema_123(
+ Provider<Schema_122> prior, GitRepositoryManager repoManager, AllUsersName allUsersName) {
super(prior);
this.repoManager = repoManager;
this.allUsersName = allUsersName;
}
@Override
- protected void migrateData(ReviewDb db, UpdateUI ui)
- throws OrmException, SQLException {
+ protected void migrateData(ReviewDb db, UpdateUI ui) throws OrmException, SQLException {
ListMultimap<Account.Id, Change.Id> imports =
MultimapBuilder.hashKeys().arrayListValues().build();
try (Statement stmt = ((JdbcSchema) db).getConnection().createStatement();
- ResultSet rs = stmt.executeQuery(
- "SELECT "
- + "account_id, "
- + "change_id "
- + "FROM starred_changes")) {
+ ResultSet rs =
+ stmt.executeQuery("SELECT " + "account_id, " + "change_id " + "FROM starred_changes")) {
while (rs.next()) {
Account.Id accountId = new Account.Id(rs.getInt(1));
Change.Id changeId = new Change.Id(rs.getInt(2));
@@ -79,11 +72,11 @@
try (Repository git = repoManager.openRepository(allUsersName);
RevWalk rw = new RevWalk(git)) {
BatchRefUpdate bru = git.getRefDatabase().newBatchUpdate();
- ObjectId id = StarredChangesUtil.writeLabels(git,
- StarredChangesUtil.DEFAULT_LABELS);
+ ObjectId id = StarredChangesUtil.writeLabels(git, StarredChangesUtil.DEFAULT_LABELS);
for (Map.Entry<Account.Id, Change.Id> e : imports.entries()) {
- bru.addCommand(new ReceiveCommand(ObjectId.zeroId(), id,
- RefNames.refsStarredChanges(e.getValue(), e.getKey())));
+ bru.addCommand(
+ new ReceiveCommand(
+ ObjectId.zeroId(), id, RefNames.refsStarredChanges(e.getValue(), e.getKey())));
}
bru.execute(rw, new TextProgressMonitor());
} catch (IOException ex) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_124.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_124.java
index 3dd44cd..7842b65 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_124.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_124.java
@@ -34,14 +34,6 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
-
-import org.eclipse.jgit.errors.ConfigInvalidException;
-import org.eclipse.jgit.lib.BatchRefUpdate;
-import org.eclipse.jgit.lib.NullProgressMonitor;
-import org.eclipse.jgit.lib.PersonIdent;
-import org.eclipse.jgit.lib.Repository;
-import org.eclipse.jgit.revwalk.RevWalk;
-
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
@@ -51,6 +43,12 @@
import java.util.Collections;
import java.util.List;
import java.util.Map;
+import org.eclipse.jgit.errors.ConfigInvalidException;
+import org.eclipse.jgit.lib.BatchRefUpdate;
+import org.eclipse.jgit.lib.NullProgressMonitor;
+import org.eclipse.jgit.lib.PersonIdent;
+import org.eclipse.jgit.lib.Repository;
+import org.eclipse.jgit.revwalk.RevWalk;
public class Schema_124 extends SchemaVersion {
private final GitRepositoryManager repoManager;
@@ -58,7 +56,8 @@
private final PersonIdent serverUser;
@Inject
- Schema_124(Provider<Schema_123> prior,
+ Schema_124(
+ Provider<Schema_123> prior,
GitRepositoryManager repoManager,
AllUsersName allUsersName,
@GerritPersonIdent PersonIdent serverUser) {
@@ -69,24 +68,23 @@
}
@Override
- protected void migrateData(ReviewDb db, UpdateUI ui)
- throws OrmException, SQLException {
+ protected void migrateData(ReviewDb db, UpdateUI ui) throws OrmException, SQLException {
ListMultimap<Account.Id, AccountSshKey> imports =
MultimapBuilder.hashKeys().arrayListValues().build();
try (Statement stmt = ((JdbcSchema) db).getConnection().createStatement();
- ResultSet rs = stmt.executeQuery(
- "SELECT "
- + "account_id, "
- + "seq, "
- + "ssh_public_key, "
- + "valid "
- + "FROM account_ssh_keys")) {
+ ResultSet rs =
+ stmt.executeQuery(
+ "SELECT "
+ + "account_id, "
+ + "seq, "
+ + "ssh_public_key, "
+ + "valid "
+ + "FROM account_ssh_keys")) {
while (rs.next()) {
Account.Id accountId = new Account.Id(rs.getInt(1));
int seq = rs.getInt(2);
String sshPublicKey = rs.getString(3);
- AccountSshKey key = new AccountSshKey(
- new AccountSshKey.Id(accountId, seq), sshPublicKey);
+ AccountSshKey key = new AccountSshKey(new AccountSshKey.Id(accountId, seq), sshPublicKey);
boolean valid = toBoolean(rs.getString(4));
if (!valid) {
key.setInvalid();
@@ -103,15 +101,14 @@
RevWalk rw = new RevWalk(git)) {
BatchRefUpdate bru = git.getRefDatabase().newBatchUpdate();
- for (Map.Entry<Account.Id, Collection<AccountSshKey>> e : imports.asMap()
- .entrySet()) {
- try (MetaDataUpdate md = new MetaDataUpdate(
- GitReferenceUpdated.DISABLED, allUsersName, git, bru)) {
+ for (Map.Entry<Account.Id, Collection<AccountSshKey>> e : imports.asMap().entrySet()) {
+ try (MetaDataUpdate md =
+ new MetaDataUpdate(GitReferenceUpdated.DISABLED, allUsersName, git, bru)) {
md.getCommitBuilder().setAuthor(serverUser);
md.getCommitBuilder().setCommitter(serverUser);
- VersionedAuthorizedKeys authorizedKeys = new VersionedAuthorizedKeys(
- new SimpleSshKeyCreator(), e.getKey());
+ VersionedAuthorizedKeys authorizedKeys =
+ new VersionedAuthorizedKeys(new SimpleSshKeyCreator(), e.getKey());
authorizedKeys.load(md);
authorizedKeys.setKeys(fixInvalidSequenceNumbers(e.getValue()));
authorizedKeys.commit(md);
@@ -124,16 +121,16 @@
}
}
- private Collection<AccountSshKey> fixInvalidSequenceNumbers(
- Collection<AccountSshKey> keys) {
+ private Collection<AccountSshKey> fixInvalidSequenceNumbers(Collection<AccountSshKey> keys) {
Ordering<AccountSshKey> o = Ordering.from(comparing(k -> k.getKey().get()));
List<AccountSshKey> fixedKeys = new ArrayList<>(keys);
AccountSshKey minKey = o.min(keys);
while (minKey.getKey().get() <= 0) {
- AccountSshKey fixedKey = new AccountSshKey(
- new AccountSshKey.Id(minKey.getKey().getParentKey(),
- Math.max(o.max(keys).getKey().get() + 1, 1)),
- minKey.getSshPublicKey());
+ AccountSshKey fixedKey =
+ new AccountSshKey(
+ new AccountSshKey.Id(
+ minKey.getKey().getParentKey(), Math.max(o.max(keys).getKey().get() + 1, 1)),
+ minKey.getSshPublicKey());
Collections.replaceAll(fixedKeys, minKey, fixedKey);
minKey = o.min(fixedKeys);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_125.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_125.java
index 5adfef2..947c115 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_125.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_125.java
@@ -36,24 +36,22 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
-
-import org.eclipse.jgit.errors.ConfigInvalidException;
-import org.eclipse.jgit.lib.PersonIdent;
-import org.eclipse.jgit.lib.Repository;
-
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
+import org.eclipse.jgit.errors.ConfigInvalidException;
+import org.eclipse.jgit.lib.PersonIdent;
+import org.eclipse.jgit.lib.Repository;
public class Schema_125 extends SchemaVersion {
private static final String COMMIT_MSG =
- "Assign default permissions on user branches\n" +
- "\n" +
- "By default each user should be able to read and update the own user\n" +
- "branch. Also the user should be able to approve and submit changes for\n" +
- "the own user branch. Assign default permissions for this and remove the\n" +
- "old exclusive read protection from the user branches.\n";
+ "Assign default permissions on user branches\n"
+ + "\n"
+ + "By default each user should be able to read and update the own user\n"
+ + "branch. Also the user should be able to approve and submit changes for\n"
+ + "the own user branch. Assign default permissions for this and remove the\n"
+ + "old exclusive read protection from the user branches.\n";
private final GitRepositoryManager repoManager;
private final AllUsersName allUsersName;
@@ -62,7 +60,8 @@
private final PersonIdent serverUser;
@Inject
- Schema_125(Provider<Schema_124> prior,
+ Schema_125(
+ Provider<Schema_124> prior,
GitRepositoryManager repoManager,
AllUsersName allUsersName,
AllProjectsName allProjectsName,
@@ -79,24 +78,23 @@
@Override
protected void migrateData(ReviewDb db, UpdateUI ui) throws OrmException {
try (Repository git = repoManager.openRepository(allUsersName);
- MetaDataUpdate md = new MetaDataUpdate(GitReferenceUpdated.DISABLED,
- allUsersName, git)) {
+ MetaDataUpdate md = new MetaDataUpdate(GitReferenceUpdated.DISABLED, allUsersName, git)) {
ProjectConfig config = ProjectConfig.read(md);
- config.getAccessSection(RefNames.REFS_USERS + "*", true)
+ config
+ .getAccessSection(RefNames.REFS_USERS + "*", true)
.remove(new Permission(Permission.READ));
GroupReference registered = systemGroupBackend.getGroup(REGISTERED_USERS);
- AccessSection users = config.getAccessSection(
- RefNames.REFS_USERS + "${" + RefPattern.USERID_SHARDED + "}", true);
+ AccessSection users =
+ config.getAccessSection(
+ RefNames.REFS_USERS + "${" + RefPattern.USERID_SHARDED + "}", true);
grant(config, users, Permission.READ, true, registered);
grant(config, users, Permission.PUSH, true, registered);
grant(config, users, Permission.SUBMIT, true, registered);
for (LabelType lt : getLabelTypes(config)) {
- if ("Code-Review".equals(lt.getName())
- || "Verified".equals(lt.getName())) {
- grant(config, users, lt, lt.getMin().getValue(),
- lt.getMax().getValue(), registered);
+ if ("Code-Review".equals(lt.getName()) || "Verified".equals(lt.getName())) {
+ grant(config, users, lt, lt.getMin().getValue(), lt.getMax().getValue(), registered);
}
}
@@ -111,13 +109,11 @@
private Collection<LabelType> getLabelTypes(ProjectConfig config)
throws IOException, ConfigInvalidException {
- Map<String, LabelType> labelTypes =
- new HashMap<>(config.getLabelSections());
+ Map<String, LabelType> labelTypes = new HashMap<>(config.getLabelSections());
Project.NameKey parent = config.getProject().getParent(allProjectsName);
while (parent != null) {
try (Repository git = repoManager.openRepository(parent);
- MetaDataUpdate md =
- new MetaDataUpdate(GitReferenceUpdated.DISABLED, parent, git)) {
+ MetaDataUpdate md = new MetaDataUpdate(GitReferenceUpdated.DISABLED, parent, git)) {
ProjectConfig parentConfig = ProjectConfig.read(md);
for (LabelType lt : parentConfig.getLabelSections().values()) {
if (!labelTypes.containsKey(lt.getName())) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_126.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_126.java
index b26ce41..2053c1a 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_126.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_126.java
@@ -33,16 +33,13 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
-
+import java.io.IOException;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.lib.PersonIdent;
import org.eclipse.jgit.lib.Repository;
-import java.io.IOException;
-
public class Schema_126 extends SchemaVersion {
- private static final String COMMIT_MSG =
- "Fix default permissions on user branches";
+ private static final String COMMIT_MSG = "Fix default permissions on user branches";
private final GitRepositoryManager repoManager;
private final AllUsersName allUsersName;
@@ -50,7 +47,8 @@
private final PersonIdent serverUser;
@Inject
- Schema_126(Provider<Schema_125> prior,
+ Schema_126(
+ Provider<Schema_125> prior,
GitRepositoryManager repoManager,
AllUsersName allUsersName,
SystemGroupBackend systemGroupBackend,
@@ -65,12 +63,10 @@
@Override
protected void migrateData(ReviewDb db, UpdateUI ui) throws OrmException {
try (Repository git = repoManager.openRepository(allUsersName);
- MetaDataUpdate md = new MetaDataUpdate(GitReferenceUpdated.DISABLED,
- allUsersName, git)) {
+ MetaDataUpdate md = new MetaDataUpdate(GitReferenceUpdated.DISABLED, allUsersName, git)) {
ProjectConfig config = ProjectConfig.read(md);
- String refsUsersShardedId =
- RefNames.REFS_USERS + "${" + RefPattern.USERID_SHARDED + "}";
+ String refsUsersShardedId = RefNames.REFS_USERS + "${" + RefPattern.USERID_SHARDED + "}";
config.remove(config.getAccessSection(refsUsersShardedId));
GroupReference registered = systemGroupBackend.getGroup(REGISTERED_USERS);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_127.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_127.java
index 783cce6..75cdef7 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_127.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_127.java
@@ -19,7 +19,6 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
-
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
@@ -45,13 +44,14 @@
H2AccountPatchReviewStore.createTableIfNotExists(url);
try (Connection con = DriverManager.getConnection(url);
PreparedStatement stmt =
- con.prepareStatement("INSERT INTO account_patch_reviews "
- + "(account_id, change_id, patch_set_id, file_name) VALUES "
- + "(?, ?, ?, ?)")) {
+ con.prepareStatement(
+ "INSERT INTO account_patch_reviews "
+ + "(account_id, change_id, patch_set_id, file_name) VALUES "
+ + "(?, ?, ?, ?)")) {
int batchCount = 0;
try (Statement s = newStatement(db);
- ResultSet rs = s.executeQuery("SELECT * from account_patch_reviews")) {
+ ResultSet rs = s.executeQuery("SELECT * from account_patch_reviews")) {
while (rs.next()) {
stmt.setInt(1, rs.getInt("account_id"));
stmt.setInt(2, rs.getInt("change_id"));
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_128.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_128.java
index d45d92c..781f281 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_128.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_128.java
@@ -31,16 +31,13 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
-
+import java.io.IOException;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.lib.PersonIdent;
import org.eclipse.jgit.lib.Repository;
-import java.io.IOException;
-
public class Schema_128 extends SchemaVersion {
- private static final String COMMIT_MSG =
- "Add addPatchSet permission to all projects";
+ private static final String COMMIT_MSG = "Add addPatchSet permission to all projects";
private final GitRepositoryManager repoManager;
private final AllProjectsName allProjectsName;
@@ -48,7 +45,8 @@
private final PersonIdent serverUser;
@Inject
- Schema_128(Provider<Schema_127> prior,
+ Schema_128(
+ Provider<Schema_127> prior,
GitRepositoryManager repoManager,
AllProjectsName allProjectsName,
SystemGroupBackend systemGroupBackend,
@@ -63,14 +61,13 @@
@Override
protected void migrateData(ReviewDb db, UpdateUI ui) throws OrmException {
try (Repository git = repoManager.openRepository(allProjectsName);
- MetaDataUpdate md = new MetaDataUpdate(GitReferenceUpdated.DISABLED,
- allProjectsName, git)) {
+ MetaDataUpdate md =
+ new MetaDataUpdate(GitReferenceUpdated.DISABLED, allProjectsName, git)) {
ProjectConfig config = ProjectConfig.read(md);
GroupReference registered = systemGroupBackend.getGroup(REGISTERED_USERS);
AccessSection refsFor = config.getAccessSection("refs/for/*", true);
- grant(config, refsFor, Permission.ADD_PATCH_SET,
- false, false, registered);
+ grant(config, refsFor, Permission.ADD_PATCH_SET, false, false, registered);
md.getCommitBuilder().setAuthor(serverUser);
md.getCommitBuilder().setCommitter(serverUser);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_129.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_129.java
index de02ec7..73ce3c3 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_129.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_129.java
@@ -19,7 +19,6 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
-
import java.sql.SQLException;
import java.sql.Statement;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_130.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_130.java
index 5dcd981..5971c7b 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_130.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_130.java
@@ -23,28 +23,27 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
-
-import org.eclipse.jgit.errors.ConfigInvalidException;
-import org.eclipse.jgit.lib.PersonIdent;
-import org.eclipse.jgit.lib.Repository;
-
import java.io.IOException;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.stream.Collectors;
+import org.eclipse.jgit.errors.ConfigInvalidException;
+import org.eclipse.jgit.lib.PersonIdent;
+import org.eclipse.jgit.lib.Repository;
public class Schema_130 extends SchemaVersion {
private static final String COMMIT_MSG =
"Remove force option from 'Push Annotated Tag' permission\n"
- + "\n"
- + "The force option on 'Push Annotated Tag' had no effect and is no longer\n"
- + "supported.";
+ + "\n"
+ + "The force option on 'Push Annotated Tag' had no effect and is no longer\n"
+ + "supported.";
private final GitRepositoryManager repoManager;
private final PersonIdent serverUser;
@Inject
- Schema_130(Provider<Schema_129> prior,
+ Schema_130(
+ Provider<Schema_129> prior,
GitRepositoryManager repoManager,
@GerritPersonIdent PersonIdent serverUser) {
super(prior);
@@ -59,8 +58,7 @@
ui.message("\tMigrating " + repoList.size() + " repositories ...");
for (Project.NameKey projectName : repoList) {
try (Repository git = repoManager.openRepository(projectName);
- MetaDataUpdate md = new MetaDataUpdate(GitReferenceUpdated.DISABLED,
- projectName, git)) {
+ MetaDataUpdate md = new MetaDataUpdate(GitReferenceUpdated.DISABLED, projectName, git)) {
ProjectConfigSchemaUpdate cfg = ProjectConfigSchemaUpdate.read(md);
cfg.removeForceFromPermission("pushTag");
if (cfg.isUpdated()) {
@@ -71,10 +69,7 @@
throw new OrmException("Cannot migrate project " + projectName, ex);
}
}
- ui.message("\tMigration completed: " + repoUpgraded.size()
- + " repositories updated:");
- ui.message("\t"
- + repoUpgraded.stream().map(n -> n.get())
- .collect(Collectors.joining(" ")));
+ ui.message("\tMigration completed: " + repoUpgraded.size() + " repositories updated:");
+ ui.message("\t" + repoUpgraded.stream().map(n -> n.get()).collect(Collectors.joining(" ")));
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_131.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_131.java
index 4e581c8..725e813 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_131.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_131.java
@@ -24,15 +24,13 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
-
-import org.eclipse.jgit.errors.ConfigInvalidException;
-import org.eclipse.jgit.lib.PersonIdent;
-import org.eclipse.jgit.lib.Repository;
-
import java.io.IOException;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.stream.Collectors;
+import org.eclipse.jgit.errors.ConfigInvalidException;
+import org.eclipse.jgit.lib.PersonIdent;
+import org.eclipse.jgit.lib.Repository;
public class Schema_131 extends SchemaVersion {
private static final String COMMIT_MSG =
@@ -42,7 +40,8 @@
private final PersonIdent serverUser;
@Inject
- Schema_131(Provider<Schema_130> prior,
+ Schema_131(
+ Provider<Schema_130> prior,
GitRepositoryManager repoManager,
@GerritPersonIdent PersonIdent serverUser) {
super(prior);
@@ -57,8 +56,7 @@
ui.message("\tMigrating " + repoList.size() + " repositories ...");
for (Project.NameKey projectName : repoList) {
try (Repository git = repoManager.openRepository(projectName);
- MetaDataUpdate md = new MetaDataUpdate(GitReferenceUpdated.DISABLED,
- projectName, git)) {
+ MetaDataUpdate md = new MetaDataUpdate(GitReferenceUpdated.DISABLED, projectName, git)) {
ProjectConfig config = ProjectConfig.read(md);
if (config.hasLegacyPermissions()) {
md.getCommitBuilder().setAuthor(serverUser);
@@ -71,10 +69,7 @@
throw new OrmException("Cannot migrate project " + projectName, ex);
}
}
- ui.message("\tMigration completed: " + repoUpgraded.size()
- + " repositories updated:");
- ui.message("\t"
- + repoUpgraded.stream().map(n -> n.get())
- .collect(Collectors.joining(" ")));
+ ui.message("\tMigration completed: " + repoUpgraded.size() + " repositories updated:");
+ ui.message("\t" + repoUpgraded.stream().map(n -> n.get()).collect(Collectors.joining(" ")));
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_135.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_135.java
index 08b2366..8e4d2e4 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_135.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_135.java
@@ -34,14 +34,12 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
-
-import org.eclipse.jgit.errors.ConfigInvalidException;
-import org.eclipse.jgit.lib.PersonIdent;
-import org.eclipse.jgit.lib.Repository;
-
import java.io.IOException;
import java.util.Set;
import java.util.stream.Stream;
+import org.eclipse.jgit.errors.ConfigInvalidException;
+import org.eclipse.jgit.lib.PersonIdent;
+import org.eclipse.jgit.lib.Repository;
public class Schema_135 extends SchemaVersion {
private static final String COMMIT_MSG =
@@ -53,7 +51,8 @@
private final PersonIdent serverUser;
@Inject
- Schema_135(Provider<Schema_134> prior,
+ Schema_135(
+ Provider<Schema_134> prior,
GitRepositoryManager repoManager,
AllProjectsName allProjectsName,
SystemGroupBackend systemGroupBackend,
@@ -68,13 +67,12 @@
@Override
protected void migrateData(ReviewDb db, UpdateUI ui) throws OrmException {
try (Repository git = repoManager.openRepository(allProjectsName);
- MetaDataUpdate md = new MetaDataUpdate(GitReferenceUpdated.DISABLED,
- allProjectsName, git)) {
+ MetaDataUpdate md =
+ new MetaDataUpdate(GitReferenceUpdated.DISABLED, allProjectsName, git)) {
ProjectConfig config = ProjectConfig.read(md);
AccessSection meta = config.getAccessSection(RefNames.REFS_CONFIG, true);
- Permission createRefsMetaConfigPermission =
- meta.getPermission(Permission.CREATE, true);
+ Permission createRefsMetaConfigPermission = meta.getPermission(Permission.CREATE, true);
Set<GroupReference> groups =
Stream.concat(
@@ -89,8 +87,7 @@
.collect(toSet());
for (GroupReference group : groups) {
- createRefsMetaConfigPermission
- .add(new PermissionRule(config.resolve(group)));
+ createRefsMetaConfigPermission.add(new PermissionRule(config.resolve(group)));
}
md.getCommitBuilder().setAuthor(serverUser);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_139.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_139.java
index 614320b..be919a1 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_139.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_139.java
@@ -34,14 +34,6 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
-
-import org.eclipse.jgit.errors.ConfigInvalidException;
-import org.eclipse.jgit.lib.BatchRefUpdate;
-import org.eclipse.jgit.lib.NullProgressMonitor;
-import org.eclipse.jgit.lib.PersonIdent;
-import org.eclipse.jgit.lib.Repository;
-import org.eclipse.jgit.revwalk.RevWalk;
-
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
@@ -51,137 +43,157 @@
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
+import org.eclipse.jgit.errors.ConfigInvalidException;
+import org.eclipse.jgit.lib.BatchRefUpdate;
+import org.eclipse.jgit.lib.NullProgressMonitor;
+import org.eclipse.jgit.lib.PersonIdent;
+import org.eclipse.jgit.lib.Repository;
+import org.eclipse.jgit.revwalk.RevWalk;
public class Schema_139 extends SchemaVersion {
- private static final String MSG = "Migrate project watches to git";
+ private static final String MSG = "Migrate project watches to git";
- private final GitRepositoryManager repoManager;
- private final AllUsersName allUsersName;
- private final PersonIdent serverUser;
+ private final GitRepositoryManager repoManager;
+ private final AllUsersName allUsersName;
+ private final PersonIdent serverUser;
- @Inject
- Schema_139(Provider<Schema_138> prior,
- GitRepositoryManager repoManager,
- AllUsersName allUsersName,
- @GerritPersonIdent PersonIdent serverUser) {
- super(prior);
- this.repoManager = repoManager;
- this.allUsersName = allUsersName;
- this.serverUser = serverUser;
- }
+ @Inject
+ Schema_139(
+ Provider<Schema_138> prior,
+ GitRepositoryManager repoManager,
+ AllUsersName allUsersName,
+ @GerritPersonIdent PersonIdent serverUser) {
+ super(prior);
+ this.repoManager = repoManager;
+ this.allUsersName = allUsersName;
+ this.serverUser = serverUser;
+ }
- @Override
- protected void migrateData(ReviewDb db, UpdateUI ui)
- throws OrmException, SQLException {
- ListMultimap<Account.Id, ProjectWatch> imports =
- MultimapBuilder.hashKeys().arrayListValues().build();
- try (Statement stmt = ((JdbcSchema) db).getConnection().createStatement();
- ResultSet rs = stmt.executeQuery(
- "SELECT "
- + "account_id, "
- + "project_name, "
- + "filter, "
- + "notify_abandoned_changes, "
- + "notify_all_comments, "
- + "notify_new_changes, "
- + "notify_new_patch_sets, "
- + "notify_submitted_changes "
- + "FROM account_project_watches")) {
- while (rs.next()) {
- Account.Id accountId = new Account.Id(rs.getInt(1));
- ProjectWatch.Builder b = ProjectWatch.builder()
- .project(new Project.NameKey(rs.getString(2)))
- .filter(rs.getString(3))
- .notifyAbandonedChanges(rs.getBoolean(4))
- .notifyAllComments(rs.getBoolean(5))
- .notifyNewChanges(rs.getBoolean(6))
- .notifyNewPatchSets(rs.getBoolean(7))
- .notifySubmittedChanges(rs.getBoolean(8));
- imports.put(accountId, b.build());
- }
- }
+ @Override
+ protected void migrateData(ReviewDb db, UpdateUI ui) throws OrmException, SQLException {
+ ListMultimap<Account.Id, ProjectWatch> imports =
+ MultimapBuilder.hashKeys().arrayListValues().build();
+ try (Statement stmt = ((JdbcSchema) db).getConnection().createStatement();
+ ResultSet rs =
+ stmt.executeQuery(
+ "SELECT "
+ + "account_id, "
+ + "project_name, "
+ + "filter, "
+ + "notify_abandoned_changes, "
+ + "notify_all_comments, "
+ + "notify_new_changes, "
+ + "notify_new_patch_sets, "
+ + "notify_submitted_changes "
+ + "FROM account_project_watches")) {
+ while (rs.next()) {
+ Account.Id accountId = new Account.Id(rs.getInt(1));
+ ProjectWatch.Builder b =
+ ProjectWatch.builder()
+ .project(new Project.NameKey(rs.getString(2)))
+ .filter(rs.getString(3))
+ .notifyAbandonedChanges(rs.getBoolean(4))
+ .notifyAllComments(rs.getBoolean(5))
+ .notifyNewChanges(rs.getBoolean(6))
+ .notifyNewPatchSets(rs.getBoolean(7))
+ .notifySubmittedChanges(rs.getBoolean(8));
+ imports.put(accountId, b.build());
+ }
+ }
- if (imports.isEmpty()) {
- return;
- }
+ if (imports.isEmpty()) {
+ return;
+ }
- try (Repository git = repoManager.openRepository(allUsersName);
- RevWalk rw = new RevWalk(git)) {
- BatchRefUpdate bru = git.getRefDatabase().newBatchUpdate();
- bru.setRefLogIdent(serverUser);
- bru.setRefLogMessage(MSG, false);
+ try (Repository git = repoManager.openRepository(allUsersName);
+ RevWalk rw = new RevWalk(git)) {
+ BatchRefUpdate bru = git.getRefDatabase().newBatchUpdate();
+ bru.setRefLogIdent(serverUser);
+ bru.setRefLogMessage(MSG, false);
- for (Map.Entry<Account.Id, Collection<ProjectWatch>> e : imports.asMap()
- .entrySet()) {
- Map<ProjectWatchKey, Set<NotifyType>> projectWatches = new HashMap<>();
- for (ProjectWatch projectWatch : e.getValue()) {
- ProjectWatchKey key = ProjectWatchKey.create(projectWatch.project(),
- projectWatch.filter());
- if (projectWatches.containsKey(key)) {
- throw new OrmDuplicateKeyException(
- "Duplicate key for watched project: " + key.toString());
- }
- Set<NotifyType> notifyValues = EnumSet.noneOf(NotifyType.class);
- if (projectWatch.notifyAbandonedChanges()) {
- notifyValues.add(NotifyType.ABANDONED_CHANGES);
- }
- if (projectWatch.notifyAllComments()) {
- notifyValues.add(NotifyType.ALL_COMMENTS);
- }
- if (projectWatch.notifyNewChanges()) {
- notifyValues.add(NotifyType.NEW_CHANGES);
- }
- if (projectWatch.notifyNewPatchSets()) {
- notifyValues.add(NotifyType.NEW_PATCHSETS);
- }
- if (projectWatch.notifySubmittedChanges()) {
- notifyValues.add(NotifyType.SUBMITTED_CHANGES);
- }
- projectWatches.put(key, notifyValues);
- }
+ for (Map.Entry<Account.Id, Collection<ProjectWatch>> e : imports.asMap().entrySet()) {
+ Map<ProjectWatchKey, Set<NotifyType>> projectWatches = new HashMap<>();
+ for (ProjectWatch projectWatch : e.getValue()) {
+ ProjectWatchKey key =
+ ProjectWatchKey.create(projectWatch.project(), projectWatch.filter());
+ if (projectWatches.containsKey(key)) {
+ throw new OrmDuplicateKeyException(
+ "Duplicate key for watched project: " + key.toString());
+ }
+ Set<NotifyType> notifyValues = EnumSet.noneOf(NotifyType.class);
+ if (projectWatch.notifyAbandonedChanges()) {
+ notifyValues.add(NotifyType.ABANDONED_CHANGES);
+ }
+ if (projectWatch.notifyAllComments()) {
+ notifyValues.add(NotifyType.ALL_COMMENTS);
+ }
+ if (projectWatch.notifyNewChanges()) {
+ notifyValues.add(NotifyType.NEW_CHANGES);
+ }
+ if (projectWatch.notifyNewPatchSets()) {
+ notifyValues.add(NotifyType.NEW_PATCHSETS);
+ }
+ if (projectWatch.notifySubmittedChanges()) {
+ notifyValues.add(NotifyType.SUBMITTED_CHANGES);
+ }
+ projectWatches.put(key, notifyValues);
+ }
- try (MetaDataUpdate md = new MetaDataUpdate(GitReferenceUpdated.DISABLED,
- allUsersName, git, bru)) {
- md.getCommitBuilder().setAuthor(serverUser);
- md.getCommitBuilder().setCommitter(serverUser);
- md.setMessage(MSG);
+ try (MetaDataUpdate md =
+ new MetaDataUpdate(GitReferenceUpdated.DISABLED, allUsersName, git, bru)) {
+ md.getCommitBuilder().setAuthor(serverUser);
+ md.getCommitBuilder().setCommitter(serverUser);
+ md.setMessage(MSG);
- WatchConfig watchConfig = new WatchConfig(e.getKey());
- watchConfig.load(md);
- watchConfig.setProjectWatches(projectWatches);
- watchConfig.commit(md);
- }
- }
- bru.execute(rw, NullProgressMonitor.INSTANCE);
- } catch (IOException | ConfigInvalidException ex) {
- throw new OrmException(ex);
- }
- }
+ WatchConfig watchConfig = new WatchConfig(e.getKey());
+ watchConfig.load(md);
+ watchConfig.setProjectWatches(projectWatches);
+ watchConfig.commit(md);
+ }
+ }
+ bru.execute(rw, NullProgressMonitor.INSTANCE);
+ } catch (IOException | ConfigInvalidException ex) {
+ throw new OrmException(ex);
+ }
+ }
- @AutoValue
- abstract static class ProjectWatch {
- abstract Project.NameKey project();
- abstract @Nullable String filter();
- abstract boolean notifyAbandonedChanges();
- abstract boolean notifyAllComments();
- abstract boolean notifyNewChanges();
- abstract boolean notifyNewPatchSets();
- abstract boolean notifySubmittedChanges();
+ @AutoValue
+ abstract static class ProjectWatch {
+ abstract Project.NameKey project();
- static Builder builder() {
- return new AutoValue_Schema_139_ProjectWatch.Builder();
- }
+ abstract @Nullable String filter();
- @AutoValue.Builder
- abstract static class Builder {
- abstract Builder project(Project.NameKey project);
- abstract Builder filter(@Nullable String filter);
- abstract Builder notifyAbandonedChanges(boolean notifyAbandonedChanges);
- abstract Builder notifyAllComments(boolean notifyAllComments);
- abstract Builder notifyNewChanges(boolean notifyNewChanges);
- abstract Builder notifyNewPatchSets(boolean notifyNewPatchSets);
- abstract Builder notifySubmittedChanges(boolean notifySubmittedChanges);
- abstract ProjectWatch build();
- }
- }
+ abstract boolean notifyAbandonedChanges();
+
+ abstract boolean notifyAllComments();
+
+ abstract boolean notifyNewChanges();
+
+ abstract boolean notifyNewPatchSets();
+
+ abstract boolean notifySubmittedChanges();
+
+ static Builder builder() {
+ return new AutoValue_Schema_139_ProjectWatch.Builder();
+ }
+
+ @AutoValue.Builder
+ abstract static class Builder {
+ abstract Builder project(Project.NameKey project);
+
+ abstract Builder filter(@Nullable String filter);
+
+ abstract Builder notifyAbandonedChanges(boolean notifyAbandonedChanges);
+
+ abstract Builder notifyAllComments(boolean notifyAllComments);
+
+ abstract Builder notifyNewChanges(boolean notifyNewChanges);
+
+ abstract Builder notifyNewPatchSets(boolean notifyNewPatchSets);
+
+ abstract Builder notifySubmittedChanges(boolean notifySubmittedChanges);
+
+ abstract ProjectWatch build();
+ }
+ }
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_83.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_83.java
index f703a35..decbfb1 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_83.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_83.java
@@ -22,11 +22,12 @@
@Inject
Schema_83() {
- super(new Provider<SchemaVersion>() {
- @Override
- public SchemaVersion get() {
- throw new ProvisionException("Upgrade first to 2.8 or 2.9");
- }
- });
+ super(
+ new Provider<SchemaVersion>() {
+ @Override
+ public SchemaVersion get() {
+ throw new ProvisionException("Upgrade first to 2.8 or 2.9");
+ }
+ });
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_87.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_87.java
index 8f4028d..8ab949e 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_87.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_87.java
@@ -20,7 +20,6 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
-
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
@@ -35,24 +34,20 @@
}
@Override
- protected void migrateData(ReviewDb db, UpdateUI ui)
- throws OrmException, SQLException {
+ protected void migrateData(ReviewDb db, UpdateUI ui) throws OrmException, SQLException {
for (AccountGroup.Id id : scanSystemGroups(db)) {
AccountGroup group = db.accountGroups().get(id);
- if (group != null
- && SystemGroupBackend.isSystemGroup(group.getGroupUUID())) {
+ if (group != null && SystemGroupBackend.isSystemGroup(group.getGroupUUID())) {
db.accountGroups().delete(Collections.singleton(group));
- db.accountGroupNames().deleteKeys(
- Collections.singleton(group.getNameKey()));
+ db.accountGroupNames().deleteKeys(Collections.singleton(group.getNameKey()));
}
}
}
- private Set<AccountGroup.Id> scanSystemGroups(ReviewDb db)
- throws SQLException {
+ private Set<AccountGroup.Id> scanSystemGroups(ReviewDb db) throws SQLException {
try (Statement stmt = newStatement(db);
- ResultSet rs = stmt.executeQuery(
- "SELECT group_id FROM account_groups WHERE group_type = 'SYSTEM'")) {
+ ResultSet rs =
+ stmt.executeQuery("SELECT group_id FROM account_groups WHERE group_type = 'SYSTEM'")) {
Set<AccountGroup.Id> ids = new HashSet<>();
while (rs.next()) {
ids.add(new AccountGroup.Id(rs.getInt(1)));
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_89.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_89.java
index a818e0d..de84993 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_89.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_89.java
@@ -21,7 +21,6 @@
import com.google.gwtorm.server.StatementExecutor;
import com.google.inject.Inject;
import com.google.inject.Provider;
-
import java.sql.SQLException;
public class Schema_89 extends SchemaVersion {
@@ -31,14 +30,11 @@
}
@Override
- protected void migrateData(ReviewDb db, UpdateUI ui) throws OrmException,
- SQLException {
+ protected void migrateData(ReviewDb db, UpdateUI ui) throws OrmException, SQLException {
SqlDialect dialect = ((JdbcSchema) db).getDialect();
try (StatementExecutor e = newExecutor(db)) {
- dialect.dropIndex(e, "patch_set_approvals",
- "patch_set_approvals_openByUser");
- dialect.dropIndex(e, "patch_set_approvals",
- "patch_set_approvals_closedByU");
+ dialect.dropIndex(e, "patch_set_approvals", "patch_set_approvals_openByUser");
+ dialect.dropIndex(e, "patch_set_approvals", "patch_set_approvals_closedByU");
}
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_90.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_90.java
index 8f1fc5d..d8f02ae 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_90.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_90.java
@@ -17,7 +17,6 @@
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.inject.Inject;
import com.google.inject.Provider;
-
import java.sql.SQLException;
import java.sql.Statement;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_94.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_94.java
index 02f78ca..5a87562 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_94.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_94.java
@@ -17,7 +17,6 @@
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.inject.Inject;
import com.google.inject.Provider;
-
import java.sql.SQLException;
import java.sql.Statement;
@@ -30,8 +29,7 @@
@Override
protected void migrateData(ReviewDb db, UpdateUI ui) throws SQLException {
try (Statement stmt = newStatement(db)) {
- stmt.execute("CREATE INDEX patch_sets_byRevision"
- + " ON patch_sets (revision)");
+ stmt.execute("CREATE INDEX patch_sets_byRevision" + " ON patch_sets (revision)");
}
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_95.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_95.java
index 1c839f7..0ce0294 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_95.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_95.java
@@ -18,11 +18,9 @@
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
-
-import org.eclipse.jgit.errors.ConfigInvalidException;
-
import java.io.IOException;
import java.sql.SQLException;
+import org.eclipse.jgit.errors.ConfigInvalidException;
public class Schema_95 extends SchemaVersion {
private final AllUsersCreator allUsersCreator;
@@ -34,8 +32,7 @@
}
@Override
- protected void migrateData(ReviewDb db, UpdateUI ui) throws OrmException,
- SQLException {
+ protected void migrateData(ReviewDb db, UpdateUI ui) throws OrmException, SQLException {
try {
allUsersCreator.create();
} catch (IOException | ConfigInvalidException e) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_98.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_98.java
index 752dcd8..4206dce 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_98.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_98.java
@@ -17,7 +17,6 @@
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.inject.Inject;
import com.google.inject.Provider;
-
import java.sql.SQLException;
import java.sql.Statement;
@@ -29,12 +28,12 @@
@Override
protected void migrateData(ReviewDb db, UpdateUI ui) throws SQLException {
- ui.message("Migrate user preference showUserInReview to "
- + "reviewCategoryStrategy");
+ ui.message("Migrate user preference showUserInReview to " + "reviewCategoryStrategy");
try (Statement stmt = newStatement(db)) {
- stmt.executeUpdate("UPDATE accounts SET "
- + "REVIEW_CATEGORY_STRATEGY='NAME' "
- + "WHERE (SHOW_USER_IN_REVIEW='Y')");
+ stmt.executeUpdate(
+ "UPDATE accounts SET "
+ + "REVIEW_CATEGORY_STRATEGY='NAME' "
+ + "WHERE (SHOW_USER_IN_REVIEW='Y')");
}
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/ScriptRunner.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/ScriptRunner.java
index 684a72e..adee5fc 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/ScriptRunner.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/ScriptRunner.java
@@ -21,7 +21,6 @@
import com.google.gwtorm.jdbc.JdbcSchema;
import com.google.gwtorm.schema.sql.SqlDialect;
import com.google.gwtorm.server.OrmException;
-
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
@@ -37,11 +36,11 @@
private final String name;
private final List<String> commands;
- static final ScriptRunner NOOP = new ScriptRunner(null, null) {
- @Override
- void run(final ReviewDb db) {
- }
- };
+ static final ScriptRunner NOOP =
+ new ScriptRunner(null, null) {
+ @Override
+ void run(final ReviewDb db) {}
+ };
ScriptRunner(final String scriptName, final InputStream script) {
this.name = scriptName;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/schema/UpdateUI.java b/gerrit-server/src/main/java/com/google/gerrit/server/schema/UpdateUI.java
index eff5575..b43aaa6 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/schema/UpdateUI.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/schema/UpdateUI.java
@@ -16,7 +16,6 @@
import com.google.gwtorm.server.OrmException;
import com.google.gwtorm.server.StatementExecutor;
-
import java.util.List;
public interface UpdateUI {
@@ -26,6 +25,5 @@
boolean isBatch();
- void pruneSchema(StatementExecutor e, List<String> pruneList)
- throws OrmException;
+ void pruneSchema(StatementExecutor e, List<String> pruneList) throws OrmException;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/securestore/DefaultSecureStore.java b/gerrit-server/src/main/java/com/google/gerrit/server/securestore/DefaultSecureStore.java
index c8190a6..677e9ff 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/securestore/DefaultSecureStore.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/securestore/DefaultSecureStore.java
@@ -18,19 +18,17 @@
import com.google.gerrit.server.config.SitePaths;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.errors.ConfigInvalidException;
-import org.eclipse.jgit.internal.storage.file.LockFile;
-import org.eclipse.jgit.lib.Constants;
-import org.eclipse.jgit.storage.file.FileBasedConfig;
-import org.eclipse.jgit.util.FS;
-
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import org.eclipse.jgit.errors.ConfigInvalidException;
+import org.eclipse.jgit.internal.storage.file.LockFile;
+import org.eclipse.jgit.lib.Constants;
+import org.eclipse.jgit.storage.file.FileBasedConfig;
+import org.eclipse.jgit.util.FS;
@Singleton
public class DefaultSecureStore extends SecureStore {
@@ -56,8 +54,8 @@
}
@Override
- public synchronized String[] getListForPlugin(String pluginName, String section,
- String subsection, String name) {
+ public synchronized String[] getListForPlugin(
+ String pluginName, String section, String subsection, String name) {
FileBasedConfig cfg = null;
if (pluginSec.containsKey(pluginName)) {
cfg = pluginSec.get(pluginName);
@@ -78,8 +76,7 @@
}
@Override
- public void setList(String section, String subsection, String name,
- List<String> values) {
+ public void setList(String section, String subsection, String name, List<String> values) {
if (values != null) {
sec.setStringList(section, subsection, name, values);
} else {
@@ -127,8 +124,7 @@
throw new IOException("Cannot lock " + path);
}
try {
- FileUtil.chmod(0600, new File(path.getParentFile(), path.getName()
- + ".lock"));
+ FileUtil.chmod(0600, new File(path.getParentFile(), path.getName() + ".lock"));
lf.write(out);
if (!lf.commit()) {
throw new IOException("Cannot commit write to " + path);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/securestore/SecureStore.java b/gerrit-server/src/main/java/com/google/gerrit/server/securestore/SecureStore.java
index 122e26b..5c87391 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/securestore/SecureStore.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/securestore/SecureStore.java
@@ -15,29 +15,25 @@
package com.google.gerrit.server.securestore;
import com.google.common.collect.Lists;
-
import java.util.List;
/**
* Abstract class for providing new SecureStore implementation for Gerrit.
*
- * SecureStore is responsible for storing sensitive data like passwords in a
- * secure manner.
+ * <p>SecureStore is responsible for storing sensitive data like passwords in a secure manner.
*
- * It is implementator's responsibility to encrypt and store values.
+ * <p>It is implementator's responsibility to encrypt and store values.
*
- * To deploy new SecureStore one needs to provide a jar file with explicitly one
- * class that extends {@code SecureStore} and put it in Gerrit server. Then run:
+ * <p>To deploy new SecureStore one needs to provide a jar file with explicitly one class that
+ * extends {@code SecureStore} and put it in Gerrit server. Then run:
*
- * `java -jar gerrit.war SwitchSecureStore -d $gerrit_site --new-secure-store-lib
- * $path_to_new_secure_store.jar`
+ * <p>`java -jar gerrit.war SwitchSecureStore -d $gerrit_site --new-secure-store-lib
+ * $path_to_new_secure_store.jar`
*
- * on stopped Gerrit instance.
+ * <p>on stopped Gerrit instance.
*/
public abstract class SecureStore {
- /**
- * Describes {@link SecureStore} entry
- */
+ /** Describes {@link SecureStore} entry */
public static class EntryKey {
public final String name;
public final String section;
@@ -58,8 +54,8 @@
}
/**
- * Extract decrypted value of stored property from SecureStore or {@code null}
- * when property was not found.
+ * Extract decrypted value of stored property from SecureStore or {@code null} when property was
+ * not found.
*
* @param section
* @param subsection
@@ -75,8 +71,8 @@
}
/**
- * Extract decrypted value of stored plugin config property from SecureStore
- * or {@code null} when property was not found.
+ * Extract decrypted value of stored plugin config property from SecureStore or {@code null} when
+ * property was not found.
*
* @param pluginName
* @param section
@@ -84,8 +80,8 @@
* @param name
* @return decrypted String value or {@code null} if not found
*/
- public final String getForPlugin(String pluginName, String section,
- String subsection, String name) {
+ public final String getForPlugin(
+ String pluginName, String section, String subsection, String name) {
String[] values = getListForPlugin(pluginName, section, subsection, name);
if (values != null && values.length > 0) {
return values[0];
@@ -94,8 +90,8 @@
}
/**
- * Extract list of plugin config values from SecureStore and decrypt every
- * value in that list, or {@code null} when property was not found.
+ * Extract list of plugin config values from SecureStore and decrypt every value in that list, or
+ * {@code null} when property was not found.
*
* @param pluginName
* @param section
@@ -103,12 +99,12 @@
* @param name
* @return decrypted list of string values or {@code null}
*/
- public abstract String[] getListForPlugin(String pluginName, String section,
- String subsection, String name);
+ public abstract String[] getListForPlugin(
+ String pluginName, String section, String subsection, String name);
/**
- * Extract list of values from SecureStore and decrypt every value in that
- * list or {@code null} when property was not found.
+ * Extract list of values from SecureStore and decrypt every value in that list or {@code null}
+ * when property was not found.
*
* @param section
* @param subsection
@@ -120,7 +116,7 @@
/**
* Store single value in SecureStore.
*
- * This method is responsible for encrypting value and storing it.
+ * <p>This method is responsible for encrypting value and storing it.
*
* @param section
* @param subsection
@@ -134,7 +130,7 @@
/**
* Store list of values in SecureStore.
*
- * This method is responsible for encrypting all values in the list and storing them.
+ * <p>This method is responsible for encrypting all values in the list and storing them.
*
* @param section
* @param subsection
@@ -144,8 +140,7 @@
public abstract void setList(String section, String subsection, String name, List<String> values);
/**
- * Remove value for given {@code section}, {@code subsection} and {@code name}
- * from SecureStore.
+ * Remove value for given {@code section}, {@code subsection} and {@code name} from SecureStore.
*
* @param section
* @param subsection
@@ -153,8 +148,6 @@
*/
public abstract void unset(String section, String subsection, String name);
- /**
- * @return list of stored entries.
- */
+ /** @return list of stored entries. */
public abstract Iterable<EntryKey> list();
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/securestore/SecureStoreClassName.java b/gerrit-server/src/main/java/com/google/gerrit/server/securestore/SecureStoreClassName.java
index 07635bd..0247fc1 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/securestore/SecureStoreClassName.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/securestore/SecureStoreClassName.java
@@ -3,10 +3,8 @@
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import com.google.inject.BindingAnnotation;
-
import java.lang.annotation.Retention;
@Retention(RUNTIME)
@BindingAnnotation
-public @interface SecureStoreClassName {
-}
+public @interface SecureStoreClassName {}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/securestore/SecureStoreProvider.java b/gerrit-server/src/main/java/com/google/gerrit/server/securestore/SecureStoreProvider.java
index 99127d8..88c2072 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/securestore/SecureStoreProvider.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/securestore/SecureStoreProvider.java
@@ -22,16 +22,13 @@
import com.google.inject.Injector;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
+import java.nio.file.Path;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.nio.file.Path;
-
@Singleton
public class SecureStoreProvider implements Provider<SecureStore> {
- private static final Logger log = LoggerFactory
- .getLogger(SecureStoreProvider.class);
+ private static final Logger log = LoggerFactory.getLogger(SecureStoreProvider.class);
private final Path libdir;
private final Injector injector;
@@ -39,9 +36,7 @@
@Inject
protected SecureStoreProvider(
- Injector injector,
- SitePaths sitePaths,
- @Nullable @SecureStoreClassName String className) {
+ Injector injector, SitePaths sitePaths, @Nullable @SecureStoreClassName String className) {
this.injector = injector;
this.libdir = sitePaths.lib_dir;
this.className = className;
@@ -62,8 +57,7 @@
try {
return (Class<? extends SecureStore>) Class.forName(className);
} catch (ClassNotFoundException e) {
- String msg =
- String.format("Cannot load secure store class: %s", className);
+ String msg = String.format("Cannot load secure store class: %s", className);
log.error(msg, e);
throw new RuntimeException(msg, e);
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/ssh/NoSshInfo.java b/gerrit-server/src/main/java/com/google/gerrit/server/ssh/NoSshInfo.java
index 6ceec2d..91a949b 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/ssh/NoSshInfo.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/ssh/NoSshInfo.java
@@ -15,7 +15,6 @@
package com.google.gerrit.server.ssh;
import com.jcraft.jsch.HostKey;
-
import java.util.Collections;
import java.util.List;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/ssh/NoSshKeyCache.java b/gerrit-server/src/main/java/com/google/gerrit/server/ssh/NoSshKeyCache.java
index f3250d9..798ce38 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/ssh/NoSshKeyCache.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/ssh/NoSshKeyCache.java
@@ -34,12 +34,10 @@
}
@Override
- public void evict(String username) {
- }
+ public void evict(String username) {}
@Override
- public AccountSshKey create(AccountSshKey.Id id, String encoded)
- throws InvalidSshKeyException {
+ public AccountSshKey create(AccountSshKey.Id id, String encoded) throws InvalidSshKeyException {
throw new InvalidSshKeyException();
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/ssh/NoSshModule.java b/gerrit-server/src/main/java/com/google/gerrit/server/ssh/NoSshModule.java
index 8781d46..abbbdae 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/ssh/NoSshModule.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/ssh/NoSshModule.java
@@ -16,9 +16,7 @@
import com.google.inject.AbstractModule;
-/**
- * Disables the SSH support by stubbing out relevant objects.
- */
+/** Disables the SSH support by stubbing out relevant objects. */
public class NoSshModule extends AbstractModule {
@Override
protected void configure() {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/ssh/SshAddressesModule.java b/gerrit-server/src/main/java/com/google/gerrit/server/ssh/SshAddressesModule.java
index f768c5e..70a6fce 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/ssh/SshAddressesModule.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/ssh/SshAddressesModule.java
@@ -20,27 +20,23 @@
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.lib.Config;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
+import org.eclipse.jgit.lib.Config;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class SshAddressesModule extends AbstractModule {
- private static final Logger log =
- LoggerFactory.getLogger(SshAddressesModule.class);
+ private static final Logger log = LoggerFactory.getLogger(SshAddressesModule.class);
public static final int DEFAULT_PORT = 29418;
public static final int IANA_SSH_PORT = 22;
@Override
- protected void configure() {
- }
+ protected void configure() {}
@Provides
@Singleton
@@ -76,8 +72,8 @@
@Provides
@Singleton
@SshAdvertisedAddresses
- List<String> getAdvertisedAddresses(@GerritServerConfig Config cfg,
- @SshListenAddresses List<SocketAddress> listen) {
+ List<String> getAdvertisedAddresses(
+ @GerritServerConfig Config cfg, @SshListenAddresses List<SocketAddress> listen) {
String[] want = cfg.getStringList("sshd", null, "advertisedaddress");
if (want.length > 0) {
return Arrays.asList(want);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/ssh/SshAdvertisedAddresses.java b/gerrit-server/src/main/java/com/google/gerrit/server/ssh/SshAdvertisedAddresses.java
index 4a6eb29..c047fcc 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/ssh/SshAdvertisedAddresses.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/ssh/SshAdvertisedAddresses.java
@@ -17,14 +17,11 @@
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import com.google.inject.BindingAnnotation;
-
import java.lang.annotation.Retention;
/**
- * Marker on the list of {@link java.net.SocketAddress}es configured to be
- * advertised by the server.
+ * Marker on the list of {@link java.net.SocketAddress}es configured to be advertised by the server.
*/
@Retention(RUNTIME)
@BindingAnnotation
-public @interface SshAdvertisedAddresses {
-}
+public @interface SshAdvertisedAddresses {}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/ssh/SshInfo.java b/gerrit-server/src/main/java/com/google/gerrit/server/ssh/SshInfo.java
index 0081cb4..430846d 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/ssh/SshInfo.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/ssh/SshInfo.java
@@ -15,7 +15,6 @@
package com.google.gerrit.server.ssh;
import com.jcraft.jsch.HostKey;
-
import java.util.List;
public interface SshInfo {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/ssh/SshKeyCreator.java b/gerrit-server/src/main/java/com/google/gerrit/server/ssh/SshKeyCreator.java
index fd0c69c..a371490 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/ssh/SshKeyCreator.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/ssh/SshKeyCreator.java
@@ -18,6 +18,5 @@
import com.google.gerrit.reviewdb.client.AccountSshKey;
public interface SshKeyCreator {
- AccountSshKey create(AccountSshKey.Id id, String encoded)
- throws InvalidSshKeyException;
+ AccountSshKey create(AccountSshKey.Id id, String encoded) throws InvalidSshKeyException;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/ssh/SshListenAddresses.java b/gerrit-server/src/main/java/com/google/gerrit/server/ssh/SshListenAddresses.java
index a4e238d..68893f3 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/ssh/SshListenAddresses.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/ssh/SshListenAddresses.java
@@ -17,14 +17,12 @@
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import com.google.inject.BindingAnnotation;
-
import java.lang.annotation.Retention;
/**
- * Marker on the list of {@link java.net.SocketAddress}es on which the SSH
- * daemon is configured to listen.
+ * Marker on the list of {@link java.net.SocketAddress}es on which the SSH daemon is configured to
+ * listen.
*/
@Retention(RUNTIME)
@BindingAnnotation
-public @interface SshListenAddresses {
-}
+public @interface SshListenAddresses {}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/tools/ToolsCatalog.java b/gerrit-server/src/main/java/com/google/gerrit/server/tools/ToolsCatalog.java
index 9e48aad..b616791 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/tools/ToolsCatalog.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/tools/ToolsCatalog.java
@@ -21,12 +21,6 @@
import com.google.gerrit.common.Version;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
-import org.eclipse.jgit.lib.Constants;
-import org.eclipse.jgit.util.RawParseUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@@ -38,12 +32,16 @@
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;
+import org.eclipse.jgit.lib.Constants;
+import org.eclipse.jgit.util.RawParseUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* Listing of all client side tools stored on this server.
- * <p>
- * Clients may download these tools through our file server, as they are
- * packaged with our own software releases.
+ *
+ * <p>Clients may download these tools through our file server, as they are packaged with our own
+ * software releases.
*/
@Singleton
public class ToolsCatalog {
@@ -79,8 +77,7 @@
private static SortedMap<String, Entry> readToc() throws IOException {
SortedMap<String, Entry> toc = new TreeMap<>();
final BufferedReader br =
- new BufferedReader(new InputStreamReader(new ByteArrayInputStream(
- read("TOC")), UTF_8));
+ new BufferedReader(new InputStreamReader(new ByteArrayInputStream(read("TOC")), UTF_8));
String line;
while ((line = br.readLine()) != null) {
if (line.length() > 0 && !line.startsWith("#")) {
@@ -144,7 +141,8 @@
/** A file served out of the tools root directory. */
public static class Entry {
public enum Type {
- DIR, FILE
+ DIR,
+ FILE
}
private final Type type;
@@ -209,8 +207,7 @@
final String version = Version.getVersion();
final int lf = RawParseUtils.nextLF(data, 0);
if (version != null && lf < data.length) {
- byte[] versionHeader =
- Constants.encode("# From Gerrit Code Review " + version + "\n");
+ byte[] versionHeader = Constants.encode("# From Gerrit Code Review " + version + "\n");
ByteArrayOutputStream buf = new ByteArrayOutputStream();
buf.write(data, 0, lf);
@@ -224,7 +221,8 @@
}
private boolean isScript(byte[] data) {
- return data != null && data.length > 3 //
+ return data != null
+ && data.length > 3 //
&& data[0] == '#' //
&& data[1] == '!' //
&& data[2] == '/';
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/util/FallbackRequestContext.java b/gerrit-server/src/main/java/com/google/gerrit/server/util/FallbackRequestContext.java
index 55c2992..de1555f 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/util/FallbackRequestContext.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/util/FallbackRequestContext.java
@@ -23,8 +23,8 @@
import com.google.inject.Singleton;
/**
- * The default RequestContext to use when not in a request scope e.g.
- * ThreadLocalRequestContext is not set.
+ * The default RequestContext to use when not in a request scope e.g. ThreadLocalRequestContext is
+ * not set.
*/
@Singleton
public class FallbackRequestContext implements RequestContext {
@@ -46,8 +46,7 @@
return new Provider<ReviewDb>() {
@Override
public ReviewDb get() {
- throw new ProvisionException(
- "Automatic ReviewDb only available in request scope");
+ throw new ProvisionException("Automatic ReviewDb only available in request scope");
}
};
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/util/GuiceRequestScopePropagator.java b/gerrit-server/src/main/java/com/google/gerrit/server/util/GuiceRequestScopePropagator.java
index 1568228..6dd5543 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/util/GuiceRequestScopePropagator.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/util/GuiceRequestScopePropagator.java
@@ -24,7 +24,6 @@
import com.google.inject.servlet.ServletScopes;
import com.google.inject.util.Providers;
import com.google.inject.util.Types;
-
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.net.SocketAddress;
@@ -49,9 +48,7 @@
this.peer = remotePeerProvider.get();
}
- /**
- * @see RequestScopePropagator#wrap(Callable)
- */
+ /** @see RequestScopePropagator#wrap(Callable) */
// ServletScopes#continueRequest is deprecated, but it's not obvious their
// recommended replacement is an appropriate drop-in solution; see
// https://gerrit-review.googlesource.com/83971
@@ -63,12 +60,10 @@
// Request scopes appear to use specific keys in their map, instead of only
// providers. Add bindings for both the key to the instance directly and the
// provider to the instance to be safe.
- seedMap.put(Key.get(typeOfProvider(String.class), CanonicalWebUrl.class),
- Providers.of(url));
+ seedMap.put(Key.get(typeOfProvider(String.class), CanonicalWebUrl.class), Providers.of(url));
seedMap.put(Key.get(String.class, CanonicalWebUrl.class), url);
- seedMap.put(Key.get(typeOfProvider(SocketAddress.class), RemotePeer.class),
- Providers.of(peer));
+ seedMap.put(Key.get(typeOfProvider(SocketAddress.class), RemotePeer.class), Providers.of(peer));
seedMap.put(Key.get(SocketAddress.class, RemotePeer.class), peer);
return ServletScopes.continueRequest(callable, seedMap);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/util/HostPlatform.java b/gerrit-server/src/main/java/com/google/gerrit/server/util/HostPlatform.java
index 074df0c..066bd4b 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/util/HostPlatform.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/util/HostPlatform.java
@@ -32,16 +32,15 @@
private static boolean compute(String platform) {
final String osDotName =
- AccessController.doPrivileged(new PrivilegedAction<String>() {
- @Override
- public String run() {
- return System.getProperty("os.name");
- }
- });
- return osDotName != null
- && osDotName.toLowerCase().contains(platform);
+ AccessController.doPrivileged(
+ new PrivilegedAction<String>() {
+ @Override
+ public String run() {
+ return System.getProperty("os.name");
+ }
+ });
+ return osDotName != null && osDotName.toLowerCase().contains(platform);
}
- private HostPlatform() {
- }
+ private HostPlatform() {}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/util/IdGenerator.java b/gerrit-server/src/main/java/com/google/gerrit/server/util/IdGenerator.java
index 78eb657..e4d2890 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/util/IdGenerator.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/util/IdGenerator.java
@@ -16,7 +16,6 @@
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
@@ -71,23 +70,30 @@
}
private static short hi16(final int in) {
- return (short) ( //
- ((in >>> 24 & 0xff)) | //
- ((in >>> 16 & 0xff) << 8) //
- );
+ return (short)
+ ( //
+ ((in >>> 24 & 0xff))
+ | //
+ ((in >>> 16 & 0xff) << 8) //
+ );
}
private static short lo16(final int in) {
- return (short) ( //
- ((in >>> 8 & 0xff)) | //
- ((in & 0xff) << 8) //
- );
+ return (short)
+ ( //
+ ((in >>> 8 & 0xff))
+ | //
+ ((in & 0xff) << 8) //
+ );
}
private static int result(final short v0, final short v1) {
- return ((v0 & 0xff) << 24) | //
- (((v0 >>> 8) & 0xff) << 16) | //
- ((v1 & 0xff) << 8) | //
+ return ((v0 & 0xff) << 24)
+ | //
+ (((v0 >>> 8) & 0xff) << 16)
+ | //
+ ((v1 & 0xff) << 8)
+ | //
((v1 >>> 8) & 0xff);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/util/LabelVote.java b/gerrit-server/src/main/java/com/google/gerrit/server/util/LabelVote.java
index 030383a..538d7d1 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/util/LabelVote.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/util/LabelVote.java
@@ -46,20 +46,17 @@
if (sign == 0) {
return create(text, (short) 1);
}
- return create(text.substring(0, i),
- (short)(sign * Short.parseShort(text.substring(i + 1))));
+ return create(text.substring(0, i), (short) (sign * Short.parseShort(text.substring(i + 1))));
}
public static LabelVote parseWithEquals(String text) {
checkArgument(!Strings.isNullOrEmpty(text), "Empty label vote");
int e = text.lastIndexOf('=');
checkArgument(e >= 0, "Label vote missing '=': %s", text);
- return create(text.substring(0, e),
- Short.parseShort(text.substring(e + 1), text.length()));
+ return create(text.substring(0, e), Short.parseShort(text.substring(e + 1), text.length()));
}
- public static StringBuilder appendTo(StringBuilder sb, String label,
- short value) {
+ public static StringBuilder appendTo(StringBuilder sb, String label, short value) {
if (value == (short) 0) {
return sb.append('-').append(label);
} else if (value < 0) {
@@ -77,12 +74,12 @@
}
public abstract String label();
+
public abstract short value();
public String format() {
// Max short string length is "-32768".length() == 6.
- return appendTo(new StringBuilder(label().length() + 6), label(), value())
- .toString();
+ return appendTo(new StringBuilder(label().length() + 6), label(), value()).toString();
}
public String formatWithEquals() {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/util/MagicBranch.java b/gerrit-server/src/main/java/com/google/gerrit/server/util/MagicBranch.java
index 6e1952b..75e14cb 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/util/MagicBranch.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/util/MagicBranch.java
@@ -16,18 +16,15 @@
import com.google.gerrit.common.data.Capable;
import com.google.gerrit.reviewdb.client.Project;
-
+import java.io.IOException;
+import java.util.Map;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.util.Map;
-
public final class MagicBranch {
- private static final Logger log =
- LoggerFactory.getLogger(MagicBranch.class);
+ private static final Logger log = LoggerFactory.getLogger(MagicBranch.class);
public static final String NEW_CHANGE = "refs/for/";
public static final String NEW_DRAFT_CHANGE = "refs/drafts/";
@@ -66,15 +63,14 @@
}
/**
- * Checks if a (magic branch)/branch_name reference exists in the
- * destination repository and only returns Capable.OK if it does not match any.
+ * Checks if a (magic branch)/branch_name reference exists in the destination repository and only
+ * returns Capable.OK if it does not match any.
*
- * These block the client from being able to even send us a pack file, as it
- * is very unlikely the user passed the --force flag and the new commit is
- * probably not going to fast-forward the branch.
+ * <p>These block the client from being able to even send us a pack file, as it is very unlikely
+ * the user passed the --force flag and the new commit is probably not going to fast-forward the
+ * branch.
*/
- public static Capable checkMagicBranchRefs(Repository repo,
- Project project) {
+ public static Capable checkMagicBranchRefs(Repository repo, Project project) {
Capable result = checkMagicBranchRef(NEW_CHANGE, repo, project);
if (result != Capable.OK) {
return result;
@@ -91,8 +87,7 @@
return Capable.OK;
}
- private static Capable checkMagicBranchRef(String branchName, Repository repo,
- Project project) {
+ private static Capable checkMagicBranchRef(String branchName, Repository repo, Project project) {
Map<String, Ref> blockingFors;
try {
blockingFors = repo.getRefDatabase().getRefs(branchName);
@@ -103,15 +98,16 @@
}
if (!blockingFors.isEmpty()) {
String projName = project.getName();
- log.error("Repository '" + projName
- + "' needs the following refs removed to receive changes: "
- + blockingFors.keySet());
+ log.error(
+ "Repository '"
+ + projName
+ + "' needs the following refs removed to receive changes: "
+ + blockingFors.keySet());
return new Capable("One or more " + branchName + " names blocks change upload");
}
return Capable.OK;
}
- private MagicBranch() {
- }
+ private MagicBranch() {}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/util/ManualRequestContext.java b/gerrit-server/src/main/java/com/google/gerrit/server/util/ManualRequestContext.java
index 3115fd1..620a2bc 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/util/ManualRequestContext.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/util/ManualRequestContext.java
@@ -21,24 +21,26 @@
import com.google.inject.Provider;
import com.google.inject.util.Providers;
-/**
- * Closeable version of a {@link RequestContext} with manually-specified
- * providers.
- */
+/** Closeable version of a {@link RequestContext} with manually-specified providers. */
public class ManualRequestContext implements RequestContext, AutoCloseable {
private final Provider<CurrentUser> userProvider;
private final Provider<ReviewDb> db;
private final ThreadLocalRequestContext requestContext;
private final RequestContext old;
- public ManualRequestContext(CurrentUser user, SchemaFactory<ReviewDb> schemaFactory,
- ThreadLocalRequestContext requestContext) throws OrmException {
+ public ManualRequestContext(
+ CurrentUser user,
+ SchemaFactory<ReviewDb> schemaFactory,
+ ThreadLocalRequestContext requestContext)
+ throws OrmException {
this(Providers.of(user), schemaFactory, requestContext);
}
- public ManualRequestContext(Provider<CurrentUser> userProvider,
+ public ManualRequestContext(
+ Provider<CurrentUser> userProvider,
SchemaFactory<ReviewDb> schemaFactory,
- ThreadLocalRequestContext requestContext) throws OrmException {
+ ThreadLocalRequestContext requestContext)
+ throws OrmException {
this.userProvider = userProvider;
this.db = Providers.of(schemaFactory.open());
this.requestContext = requestContext;
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/util/MostSpecificComparator.java b/gerrit-server/src/main/java/com/google/gerrit/server/util/MostSpecificComparator.java
index 159763c..4019851 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/util/MostSpecificComparator.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/util/MostSpecificComparator.java
@@ -16,36 +16,31 @@
import com.google.gerrit.common.data.RefConfigSection;
import com.google.gerrit.server.project.RefPattern;
-
-import org.apache.commons.lang.StringUtils;
-
import java.util.Comparator;
+import org.apache.commons.lang.StringUtils;
/**
* Order the Ref Pattern by the most specific. This sort is done by:
+ *
* <ul>
- * <li>1 - The minor value of Levenshtein string distance between the branch
- * name and the regex string shortest example. A shorter distance is a more
- * specific match.
- * <li>2 - Finites first, infinities after.
- * <li>3 - Number of transitions. More transitions is more specific.
- * <li>4 - Length of the expression text.
+ * <li>1 - The minor value of Levenshtein string distance between the branch name and the regex
+ * string shortest example. A shorter distance is a more specific match.
+ * <li>2 - Finites first, infinities after.
+ * <li>3 - Number of transitions. More transitions is more specific.
+ * <li>4 - Length of the expression text.
* </ul>
*
- * Levenshtein distance is a measure of the similarity between two strings.
- * The distance is the number of deletions, insertions, or substitutions
- * required to transform one string into another.
+ * Levenshtein distance is a measure of the similarity between two strings. The distance is the
+ * number of deletions, insertions, or substitutions required to transform one string into another.
*
- * For example, if given refs/heads/m* and refs/heads/*, the distances are 5
- * and 6. It means that refs/heads/m* is more specific because it's closer to
- * refs/heads/master than refs/heads/*.
+ * <p>For example, if given refs/heads/m* and refs/heads/*, the distances are 5 and 6. It means that
+ * refs/heads/m* is more specific because it's closer to refs/heads/master than refs/heads/*.
*
- * Another example could be refs/heads/* and refs/heads/[a-zA-Z]*, the
- * distances are both 6. Both are infinite, but refs/heads/[a-zA-Z]* has more
- * transitions, which after all turns it more specific.
+ * <p>Another example could be refs/heads/* and refs/heads/[a-zA-Z]*, the distances are both 6. Both
+ * are infinite, but refs/heads/[a-zA-Z]* has more transitions, which after all turns it more
+ * specific.
*/
-public final class MostSpecificComparator implements
- Comparator<RefConfigSection> {
+public final class MostSpecificComparator implements Comparator<RefConfigSection> {
private final String refName;
public MostSpecificComparator(String refName) {
@@ -111,8 +106,7 @@
private int transitions(String pattern) {
if (RefPattern.isRE(pattern)) {
- return RefPattern.toRegExp(pattern).toAutomaton()
- .getNumberOfTransitions();
+ return RefPattern.toRegExp(pattern).toAutomaton().getNumberOfTransitions();
} else if (pattern.endsWith("/*")) {
return pattern.length();
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/util/OneOffRequestContext.java b/gerrit-server/src/main/java/com/google/gerrit/server/util/OneOffRequestContext.java
index f4719aa..28be669 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/util/OneOffRequestContext.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/util/OneOffRequestContext.java
@@ -25,12 +25,12 @@
/**
* Helper to create one-off request contexts.
- * <p>
- * Each call to {@link #open()} opens a new {@link ReviewDb}, so this class
- * should only be used in a bounded try/finally block.
- * <p>
- * The user in the request context is {@link InternalUser} or the
- * {@link IdentifiedUser} associated to the userId passed as parameter.
+ *
+ * <p>Each call to {@link #open()} opens a new {@link ReviewDb}, so this class should only be used
+ * in a bounded try/finally block.
+ *
+ * <p>The user in the request context is {@link InternalUser} or the {@link IdentifiedUser}
+ * associated to the userId passed as parameter.
*/
@Singleton
public class OneOffRequestContext {
@@ -40,7 +40,8 @@
private final IdentifiedUser.GenericFactory identifiedUserFactory;
@Inject
- OneOffRequestContext(InternalUser.Factory userFactory,
+ OneOffRequestContext(
+ InternalUser.Factory userFactory,
SchemaFactory<ReviewDb> schemaFactory,
ThreadLocalRequestContext requestContext,
IdentifiedUser.GenericFactory identifiedUserFactory) {
@@ -51,12 +52,11 @@
}
public ManualRequestContext open() throws OrmException {
- return new ManualRequestContext(userFactory.create(),
- schemaFactory, requestContext);
+ return new ManualRequestContext(userFactory.create(), schemaFactory, requestContext);
}
public ManualRequestContext openAs(Account.Id userId) throws OrmException {
- return new ManualRequestContext(identifiedUserFactory.create(userId),
- schemaFactory, requestContext);
+ return new ManualRequestContext(
+ identifiedUserFactory.create(userId), schemaFactory, requestContext);
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/util/PluginLogFile.java b/gerrit-server/src/main/java/com/google/gerrit/server/util/PluginLogFile.java
index 17f6535..0d7a95a 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/util/PluginLogFile.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/util/PluginLogFile.java
@@ -17,7 +17,6 @@
import com.google.gerrit.extensions.events.LifecycleListener;
import com.google.gerrit.extensions.systemstatus.ServerInformation;
import com.google.inject.Inject;
-
import org.apache.log4j.AsyncAppender;
import org.apache.log4j.Layout;
import org.apache.log4j.LogManager;
@@ -31,10 +30,8 @@
private final Layout layout;
@Inject
- public PluginLogFile(SystemLog systemLog,
- ServerInformation serverInfo,
- String logName,
- Layout layout) {
+ public PluginLogFile(
+ SystemLog systemLog, ServerInformation serverInfo, String logName, Layout layout) {
this.systemLog = systemLog;
this.serverInfo = serverInfo;
this.logName = logName;
@@ -43,8 +40,7 @@
@Override
public void start() {
- AsyncAppender asyncAppender =
- systemLog.createAsyncAppender(logName, layout);
+ AsyncAppender asyncAppender = systemLog.createAsyncAppender(logName, layout);
Logger logger = LogManager.getLogger(logName);
logger.removeAppender(logName);
logger.addAppender(asyncAppender);
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/util/PluginRequestContext.java b/gerrit-server/src/main/java/com/google/gerrit/server/util/PluginRequestContext.java
index 943e518..3f3f647 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/util/PluginRequestContext.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/util/PluginRequestContext.java
@@ -38,8 +38,7 @@
return new Provider<ReviewDb>() {
@Override
public ReviewDb get() {
- throw new ProvisionException(
- "Automatic ReviewDb only available in request scope");
+ throw new ProvisionException("Automatic ReviewDb only available in request scope");
}
};
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/util/RangeUtil.java b/gerrit-server/src/main/java/com/google/gerrit/server/util/RangeUtil.java
index 92873d3..f7f2cff 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/util/RangeUtil.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/util/RangeUtil.java
@@ -16,13 +16,11 @@
import com.google.common.primitives.Ints;
import com.google.gerrit.common.Nullable;
-
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public final class RangeUtil {
- private static final Pattern RANGE_PATTERN =
- Pattern.compile("(>|>=|=|<|<=|)([+-]?\\d+)$");
+ private static final Pattern RANGE_PATTERN = Pattern.compile("(>|>=|=|<|<=|)([+-]?\\d+)$");
private RangeUtil() {}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/util/RegexListSearcher.java b/gerrit-server/src/main/java/com/google/gerrit/server/util/RegexListSearcher.java
index bbc97df..91cb709 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/util/RegexListSearcher.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/util/RegexListSearcher.java
@@ -21,11 +21,9 @@
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.primitives.Chars;
-
import dk.brics.automaton.Automaton;
import dk.brics.automaton.RegExp;
import dk.brics.automaton.RunAutomaton;
-
import java.util.Collections;
import java.util.List;
@@ -88,12 +86,10 @@
}
if (prefixOnly) {
- return begin < end ? list.subList(begin, end) : ImmutableList.<T> of();
+ return begin < end ? list.subList(begin, end) : ImmutableList.<T>of();
}
- return Iterables.filter(
- list.subList(begin, end),
- x -> pattern.run(apply(x)));
+ return Iterables.filter(list.subList(begin, end), x -> pattern.run(apply(x)));
}
public boolean hasMatch(List<T> list) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/util/RequestContext.java b/gerrit-server/src/main/java/com/google/gerrit/server/util/RequestContext.java
index 506a1c3..37fd7bc 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/util/RequestContext.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/util/RequestContext.java
@@ -19,10 +19,11 @@
import com.google.inject.Provider;
/**
- * The RequestContext is an interface exposing the fields that are needed
- * by the GerritGlobalModule scope.
+ * The RequestContext is an interface exposing the fields that are needed by the GerritGlobalModule
+ * scope.
*/
public interface RequestContext {
CurrentUser getUser();
+
Provider<ReviewDb> getReviewDbProvider();
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/util/RequestId.java b/gerrit-server/src/main/java/com/google/gerrit/server/util/RequestId.java
index 4f43c2a..dc7dd3d 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/util/RequestId.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/util/RequestId.java
@@ -19,13 +19,13 @@
import com.google.gerrit.common.TimeUtil;
import com.google.gerrit.reviewdb.client.Change;
import com.google.gerrit.reviewdb.client.Project;
-
import java.net.InetAddress;
import java.net.UnknownHostException;
/** Unique identifier for an end-user request, used in logs and similar. */
public class RequestId {
private static final String MACHINE_ID;
+
static {
String id;
try {
@@ -48,10 +48,15 @@
private RequestId(String resourceId) {
Hasher h = Hashing.sha1().newHasher();
- h.putLong(Thread.currentThread().getId())
- .putUnencodedChars(MACHINE_ID);
- str = "[" + resourceId + "-" + TimeUtil.nowTs().getTime() +
- "-" + h.hash().toString().substring(0, 8) + "]";
+ h.putLong(Thread.currentThread().getId()).putUnencodedChars(MACHINE_ID);
+ str =
+ "["
+ + resourceId
+ + "-"
+ + TimeUtil.nowTs().getTime()
+ + "-"
+ + h.hash().toString().substring(0, 8)
+ + "]";
}
@Override
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/util/RequestScopePropagator.java b/gerrit-server/src/main/java/com/google/gerrit/server/util/RequestScopePropagator.java
index f3b44e0..4d66809e 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/util/RequestScopePropagator.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/util/RequestScopePropagator.java
@@ -27,21 +27,18 @@
import com.google.inject.Provider;
import com.google.inject.Scope;
import com.google.inject.servlet.ServletScopes;
-
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
/**
* Base class for propagating request-scoped data between threads.
- * <p>
- * Request scopes are typically linked to a {@link ThreadLocal}, which is only
- * available to the current thread. In order to allow background work involving
- * RequestScoped data, the ThreadLocal data must be copied from the request thread to
- * the new background thread.
- * <p>
- * Every type of RequestScope must provide an implementation of
- * RequestScopePropagator. See {@link #wrap(Callable)} for details on the
- * implementation, usage, and restrictions.
+ *
+ * <p>Request scopes are typically linked to a {@link ThreadLocal}, which is only available to the
+ * current thread. In order to allow background work involving RequestScoped data, the ThreadLocal
+ * data must be copied from the request thread to the new background thread.
+ *
+ * <p>Every type of RequestScope must provide an implementation of RequestScopePropagator. See
+ * {@link #wrap(Callable)} for details on the implementation, usage, and restrictions.
*
* @see ThreadLocalRequestScopePropagator
*/
@@ -51,7 +48,8 @@
private final ThreadLocalRequestContext local;
private final Provider<RequestScopedReviewDbProvider> dbProviderProvider;
- protected RequestScopePropagator(Scope scope,
+ protected RequestScopePropagator(
+ Scope scope,
ThreadLocalRequestContext local,
Provider<RequestScopedReviewDbProvider> dbProviderProvider) {
this.scope = scope;
@@ -60,26 +58,24 @@
}
/**
- * Ensures that the current request state is available when the passed in
- * Callable is invoked.
+ * Ensures that the current request state is available when the passed in Callable is invoked.
*
- * If needed wraps the passed in Callable in a new {@link Callable} that
- * propagates the current request state when the returned Callable is invoked.
- * The method must be called in a request scope and the returned Callable may
- * only be invoked in a thread that is not already in a request scope or is in
- * the same request scope. The returned Callable will inherit toString() from
- * the passed in Callable. A
- * {@link com.google.gerrit.server.git.WorkQueue.Executor} does not accept a
- * Callable, so there is no ProjectCallable implementation. Implementations of
- * this method must be consistent with Guice's
- * {@link ServletScopes#continueRequest(Callable, java.util.Map)}.
- * <p>
- * There are some limitations:
+ * <p>If needed wraps the passed in Callable in a new {@link Callable} that propagates the current
+ * request state when the returned Callable is invoked. The method must be called in a request
+ * scope and the returned Callable may only be invoked in a thread that is not already in a
+ * request scope or is in the same request scope. The returned Callable will inherit toString()
+ * from the passed in Callable. A {@link com.google.gerrit.server.git.WorkQueue.Executor} does not
+ * accept a Callable, so there is no ProjectCallable implementation. Implementations of this
+ * method must be consistent with Guice's {@link ServletScopes#continueRequest(Callable,
+ * java.util.Map)}.
+ *
+ * <p>There are some limitations:
+ *
* <ul>
- * <li>Derived objects (i.e. anything marked created in a request scope) will
- * not be transported.</li>
- * <li>State changes to the request scoped context after this method is called
- * will not be seen in the continued thread.</li>
+ * <li>Derived objects (i.e. anything marked created in a request scope) will not be
+ * transported.
+ * <li>State changes to the request scoped context after this method is called will not be seen
+ * in the continued thread.
* </ul>
*
* @param callable the Callable to wrap.
@@ -88,8 +84,7 @@
@SuppressWarnings("javadoc") // See GuiceRequestScopePropagator#wrapImpl
public final <T> Callable<T> wrap(final Callable<T> callable) {
final RequestContext callerContext = checkNotNull(local.getContext());
- final Callable<T> wrapped =
- wrapImpl(context(callerContext, cleanup(callable)));
+ final Callable<T> wrapped = wrapImpl(context(callerContext, cleanup(callable)));
return new Callable<T>() {
@Override
public T call() throws Exception {
@@ -107,15 +102,14 @@
}
/**
- * Wraps runnable in a new {@link Runnable} that propagates the current
- * request state when the runnable is invoked. The method must be called in a
- * request scope and the returned Runnable may only be invoked in a thread
- * that is not already in a request scope. The returned Runnable will inherit
- * toString() from the passed in Runnable. Furthermore, if the passed runnable
- * is of type {@link ProjectRunnable}, the returned runnable will be of the
- * same type with the methods delegated.
+ * Wraps runnable in a new {@link Runnable} that propagates the current request state when the
+ * runnable is invoked. The method must be called in a request scope and the returned Runnable may
+ * only be invoked in a thread that is not already in a request scope. The returned Runnable will
+ * inherit toString() from the passed in Runnable. Furthermore, if the passed runnable is of type
+ * {@link ProjectRunnable}, the returned runnable will be of the same type with the methods
+ * delegated.
*
- * See {@link #wrap(Callable)} for details on implementation and usage.
+ * <p>See {@link #wrap(Callable)} for details on implementation and usage.
*
* @param runnable the Runnable to wrap.
* @return a new Runnable which will execute in the current request scope.
@@ -175,27 +169,26 @@
};
}
- /**
- * @see #wrap(Callable)
- */
+ /** @see #wrap(Callable) */
protected abstract <T> Callable<T> wrapImpl(Callable<T> callable);
- protected <T> Callable<T> context(final RequestContext context,
- final Callable<T> callable) {
+ protected <T> Callable<T> context(final RequestContext context, final Callable<T> callable) {
return new Callable<T>() {
@Override
public T call() throws Exception {
- RequestContext old = local.setContext(new RequestContext() {
- @Override
- public CurrentUser getUser() {
- return context.getUser();
- }
+ RequestContext old =
+ local.setContext(
+ new RequestContext() {
+ @Override
+ public CurrentUser getUser() {
+ return context.getUser();
+ }
- @Override
- public Provider<ReviewDb> getReviewDbProvider() {
- return dbProviderProvider.get();
- }
- });
+ @Override
+ public Provider<ReviewDb> getReviewDbProvider() {
+ return dbProviderProvider.get();
+ }
+ });
try {
return callable.call();
} finally {
@@ -209,14 +202,17 @@
return new Callable<T>() {
@Override
public T call() throws Exception {
- RequestCleanup cleanup = scope.scope(
- Key.get(RequestCleanup.class),
- new Provider<RequestCleanup>() {
- @Override
- public RequestCleanup get() {
- return new RequestCleanup();
- }
- }).get();
+ RequestCleanup cleanup =
+ scope
+ .scope(
+ Key.get(RequestCleanup.class),
+ new Provider<RequestCleanup>() {
+ @Override
+ public RequestCleanup get() {
+ return new RequestCleanup();
+ }
+ })
+ .get();
try {
return callable.call();
} finally {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/util/ServerRequestContext.java b/gerrit-server/src/main/java/com/google/gerrit/server/util/ServerRequestContext.java
index ede3365..af903c4 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/util/ServerRequestContext.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/util/ServerRequestContext.java
@@ -40,8 +40,7 @@
return new Provider<ReviewDb>() {
@Override
public ReviewDb get() {
- throw new ProvisionException(
- "Automatic ReviewDb only available in request scope");
+ throw new ProvisionException("Automatic ReviewDb only available in request scope");
}
};
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/util/SocketUtil.java b/gerrit-server/src/main/java/com/google/gerrit/server/util/SocketUtil.java
index 4991c58..5b22f73 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/util/SocketUtil.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/util/SocketUtil.java
@@ -23,8 +23,7 @@
public final class SocketUtil {
/** True if this InetAddress is a raw IPv6 in dotted quad notation. */
public static boolean isIPv6(final InetAddress ip) {
- return ip instanceof Inet6Address
- && ip.getHostName().equals(ip.getHostAddress());
+ return ip instanceof Inet6Address && ip.getHostName().equals(ip.getHostAddress());
}
/** Get the name or IP address, or {@code *} if this address is a wildcard IP. */
@@ -110,12 +109,10 @@
}
/** Parse and resolve an address string, looking up the IP address. */
- public static InetSocketAddress resolve(final String desc,
- final int defaultPort) {
+ public static InetSocketAddress resolve(final String desc, final int defaultPort) {
final InetSocketAddress addr = parse(desc, defaultPort);
if (addr.getAddress() != null && addr.getAddress().isAnyLocalAddress()) {
return addr;
-
}
try {
final InetAddress host = InetAddress.getByName(addr.getHostName());
@@ -125,6 +122,5 @@
}
}
- private SocketUtil() {
- }
+ private SocketUtil() {}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/util/SubmoduleSectionParser.java b/gerrit-server/src/main/java/com/google/gerrit/server/util/SubmoduleSectionParser.java
index 6b5c991..61c863b 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/util/SubmoduleSectionParser.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/util/SubmoduleSectionParser.java
@@ -17,19 +17,17 @@
import com.google.gerrit.reviewdb.client.Branch;
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.reviewdb.client.SubmoduleSubscription;
-
-import org.eclipse.jgit.lib.Config;
-import org.eclipse.jgit.lib.Constants;
-
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashSet;
import java.util.Set;
+import org.eclipse.jgit.lib.Config;
+import org.eclipse.jgit.lib.Constants;
/**
* It parses from a configuration file submodule sections.
- * <p>
- * Example of submodule sections:
+ *
+ * <p>Example of submodule sections:
*
* <pre>
* [submodule "project-a"]
@@ -49,9 +47,8 @@
private final String canonicalWebUrl;
private final Branch.NameKey superProjectBranch;
- public SubmoduleSectionParser(Config bbc,
- String canonicalWebUrl,
- Branch.NameKey superProjectBranch) {
+ public SubmoduleSectionParser(
+ Config bbc, String canonicalWebUrl, Branch.NameKey superProjectBranch) {
this.bbc = bbc;
this.canonicalWebUrl = canonicalWebUrl;
this.superProjectBranch = superProjectBranch;
@@ -74,8 +71,12 @@
String branch = bbc.getString("submodule", id, "branch");
try {
- if (url != null && url.length() > 0 && path != null && path.length() > 0
- && branch != null && branch.length() > 0) {
+ if (url != null
+ && url.length() > 0
+ && path != null
+ && path.length() > 0
+ && branch != null
+ && branch.length() > 0) {
// All required fields filled.
String project;
@@ -107,8 +108,7 @@
URI thisServerURI = new URI(canonicalWebUrl);
String thisHost = thisServerURI.getHost();
String targetHost = targetServerURI.getHost();
- if (thisHost == null || targetHost == null ||
- !targetHost.equalsIgnoreCase(thisHost)) {
+ if (thisHost == null || targetHost == null || !targetHost.equalsIgnoreCase(thisHost)) {
return null;
}
String p1 = targetServerURI.getPath();
@@ -128,14 +128,14 @@
}
if (project.endsWith(Constants.DOT_GIT_EXT)) {
- project = project.substring(0, //
- project.length() - Constants.DOT_GIT_EXT.length());
+ project =
+ project.substring(
+ 0, //
+ project.length() - Constants.DOT_GIT_EXT.length());
}
Project.NameKey projectKey = new Project.NameKey(project);
return new SubmoduleSubscription(
- superProjectBranch,
- new Branch.NameKey(projectKey, branch),
- path);
+ superProjectBranch, new Branch.NameKey(projectKey, branch), path);
}
} catch (URISyntaxException e) {
// Error in url syntax (in fact it is uri syntax)
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/util/SystemLog.java b/gerrit-server/src/main/java/com/google/gerrit/server/util/SystemLog.java
index c857c40..65fbfd6 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/util/SystemLog.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/util/SystemLog.java
@@ -22,7 +22,8 @@
import com.google.gerrit.server.config.SitePaths;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
+import java.io.IOException;
+import java.nio.file.Path;
import org.apache.log4j.Appender;
import org.apache.log4j.AsyncAppender;
import org.apache.log4j.DailyRollingFileAppender;
@@ -35,13 +36,9 @@
import org.eclipse.jgit.lib.Config;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.nio.file.Path;
-
@Singleton
public class SystemLog {
- private static final org.slf4j.Logger log =
- LoggerFactory.getLogger(SystemLog.class);
+ private static final org.slf4j.Logger log = LoggerFactory.getLogger(SystemLog.class);
public static final String LOG4J_CONFIGURATION = "log4j.configuration";
@@ -86,8 +83,8 @@
if (appender != null) {
async.addAppender(appender);
} else {
- log.warn("No appender with the name: " + name + " was found. " + name
- + " logging is disabled");
+ log.warn(
+ "No appender with the name: " + name + " was found. " + name + " logging is disabled");
}
}
async.activateOptions();
@@ -104,8 +101,7 @@
private static final class DieErrorHandler implements ErrorHandler {
@Override
- public void error(String message, Exception e, int errorCode,
- LoggingEvent event) {
+ public void error(String message, Exception e, int errorCode, LoggingEvent event) {
error(e != null ? e.getMessage() : message);
}
@@ -120,19 +116,15 @@
}
@Override
- public void activateOptions() {
- }
+ public void activateOptions() {}
@Override
- public void setAppender(Appender appender) {
- }
+ public void setAppender(Appender appender) {}
@Override
- public void setBackupAppender(Appender appender) {
- }
+ public void setBackupAppender(Appender appender) {}
@Override
- public void setLogger(Logger logger) {
- }
+ public void setLogger(Logger logger) {}
}
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/util/ThreadLocalRequestContext.java b/gerrit-server/src/main/java/com/google/gerrit/server/util/ThreadLocalRequestContext.java
index 3e405a9..e065c6b 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/util/ThreadLocalRequestContext.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/util/ThreadLocalRequestContext.java
@@ -29,9 +29,9 @@
import com.google.inject.name.Names;
/**
- * ThreadLocalRequestContext manages the current RequestContext using a
- * ThreadLocal. When the context is set, the fields exposed by the context
- * are considered in scope. Otherwise, the FallbackRequestContext is used.
+ * ThreadLocalRequestContext manages the current RequestContext using a ThreadLocal. When the
+ * context is set, the fields exposed by the context are considered in scope. Otherwise, the
+ * FallbackRequestContext is used.
*/
public class ThreadLocalRequestContext {
private static final String FALLBACK = "FALLBACK";
@@ -41,13 +41,13 @@
@Override
protected void configure() {
bind(ThreadLocalRequestContext.class);
- bind(RequestContext.class).annotatedWith(Names.named(FALLBACK))
+ bind(RequestContext.class)
+ .annotatedWith(Names.named(FALLBACK))
.to(FallbackRequestContext.class);
}
@Provides
- RequestContext provideRequestContext(
- @Named(FALLBACK) RequestContext fallback) {
+ RequestContext provideRequestContext(@Named(FALLBACK) RequestContext fallback) {
return MoreObjects.firstNonNull(local.get(), fallback);
}
@@ -61,8 +61,7 @@
if (user.isIdentifiedUser()) {
return user.asIdentifiedUser();
}
- throw new ProvisionException(NotSignedInException.MESSAGE,
- new NotSignedInException());
+ throw new ProvisionException(NotSignedInException.MESSAGE, new NotSignedInException());
}
@Provides
@@ -75,8 +74,7 @@
private static final ThreadLocal<RequestContext> local = new ThreadLocal<>();
@Inject
- ThreadLocalRequestContext() {
- }
+ ThreadLocalRequestContext() {}
public RequestContext setContext(@Nullable RequestContext ctx) {
RequestContext old = getContext();
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/util/ThreadLocalRequestScopePropagator.java b/gerrit-server/src/main/java/com/google/gerrit/server/util/ThreadLocalRequestScopePropagator.java
index a31c7c7..4b27208 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/util/ThreadLocalRequestScopePropagator.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/util/ThreadLocalRequestScopePropagator.java
@@ -18,21 +18,20 @@
import com.google.inject.OutOfScopeException;
import com.google.inject.Provider;
import com.google.inject.Scope;
-
import java.util.concurrent.Callable;
/**
- * {@link RequestScopePropagator} implementation for request scopes based on
- * a {@link ThreadLocal} context.
+ * {@link RequestScopePropagator} implementation for request scopes based on a {@link ThreadLocal}
+ * context.
*
* @param <C> "context" type stored in the {@link ThreadLocal}.
*/
-public abstract class ThreadLocalRequestScopePropagator<C>
- extends RequestScopePropagator {
+public abstract class ThreadLocalRequestScopePropagator<C> extends RequestScopePropagator {
private final ThreadLocal<C> threadLocal;
- protected ThreadLocalRequestScopePropagator(Scope scope,
+ protected ThreadLocalRequestScopePropagator(
+ Scope scope,
ThreadLocal<C> threadLocal,
ThreadLocalRequestContext local,
Provider<RequestScopedReviewDbProvider> dbProviderProvider) {
@@ -40,9 +39,7 @@
this.threadLocal = threadLocal;
}
- /**
- * @see RequestScopePropagator#wrap(Callable)
- */
+ /** @see RequestScopePropagator#wrap(Callable) */
@Override
protected final <T> Callable<T> wrapImpl(final Callable<T> callable) {
final C ctx = continuingContext(requireContext());
@@ -73,15 +70,13 @@
}
/**
- * Returns a new context object based on the passed in context that has no
- * request scoped objects initialized.
- * <p>
- * Note that some code paths expect request-scoped objects like
- * {@code CurrentUser} to be constructible starting from just the context
- * object returned by this method. For example, in the SSH scope, the context
- * includes the {@code SshSession}, which is used by
- * {@code SshCurrentUserProvider} to construct a new {@code CurrentUser} in
- * the new thread.
+ * Returns a new context object based on the passed in context that has no request scoped objects
+ * initialized.
+ *
+ * <p>Note that some code paths expect request-scoped objects like {@code CurrentUser} to be
+ * constructible starting from just the context object returned by this method. For example, in
+ * the SSH scope, the context includes the {@code SshSession}, which is used by {@code
+ * SshCurrentUserProvider} to construct a new {@code CurrentUser} in the new thread.
*
* @param ctx the context to continue.
* @return a new context.
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/util/TreeFormatter.java b/gerrit-server/src/main/java/com/google/gerrit/server/util/TreeFormatter.java
index 883f972..8d511f3 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/util/TreeFormatter.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/util/TreeFormatter.java
@@ -21,7 +21,9 @@
public interface TreeNode {
String getDisplayName();
+
boolean isVisible();
+
SortedSet<? extends TreeNode> getChildren();
}
@@ -62,8 +64,7 @@
printTree(rootNode, 0, true);
}
- private void printTree(final TreeNode node, final int level,
- final boolean isLast) {
+ private void printTree(final TreeNode node, final int level, final boolean isLast) {
printNode(node, level, isLast);
final SortedSet<? extends TreeNode> childNodes = node.getChildren();
int i = 0;
@@ -80,8 +81,7 @@
}
}
- private void printNode(final TreeNode node, final int level,
- final boolean isLast) {
+ private void printNode(final TreeNode node, final int level, final boolean isLast) {
printIndention(level);
stdout.print(isLast ? LAST_NODE_PREFIX : NODE_PREFIX);
if (node.isVisible()) {
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/validators/AssigneeValidationListener.java b/gerrit-server/src/main/java/com/google/gerrit/server/validators/AssigneeValidationListener.java
index 5d1191c..a97ce0b 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/validators/AssigneeValidationListener.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/validators/AssigneeValidationListener.java
@@ -18,9 +18,7 @@
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.reviewdb.client.Change;
-/**
- * Listener to provide validation of assignees.
- */
+/** Listener to provide validation of assignees. */
@ExtensionPoint
public interface AssigneeValidationListener {
/**
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/validators/GroupCreationValidationListener.java b/gerrit-server/src/main/java/com/google/gerrit/server/validators/GroupCreationValidationListener.java
index 03bdf37..98a09f3 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/validators/GroupCreationValidationListener.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/validators/GroupCreationValidationListener.java
@@ -17,19 +17,16 @@
import com.google.gerrit.extensions.annotations.ExtensionPoint;
import com.google.gerrit.server.account.CreateGroupArgs;
-/**
- * Listener to provide validation on group creation.
- */
+/** Listener to provide validation on group creation. */
@ExtensionPoint
public interface GroupCreationValidationListener {
/**
* Group creation validation.
*
- * Invoked by Gerrit just before a new group is going to be created.
+ * <p>Invoked by Gerrit just before a new group is going to be created.
*
* @param args arguments for the group creation
* @throws ValidationException if validation fails
*/
- void validateNewGroup(CreateGroupArgs args)
- throws ValidationException;
+ void validateNewGroup(CreateGroupArgs args) throws ValidationException;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/validators/HashtagValidationListener.java b/gerrit-server/src/main/java/com/google/gerrit/server/validators/HashtagValidationListener.java
index 1baab7c..fbf8e76 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/validators/HashtagValidationListener.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/validators/HashtagValidationListener.java
@@ -16,12 +16,9 @@
import com.google.gerrit.extensions.annotations.ExtensionPoint;
import com.google.gerrit.reviewdb.client.Change;
-
import java.util.Set;
-/**
- * Listener to provide validation of hashtag changes.
- */
+/** Listener to provide validation of hashtag changes. */
@ExtensionPoint
public interface HashtagValidationListener {
/**
@@ -32,6 +29,6 @@
* @param toRemove the hashtags to be removed
* @throws ValidationException if validation fails
*/
- void validateHashtags(Change change, Set<String> toAdd,
- Set<String> toRemove) throws ValidationException;
+ void validateHashtags(Change change, Set<String> toAdd, Set<String> toRemove)
+ throws ValidationException;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/validators/OutgoingEmailValidationListener.java b/gerrit-server/src/main/java/com/google/gerrit/server/validators/OutgoingEmailValidationListener.java
index 667ef0d..9f152a5 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/validators/OutgoingEmailValidationListener.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/validators/OutgoingEmailValidationListener.java
@@ -18,18 +18,13 @@
import com.google.gerrit.extensions.annotations.ExtensionPoint;
import com.google.gerrit.server.mail.Address;
import com.google.gerrit.server.mail.send.EmailHeader;
-
import java.util.Map;
import java.util.Set;
-/**
- * Listener to provide validation on outgoing email notification.
- */
+/** Listener to provide validation on outgoing email notification. */
@ExtensionPoint
public interface OutgoingEmailValidationListener {
- /**
- * Arguments supplied to validateOutgoingEmail.
- */
+ /** Arguments supplied to validateOutgoingEmail. */
class Args {
// in arguments
public String messageClass;
@@ -45,18 +40,14 @@
/**
* Outgoing e-mail validation.
*
- * Invoked by Gerrit just before an e-mail is sent, after all e-mail templates
- * have been applied.
+ * <p>Invoked by Gerrit just before an e-mail is sent, after all e-mail templates have been
+ * applied.
*
- * Plugins may modify the following fields in args:
- * - smtpFromAddress
- * - smtpRcptTo
- * - body
- * - headers
+ * <p>Plugins may modify the following fields in args: - smtpFromAddress - smtpRcptTo - body -
+ * headers
*
* @param args E-mail properties. Some are mutable.
* @throws ValidationException if validation fails.
*/
- void validateOutgoingEmail(OutgoingEmailValidationListener.Args args)
- throws ValidationException;
+ void validateOutgoingEmail(OutgoingEmailValidationListener.Args args) throws ValidationException;
}
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/validators/ProjectCreationValidationListener.java b/gerrit-server/src/main/java/com/google/gerrit/server/validators/ProjectCreationValidationListener.java
index 6012328..adb13a7 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/validators/ProjectCreationValidationListener.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/validators/ProjectCreationValidationListener.java
@@ -17,19 +17,16 @@
import com.google.gerrit.extensions.annotations.ExtensionPoint;
import com.google.gerrit.server.project.CreateProjectArgs;
-/**
- * Listener to provide validation on project creation.
- */
+/** Listener to provide validation on project creation. */
@ExtensionPoint
public interface ProjectCreationValidationListener {
/**
* Project creation validation.
*
- * Invoked by Gerrit just before a new project is going to be created.
+ * <p>Invoked by Gerrit just before a new project is going to be created.
*
* @param args arguments for the project creation
* @throws ValidationException if validation fails
*/
- void validateNewProject(CreateProjectArgs args)
- throws ValidationException;
+ void validateNewProject(CreateProjectArgs args) throws ValidationException;
}
diff --git a/gerrit-server/src/main/java/gerrit/AbstractCommitUserIdentityPredicate.java b/gerrit-server/src/main/java/gerrit/AbstractCommitUserIdentityPredicate.java
index a91bead..c2aaa76 100644
--- a/gerrit-server/src/main/java/gerrit/AbstractCommitUserIdentityPredicate.java
+++ b/gerrit-server/src/main/java/gerrit/AbstractCommitUserIdentityPredicate.java
@@ -16,7 +16,6 @@
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.reviewdb.client.UserIdentity;
-
import com.googlecode.prolog_cafe.exceptions.PrologException;
import com.googlecode.prolog_cafe.lang.IntegerTerm;
import com.googlecode.prolog_cafe.lang.Operation;
diff --git a/gerrit-server/src/main/java/gerrit/PRED__load_commit_labels_1.java b/gerrit-server/src/main/java/gerrit/PRED__load_commit_labels_1.java
index b9b6c5a..8b5a33d 100644
--- a/gerrit-server/src/main/java/gerrit/PRED__load_commit_labels_1.java
+++ b/gerrit-server/src/main/java/gerrit/PRED__load_commit_labels_1.java
@@ -8,7 +8,6 @@
import com.google.gerrit.rules.StoredValues;
import com.google.gerrit.server.query.change.ChangeData;
import com.google.gwtorm.server.OrmException;
-
import com.googlecode.prolog_cafe.exceptions.JavaException;
import com.googlecode.prolog_cafe.exceptions.PrologException;
import com.googlecode.prolog_cafe.lang.IntegerTerm;
@@ -39,8 +38,7 @@
Term listHead = Prolog.Nil;
try {
ChangeData cd = StoredValues.CHANGE_DATA.get(engine);
- LabelTypes types =
- StoredValues.CHANGE_CONTROL.get(engine).getLabelTypes();
+ LabelTypes types = StoredValues.CHANGE_CONTROL.get(engine).getLabelTypes();
for (PatchSetApproval a : cd.currentApprovals()) {
LabelType t = types.byLabel(a.getLabelId());
@@ -48,18 +46,14 @@
continue;
}
- StructureTerm labelTerm = new StructureTerm(
- sym_label,
- SymbolTerm.intern(t.getName()),
- new IntegerTerm(a.getValue()));
+ StructureTerm labelTerm =
+ new StructureTerm(
+ sym_label, SymbolTerm.intern(t.getName()), new IntegerTerm(a.getValue()));
- StructureTerm userTerm = new StructureTerm(
- sym_user,
- new IntegerTerm(a.getAccountId().get()));
+ StructureTerm userTerm =
+ new StructureTerm(sym_user, new IntegerTerm(a.getAccountId().get()));
- listHead = new ListTerm(
- new StructureTerm(sym_commit_label, labelTerm, userTerm),
- listHead);
+ listHead = new ListTerm(new StructureTerm(sym_commit_label, labelTerm, userTerm), listHead);
}
} catch (OrmException err) {
throw new JavaException(this, 1, err);
diff --git a/gerrit-server/src/main/java/gerrit/PRED__user_label_range_4.java b/gerrit-server/src/main/java/gerrit/PRED__user_label_range_4.java
index 8efc2f1..d06664e 100644
--- a/gerrit-server/src/main/java/gerrit/PRED__user_label_range_4.java
+++ b/gerrit-server/src/main/java/gerrit/PRED__user_label_range_4.java
@@ -19,7 +19,6 @@
import com.google.gerrit.rules.StoredValues;
import com.google.gerrit.server.CurrentUser;
import com.google.gerrit.server.project.ChangeControl;
-
import com.googlecode.prolog_cafe.exceptions.IllegalTypeException;
import com.googlecode.prolog_cafe.exceptions.PInstantiationException;
import com.googlecode.prolog_cafe.exceptions.PrologException;
diff --git a/gerrit-server/src/main/java/gerrit/PRED_change_branch_1.java b/gerrit-server/src/main/java/gerrit/PRED_change_branch_1.java
index ee5bdc9..f050c7f 100644
--- a/gerrit-server/src/main/java/gerrit/PRED_change_branch_1.java
+++ b/gerrit-server/src/main/java/gerrit/PRED_change_branch_1.java
@@ -16,7 +16,6 @@
import com.google.gerrit.reviewdb.client.Branch;
import com.google.gerrit.rules.StoredValues;
-
import com.googlecode.prolog_cafe.exceptions.PrologException;
import com.googlecode.prolog_cafe.lang.Operation;
import com.googlecode.prolog_cafe.lang.Predicate;
diff --git a/gerrit-server/src/main/java/gerrit/PRED_change_owner_1.java b/gerrit-server/src/main/java/gerrit/PRED_change_owner_1.java
index b56b036..b9dac68 100644
--- a/gerrit-server/src/main/java/gerrit/PRED_change_owner_1.java
+++ b/gerrit-server/src/main/java/gerrit/PRED_change_owner_1.java
@@ -16,7 +16,6 @@
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.rules.StoredValues;
-
import com.googlecode.prolog_cafe.exceptions.PrologException;
import com.googlecode.prolog_cafe.lang.IntegerTerm;
import com.googlecode.prolog_cafe.lang.Operation;
diff --git a/gerrit-server/src/main/java/gerrit/PRED_change_project_1.java b/gerrit-server/src/main/java/gerrit/PRED_change_project_1.java
index e131605..568ef2b 100644
--- a/gerrit-server/src/main/java/gerrit/PRED_change_project_1.java
+++ b/gerrit-server/src/main/java/gerrit/PRED_change_project_1.java
@@ -16,7 +16,6 @@
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.rules.StoredValues;
-
import com.googlecode.prolog_cafe.exceptions.PrologException;
import com.googlecode.prolog_cafe.lang.Operation;
import com.googlecode.prolog_cafe.lang.Predicate;
diff --git a/gerrit-server/src/main/java/gerrit/PRED_change_topic_1.java b/gerrit-server/src/main/java/gerrit/PRED_change_topic_1.java
index d1a91d9..534d097 100644
--- a/gerrit-server/src/main/java/gerrit/PRED_change_topic_1.java
+++ b/gerrit-server/src/main/java/gerrit/PRED_change_topic_1.java
@@ -16,7 +16,6 @@
import com.google.gerrit.reviewdb.client.Change;
import com.google.gerrit.rules.StoredValues;
-
import com.googlecode.prolog_cafe.exceptions.PrologException;
import com.googlecode.prolog_cafe.lang.Operation;
import com.googlecode.prolog_cafe.lang.Predicate;
diff --git a/gerrit-server/src/main/java/gerrit/PRED_commit_author_3.java b/gerrit-server/src/main/java/gerrit/PRED_commit_author_3.java
index 9ef68f5..51d0913 100644
--- a/gerrit-server/src/main/java/gerrit/PRED_commit_author_3.java
+++ b/gerrit-server/src/main/java/gerrit/PRED_commit_author_3.java
@@ -17,7 +17,6 @@
import com.google.gerrit.reviewdb.client.PatchSetInfo;
import com.google.gerrit.reviewdb.client.UserIdentity;
import com.google.gerrit.rules.StoredValues;
-
import com.googlecode.prolog_cafe.exceptions.PrologException;
import com.googlecode.prolog_cafe.lang.Operation;
import com.googlecode.prolog_cafe.lang.Prolog;
diff --git a/gerrit-server/src/main/java/gerrit/PRED_commit_committer_3.java b/gerrit-server/src/main/java/gerrit/PRED_commit_committer_3.java
index d73ed9b..7fa9ff4 100644
--- a/gerrit-server/src/main/java/gerrit/PRED_commit_committer_3.java
+++ b/gerrit-server/src/main/java/gerrit/PRED_commit_committer_3.java
@@ -17,7 +17,6 @@
import com.google.gerrit.reviewdb.client.PatchSetInfo;
import com.google.gerrit.reviewdb.client.UserIdentity;
import com.google.gerrit.rules.StoredValues;
-
import com.googlecode.prolog_cafe.exceptions.PrologException;
import com.googlecode.prolog_cafe.lang.Operation;
import com.googlecode.prolog_cafe.lang.Prolog;
diff --git a/gerrit-server/src/main/java/gerrit/PRED_commit_delta_4.java b/gerrit-server/src/main/java/gerrit/PRED_commit_delta_4.java
index 8fcb98c..97e5219 100644
--- a/gerrit-server/src/main/java/gerrit/PRED_commit_delta_4.java
+++ b/gerrit-server/src/main/java/gerrit/PRED_commit_delta_4.java
@@ -18,7 +18,6 @@
import com.google.gerrit.rules.StoredValues;
import com.google.gerrit.server.patch.PatchList;
import com.google.gerrit.server.patch.PatchListEntry;
-
import com.googlecode.prolog_cafe.exceptions.IllegalTypeException;
import com.googlecode.prolog_cafe.exceptions.PInstantiationException;
import com.googlecode.prolog_cafe.exceptions.PrologException;
@@ -29,15 +28,13 @@
import com.googlecode.prolog_cafe.lang.SymbolTerm;
import com.googlecode.prolog_cafe.lang.Term;
import com.googlecode.prolog_cafe.lang.VariableTerm;
-
import java.util.Iterator;
import java.util.regex.Pattern;
/**
- * Given a regular expression, checks it against the file list in the most
- * recent patchset of a change. For all files that match the regex, returns the
- * (new) path of the file, the change type, and the old path of the file if
- * applicable (if the file was copied or renamed).
+ * Given a regular expression, checks it against the file list in the most recent patchset of a
+ * change. For all files that match the regex, returns the (new) path of the file, the change type,
+ * and the old path of the file if applicable (if the file was copied or renamed).
*
* <pre>
* 'commit_delta'(+Regex, -ChangeType, -NewPath, -OldPath)
@@ -96,10 +93,9 @@
Term a4 = engine.r4;
Term a5 = engine.r5;
- Pattern regex = (Pattern)((JavaObjectTerm)a1).object();
+ Pattern regex = (Pattern) ((JavaObjectTerm) a1).object();
@SuppressWarnings("unchecked")
- Iterator<PatchListEntry> iter =
- (Iterator<PatchListEntry>)((JavaObjectTerm)a5).object();
+ Iterator<PatchListEntry> iter = (Iterator<PatchListEntry>) ((JavaObjectTerm) a5).object();
while (iter.hasNext()) {
PatchListEntry patch = iter.next();
String newName = patch.getNewName();
@@ -110,8 +106,7 @@
continue;
}
- if (regex.matcher(newName).find() ||
- (oldName != null && regex.matcher(oldName).find())) {
+ if (regex.matcher(newName).find() || (oldName != null && regex.matcher(oldName).find())) {
SymbolTerm changeSym = getTypeSymbol(changeType);
SymbolTerm newSym = SymbolTerm.create(newName);
SymbolTerm oldSym = Prolog.Nil;
@@ -148,8 +143,7 @@
Term a5 = engine.r5;
@SuppressWarnings("unchecked")
- Iterator<PatchListEntry> iter =
- (Iterator<PatchListEntry>)((JavaObjectTerm)a5).object();
+ Iterator<PatchListEntry> iter = (Iterator<PatchListEntry>) ((JavaObjectTerm) a5).object();
if (!iter.hasNext()) {
return engine.fail();
}
diff --git a/gerrit-server/src/main/java/gerrit/PRED_commit_edits_2.java b/gerrit-server/src/main/java/gerrit/PRED_commit_edits_2.java
index c97a964..95be5cb 100644
--- a/gerrit-server/src/main/java/gerrit/PRED_commit_edits_2.java
+++ b/gerrit-server/src/main/java/gerrit/PRED_commit_edits_2.java
@@ -18,7 +18,6 @@
import com.google.gerrit.server.patch.PatchList;
import com.google.gerrit.server.patch.PatchListEntry;
import com.google.gerrit.server.patch.Text;
-
import com.googlecode.prolog_cafe.exceptions.IllegalTypeException;
import com.googlecode.prolog_cafe.exceptions.JavaException;
import com.googlecode.prolog_cafe.exceptions.PInstantiationException;
@@ -29,7 +28,9 @@
import com.googlecode.prolog_cafe.lang.SymbolTerm;
import com.googlecode.prolog_cafe.lang.Term;
import com.googlecode.prolog_cafe.lang.VariableTerm;
-
+import java.io.IOException;
+import java.util.List;
+import java.util.regex.Pattern;
import org.eclipse.jgit.diff.Edit;
import org.eclipse.jgit.errors.CorruptObjectException;
import org.eclipse.jgit.errors.IncorrectObjectTypeException;
@@ -43,13 +44,8 @@
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.treewalk.TreeWalk;
-import java.io.IOException;
-import java.util.List;
-import java.util.regex.Pattern;
-
/**
- * Returns true if any of the files that match FileNameRegex have edited lines
- * that match EditRegex
+ * Returns true if any of the files that match FileNameRegex have edited lines that match EditRegex
*
* <pre>
* 'commit_edits'(+FileNameRegex, +EditRegex)
@@ -98,8 +94,8 @@
continue;
}
- if (fileRegex.matcher(newName).find() ||
- (oldName != null && fileRegex.matcher(oldName).find())) {
+ if (fileRegex.matcher(newName).find()
+ || (oldName != null && fileRegex.matcher(oldName).find())) {
List<Edit> edits = entry.getEdits();
if (edits.isEmpty()) {
@@ -146,8 +142,8 @@
}
private Text load(final ObjectId tree, final String path, final ObjectReader reader)
- throws MissingObjectException, IncorrectObjectTypeException,
- CorruptObjectException, IOException {
+ throws MissingObjectException, IncorrectObjectTypeException, CorruptObjectException,
+ IOException {
if (path == null) {
return Text.EMPTY;
}
diff --git a/gerrit-server/src/main/java/gerrit/PRED_commit_message_1.java b/gerrit-server/src/main/java/gerrit/PRED_commit_message_1.java
index 6fc1c2f..16a5b13 100644
--- a/gerrit-server/src/main/java/gerrit/PRED_commit_message_1.java
+++ b/gerrit-server/src/main/java/gerrit/PRED_commit_message_1.java
@@ -16,7 +16,6 @@
import com.google.gerrit.reviewdb.client.PatchSetInfo;
import com.google.gerrit.rules.StoredValues;
-
import com.googlecode.prolog_cafe.exceptions.PrologException;
import com.googlecode.prolog_cafe.lang.Operation;
import com.googlecode.prolog_cafe.lang.Predicate;
diff --git a/gerrit-server/src/main/java/gerrit/PRED_commit_stats_3.java b/gerrit-server/src/main/java/gerrit/PRED_commit_stats_3.java
index a855868..6ed82e5 100644
--- a/gerrit-server/src/main/java/gerrit/PRED_commit_stats_3.java
+++ b/gerrit-server/src/main/java/gerrit/PRED_commit_stats_3.java
@@ -18,14 +18,12 @@
import com.google.gerrit.rules.StoredValues;
import com.google.gerrit.server.patch.PatchList;
import com.google.gerrit.server.patch.PatchListEntry;
-
import com.googlecode.prolog_cafe.exceptions.PrologException;
import com.googlecode.prolog_cafe.lang.IntegerTerm;
import com.googlecode.prolog_cafe.lang.Operation;
import com.googlecode.prolog_cafe.lang.Predicate;
import com.googlecode.prolog_cafe.lang.Prolog;
import com.googlecode.prolog_cafe.lang.Term;
-
import java.util.List;
/**
@@ -54,15 +52,13 @@
PatchList pl = StoredValues.PATCH_LIST.get(engine);
// Account for magic files
if (!a1.unify(
- new IntegerTerm(
- pl.getPatches().size() - countMagicFiles(pl.getPatches())),
- engine.trail)) {
+ new IntegerTerm(pl.getPatches().size() - countMagicFiles(pl.getPatches())), engine.trail)) {
return engine.fail();
}
- if (!a2.unify(new IntegerTerm(pl.getInsertions()),engine.trail)) {
+ if (!a2.unify(new IntegerTerm(pl.getInsertions()), engine.trail)) {
return engine.fail();
}
- if (!a3.unify(new IntegerTerm(pl.getDeletions()),engine.trail)) {
+ if (!a3.unify(new IntegerTerm(pl.getDeletions()), engine.trail)) {
return engine.fail();
}
return cont;
diff --git a/gerrit-server/src/main/java/gerrit/PRED_current_user_1.java b/gerrit-server/src/main/java/gerrit/PRED_current_user_1.java
index a3e1a96..6dc1e52 100644
--- a/gerrit-server/src/main/java/gerrit/PRED_current_user_1.java
+++ b/gerrit-server/src/main/java/gerrit/PRED_current_user_1.java
@@ -19,7 +19,6 @@
import com.google.gerrit.server.AnonymousUser;
import com.google.gerrit.server.CurrentUser;
import com.google.gerrit.server.PeerDaemonUser;
-
import com.googlecode.prolog_cafe.exceptions.EvaluationException;
import com.googlecode.prolog_cafe.exceptions.PrologException;
import com.googlecode.prolog_cafe.lang.IntegerTerm;
@@ -47,8 +46,7 @@
CurrentUser curUser = StoredValues.CURRENT_USER.getOrNull(engine);
if (curUser == null) {
- throw new EvaluationException(
- "Current user not available in this rule type");
+ throw new EvaluationException("Current user not available in this rule type");
}
Term resultTerm;
diff --git a/gerrit-server/src/main/java/gerrit/PRED_current_user_2.java b/gerrit-server/src/main/java/gerrit/PRED_current_user_2.java
index 87c7138..7da1ce8 100644
--- a/gerrit-server/src/main/java/gerrit/PRED_current_user_2.java
+++ b/gerrit-server/src/main/java/gerrit/PRED_current_user_2.java
@@ -21,7 +21,6 @@
import com.google.gerrit.rules.StoredValues;
import com.google.gerrit.server.CurrentUser;
import com.google.gerrit.server.IdentifiedUser;
-
import com.googlecode.prolog_cafe.exceptions.IllegalTypeException;
import com.googlecode.prolog_cafe.exceptions.PInstantiationException;
import com.googlecode.prolog_cafe.exceptions.PrologException;
@@ -34,14 +33,13 @@
import com.googlecode.prolog_cafe.lang.SymbolTerm;
import com.googlecode.prolog_cafe.lang.Term;
import com.googlecode.prolog_cafe.lang.VariableTerm;
-
import java.util.Map;
/**
* Loads a CurrentUser object for a user identity.
- * <p>
- * Values are cached in the hash {@code current_user}, avoiding recreation
- * during a single evaluation.
+ *
+ * <p>Values are cached in the hash {@code current_user}, avoiding recreation during a single
+ * evaluation.
*
* <pre>
* current_user(user(+AccountId), -CurrentUser).
diff --git a/gerrit-server/src/main/java/gerrit/PRED_get_legacy_label_types_1.java b/gerrit-server/src/main/java/gerrit/PRED_get_legacy_label_types_1.java
index f93e424..ea3fb17 100644
--- a/gerrit-server/src/main/java/gerrit/PRED_get_legacy_label_types_1.java
+++ b/gerrit-server/src/main/java/gerrit/PRED_get_legacy_label_types_1.java
@@ -17,7 +17,6 @@
import com.google.gerrit.common.data.LabelType;
import com.google.gerrit.common.data.LabelValue;
import com.google.gerrit.rules.StoredValues;
-
import com.googlecode.prolog_cafe.exceptions.PrologException;
import com.googlecode.prolog_cafe.lang.IntegerTerm;
import com.googlecode.prolog_cafe.lang.ListTerm;
@@ -27,18 +26,17 @@
import com.googlecode.prolog_cafe.lang.StructureTerm;
import com.googlecode.prolog_cafe.lang.SymbolTerm;
import com.googlecode.prolog_cafe.lang.Term;
-
import java.util.List;
/**
* Obtain a list of label types from the server configuration.
- * <p>
- * Unifies to a Prolog list of: {@code label_type(Label, Fun, Min, Max)}
- * where:
+ *
+ * <p>Unifies to a Prolog list of: {@code label_type(Label, Fun, Min, Max)} where:
+ *
* <ul>
- * <li>{@code Label} - the newer style label name</li>
- * <li>{@code Fun} - legacy function name</li>
- * <li>{@code Min, Max} - the smallest and largest configured values.</li>
+ * <li>{@code Label} - the newer style label name
+ * <li>{@code Fun} - legacy function name
+ * <li>{@code Min, Max} - the smallest and largest configured values.
* </ul>
*/
class PRED_get_legacy_label_types_1 extends Predicate.P1 {
@@ -53,8 +51,7 @@
public Operation exec(Prolog engine) throws PrologException {
engine.setB0();
Term a1 = arg1.dereference();
- List<LabelType> list =
- StoredValues.CHANGE_CONTROL.get(engine).getLabelTypes().getLabelTypes();
+ List<LabelType> list = StoredValues.CHANGE_CONTROL.get(engine).getLabelTypes().getLabelTypes();
Term head = Prolog.Nil;
for (int idx = list.size() - 1; 0 <= idx; idx--) {
head = new ListTerm(export(list.get(idx)), head);
@@ -66,13 +63,13 @@
return cont;
}
- static final SymbolTerm symLabelType = SymbolTerm.intern(
- "label_type", 4);
+ static final SymbolTerm symLabelType = SymbolTerm.intern("label_type", 4);
static Term export(LabelType type) {
LabelValue min = type.getMin();
LabelValue max = type.getMax();
- return new StructureTerm(symLabelType,
+ return new StructureTerm(
+ symLabelType,
SymbolTerm.intern(type.getName()),
SymbolTerm.intern(type.getFunctionName()),
min != null ? new IntegerTerm(min.getValue()) : NONE,
diff --git a/gerrit-server/src/main/java/gerrit/PRED_project_default_submit_type_1.java b/gerrit-server/src/main/java/gerrit/PRED_project_default_submit_type_1.java
index b1a8a74..cedad9e 100644
--- a/gerrit-server/src/main/java/gerrit/PRED_project_default_submit_type_1.java
+++ b/gerrit-server/src/main/java/gerrit/PRED_project_default_submit_type_1.java
@@ -17,7 +17,6 @@
import com.google.gerrit.extensions.client.SubmitType;
import com.google.gerrit.rules.StoredValues;
import com.google.gerrit.server.project.ChangeControl;
-
import com.googlecode.prolog_cafe.exceptions.PrologException;
import com.googlecode.prolog_cafe.lang.Operation;
import com.googlecode.prolog_cafe.lang.Predicate;
diff --git a/gerrit-server/src/main/java/gerrit/PRED_uploader_1.java b/gerrit-server/src/main/java/gerrit/PRED_uploader_1.java
index 06977b3..77d31d9 100644
--- a/gerrit-server/src/main/java/gerrit/PRED_uploader_1.java
+++ b/gerrit-server/src/main/java/gerrit/PRED_uploader_1.java
@@ -17,7 +17,6 @@
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.reviewdb.client.PatchSet;
import com.google.gerrit.rules.StoredValues;
-
import com.googlecode.prolog_cafe.exceptions.PrologException;
import com.googlecode.prolog_cafe.lang.IntegerTerm;
import com.googlecode.prolog_cafe.lang.Operation;
@@ -26,13 +25,11 @@
import com.googlecode.prolog_cafe.lang.StructureTerm;
import com.googlecode.prolog_cafe.lang.SymbolTerm;
import com.googlecode.prolog_cafe.lang.Term;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PRED_uploader_1 extends Predicate.P1 {
- private static final Logger log =
- LoggerFactory.getLogger(PRED_uploader_1.class);
+ private static final Logger log = LoggerFactory.getLogger(PRED_uploader_1.class);
private static final SymbolTerm user = SymbolTerm.intern("user", 1);
@@ -48,15 +45,15 @@
PatchSet patchSet = StoredValues.getPatchSet(engine);
if (patchSet == null) {
- log.error("Failed to load current patch set of change "
- + StoredValues.getChange(engine).getChangeId());
+ log.error(
+ "Failed to load current patch set of change "
+ + StoredValues.getChange(engine).getChangeId());
return engine.fail();
}
Account.Id uploaderId = patchSet.getUploader();
- if (!a1.unify(new StructureTerm(user, new IntegerTerm(uploaderId.get())),
- engine.trail)) {
+ if (!a1.unify(new StructureTerm(user, new IntegerTerm(uploaderId.get())), engine.trail)) {
return engine.fail();
}
return cont;
diff --git a/gerrit-server/src/test/java/com/google/gerrit/metrics/proc/ProcMetricModuleTest.java b/gerrit-server/src/test/java/com/google/gerrit/metrics/proc/ProcMetricModuleTest.java
index 70ad137..9974bc6 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/metrics/proc/ProcMetricModuleTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/metrics/proc/ProcMetricModuleTest.java
@@ -16,6 +16,10 @@
import static com.google.common.truth.Truth.assertThat;
+import com.codahale.metrics.Counter;
+import com.codahale.metrics.Gauge;
+import com.codahale.metrics.Metric;
+import com.codahale.metrics.MetricRegistry;
import com.google.gerrit.common.Version;
import com.google.gerrit.lifecycle.LifecycleManager;
import com.google.gerrit.metrics.CallbackMetric0;
@@ -29,29 +33,19 @@
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
-
-import com.codahale.metrics.Counter;
-import com.codahale.metrics.Gauge;
-import com.codahale.metrics.Metric;
-import com.codahale.metrics.MetricRegistry;
-
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicInteger;
-
public class ProcMetricModuleTest {
- @Rule
- public ExpectedException exception = ExpectedException.none();
+ @Rule public ExpectedException exception = ExpectedException.none();
- @Inject
- MetricMaker metrics;
+ @Inject MetricMaker metrics;
- @Inject
- MetricRegistry registry;
+ @Inject MetricRegistry registry;
@Test
public void constantBuildLabel() {
@@ -62,8 +56,8 @@
@Test
public void procUptime() {
Gauge<Long> birth = gauge("proc/birth_timestamp");
- assertThat(birth.getValue()).isAtMost(
- TimeUnit.MILLISECONDS.toMicros(System.currentTimeMillis()));
+ assertThat(birth.getValue())
+ .isAtMost(TimeUnit.MILLISECONDS.toMicros(System.currentTimeMillis()));
Gauge<Long> uptime = gauge("proc/uptime");
assertThat(uptime.getValue()).isAtLeast(1L);
@@ -71,10 +65,8 @@
@Test
public void counter0() {
- Counter0 cntr = metrics.newCounter(
- "test/count",
- new Description("simple test")
- .setCumulative());
+ Counter0 cntr =
+ metrics.newCounter("test/count", new Description("simple test").setCumulative());
Counter raw = get("test/count", Counter.class);
assertThat(raw.getCount()).isEqualTo(0);
@@ -88,11 +80,9 @@
@Test
public void counter1() {
- Counter1<String> cntr = metrics.newCounter(
- "test/count",
- new Description("simple test")
- .setCumulative(),
- Field.ofString("action"));
+ Counter1<String> cntr =
+ metrics.newCounter(
+ "test/count", new Description("simple test").setCumulative(), Field.ofString("action"));
Counter total = get("test/count_total", Counter.class);
assertThat(total.getCount()).isEqualTo(0);
@@ -111,12 +101,13 @@
@Test
public void counterPrefixFields() {
- Counter1<String> cntr = metrics.newCounter(
- "test/count",
- new Description("simple test")
- .setCumulative()
- .setFieldOrdering(FieldOrdering.PREFIX_FIELDS_BASENAME),
- Field.ofString("action"));
+ Counter1<String> cntr =
+ metrics.newCounter(
+ "test/count",
+ new Description("simple test")
+ .setCumulative()
+ .setFieldOrdering(FieldOrdering.PREFIX_FIELDS_BASENAME),
+ Field.ofString("action"));
Counter total = get("test/count_total", Counter.class);
assertThat(total.getCount()).isEqualTo(0);
@@ -135,20 +126,20 @@
@Test
public void callbackMetric0() {
- final CallbackMetric0<Long> cntr = metrics.newCallbackMetric(
- "test/count",
- Long.class,
- new Description("simple test")
- .setCumulative());
+ final CallbackMetric0<Long> cntr =
+ metrics.newCallbackMetric(
+ "test/count", Long.class, new Description("simple test").setCumulative());
final AtomicInteger invocations = new AtomicInteger(0);
- metrics.newTrigger(cntr, new Runnable() {
- @Override
- public void run() {
- invocations.getAndIncrement();
- cntr.set(42L);
- }
- });
+ metrics.newTrigger(
+ cntr,
+ new Runnable() {
+ @Override
+ public void run() {
+ invocations.getAndIncrement();
+ cntr.set(42L);
+ }
+ });
// Triggers run immediately with DropWizard binding.
assertThat(invocations.get()).isEqualTo(1);
@@ -189,8 +180,7 @@
@Before
public void setup() {
- Injector injector =
- Guice.createInjector(new DropWizardMetricMaker.ApiModule());
+ Injector injector = Guice.createInjector(new DropWizardMetricMaker.ApiModule());
LifecycleManager mgr = new LifecycleManager();
mgr.add(injector);
diff --git a/gerrit-server/src/test/java/com/google/gerrit/rules/GerritCommonTest.java b/gerrit-server/src/test/java/com/google/gerrit/rules/GerritCommonTest.java
index 279ad61..28f10d9 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/rules/GerritCommonTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/rules/GerritCommonTest.java
@@ -20,49 +20,41 @@
import com.google.gerrit.server.project.ChangeControl;
import com.google.gerrit.server.project.Util;
import com.google.inject.AbstractModule;
-
import com.googlecode.prolog_cafe.exceptions.CompileException;
import com.googlecode.prolog_cafe.exceptions.ReductionLimitException;
import com.googlecode.prolog_cafe.lang.JavaObjectTerm;
import com.googlecode.prolog_cafe.lang.Prolog;
import com.googlecode.prolog_cafe.lang.StructureTerm;
import com.googlecode.prolog_cafe.lang.SymbolTerm;
-
+import java.io.PushbackReader;
+import java.io.StringReader;
+import java.util.Arrays;
import org.easymock.EasyMock;
import org.eclipse.jgit.lib.Config;
import org.junit.Before;
import org.junit.Test;
-import java.io.PushbackReader;
-import java.io.StringReader;
-import java.util.Arrays;
-
public class GerritCommonTest extends PrologTestCase {
@Before
public void setUp() throws Exception {
- load("gerrit", "gerrit_common_test.pl", new AbstractModule() {
- @Override
- protected void configure() {
- Config cfg = new Config();
- cfg.setInt("rules", null, "reductionLimit", 1300);
- cfg.setInt("rules", null, "compileReductionLimit", (int) 1e6);
- bind(PrologEnvironment.Args.class).toInstance(
- new PrologEnvironment.Args(
- null,
- null,
- null,
- null,
- null,
- null,
- cfg));
- }
- });
+ load(
+ "gerrit",
+ "gerrit_common_test.pl",
+ new AbstractModule() {
+ @Override
+ protected void configure() {
+ Config cfg = new Config();
+ cfg.setInt("rules", null, "reductionLimit", 1300);
+ cfg.setInt("rules", null, "compileReductionLimit", (int) 1e6);
+ bind(PrologEnvironment.Args.class)
+ .toInstance(new PrologEnvironment.Args(null, null, null, null, null, null, cfg));
+ }
+ });
}
@Override
protected void setUpEnvironment(PrologEnvironment env) {
- LabelTypes labelTypes =
- new LabelTypes(Arrays.asList(Util.codeReview(), Util.verified()));
+ LabelTypes labelTypes = new LabelTypes(Arrays.asList(Util.codeReview(), Util.verified()));
ChangeControl ctl = EasyMock.createMock(ChangeControl.class);
expect(ctl.getLabelTypes()).andStubReturn(labelTypes);
EasyMock.replay(ctl);
@@ -79,20 +71,20 @@
PrologEnvironment env = envFactory.create(machine);
setUpEnvironment(env);
- String script = "loopy :- b(5).\n"
- + "b(N) :- N > 0, !, S = N - 1, b(S).\n"
- + "b(_) :- true.\n";
+ String script = "loopy :- b(5).\n" + "b(N) :- N > 0, !, S = N - 1, b(S).\n" + "b(_) :- true.\n";
SymbolTerm nameTerm = SymbolTerm.create("testReductionLimit");
- JavaObjectTerm inTerm = new JavaObjectTerm(
- new PushbackReader(new StringReader(script), Prolog.PUSHBACK_SIZE));
+ JavaObjectTerm inTerm =
+ new JavaObjectTerm(new PushbackReader(new StringReader(script), Prolog.PUSHBACK_SIZE));
if (!env.execute(Prolog.BUILTIN, "consult_stream", nameTerm, inTerm)) {
throw new CompileException("Cannot consult " + nameTerm);
}
exception.expect(ReductionLimitException.class);
exception.expectMessage("exceeded reduction limit of 1300");
- env.once(Prolog.BUILTIN, "call", new StructureTerm(":",
- SymbolTerm.create("user"), SymbolTerm.create("loopy")));
+ env.once(
+ Prolog.BUILTIN,
+ "call",
+ new StructureTerm(":", SymbolTerm.create("user"), SymbolTerm.create("loopy")));
}
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/rules/PrologTestCase.java b/gerrit-server/src/test/java/com/google/gerrit/rules/PrologTestCase.java
index dc8004a..6f6d189 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/rules/PrologTestCase.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/rules/PrologTestCase.java
@@ -22,7 +22,6 @@
import com.google.gerrit.testutil.GerritBaseTests;
import com.google.inject.Guice;
import com.google.inject.Module;
-
import com.googlecode.prolog_cafe.exceptions.CompileException;
import com.googlecode.prolog_cafe.lang.BufferingPrologControl;
import com.googlecode.prolog_cafe.lang.JavaObjectTerm;
@@ -33,7 +32,6 @@
import com.googlecode.prolog_cafe.lang.SymbolTerm;
import com.googlecode.prolog_cafe.lang.Term;
import com.googlecode.prolog_cafe.lang.VariableTerm;
-
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
@@ -44,7 +42,6 @@
import java.util.Arrays;
import java.util.List;
-
/** Base class for any tests written in Prolog. */
public abstract class PrologTestCase extends GerritBaseTests {
private static final SymbolTerm test_1 = SymbolTerm.intern("test", 1);
@@ -62,8 +59,7 @@
moduleList.add(new PrologModule.EnvironmentModule());
moduleList.addAll(Arrays.asList(modules));
- envFactory = Guice.createInjector(moduleList)
- .getInstance(PrologEnvironment.Factory.class);
+ envFactory = Guice.createInjector(moduleList).getInstance(PrologEnvironment.Factory.class);
PrologEnvironment env = envFactory.create(newMachine());
consult(env, getClass(), prologResource);
@@ -71,9 +67,9 @@
hasSetup = has(env, "setup");
hasTeardown = has(env, "teardown");
- StructureTerm head = new StructureTerm(":",
- SymbolTerm.intern(pkg),
- new StructureTerm(test_1, new VariableTerm()));
+ StructureTerm head =
+ new StructureTerm(
+ ":", SymbolTerm.intern(pkg), new StructureTerm(test_1, new VariableTerm()));
tests = new ArrayList<>();
for (Term[] pair : env.all(Prolog.BUILTIN, "clause", head, new VariableTerm())) {
@@ -88,8 +84,7 @@
*
* @param env Prolog environment.
*/
- protected void setUpEnvironment(PrologEnvironment env) {
- }
+ protected void setUpEnvironment(PrologEnvironment env) {}
private PrologMachineCopy newMachine() {
BufferingPrologControl ctl = new BufferingPrologControl();
@@ -98,17 +93,17 @@
return PrologMachineCopy.save(ctl);
}
- protected void consult(BufferingPrologControl env,
- Class<?> clazz,
- String prologResource) throws CompileException, IOException {
+ protected void consult(BufferingPrologControl env, Class<?> clazz, String prologResource)
+ throws CompileException, IOException {
try (InputStream in = clazz.getResourceAsStream(prologResource)) {
if (in == null) {
throw new FileNotFoundException(prologResource);
}
SymbolTerm pathTerm = SymbolTerm.create(prologResource);
JavaObjectTerm inTerm =
- new JavaObjectTerm(new PushbackReader(new BufferedReader(
- new InputStreamReader(in, UTF_8)), Prolog.PUSHBACK_SIZE));
+ new JavaObjectTerm(
+ new PushbackReader(
+ new BufferedReader(new InputStreamReader(in, UTF_8)), Prolog.PUSHBACK_SIZE));
if (!env.execute(Prolog.BUILTIN, "consult_stream", pathTerm, inTerm)) {
throw new CompileException("Cannot consult " + prologResource);
}
@@ -161,13 +156,14 @@
}
if (all.size() != 1) {
- errors++;
+ errors++;
}
}
long end = TimeUtil.nowMs();
System.out.println("-------------------------------");
- System.out.format("Prolog tests: %d, Failures: %d, Time elapsed %.3f sec",
+ System.out.format(
+ "Prolog tests: %d, Failures: %d, Time elapsed %.3f sec",
tests.size(), errors, (end - start) / 1000.0);
System.out.println();
@@ -177,9 +173,9 @@
private void call(BufferingPrologControl env, String name) {
StructureTerm head = SymbolTerm.create(pkg, name, 0);
assert_()
- .withFailureMessage("Cannot invoke " + pkg + ":" + name)
- .that(env.execute(Prolog.BUILTIN, "call", head))
- .isTrue();
+ .withFailureMessage("Cannot invoke " + pkg + ":" + name)
+ .that(env.execute(Prolog.BUILTIN, "call", head))
+ .isTrue();
}
private Term removePackage(Term test) {
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/ChangeUtilTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/ChangeUtilTest.java
index 92d3a1c..5f73d2c 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/ChangeUtilTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/ChangeUtilTest.java
@@ -16,9 +16,8 @@
import static com.google.common.truth.Truth.assertThat;
-import org.junit.Test;
-
import java.util.regex.Pattern;
+import org.junit.Test;
public class ChangeUtilTest {
@Test
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/IdentifiedUserTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/IdentifiedUserTest.java
index c746c63..4689688 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/IdentifiedUserTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/IdentifiedUserTest.java
@@ -37,25 +37,21 @@
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.util.Providers;
-
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
import org.eclipse.jgit.lib.Config;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Set;
-
@RunWith(ConfigSuite.class)
public class IdentifiedUserTest {
- @ConfigSuite.Parameter
- public Config config;
+ @ConfigSuite.Parameter public Config config;
private IdentifiedUser identifiedUser;
- @Inject
- private IdentifiedUser.GenericFactory identifiedUserFactory;
+ @Inject private IdentifiedUser.GenericFactory identifiedUserFactory;
private static final String[] TEST_CASES = {
"",
@@ -66,37 +62,42 @@
@Before
public void setUp() throws Exception {
final FakeAccountCache accountCache = new FakeAccountCache();
- final Realm mockRealm = new FakeRealm() {
- HashSet<String> emails = new HashSet<>(Arrays.asList(TEST_CASES));
+ final Realm mockRealm =
+ new FakeRealm() {
+ HashSet<String> emails = new HashSet<>(Arrays.asList(TEST_CASES));
- @Override
- public boolean hasEmailAddress(IdentifiedUser who, String email) {
- return emails.contains(email);
- }
+ @Override
+ public boolean hasEmailAddress(IdentifiedUser who, String email) {
+ return emails.contains(email);
+ }
- @Override
- public Set<String> getEmailAddresses(IdentifiedUser who) {
- return emails;
- }
- };
+ @Override
+ public Set<String> getEmailAddresses(IdentifiedUser who) {
+ return emails;
+ }
+ };
- AbstractModule mod = new AbstractModule() {
- @Override
- protected void configure() {
- bind(Boolean.class).annotatedWith(DisableReverseDnsLookup.class)
- .toInstance(Boolean.FALSE);
- bind(Config.class).annotatedWith(GerritServerConfig.class).toInstance(config);
- bind(String.class).annotatedWith(AnonymousCowardName.class)
- .toProvider(AnonymousCowardNameProvider.class);
- bind(String.class).annotatedWith(CanonicalWebUrl.class)
- .toInstance("http://localhost:8080/");
- bind(AccountCache.class).toInstance(accountCache);
- bind(GroupBackend.class).to(SystemGroupBackend.class).in(SINGLETON);
- bind(CapabilityControl.Factory.class)
- .toProvider(Providers.<CapabilityControl.Factory>of(null));
- bind(Realm.class).toInstance(mockRealm);
- }
- };
+ AbstractModule mod =
+ new AbstractModule() {
+ @Override
+ protected void configure() {
+ bind(Boolean.class)
+ .annotatedWith(DisableReverseDnsLookup.class)
+ .toInstance(Boolean.FALSE);
+ bind(Config.class).annotatedWith(GerritServerConfig.class).toInstance(config);
+ bind(String.class)
+ .annotatedWith(AnonymousCowardName.class)
+ .toProvider(AnonymousCowardNameProvider.class);
+ bind(String.class)
+ .annotatedWith(CanonicalWebUrl.class)
+ .toInstance("http://localhost:8080/");
+ bind(AccountCache.class).toInstance(accountCache);
+ bind(GroupBackend.class).to(SystemGroupBackend.class).in(SINGLETON);
+ bind(CapabilityControl.Factory.class)
+ .toProvider(Providers.<CapabilityControl.Factory>of(null));
+ bind(Realm.class).toInstance(mockRealm);
+ }
+ };
Injector injector = Guice.createInjector(mod);
injector.injectMembers(this);
@@ -122,7 +123,6 @@
assertThat(identifiedUser.hasEmailAddress(TEST_CASES[2])).isTrue();
assertThat(identifiedUser.hasEmailAddress(TEST_CASES[2].toLowerCase())).isTrue();
-
assertThat(identifiedUser.hasEmailAddress("non-exist@email.com")).isFalse();
/* assert again to test cached email address by IdentifiedUser.invalidEmails */
assertThat(identifiedUser.hasEmailAddress("non-exist@email.com")).isFalse();
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/StringUtilTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/StringUtilTest.java
index ed42c40..acf2577 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/StringUtilTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/StringUtilTest.java
@@ -19,39 +19,31 @@
import org.junit.Test;
public class StringUtilTest {
- /**
- * Test the boundary condition that the first character of a string
- * should be escaped.
- */
+ /** Test the boundary condition that the first character of a string should be escaped. */
@Test
public void escapeFirstChar() {
assertEquals(StringUtil.escapeString("\tLeading tab"), "\\tLeading tab");
}
- /**
- * Test the boundary condition that the last character of a string
- * should be escaped.
- */
+ /** Test the boundary condition that the last character of a string should be escaped. */
@Test
public void escapeLastChar() {
assertEquals(StringUtil.escapeString("Trailing tab\t"), "Trailing tab\\t");
}
- /**
- * Test that various forms of input strings are escaped (or left as-is)
- * in the expected way.
- */
+ /** Test that various forms of input strings are escaped (or left as-is) in the expected way. */
@Test
public void escapeString() {
- final String[] testPairs =
- { "", "",
- "plain string", "plain string",
- "string with \"quotes\"", "string with \"quotes\"",
- "string with 'quotes'", "string with 'quotes'",
- "string with 'quotes'", "string with 'quotes'",
- "C:\\Program Files\\MyProgram", "C:\\\\Program Files\\\\MyProgram",
- "string\nwith\nnewlines", "string\\nwith\\nnewlines",
- "string\twith\ttabs", "string\\twith\\ttabs", };
+ final String[] testPairs = {
+ "", "",
+ "plain string", "plain string",
+ "string with \"quotes\"", "string with \"quotes\"",
+ "string with 'quotes'", "string with 'quotes'",
+ "string with 'quotes'", "string with 'quotes'",
+ "C:\\Program Files\\MyProgram", "C:\\\\Program Files\\\\MyProgram",
+ "string\nwith\nnewlines", "string\\nwith\\nnewlines",
+ "string\twith\ttabs", "string\\twith\\ttabs",
+ };
for (int i = 0; i < testPairs.length; i += 2) {
assertEquals(StringUtil.escapeString(testPairs[i]), testPairs[i + 1]);
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/account/AuthorizedKeysTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/account/AuthorizedKeysTest.java
index 585dd04..4b43197 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/account/AuthorizedKeysTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/account/AuthorizedKeysTest.java
@@ -18,39 +18,37 @@
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.reviewdb.client.AccountSshKey;
-
-import org.junit.Test;
-
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
+import org.junit.Test;
public class AuthorizedKeysTest {
private static final String KEY1 =
"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQCgug5VyMXQGnem2H1KVC4/HcRcD4zzBqS"
- + "uJBRWVonSSoz3RoAZ7bWXCVVGwchtXwUURD689wFYdiPecOrWOUgeeyRq754YWRhU+W28"
- + "vf8IZixgjCmiBhaL2gt3wff6pP+NXJpTSA4aeWE5DfNK5tZlxlSxqkKOS8JRSUeNQov5T"
- + "w== john.doe@example.com";
+ + "uJBRWVonSSoz3RoAZ7bWXCVVGwchtXwUURD689wFYdiPecOrWOUgeeyRq754YWRhU+W28"
+ + "vf8IZixgjCmiBhaL2gt3wff6pP+NXJpTSA4aeWE5DfNK5tZlxlSxqkKOS8JRSUeNQov5T"
+ + "w== john.doe@example.com";
private static final String KEY2 =
"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQDm5yP7FmEoqzQRDyskX+9+N0q9GrvZeh5"
- + "RG52EUpE4ms/Ujm3ewV1LoGzc/lYKJAIbdcZQNJ9+06EfWZaIRA3oOwAPe1eCnX+aLr8E"
- + "6Tw2gDMQOGc5e9HfyXpC2pDvzauoZNYqLALOG3y/1xjo7IH8GYRS2B7zO/Mf9DdCcCKSf"
- + "w== john.doe@example.com";
+ + "RG52EUpE4ms/Ujm3ewV1LoGzc/lYKJAIbdcZQNJ9+06EfWZaIRA3oOwAPe1eCnX+aLr8E"
+ + "6Tw2gDMQOGc5e9HfyXpC2pDvzauoZNYqLALOG3y/1xjo7IH8GYRS2B7zO/Mf9DdCcCKSf"
+ + "w== john.doe@example.com";
private static final String KEY3 =
"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQCaS7RHEcZ/zjl9hkWkqnm29RNr2OQ/TZ5"
- + "jk2qBVMH3BgzPsTsEs+7ag9tfD8OCj+vOcwm626mQBZoR2e3niHa/9gnHBHFtOrGfzKbp"
- + "RjTWtiOZbB9HF+rqMVD+Dawo/oicX/dDg7VAgOFSPothe6RMhbgWf84UcK5aQd5eP5y+t"
- + "Q== john.doe@example.com";
+ + "jk2qBVMH3BgzPsTsEs+7ag9tfD8OCj+vOcwm626mQBZoR2e3niHa/9gnHBHFtOrGfzKbp"
+ + "RjTWtiOZbB9HF+rqMVD+Dawo/oicX/dDg7VAgOFSPothe6RMhbgWf84UcK5aQd5eP5y+t"
+ + "Q== john.doe@example.com";
private static final String KEY4 =
"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQDIJzW9BaAeO+upFletwwEBnGS15lJmS5i"
- + "08/NiFef0jXtNNKcLtnd13bq8jOi5VA2is0bwof1c8YbwcvUkdFa8RL5aXoyZBpfYZsWs"
- + "/YBLZGiHy5rjooMZQMnH37A50cBPnXr0AQz0WRBxLDBDyOZho+O/DfYAKv4rzPSQ3yw4+"
- + "w== john.doe@example.com";
+ + "08/NiFef0jXtNNKcLtnd13bq8jOi5VA2is0bwof1c8YbwcvUkdFa8RL5aXoyZBpfYZsWs"
+ + "/YBLZGiHy5rjooMZQMnH37A50cBPnXr0AQz0WRBxLDBDyOZho+O/DfYAKv4rzPSQ3yw4+"
+ + "w== john.doe@example.com";
private static final String KEY5 =
"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQCgBRKGhiXvY6D9sM+Vbth5Kate57YF7kD"
- + "rqIyUiYIMJK93/AXc8qR/J/p3OIFQAxvLz1qozAur3j5HaiwvxVU19IiSA0vafdhaDLRi"
- + "zRuEL5e/QOu9yGq9xkWApCmg6edpWAHG+Bx4AldU78MiZvzoB7gMMdxc9RmZ1gYj/DjxV"
- + "w== john.doe@example.com";
+ + "rqIyUiYIMJK93/AXc8qR/J/p3OIFQAxvLz1qozAur3j5HaiwvxVU19IiSA0vafdhaDLRi"
+ + "zRuEL5e/QOu9yGq9xkWApCmg6edpWAHG+Bx4AldU78MiZvzoB7gMMdxc9RmZ1gYj/DjxV"
+ + "w== john.doe@example.com";
@Test
public void test() throws Exception {
@@ -105,26 +103,25 @@
authorizedKeys.append(toWindowsLineEndings(addKey(keys, KEY5)));
assertParse(authorizedKeys, keys);
-
}
private static String toWindowsLineEndings(String s) {
return s.replaceAll("\n", "\r\n");
}
- private static void assertSerialization(List<Optional<AccountSshKey>> keys,
- StringBuilder expected) {
+ private static void assertSerialization(
+ List<Optional<AccountSshKey>> keys, StringBuilder expected) {
assertThat(AuthorizedKeys.serialize(keys)).isEqualTo(expected.toString());
}
- private static void assertParse(StringBuilder authorizedKeys,
- List<Optional<AccountSshKey>> expectedKeys) {
+ private static void assertParse(
+ StringBuilder authorizedKeys, List<Optional<AccountSshKey>> expectedKeys) {
Account.Id accountId = new Account.Id(1);
List<Optional<AccountSshKey>> parsedKeys =
AuthorizedKeys.parse(accountId, authorizedKeys.toString());
assertThat(parsedKeys).containsExactlyElementsIn(expectedKeys);
int seq = 1;
- for(Optional<AccountSshKey> sshKey : parsedKeys) {
+ for (Optional<AccountSshKey> sshKey : parsedKeys) {
if (sshKey.isPresent()) {
assertThat(sshKey.get().getAccount()).isEqualTo(accountId);
assertThat(sshKey.get().getKey().get()).isEqualTo(seq);
@@ -139,8 +136,7 @@
* @return the expected line for this key in the authorized_keys file
*/
private static String addKey(List<Optional<AccountSshKey>> keys, String pub) {
- AccountSshKey.Id keyId =
- new AccountSshKey.Id(new Account.Id(1), keys.size() + 1);
+ AccountSshKey.Id keyId = new AccountSshKey.Id(new Account.Id(1), keys.size() + 1);
AccountSshKey key = new AccountSshKey(keyId, pub);
keys.add(Optional.of(key));
return key.getSshPublicKey() + "\n";
@@ -151,15 +147,12 @@
*
* @return the expected line for this key in the authorized_keys file
*/
- private static String addInvalidKey(List<Optional<AccountSshKey>> keys,
- String pub) {
- AccountSshKey.Id keyId =
- new AccountSshKey.Id(new Account.Id(1), keys.size() + 1);
+ private static String addInvalidKey(List<Optional<AccountSshKey>> keys, String pub) {
+ AccountSshKey.Id keyId = new AccountSshKey.Id(new Account.Id(1), keys.size() + 1);
AccountSshKey key = new AccountSshKey(keyId, pub);
key.setInvalid();
keys.add(Optional.of(key));
- return AuthorizedKeys.INVALID_KEY_COMMENT_PREFIX
- + key.getSshPublicKey() + "\n";
+ return AuthorizedKeys.INVALID_KEY_COMMENT_PREFIX + key.getSshPublicKey() + "\n";
}
/**
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/account/UniversalGroupBackendTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/account/UniversalGroupBackendTest.java
index 660edc9..5444c5b 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/account/UniversalGroupBackendTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/account/UniversalGroupBackendTest.java
@@ -36,17 +36,14 @@
import com.google.gerrit.server.IdentifiedUser;
import com.google.gerrit.server.group.SystemGroupBackend;
import com.google.gerrit.testutil.GerritBaseTests;
-
+import java.util.Set;
import org.easymock.IAnswer;
import org.eclipse.jgit.lib.Config;
import org.junit.Before;
import org.junit.Test;
-import java.util.Set;
-
public class UniversalGroupBackendTest extends GerritBaseTests {
- private static final AccountGroup.UUID OTHER_UUID =
- new AccountGroup.UUID("other");
+ private static final AccountGroup.UUID OTHER_UUID = new AccountGroup.UUID("other");
private UniversalGroupBackend backend;
private IdentifiedUser user;
@@ -71,10 +68,8 @@
@Test
public void get() {
- assertEquals("Registered Users",
- backend.get(REGISTERED_USERS).getName());
- assertEquals("Project Owners",
- backend.get(PROJECT_OWNERS).getName());
+ assertEquals("Registered Users", backend.get(REGISTERED_USERS).getName());
+ assertEquals("Project Owners", backend.get(PROJECT_OWNERS).getName());
assertNull(backend.get(OTHER_UUID));
}
@@ -113,25 +108,25 @@
expect(backend.handles(handled)).andStubReturn(true);
expect(backend.handles(not(eq(handled)))).andStubReturn(false);
expect(backend.membershipsOf(anyObject(IdentifiedUser.class)))
- .andStubAnswer(new IAnswer<GroupMembership>() {
- @Override
- public GroupMembership answer() throws Throwable {
- Object[] args = getCurrentArguments();
- GroupMembership membership = createMock(GroupMembership.class);
- expect(membership.contains(eq(handled))).andStubReturn(args[0] == member);
- expect(membership.contains(not(eq(notHandled)))).andStubReturn(false);
- replay(membership);
- return membership;
- }
- });
+ .andStubAnswer(
+ new IAnswer<GroupMembership>() {
+ @Override
+ public GroupMembership answer() throws Throwable {
+ Object[] args = getCurrentArguments();
+ GroupMembership membership = createMock(GroupMembership.class);
+ expect(membership.contains(eq(handled))).andStubReturn(args[0] == member);
+ expect(membership.contains(not(eq(notHandled)))).andStubReturn(false);
+ replay(membership);
+ return membership;
+ }
+ });
replay(member, notMember, backend);
backends = new DynamicSet<>();
backends.add(backend);
backend = new UniversalGroupBackend(backends);
- GroupMembership checker =
- backend.membershipsOf(member);
+ GroupMembership checker = backend.membershipsOf(member);
assertFalse(checker.contains(REGISTERED_USERS));
assertFalse(checker.contains(OTHER_UUID));
assertTrue(checker.contains(handled));
@@ -140,5 +135,4 @@
assertFalse(checker.contains(handled));
assertFalse(checker.contains(notHandled));
}
-
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/account/WatchConfigTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/account/WatchConfigTest.java
index c40ca83..cf61de2 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/account/WatchConfigTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/account/WatchConfigTest.java
@@ -22,17 +22,15 @@
import com.google.gerrit.server.account.WatchConfig.NotifyValue;
import com.google.gerrit.server.account.WatchConfig.ProjectWatchKey;
import com.google.gerrit.server.git.ValidationError;
-
-import org.eclipse.jgit.lib.Config;
-import org.junit.Before;
-import org.junit.Test;
-
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
+import org.eclipse.jgit.lib.Config;
+import org.junit.Before;
+import org.junit.Test;
public class WatchConfigTest implements ValidationError.Sink {
private List<ValidationError> validationErrors = new ArrayList<>();
@@ -45,14 +43,15 @@
@Test
public void parseWatchConfig() throws Exception {
Config cfg = new Config();
- cfg.fromText("[project \"myProject\"]\n"
- + " notify = * [ALL_COMMENTS, NEW_PATCHSETS]\n"
- + " notify = branch:master [NEW_CHANGES]\n"
- + " notify = branch:master [NEW_PATCHSETS]\n"
- + " notify = branch:foo []\n"
- + "[project \"otherProject\"]\n"
- + " notify = [NEW_PATCHSETS]\n"
- + " notify = * [NEW_PATCHSETS, ALL_COMMENTS]\n");
+ cfg.fromText(
+ "[project \"myProject\"]\n"
+ + " notify = * [ALL_COMMENTS, NEW_PATCHSETS]\n"
+ + " notify = branch:master [NEW_CHANGES]\n"
+ + " notify = branch:master [NEW_PATCHSETS]\n"
+ + " notify = branch:foo []\n"
+ + "[project \"otherProject\"]\n"
+ + " notify = [NEW_PATCHSETS]\n"
+ + " notify = * [NEW_PATCHSETS, ALL_COMMENTS]\n");
Map<ProjectWatchKey, Set<NotifyType>> projectWatches =
WatchConfig.parse(new Account.Id(1000000), cfg, this);
@@ -60,18 +59,19 @@
Project.NameKey myProject = new Project.NameKey("myProject");
Project.NameKey otherProject = new Project.NameKey("otherProject");
- Map<ProjectWatchKey, Set<NotifyType>> expectedProjectWatches =
- new HashMap<>();
- expectedProjectWatches.put(ProjectWatchKey.create(myProject, null),
+ Map<ProjectWatchKey, Set<NotifyType>> expectedProjectWatches = new HashMap<>();
+ expectedProjectWatches.put(
+ ProjectWatchKey.create(myProject, null),
EnumSet.of(NotifyType.ALL_COMMENTS, NotifyType.NEW_PATCHSETS));
expectedProjectWatches.put(
ProjectWatchKey.create(myProject, "branch:master"),
EnumSet.of(NotifyType.NEW_CHANGES, NotifyType.NEW_PATCHSETS));
- expectedProjectWatches.put(ProjectWatchKey.create(myProject, "branch:foo"),
- EnumSet.noneOf(NotifyType.class));
- expectedProjectWatches.put(ProjectWatchKey.create(otherProject, null),
- EnumSet.of(NotifyType.NEW_PATCHSETS));
- expectedProjectWatches.put(ProjectWatchKey.create(otherProject, null),
+ expectedProjectWatches.put(
+ ProjectWatchKey.create(myProject, "branch:foo"), EnumSet.noneOf(NotifyType.class));
+ expectedProjectWatches.put(
+ ProjectWatchKey.create(otherProject, null), EnumSet.of(NotifyType.NEW_PATCHSETS));
+ expectedProjectWatches.put(
+ ProjectWatchKey.create(otherProject, null),
EnumSet.of(NotifyType.ALL_COMMENTS, NotifyType.NEW_PATCHSETS));
assertThat(projectWatches).containsExactlyEntriesIn(expectedProjectWatches);
}
@@ -79,35 +79,40 @@
@Test
public void parseInvalidWatchConfig() throws Exception {
Config cfg = new Config();
- cfg.fromText("[project \"myProject\"]\n"
- + " notify = * [ALL_COMMENTS, NEW_PATCHSETS]\n"
- + " notify = branch:master [INVALID, NEW_CHANGES]\n"
- + "[project \"otherProject\"]\n"
- + " notify = [NEW_PATCHSETS]\n");
+ cfg.fromText(
+ "[project \"myProject\"]\n"
+ + " notify = * [ALL_COMMENTS, NEW_PATCHSETS]\n"
+ + " notify = branch:master [INVALID, NEW_CHANGES]\n"
+ + "[project \"otherProject\"]\n"
+ + " notify = [NEW_PATCHSETS]\n");
WatchConfig.parse(new Account.Id(1000000), cfg, this);
assertThat(validationErrors).hasSize(1);
- assertThat(validationErrors.get(0).getMessage()).isEqualTo(
- "watch.config: Invalid notify type INVALID in project watch of"
- + " account 1000000 for project myProject: branch:master"
- + " [INVALID, NEW_CHANGES]");
+ assertThat(validationErrors.get(0).getMessage())
+ .isEqualTo(
+ "watch.config: Invalid notify type INVALID in project watch of"
+ + " account 1000000 for project myProject: branch:master"
+ + " [INVALID, NEW_CHANGES]");
}
@Test
public void parseNotifyValue() throws Exception {
assertParseNotifyValue("* []", null, EnumSet.noneOf(NotifyType.class));
- assertParseNotifyValue("* [ALL_COMMENTS]", null,
- EnumSet.of(NotifyType.ALL_COMMENTS));
+ assertParseNotifyValue("* [ALL_COMMENTS]", null, EnumSet.of(NotifyType.ALL_COMMENTS));
assertParseNotifyValue("[]", null, EnumSet.noneOf(NotifyType.class));
- assertParseNotifyValue("[ALL_COMMENTS, NEW_PATCHSETS]", null,
+ assertParseNotifyValue(
+ "[ALL_COMMENTS, NEW_PATCHSETS]",
+ null,
EnumSet.of(NotifyType.ALL_COMMENTS, NotifyType.NEW_PATCHSETS));
- assertParseNotifyValue("branch:master []", "branch:master",
+ assertParseNotifyValue("branch:master []", "branch:master", EnumSet.noneOf(NotifyType.class));
+ assertParseNotifyValue(
+ "branch:master || branch:stable []",
+ "branch:master || branch:stable",
EnumSet.noneOf(NotifyType.class));
- assertParseNotifyValue("branch:master || branch:stable []",
- "branch:master || branch:stable", EnumSet.noneOf(NotifyType.class));
- assertParseNotifyValue("branch:master [ALL_COMMENTS]", "branch:master",
- EnumSet.of(NotifyType.ALL_COMMENTS));
- assertParseNotifyValue("branch:master [ALL_COMMENTS, NEW_PATCHSETS]",
+ assertParseNotifyValue(
+ "branch:master [ALL_COMMENTS]", "branch:master", EnumSet.of(NotifyType.ALL_COMMENTS));
+ assertParseNotifyValue(
+ "branch:master [ALL_COMMENTS, NEW_PATCHSETS]",
"branch:master",
EnumSet.of(NotifyType.ALL_COMMENTS, NotifyType.NEW_PATCHSETS));
assertParseNotifyValue("* [ALL]", null, EnumSet.of(NotifyType.ALL));
@@ -129,31 +134,34 @@
public void toNotifyValue() throws Exception {
assertToNotifyValue(null, EnumSet.noneOf(NotifyType.class), "* []");
assertToNotifyValue("*", EnumSet.noneOf(NotifyType.class), "* []");
- assertToNotifyValue(null, EnumSet.of(NotifyType.ALL_COMMENTS),
- "* [ALL_COMMENTS]");
- assertToNotifyValue("branch:master", EnumSet.noneOf(NotifyType.class),
- "branch:master []");
- assertToNotifyValue("branch:master",
+ assertToNotifyValue(null, EnumSet.of(NotifyType.ALL_COMMENTS), "* [ALL_COMMENTS]");
+ assertToNotifyValue("branch:master", EnumSet.noneOf(NotifyType.class), "branch:master []");
+ assertToNotifyValue(
+ "branch:master",
EnumSet.of(NotifyType.ALL_COMMENTS, NotifyType.NEW_PATCHSETS),
"branch:master [ALL_COMMENTS, NEW_PATCHSETS]");
- assertToNotifyValue("branch:master",
- EnumSet.of(NotifyType.ABANDONED_CHANGES, NotifyType.ALL_COMMENTS,
- NotifyType.NEW_CHANGES, NotifyType.NEW_PATCHSETS,
+ assertToNotifyValue(
+ "branch:master",
+ EnumSet.of(
+ NotifyType.ABANDONED_CHANGES,
+ NotifyType.ALL_COMMENTS,
+ NotifyType.NEW_CHANGES,
+ NotifyType.NEW_PATCHSETS,
NotifyType.SUBMITTED_CHANGES),
"branch:master [ABANDONED_CHANGES, ALL_COMMENTS, NEW_CHANGES,"
- + " NEW_PATCHSETS, SUBMITTED_CHANGES]");
+ + " NEW_PATCHSETS, SUBMITTED_CHANGES]");
assertToNotifyValue("*", EnumSet.of(NotifyType.ALL), "* [ALL]");
}
- private void assertParseNotifyValue(String notifyValue,
- String expectedFilter, Set<NotifyType> expectedNotifyTypes) {
+ private void assertParseNotifyValue(
+ String notifyValue, String expectedFilter, Set<NotifyType> expectedNotifyTypes) {
NotifyValue nv = parseNotifyValue(notifyValue);
assertThat(nv.filter()).isEqualTo(expectedFilter);
assertThat(nv.notifyTypes()).containsExactlyElementsIn(expectedNotifyTypes);
}
- private static void assertToNotifyValue(String filter,
- Set<NotifyType> notifyTypes, String expectedNotifyValue) {
+ private static void assertToNotifyValue(
+ String filter, Set<NotifyType> notifyTypes, String expectedNotifyValue) {
NotifyValue nv = NotifyValue.create(filter, notifyTypes);
assertThat(nv.toString()).isEqualTo(expectedNotifyValue);
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/change/HashtagsTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/change/HashtagsTest.java
index 50a6c11..96bac3c 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/change/HashtagsTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/change/HashtagsTest.java
@@ -17,7 +17,6 @@
import static com.google.common.truth.Truth.assertThat;
import com.google.common.collect.Sets;
-
import org.junit.Test;
public class HashtagsTest {
@@ -41,59 +40,56 @@
public void singleHashtag() throws Exception {
String commitMessage = "#Subject\n\nLine 1\n\nLine 2";
assertThat(HashtagsUtil.extractTags(commitMessage))
- .containsExactlyElementsIn(Sets.newHashSet("Subject"));
+ .containsExactlyElementsIn(Sets.newHashSet("Subject"));
}
@Test
public void singleHashtagNumeric() throws Exception {
String commitMessage = "Subject\n\n#123\n\nLine 2";
assertThat(HashtagsUtil.extractTags(commitMessage))
- .containsExactlyElementsIn(Sets.newHashSet("123"));
+ .containsExactlyElementsIn(Sets.newHashSet("123"));
}
@Test
public void multipleHashtags() throws Exception {
String commitMessage = "#Subject\n\n#Hashtag\n\nLine 2";
assertThat(HashtagsUtil.extractTags(commitMessage))
- .containsExactlyElementsIn(Sets.newHashSet("Subject", "Hashtag"));
+ .containsExactlyElementsIn(Sets.newHashSet("Subject", "Hashtag"));
}
@Test
public void repeatedHashtag() throws Exception {
String commitMessage = "#Subject\n\n#Hashtag1\n\n#Hashtag2\n\n#Hashtag1";
assertThat(HashtagsUtil.extractTags(commitMessage))
- .containsExactlyElementsIn(
- Sets.newHashSet("Subject", "Hashtag1", "Hashtag2"));
+ .containsExactlyElementsIn(Sets.newHashSet("Subject", "Hashtag1", "Hashtag2"));
}
@Test
public void multipleHashtagsNoSpaces() throws Exception {
String commitMessage = "Subject\n\n#Hashtag1#Hashtag2";
assertThat(HashtagsUtil.extractTags(commitMessage))
- .containsExactlyElementsIn(Sets.newHashSet("Hashtag1"));
+ .containsExactlyElementsIn(Sets.newHashSet("Hashtag1"));
}
@Test
public void hyphenatedHashtag() throws Exception {
String commitMessage = "Subject\n\n#Hyphenated-Hashtag";
assertThat(HashtagsUtil.extractTags(commitMessage))
- .containsExactlyElementsIn(Sets.newHashSet("Hyphenated-Hashtag"));
+ .containsExactlyElementsIn(Sets.newHashSet("Hyphenated-Hashtag"));
}
@Test
public void underscoredHashtag() throws Exception {
String commitMessage = "Subject\n\n#Underscored_Hashtag";
assertThat(HashtagsUtil.extractTags(commitMessage))
- .containsExactlyElementsIn(Sets.newHashSet("Underscored_Hashtag"));
+ .containsExactlyElementsIn(Sets.newHashSet("Underscored_Hashtag"));
}
@Test
public void hashtagsWithAccentedCharacters() throws Exception {
- String commitMessage = "Jag #måste #öva på min #Svenska!\n\n"
- + "Jag behöver en #läkare.";
+ String commitMessage = "Jag #måste #öva på min #Svenska!\n\n" + "Jag behöver en #läkare.";
assertThat(HashtagsUtil.extractTags(commitMessage))
- .containsExactlyElementsIn(
- Sets.newHashSet("måste", "öva", "Svenska", "läkare"));
+ .containsExactlyElementsIn(Sets.newHashSet("måste", "öva", "Svenska", "läkare"));
}
@Test
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/change/IncludedInResolverTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/change/IncludedInResolverTest.java
index 3e19366..e91c3b4 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/change/IncludedInResolverTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/change/IncludedInResolverTest.java
@@ -14,6 +14,10 @@
package com.google.gerrit.server.change;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.MergeCommand.FastForwardMode;
import org.eclipse.jgit.junit.RepositoryTestCase;
@@ -27,11 +31,6 @@
import org.junit.Before;
import org.junit.Test;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
public class IncludedInResolverTest extends RepositoryTestCase {
// Branch names
@@ -68,21 +67,21 @@
/*- The following graph will be created.
- o tag 2.5, 2.5_annotated, 2.5_annotated_twice
- |\
- | o tag 2.0.1
- | o tag 2.0
- o | tag 1.3
- |/
- o c3
+ o tag 2.5, 2.5_annotated, 2.5_annotated_twice
+ |\
+ | o tag 2.0.1
+ | o tag 2.0
+ o | tag 1.3
+ |/
+ o c3
- | o tag 1.0.1
- |/
- o tag 1.0
- o c2
- o c1
+ | o tag 1.0.1
+ |/
+ o tag 1.0
+ o c2
+ o c1
- */
+ */
// TODO(dborowitz): Use try/finally when this doesn't double-close the repo.
@SuppressWarnings("resource")
@@ -96,8 +95,7 @@
RevCommit c3 = git.commit().setMessage("c3").call();
// Version 1.01
createAndCheckoutBranch(commit_v1_0, BRANCH_1_0);
- RevCommit commit_v1_0_1 =
- git.commit().setMessage("verREFS_HEADS_RELsion 1.0.1").call();
+ RevCommit commit_v1_0_1 = git.commit().setMessage("verREFS_HEADS_RELsion 1.0.1").call();
git.tag().setName(TAG_1_0_1).setObjectId(commit_v1_0_1).call();
// Version 1.3
createAndCheckoutBranch(c3, BRANCH_1_3);
@@ -112,18 +110,21 @@
// Version 2.5
createAndCheckoutBranch(commit_v1_3, BRANCH_2_5);
- git.merge().include(commit_v2_0_1).setCommit(false)
- .setFastForward(FastForwardMode.NO_FF).call();
- commit_v2_5 = git.commit().setMessage("version 2.5").call();
- git.tag().setName(TAG_2_5).setObjectId(commit_v2_5).setAnnotated(false)
+ git.merge()
+ .include(commit_v2_0_1)
+ .setCommit(false)
+ .setFastForward(FastForwardMode.NO_FF)
.call();
+ commit_v2_5 = git.commit().setMessage("version 2.5").call();
+ git.tag().setName(TAG_2_5).setObjectId(commit_v2_5).setAnnotated(false).call();
Ref ref_tag_2_5_annotated =
- git.tag().setName(TAG_2_5_ANNOTATED).setObjectId(commit_v2_5)
- .setAnnotated(true).call();
- RevTag tag_2_5_annotated =
- revWalk.parseTag(ref_tag_2_5_annotated.getObjectId());
- git.tag().setName(TAG_2_5_ANNOTATED_TWICE).setObjectId(tag_2_5_annotated)
- .setAnnotated(true).call();
+ git.tag().setName(TAG_2_5_ANNOTATED).setObjectId(commit_v2_5).setAnnotated(true).call();
+ RevTag tag_2_5_annotated = revWalk.parseTag(ref_tag_2_5_annotated.getObjectId());
+ git.tag()
+ .setName(TAG_2_5_ANNOTATED_TWICE)
+ .setObjectId(tag_2_5_annotated)
+ .setAnnotated(true)
+ .call();
}
@Override
@@ -198,8 +199,7 @@
Assert.assertEquals(list1, list2);
}
- private void createAndCheckoutBranch(ObjectId objectId, String branchName)
- throws IOException {
+ private void createAndCheckoutBranch(ObjectId objectId, String branchName) throws IOException {
String fullBranchName = "refs/heads/" + branchName;
super.createBranch(objectId, fullBranchName);
super.checkoutBranch(fullBranchName);
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/change/WalkSorterTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/change/WalkSorterTest.java
index 7f6bb5e..37e4d3f 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/change/WalkSorterTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/change/WalkSorterTest.java
@@ -30,7 +30,8 @@
import com.google.gerrit.testutil.InMemoryRepositoryManager;
import com.google.gerrit.testutil.InMemoryRepositoryManager.Repo;
import com.google.gerrit.testutil.TestChanges;
-
+import java.util.ArrayList;
+import java.util.List;
import org.eclipse.jgit.junit.TestRepository;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.revwalk.RevCommit;
@@ -38,9 +39,6 @@
import org.junit.Before;
import org.junit.Test;
-import java.util.ArrayList;
-import java.util.List;
-
public class WalkSorterTest extends GerritBaseTests {
private Account.Id userId;
private InMemoryRepositoryManager repoManager;
@@ -65,10 +63,11 @@
List<ChangeData> changes = ImmutableList.of(cd1, cd2, cd3);
WalkSorter sorter = new WalkSorter(repoManager);
- assertSorted(sorter, changes, ImmutableList.of(
- patchSetData(cd3, c3_1),
- patchSetData(cd2, c2_1),
- patchSetData(cd1, c1_1)));
+ assertSorted(
+ sorter,
+ changes,
+ ImmutableList.of(
+ patchSetData(cd3, c3_1), patchSetData(cd2, c2_1), patchSetData(cd1, c1_1)));
// Add new patch sets whose commits are in reverse order, so output is in
// reverse order.
@@ -80,10 +79,11 @@
addPatchSet(cd2, c2_2);
addPatchSet(cd3, c3_2);
- assertSorted(sorter, changes, ImmutableList.of(
- patchSetData(cd1, c1_2),
- patchSetData(cd2, c2_2),
- patchSetData(cd3, c3_2)));
+ assertSorted(
+ sorter,
+ changes,
+ ImmutableList.of(
+ patchSetData(cd1, c1_2), patchSetData(cd2, c2_2), patchSetData(cd3, c3_2)));
}
@Test
@@ -99,9 +99,8 @@
List<ChangeData> changes = ImmutableList.of(cd1, cd3);
WalkSorter sorter = new WalkSorter(repoManager);
- assertSorted(sorter, changes, ImmutableList.of(
- patchSetData(cd3, c3_1),
- patchSetData(cd1, c1_1)));
+ assertSorted(
+ sorter, changes, ImmutableList.of(patchSetData(cd3, c3_1), patchSetData(cd1, c1_1)));
}
@Test
@@ -115,12 +114,9 @@
RevWalk rw = p.getRevWalk();
rw.parseCommit(c1);
- assertThat(rw.parseCommit(c2).getCommitTime())
- .isEqualTo(c1.getCommitTime());
- assertThat(rw.parseCommit(c3).getCommitTime())
- .isEqualTo(c1.getCommitTime());
- assertThat(rw.parseCommit(c4).getCommitTime())
- .isEqualTo(c1.getCommitTime());
+ assertThat(rw.parseCommit(c2).getCommitTime()).isEqualTo(c1.getCommitTime());
+ assertThat(rw.parseCommit(c3).getCommitTime()).isEqualTo(c1.getCommitTime());
+ assertThat(rw.parseCommit(c4).getCommitTime()).isEqualTo(c1.getCommitTime());
ChangeData cd1 = newChange(p, c1);
ChangeData cd2 = newChange(p, c2);
@@ -130,11 +126,14 @@
List<ChangeData> changes = ImmutableList.of(cd1, cd2, cd3, cd4);
WalkSorter sorter = new WalkSorter(repoManager);
- assertSorted(sorter, changes, ImmutableList.of(
- patchSetData(cd4, c4),
- patchSetData(cd3, c3),
- patchSetData(cd2, c2),
- patchSetData(cd1, c1)));
+ assertSorted(
+ sorter,
+ changes,
+ ImmutableList.of(
+ patchSetData(cd4, c4),
+ patchSetData(cd3, c3),
+ patchSetData(cd2, c2),
+ patchSetData(cd1, c1)));
}
@Test
@@ -148,12 +147,9 @@
RevWalk rw = p.getRevWalk();
rw.parseCommit(c1);
- assertThat(rw.parseCommit(c2).getCommitTime())
- .isLessThan(c1.getCommitTime());
- assertThat(rw.parseCommit(c3).getCommitTime())
- .isLessThan(c2.getCommitTime());
- assertThat(rw.parseCommit(c4).getCommitTime())
- .isLessThan(c3.getCommitTime());
+ assertThat(rw.parseCommit(c2).getCommitTime()).isLessThan(c1.getCommitTime());
+ assertThat(rw.parseCommit(c3).getCommitTime()).isLessThan(c2.getCommitTime());
+ assertThat(rw.parseCommit(c4).getCommitTime()).isLessThan(c3.getCommitTime());
ChangeData cd1 = newChange(p, c1);
ChangeData cd2 = newChange(p, c2);
@@ -163,11 +159,14 @@
List<ChangeData> changes = ImmutableList.of(cd1, cd2, cd3, cd4);
WalkSorter sorter = new WalkSorter(repoManager);
- assertSorted(sorter, changes, ImmutableList.of(
- patchSetData(cd4, c4),
- patchSetData(cd3, c3),
- patchSetData(cd2, c2),
- patchSetData(cd1, c1)));
+ assertSorted(
+ sorter,
+ changes,
+ ImmutableList.of(
+ patchSetData(cd4, c4),
+ patchSetData(cd3, c3),
+ patchSetData(cd2, c2),
+ patchSetData(cd1, c1)));
}
@Test
@@ -181,12 +180,9 @@
RevWalk rw = p.getRevWalk();
rw.parseCommit(c1);
- assertThat(rw.parseCommit(c2).getCommitTime())
- .isLessThan(c1.getCommitTime());
- assertThat(rw.parseCommit(c3).getCommitTime())
- .isLessThan(c2.getCommitTime());
- assertThat(rw.parseCommit(c4).getCommitTime())
- .isLessThan(c3.getCommitTime());
+ assertThat(rw.parseCommit(c2).getCommitTime()).isLessThan(c1.getCommitTime());
+ assertThat(rw.parseCommit(c3).getCommitTime()).isLessThan(c2.getCommitTime());
+ assertThat(rw.parseCommit(c4).getCommitTime()).isLessThan(c3.getCommitTime());
ChangeData cd1 = newChange(p, c1);
ChangeData cd2 = newChange(p, c2);
@@ -194,10 +190,8 @@
List<ChangeData> changes = ImmutableList.of(cd1, cd2, cd4);
WalkSorter sorter = new WalkSorter(repoManager);
- List<PatchSetData> expected = ImmutableList.of(
- patchSetData(cd4, c4),
- patchSetData(cd2, c2),
- patchSetData(cd1, c1));
+ List<PatchSetData> expected =
+ ImmutableList.of(patchSetData(cd4, c4), patchSetData(cd2, c2), patchSetData(cd1, c1));
for (List<ChangeData> list : permutations(changes)) {
// Not inOrder(); since child of c2 is missing, partial topo sort isn't
@@ -216,12 +210,9 @@
RevWalk rw = p.getRevWalk();
rw.parseCommit(c1);
- assertThat(rw.parseCommit(c2).getCommitTime())
- .isEqualTo(c1.getCommitTime());
- assertThat(rw.parseCommit(c3).getCommitTime())
- .isEqualTo(c1.getCommitTime());
- assertThat(rw.parseCommit(c4).getCommitTime())
- .isEqualTo(c1.getCommitTime());
+ assertThat(rw.parseCommit(c2).getCommitTime()).isEqualTo(c1.getCommitTime());
+ assertThat(rw.parseCommit(c3).getCommitTime()).isEqualTo(c1.getCommitTime());
+ assertThat(rw.parseCommit(c4).getCommitTime()).isEqualTo(c1.getCommitTime());
ChangeData cd1 = newChange(p, c1);
ChangeData cd2 = newChange(p, c2);
@@ -231,11 +222,14 @@
List<ChangeData> changes = ImmutableList.of(cd1, cd2, cd3, cd4);
WalkSorter sorter = new WalkSorter(repoManager);
- assertSorted(sorter, changes, ImmutableList.of(
- patchSetData(cd4, c4),
- patchSetData(cd3, c3),
- patchSetData(cd2, c2),
- patchSetData(cd1, c1)));
+ assertSorted(
+ sorter,
+ changes,
+ ImmutableList.of(
+ patchSetData(cd4, c4),
+ patchSetData(cd3, c3),
+ patchSetData(cd2, c2),
+ patchSetData(cd1, c1)));
}
@Test
@@ -281,17 +275,14 @@
List<ChangeData> changes = ImmutableList.of(cd1, cd2);
WalkSorter sorter = new WalkSorter(repoManager);
- assertSorted(sorter, changes, ImmutableList.of(
- patchSetData(cd1, c1_2),
- patchSetData(cd2, c2_2)));
+ assertSorted(
+ sorter, changes, ImmutableList.of(patchSetData(cd1, c1_2), patchSetData(cd2, c2_2)));
// If we restrict to PS1 of each change, the sorter uses that commit.
- sorter.includePatchSets(ImmutableSet.of(
- new PatchSet.Id(cd1.getId(), 1),
- new PatchSet.Id(cd2.getId(), 1)));
- assertSorted(sorter, changes, ImmutableList.of(
- patchSetData(cd2, 1, c2_1),
- patchSetData(cd1, 1, c1_1)));
+ sorter.includePatchSets(
+ ImmutableSet.of(new PatchSet.Id(cd1.getId(), 1), new PatchSet.Id(cd2.getId(), 1)));
+ assertSorted(
+ sorter, changes, ImmutableList.of(patchSetData(cd2, 1, c2_1), patchSetData(cd1, 1, c1_1)));
}
@Test
@@ -305,8 +296,9 @@
ChangeData cd2 = newChange(pb, c2);
List<ChangeData> changes = ImmutableList.of(cd1, cd2);
- WalkSorter sorter = new WalkSorter(repoManager)
- .includePatchSets(ImmutableSet.of(cd1.currentPatchSet().getId()));
+ WalkSorter sorter =
+ new WalkSorter(repoManager)
+ .includePatchSets(ImmutableSet.of(cd1.currentPatchSet().getId()));
assertSorted(sorter, changes, ImmutableList.of(patchSetData(cd1, c1)));
}
@@ -318,19 +310,13 @@
ChangeData cd = newChange(p, c);
List<ChangeData> changes = ImmutableList.of(cd);
- RevCommit actual = new WalkSorter(repoManager)
- .setRetainBody(true)
- .sort(changes)
- .iterator().next()
- .commit();
+ RevCommit actual =
+ new WalkSorter(repoManager).setRetainBody(true).sort(changes).iterator().next().commit();
assertThat(actual.getRawBuffer()).isNotNull();
assertThat(actual.getShortMessage()).isEqualTo("message");
- actual = new WalkSorter(repoManager)
- .setRetainBody(false)
- .sort(changes)
- .iterator().next()
- .commit();
+ actual =
+ new WalkSorter(repoManager).setRetainBody(false).sort(changes).iterator().next().commit();
assertThat(actual.getRawBuffer()).isNull();
}
@@ -346,8 +332,7 @@
assertSorted(sorter, changes, ImmutableList.of(patchSetData(cd, c)));
}
- private ChangeData newChange(TestRepository<Repo> tr, ObjectId id)
- throws Exception {
+ private ChangeData newChange(TestRepository<Repo> tr, ObjectId id) throws Exception {
Project.NameKey project = tr.getRepository().getDescription().getProject();
Change c = TestChanges.newChange(project, userId);
ChangeData cd = ChangeData.createForTest(project, c.getId(), 1);
@@ -367,28 +352,23 @@
return ps;
}
- private TestRepository<Repo> newRepo(String name)
- throws Exception {
- return new TestRepository<>(
- repoManager.createRepository(new Project.NameKey(name)));
+ private TestRepository<Repo> newRepo(String name) throws Exception {
+ return new TestRepository<>(repoManager.createRepository(new Project.NameKey(name)));
}
- private static PatchSetData patchSetData(ChangeData cd, RevCommit commit)
- throws Exception {
+ private static PatchSetData patchSetData(ChangeData cd, RevCommit commit) throws Exception {
return PatchSetData.create(cd, cd.currentPatchSet(), commit);
}
- private static PatchSetData patchSetData(ChangeData cd, int psId,
- RevCommit commit) throws Exception {
- return PatchSetData.create(
- cd, cd.patchSet(new PatchSet.Id(cd.getId(), psId)), commit);
+ private static PatchSetData patchSetData(ChangeData cd, int psId, RevCommit commit)
+ throws Exception {
+ return PatchSetData.create(cd, cd.patchSet(new PatchSet.Id(cd.getId(), psId)), commit);
}
- private static void assertSorted(WalkSorter sorter, List<ChangeData> changes,
- List<PatchSetData> expected) throws Exception {
+ private static void assertSorted(
+ WalkSorter sorter, List<ChangeData> changes, List<PatchSetData> expected) throws Exception {
for (List<ChangeData> list : permutations(changes)) {
- assertThat(sorter.sort(list))
- .containsExactlyElementsIn(expected).inOrder();
+ assertThat(sorter.sort(list)).containsExactlyElementsIn(expected).inOrder();
}
}
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/config/ConfigUtilTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/config/ConfigUtilTest.java
index 8f7e5b2..fc0b1dcd 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/config/ConfigUtilTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/config/ConfigUtilTest.java
@@ -23,13 +23,11 @@
import static org.junit.Assert.assertEquals;
import com.google.gerrit.extensions.client.Theme;
-
-import org.eclipse.jgit.lib.Config;
-import org.junit.Test;
-
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
+import org.eclipse.jgit.lib.Config;
+import org.junit.Test;
public class ConfigUtilTest {
private static final String SECT = "foo";
@@ -54,6 +52,7 @@
public Theme td;
public List<String> list;
public Map<String, String> map;
+
static SectionInfo defaults() {
SectionInfo i = new SectionInfo();
i.i = 1;
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/config/ListCapabilitiesTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/config/ListCapabilitiesTest.java
index bd9f463..6fe48dc 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/config/ListCapabilitiesTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/config/ListCapabilitiesTest.java
@@ -26,39 +26,38 @@
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
-
+import java.util.Map;
import org.junit.Before;
import org.junit.Test;
-import java.util.Map;
-
public class ListCapabilitiesTest {
private Injector injector;
@Before
public void setUp() throws Exception {
- AbstractModule mod = new AbstractModule() {
- @Override
- protected void configure() {
- DynamicMap.mapOf(binder(), CapabilityDefinition.class);
- bind(CapabilityDefinition.class)
- .annotatedWith(Exports.named("printHello"))
- .toInstance(new CapabilityDefinition() {
- @Override
- public String getDescription() {
- return "Print Hello";
- }
- });
- }
- };
+ AbstractModule mod =
+ new AbstractModule() {
+ @Override
+ protected void configure() {
+ DynamicMap.mapOf(binder(), CapabilityDefinition.class);
+ bind(CapabilityDefinition.class)
+ .annotatedWith(Exports.named("printHello"))
+ .toInstance(
+ new CapabilityDefinition() {
+ @Override
+ public String getDescription() {
+ return "Print Hello";
+ }
+ });
+ }
+ };
injector = Guice.createInjector(mod);
}
@Test
public void list() throws Exception {
Map<String, CapabilityInfo> m =
- injector.getInstance(ListCapabilities.class)
- .apply(new ConfigResource());
+ injector.getInstance(ListCapabilities.class).apply(new ConfigResource());
for (String id : GlobalCapability.getAllNames()) {
assertTrue("contains " + id, m.containsKey(id));
assertEquals(id, m.get(id).id);
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/config/RepositoryConfigTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/config/RepositoryConfigTest.java
index 88eec7e..804e2f2 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/config/RepositoryConfigTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/config/RepositoryConfigTest.java
@@ -19,14 +19,12 @@
import com.google.common.collect.ImmutableList;
import com.google.gerrit.extensions.client.SubmitType;
import com.google.gerrit.reviewdb.client.Project.NameKey;
-
-import org.eclipse.jgit.lib.Config;
-import org.junit.Before;
-import org.junit.Test;
-
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
+import org.eclipse.jgit.lib.Config;
+import org.junit.Before;
+import org.junit.Test;
public class RepositoryConfigTest {
@@ -75,28 +73,26 @@
@Test
public void defaultSubmitTypeForStartWithFilter() {
- configureDefaultSubmitType("somePath/somePath/*",
- SubmitType.REBASE_IF_NECESSARY);
+ configureDefaultSubmitType("somePath/somePath/*", SubmitType.REBASE_IF_NECESSARY);
configureDefaultSubmitType("somePath/*", SubmitType.CHERRY_PICK);
configureDefaultSubmitType("*", SubmitType.MERGE_ALWAYS);
assertThat(repoCfg.getDefaultSubmitType(new NameKey("someProject")))
.isEqualTo(SubmitType.MERGE_ALWAYS);
- assertThat(
- repoCfg.getDefaultSubmitType(new NameKey("somePath/someProject")))
+ assertThat(repoCfg.getDefaultSubmitType(new NameKey("somePath/someProject")))
.isEqualTo(SubmitType.CHERRY_PICK);
- assertThat(
- repoCfg.getDefaultSubmitType(new NameKey(
- "somePath/somePath/someProject"))).isEqualTo(
- SubmitType.REBASE_IF_NECESSARY);
+ assertThat(repoCfg.getDefaultSubmitType(new NameKey("somePath/somePath/someProject")))
+ .isEqualTo(SubmitType.REBASE_IF_NECESSARY);
}
- private void configureDefaultSubmitType(String projectFilter,
- SubmitType submitType) {
- cfg.setString(RepositoryConfig.SECTION_NAME, projectFilter,
- RepositoryConfig.DEFAULT_SUBMIT_TYPE_NAME, submitType.toString());
+ private void configureDefaultSubmitType(String projectFilter, SubmitType submitType) {
+ cfg.setString(
+ RepositoryConfig.SECTION_NAME,
+ projectFilter,
+ RepositoryConfig.DEFAULT_SUBMIT_TYPE_NAME,
+ submitType.toString());
}
@Test
@@ -116,8 +112,7 @@
public void ownerGroupsForSpecificFilter() {
ImmutableList<String> ownerGroups = ImmutableList.of("group1", "group2");
configureOwnerGroups("someProject", ownerGroups);
- assertThat(repoCfg.getOwnerGroups(new NameKey("someOtherProject")))
- .isEmpty();
+ assertThat(repoCfg.getOwnerGroups(new NameKey("someOtherProject"))).isEmpty();
assertThat(repoCfg.getOwnerGroups(new NameKey("someProject")))
.containsExactlyElementsIn(ownerGroups);
}
@@ -138,38 +133,36 @@
assertThat(repoCfg.getOwnerGroups(new NameKey("somePath/someProject")))
.containsExactlyElementsIn(ownerGroups2);
- assertThat(
- repoCfg.getOwnerGroups(new NameKey("somePath/somePath/someProject")))
+ assertThat(repoCfg.getOwnerGroups(new NameKey("somePath/somePath/someProject")))
.containsExactlyElementsIn(ownerGroups3);
}
- private void configureOwnerGroups(String projectFilter,
- List<String> ownerGroups) {
- cfg.setStringList(RepositoryConfig.SECTION_NAME, projectFilter,
- RepositoryConfig.OWNER_GROUP_NAME, ownerGroups);
+ private void configureOwnerGroups(String projectFilter, List<String> ownerGroups) {
+ cfg.setStringList(
+ RepositoryConfig.SECTION_NAME,
+ projectFilter,
+ RepositoryConfig.OWNER_GROUP_NAME,
+ ownerGroups);
}
@Test
public void basePathWhenNotConfigured() {
- assertThat((Object)repoCfg.getBasePath(new NameKey("someProject"))).isNull();
+ assertThat((Object) repoCfg.getBasePath(new NameKey("someProject"))).isNull();
}
@Test
public void basePathForStarFilter() {
String basePath = "/someAbsolutePath/someDirectory";
configureBasePath("*", basePath);
- assertThat(repoCfg.getBasePath(new NameKey("someProject")).toString())
- .isEqualTo(basePath);
+ assertThat(repoCfg.getBasePath(new NameKey("someProject")).toString()).isEqualTo(basePath);
}
@Test
public void basePathForSpecificFilter() {
String basePath = "/someAbsolutePath/someDirectory";
configureBasePath("someProject", basePath);
- assertThat((Object) repoCfg.getBasePath(new NameKey("someOtherProject")))
- .isNull();
- assertThat(repoCfg.getBasePath(new NameKey("someProject")).toString())
- .isEqualTo(basePath);
+ assertThat((Object) repoCfg.getBasePath(new NameKey("someOtherProject"))).isNull();
+ assertThat(repoCfg.getBasePath(new NameKey("someProject")).toString()).isEqualTo(basePath);
}
@Test
@@ -184,23 +177,19 @@
configureBasePath("project/*", basePath3);
configureBasePath("*", basePath4);
- assertThat(repoCfg.getBasePath(new NameKey("project1")).toString())
- .isEqualTo(basePath1);
- assertThat(repoCfg.getBasePath(new NameKey("project/project/someProject"))
- .toString()).isEqualTo(basePath2);
- assertThat(
- repoCfg.getBasePath(new NameKey("project/someProject")).toString())
- .isEqualTo(basePath3);
- assertThat(repoCfg.getBasePath(new NameKey("someProject")).toString())
- .isEqualTo(basePath4);
+ assertThat(repoCfg.getBasePath(new NameKey("project1")).toString()).isEqualTo(basePath1);
+ assertThat(repoCfg.getBasePath(new NameKey("project/project/someProject")).toString())
+ .isEqualTo(basePath2);
+ assertThat(repoCfg.getBasePath(new NameKey("project/someProject")).toString())
+ .isEqualTo(basePath3);
+ assertThat(repoCfg.getBasePath(new NameKey("someProject")).toString()).isEqualTo(basePath4);
}
@Test
public void allBasePath() {
- ImmutableList<Path> allBasePaths = ImmutableList.of(
- Paths.get("/someBasePath1"),
- Paths.get("/someBasePath2"),
- Paths.get("/someBasePath2"));
+ ImmutableList<Path> allBasePaths =
+ ImmutableList.of(
+ Paths.get("/someBasePath1"), Paths.get("/someBasePath2"), Paths.get("/someBasePath2"));
configureBasePath("*", allBasePaths.get(0).toString());
configureBasePath("project/*", allBasePaths.get(1).toString());
@@ -210,7 +199,7 @@
}
private void configureBasePath(String projectFilter, String basePath) {
- cfg.setString(RepositoryConfig.SECTION_NAME, projectFilter,
- RepositoryConfig.BASE_PATH_NAME, basePath);
+ cfg.setString(
+ RepositoryConfig.SECTION_NAME, projectFilter, RepositoryConfig.BASE_PATH_NAME, basePath);
}
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/config/ScheduleConfigTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/config/ScheduleConfigTest.java
index e93de50..e6f36b9 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/config/ScheduleConfigTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/config/ScheduleConfigTest.java
@@ -20,12 +20,11 @@
import static java.util.concurrent.TimeUnit.MINUTES;
import static org.junit.Assert.assertEquals;
+import java.util.concurrent.TimeUnit;
import org.eclipse.jgit.lib.Config;
import org.joda.time.DateTime;
import org.junit.Test;
-import java.util.concurrent.TimeUnit;
-
public class ScheduleConfigTest {
// Friday June 13, 2014 10:00 UTC
@@ -43,8 +42,7 @@
assertEquals(ms(19, HOURS) + ms(30, MINUTES), initialDelay("05:30", "1d"));
assertEquals(ms(1, HOURS), initialDelay("11:00", "1w"));
- assertEquals(ms(7, DAYS) - ms(4, HOURS) - ms(30, MINUTES),
- initialDelay("05:30", "1w"));
+ assertEquals(ms(7, DAYS) - ms(4, HOURS) - ms(30, MINUTES), initialDelay("05:30", "1w"));
assertEquals(ms(3, DAYS) + ms(1, HOURS), initialDelay("Mon 11:00", "1w"));
assertEquals(ms(1, HOURS), initialDelay("Fri 11:00", "1w"));
@@ -71,9 +69,8 @@
}
private static long initialDelay(String startTime, String interval) {
- return new ScheduleConfig(
- config(startTime, interval),
- "section", "subsection", NOW).getInitialDelay();
+ return new ScheduleConfig(config(startTime, interval), "section", "subsection", NOW)
+ .getInitialDelay();
}
private static Config config(String startTime, String interval) {
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/config/SitePathsTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/config/SitePathsTest.java
index 29a7dde..d0f0766 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/config/SitePathsTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/config/SitePathsTest.java
@@ -22,14 +22,12 @@
import com.google.gerrit.server.util.HostPlatform;
import com.google.gerrit.testutil.GerritBaseTests;
-
-import org.junit.Test;
-
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.NotDirectoryException;
import java.nio.file.Path;
import java.nio.file.Paths;
+import org.junit.Test;
public class SitePathsTest extends GerritBaseTests {
@Test
@@ -93,8 +91,7 @@
assertNull(site.resolve(""));
assertNotNull(site.resolve("a"));
- assertEquals(root.resolve("a").toAbsolutePath().normalize(),
- site.resolve("a"));
+ assertEquals(root.resolve("a").toAbsolutePath().normalize(), site.resolve("a"));
final String pfx = HostPlatform.isWin32() ? "C:/" : "/";
assertNotNull(site.resolve(pfx + "a"));
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/edit/ChangeEditTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/edit/ChangeEditTest.java
index 8c963bd..6509c4b 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/edit/ChangeEditTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/edit/ChangeEditTest.java
@@ -20,7 +20,6 @@
import com.google.gerrit.reviewdb.client.Change;
import com.google.gerrit.reviewdb.client.PatchSet;
import com.google.gerrit.reviewdb.client.RefNames;
-
import org.junit.Test;
public class ChangeEditTest {
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/events/EventDeserializerTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/events/EventDeserializerTest.java
index b6e73ff..355f775 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/events/EventDeserializerTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/events/EventDeserializerTest.java
@@ -22,7 +22,6 @@
import com.google.gerrit.server.data.RefUpdateAttribute;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
-
import org.junit.Test;
public class EventDeserializerTest {
@@ -39,32 +38,32 @@
accountAttribute.email = "some.user@domain.com";
refUpdatedEvent.submitter = createSupplier(accountAttribute);
- Gson gsonSerializer = new GsonBuilder()
- .registerTypeAdapter(Supplier.class, new SupplierSerializer()).create();
+ Gson gsonSerializer =
+ new GsonBuilder().registerTypeAdapter(Supplier.class, new SupplierSerializer()).create();
String serializedEvent = gsonSerializer.toJson(refUpdatedEvent);
- Gson gsonDeserializer = new GsonBuilder()
- .registerTypeAdapter(Event.class, new EventDeserializer())
- .registerTypeAdapter(Supplier.class, new SupplierDeserializer())
- .create();
+ Gson gsonDeserializer =
+ new GsonBuilder()
+ .registerTypeAdapter(Event.class, new EventDeserializer())
+ .registerTypeAdapter(Supplier.class, new SupplierDeserializer())
+ .create();
- RefUpdatedEvent e = (RefUpdatedEvent) gsonDeserializer
- .fromJson(serializedEvent, Event.class);
+ RefUpdatedEvent e = (RefUpdatedEvent) gsonDeserializer.fromJson(serializedEvent, Event.class);
assertThat(e).isNotNull();
assertThat(e.refUpdate).isInstanceOf(Supplier.class);
- assertThat(e.refUpdate.get().refName)
- .isEqualTo(refUpdatedAttribute.refName);
+ assertThat(e.refUpdate.get().refName).isEqualTo(refUpdatedAttribute.refName);
assertThat(e.submitter).isInstanceOf(Supplier.class);
assertThat(e.submitter.get().email).isEqualTo(accountAttribute.email);
}
private <T> Supplier<T> createSupplier(final T value) {
- return Suppliers.memoize(new Supplier<T>() {
- @Override
- public T get() {
- return value;
- }
- });
+ return Suppliers.memoize(
+ new Supplier<T>() {
+ @Override
+ public T get() {
+ return value;
+ }
+ });
}
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/events/EventTypesTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/events/EventTypesTest.java
index de13fd8..c822d6c 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/events/EventTypesTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/events/EventTypesTest.java
@@ -21,6 +21,7 @@
public class EventTypesTest {
public static class TestEvent extends Event {
private static final String TYPE = "test-event";
+
public TestEvent() {
super(TYPE);
}
@@ -28,6 +29,7 @@
public static class AnotherTestEvent extends Event {
private static final String TYPE = "another-test-event";
+
public AnotherTestEvent() {
super("another-test-event");
}
@@ -38,8 +40,7 @@
EventTypes.register(TestEvent.TYPE, TestEvent.class);
EventTypes.register(AnotherTestEvent.TYPE, AnotherTestEvent.class);
assertThat(EventTypes.getClass(TestEvent.TYPE)).isEqualTo(TestEvent.class);
- assertThat(EventTypes.getClass(AnotherTestEvent.TYPE))
- .isEqualTo(AnotherTestEvent.class);
+ assertThat(EventTypes.getClass(AnotherTestEvent.TYPE)).isEqualTo(AnotherTestEvent.class);
}
@Test
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/git/BatchUpdateTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/git/BatchUpdateTest.java
index 87bfa00..e3f8530 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/git/BatchUpdateTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/git/BatchUpdateTest.java
@@ -24,7 +24,6 @@
import com.google.inject.Injector;
import com.google.inject.Provider;
import com.google.inject.util.Providers;
-
import org.eclipse.jgit.internal.storage.dfs.InMemoryRepository;
import org.eclipse.jgit.junit.TestRepository;
import org.eclipse.jgit.revwalk.RevCommit;
@@ -34,26 +33,19 @@
import org.junit.Test;
public class BatchUpdateTest {
- @Inject
- private AccountManager accountManager;
+ @Inject private AccountManager accountManager;
- @Inject
- private IdentifiedUser.GenericFactory userFactory;
+ @Inject private IdentifiedUser.GenericFactory userFactory;
- @Inject
- private InMemoryDatabase schemaFactory;
+ @Inject private InMemoryDatabase schemaFactory;
- @Inject
- private InMemoryRepositoryManager repoManager;
+ @Inject private InMemoryRepositoryManager repoManager;
- @Inject
- private SchemaCreator schemaCreator;
+ @Inject private SchemaCreator schemaCreator;
- @Inject
- private ThreadLocalRequestContext requestContext;
+ @Inject private ThreadLocalRequestContext requestContext;
- @Inject
- private BatchUpdate.Factory batchUpdateFactory;
+ @Inject private BatchUpdate.Factory batchUpdateFactory;
private LifecycleManager lifecycle;
private ReviewDb db;
@@ -71,8 +63,7 @@
db = schemaFactory.open();
schemaCreator.create(db);
- Account.Id userId = accountManager.authenticate(AuthRequest.forUser("user"))
- .getAccountId();
+ Account.Id userId = accountManager.authenticate(AuthRequest.forUser("user")).getAccountId();
user = userFactory.create(userId);
project = new Project.NameKey("test");
@@ -80,17 +71,18 @@
InMemoryRepository inMemoryRepo = repoManager.createRepository(project);
repo = new TestRepository<>(inMemoryRepo);
- requestContext.setContext(new RequestContext() {
- @Override
- public CurrentUser getUser() {
- return user;
- }
+ requestContext.setContext(
+ new RequestContext() {
+ @Override
+ public CurrentUser getUser() {
+ return user;
+ }
- @Override
- public Provider<ReviewDb> getReviewDbProvider() {
- return Providers.of(db);
- }
- });
+ @Override
+ public Provider<ReviewDb> getReviewDbProvider() {
+ return Providers.of(db);
+ }
+ });
}
@After
@@ -111,24 +103,22 @@
@Test
public void addRefUpdateFromFastForwardCommit() throws Exception {
final RevCommit masterCommit = repo.branch("master").commit().create();
- final RevCommit branchCommit =
- repo.branch("branch").commit().parent(masterCommit).create();
+ final RevCommit branchCommit = repo.branch("branch").commit().parent(masterCommit).create();
- try (BatchUpdate bu = batchUpdateFactory
- .create(db, project, user, TimeUtil.nowTs())) {
- bu.addRepoOnlyOp(new RepoOnlyOp() {
- @Override
- public void updateRepo(RepoContext ctx) throws Exception {
- ctx.addRefUpdate(
- new ReceiveCommand(masterCommit.getId(), branchCommit.getId(),
- "refs/heads/master"));
- }
- });
+ try (BatchUpdate bu = batchUpdateFactory.create(db, project, user, TimeUtil.nowTs())) {
+ bu.addRepoOnlyOp(
+ new RepoOnlyOp() {
+ @Override
+ public void updateRepo(RepoContext ctx) throws Exception {
+ ctx.addRefUpdate(
+ new ReceiveCommand(
+ masterCommit.getId(), branchCommit.getId(), "refs/heads/master"));
+ }
+ });
bu.execute();
}
assertEquals(
- repo.getRepository().exactRef("refs/heads/master").getObjectId(),
- branchCommit.getId());
+ repo.getRepository().exactRef("refs/heads/master").getObjectId(), branchCommit.getId());
}
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/git/DestinationListTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/git/DestinationListTest.java
index fb046fd..e067632 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/git/DestinationListTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/git/DestinationListTest.java
@@ -20,14 +20,11 @@
import com.google.gerrit.reviewdb.client.Branch;
import com.google.gerrit.reviewdb.client.Project;
-
-import junit.framework.TestCase;
-
-import org.junit.Test;
-
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
+import junit.framework.TestCase;
+import org.junit.Test;
public class DestinationListTest extends TestCase {
public static final String R_FOO = "refs/heads/foo";
@@ -62,6 +59,7 @@
public static final Branch.NameKey B_COMPLEX = dest(P_COMPLEX, R_FOO);
public static final Set<Branch.NameKey> D_SIMPLE = new HashSet<>();
+
static {
D_SIMPLE.clear();
D_SIMPLE.add(B_FOO);
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/git/GroupCollectorTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/git/GroupCollectorTest.java
index ff9b81b..e5e8e26 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/git/GroupCollectorTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/git/GroupCollectorTest.java
@@ -21,7 +21,6 @@
import com.google.common.collect.SortedSetMultimap;
import com.google.gerrit.reviewdb.client.Change;
import com.google.gerrit.reviewdb.client.PatchSet;
-
import org.eclipse.jgit.internal.storage.dfs.DfsRepositoryDescription;
import org.eclipse.jgit.internal.storage.dfs.InMemoryRepository;
import org.eclipse.jgit.junit.TestRepository;
@@ -37,8 +36,7 @@
@Before
public void setUp() throws Exception {
- tr = new TestRepository<>(
- new InMemoryRepository(new DfsRepositoryDescription("repo")));
+ tr = new TestRepository<>(new InMemoryRepository(new DfsRepositoryDescription("repo")));
}
@Test
@@ -46,58 +44,48 @@
RevCommit branchTip = tr.commit().create();
RevCommit a = tr.commit().parent(branchTip).create();
- SortedSetMultimap<ObjectId, String> groups = collectGroups(
- newWalk(a, branchTip),
- patchSets(),
- groups());
+ SortedSetMultimap<ObjectId, String> groups =
+ collectGroups(newWalk(a, branchTip), patchSets(), groups());
assertThat(groups).containsEntry(a, a.name());
}
@Test
- public void commitWhoseParentIsNewPatchSetGetsParentsGroup()
- throws Exception {
+ public void commitWhoseParentIsNewPatchSetGetsParentsGroup() throws Exception {
RevCommit branchTip = tr.commit().create();
RevCommit a = tr.commit().parent(branchTip).create();
RevCommit b = tr.commit().parent(a).create();
- SortedSetMultimap<ObjectId, String> groups = collectGroups(
- newWalk(b, branchTip),
- patchSets(),
- groups());
+ SortedSetMultimap<ObjectId, String> groups =
+ collectGroups(newWalk(b, branchTip), patchSets(), groups());
assertThat(groups).containsEntry(a, a.name());
assertThat(groups).containsEntry(b, a.name());
}
@Test
- public void commitWhoseParentIsExistingPatchSetGetsParentsGroup()
- throws Exception {
+ public void commitWhoseParentIsExistingPatchSetGetsParentsGroup() throws Exception {
RevCommit branchTip = tr.commit().create();
RevCommit a = tr.commit().parent(branchTip).create();
RevCommit b = tr.commit().parent(a).create();
String group = "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef";
- SortedSetMultimap<ObjectId, String> groups = collectGroups(
- newWalk(b, branchTip),
- patchSets().put(a, psId(1, 1)),
- groups().put(psId(1, 1), group));
+ SortedSetMultimap<ObjectId, String> groups =
+ collectGroups(
+ newWalk(b, branchTip), patchSets().put(a, psId(1, 1)), groups().put(psId(1, 1), group));
assertThat(groups).containsEntry(a, group);
assertThat(groups).containsEntry(b, group);
}
@Test
- public void commitWhoseParentIsExistingPatchSetWithNoGroup()
- throws Exception {
+ public void commitWhoseParentIsExistingPatchSetWithNoGroup() throws Exception {
RevCommit branchTip = tr.commit().create();
RevCommit a = tr.commit().parent(branchTip).create();
RevCommit b = tr.commit().parent(a).create();
- SortedSetMultimap<ObjectId, String> groups = collectGroups(
- newWalk(b, branchTip),
- patchSets().put(a, psId(1, 1)),
- groups());
+ SortedSetMultimap<ObjectId, String> groups =
+ collectGroups(newWalk(b, branchTip), patchSets().put(a, psId(1, 1)), groups());
assertThat(groups).containsEntry(a, a.name());
assertThat(groups).containsEntry(b, a.name());
@@ -110,10 +98,8 @@
RevCommit b = tr.commit().parent(branchTip).create();
RevCommit m = tr.commit().parent(a).parent(b).create();
- SortedSetMultimap<ObjectId, String> groups = collectGroups(
- newWalk(m, branchTip),
- patchSets(),
- groups());
+ SortedSetMultimap<ObjectId, String> groups =
+ collectGroups(newWalk(m, branchTip), patchSets(), groups());
assertThat(groups).containsEntry(a, a.name());
assertThat(groups).containsEntry(b, a.name());
@@ -128,10 +114,9 @@
RevCommit m = tr.commit().parent(a).parent(b).create();
String group = "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef";
- SortedSetMultimap<ObjectId, String> groups = collectGroups(
- newWalk(m, branchTip),
- patchSets().put(b, psId(1, 1)),
- groups().put(psId(1, 1), group));
+ SortedSetMultimap<ObjectId, String> groups =
+ collectGroups(
+ newWalk(m, branchTip), patchSets().put(b, psId(1, 1)), groups().put(psId(1, 1), group));
// Merge commit and other parent get the existing group.
assertThat(groups).containsEntry(a, group);
@@ -140,8 +125,7 @@
}
@Test
- public void mergeCommitWhereBothParentsHaveDifferentGroups()
- throws Exception {
+ public void mergeCommitWhereBothParentsHaveDifferentGroups() throws Exception {
RevCommit branchTip = tr.commit().create();
RevCommit a = tr.commit().parent(branchTip).create();
RevCommit b = tr.commit().parent(branchTip).create();
@@ -149,20 +133,16 @@
String group1 = "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef";
String group2 = "1234567812345678123456781234567812345678";
- SortedSetMultimap<ObjectId, String> groups = collectGroups(
- newWalk(m, branchTip),
- patchSets()
- .put(a, psId(1, 1))
- .put(b, psId(2, 1)),
- groups()
- .put(psId(1, 1), group1)
- .put(psId(2, 1), group2));
+ SortedSetMultimap<ObjectId, String> groups =
+ collectGroups(
+ newWalk(m, branchTip),
+ patchSets().put(a, psId(1, 1)).put(b, psId(2, 1)),
+ groups().put(psId(1, 1), group1).put(psId(2, 1), group2));
assertThat(groups).containsEntry(a, group1);
assertThat(groups).containsEntry(b, group2);
// Merge commit gets joined group of parents.
- assertThat(groups.asMap())
- .containsEntry(m, ImmutableSet.of(group1, group2));
+ assertThat(groups.asMap()).containsEntry(m, ImmutableSet.of(group1, group2));
}
@Test
@@ -175,60 +155,48 @@
String group1 = "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef";
String group2a = "1234567812345678123456781234567812345678";
String group2b = "ef123456ef123456ef123456ef123456ef123456";
- SortedSetMultimap<ObjectId, String> groups = collectGroups(
- newWalk(m, branchTip),
- patchSets()
- .put(a, psId(1, 1))
- .put(b, psId(2, 1)),
- groups()
- .put(psId(1, 1), group1)
- .put(psId(2, 1), group2a)
- .put(psId(2, 1), group2b));
+ SortedSetMultimap<ObjectId, String> groups =
+ collectGroups(
+ newWalk(m, branchTip),
+ patchSets().put(a, psId(1, 1)).put(b, psId(2, 1)),
+ groups().put(psId(1, 1), group1).put(psId(2, 1), group2a).put(psId(2, 1), group2b));
assertThat(groups).containsEntry(a, group1);
- assertThat(groups.asMap())
- .containsEntry(b, ImmutableSet.of(group2a, group2b));
+ assertThat(groups.asMap()).containsEntry(b, ImmutableSet.of(group2a, group2b));
// Joined parent groups are split and resorted.
- assertThat(groups.asMap())
- .containsEntry(m, ImmutableSet.of(group1, group2a, group2b));
+ assertThat(groups.asMap()).containsEntry(m, ImmutableSet.of(group1, group2a, group2b));
}
@Test
- public void mergeCommitWithOneUninterestingParentAndOtherParentIsExisting()
- throws Exception {
+ public void mergeCommitWithOneUninterestingParentAndOtherParentIsExisting() throws Exception {
RevCommit branchTip = tr.commit().create();
RevCommit a = tr.commit().parent(branchTip).create();
RevCommit m = tr.commit().parent(branchTip).parent(a).create();
String group = "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef";
- SortedSetMultimap<ObjectId, String> groups = collectGroups(
- newWalk(m, branchTip),
- patchSets().put(a, psId(1, 1)),
- groups().put(psId(1, 1), group));
+ SortedSetMultimap<ObjectId, String> groups =
+ collectGroups(
+ newWalk(m, branchTip), patchSets().put(a, psId(1, 1)), groups().put(psId(1, 1), group));
assertThat(groups).containsEntry(a, group);
assertThat(groups).containsEntry(m, group);
}
@Test
- public void mergeCommitWithOneUninterestingParentAndOtherParentIsNew()
- throws Exception {
+ public void mergeCommitWithOneUninterestingParentAndOtherParentIsNew() throws Exception {
RevCommit branchTip = tr.commit().create();
RevCommit a = tr.commit().parent(branchTip).create();
RevCommit m = tr.commit().parent(branchTip).parent(a).create();
- SortedSetMultimap<ObjectId, String> groups = collectGroups(
- newWalk(m, branchTip),
- patchSets(),
- groups());
+ SortedSetMultimap<ObjectId, String> groups =
+ collectGroups(newWalk(m, branchTip), patchSets(), groups());
assertThat(groups).containsEntry(a, a.name());
assertThat(groups).containsEntry(m, a.name());
}
@Test
- public void multipleMergeCommitsInHistoryAllResolveToSameGroup()
- throws Exception {
+ public void multipleMergeCommitsInHistoryAllResolveToSameGroup() throws Exception {
RevCommit branchTip = tr.commit().create();
RevCommit a = tr.commit().parent(branchTip).create();
RevCommit b = tr.commit().parent(branchTip).create();
@@ -236,10 +204,8 @@
RevCommit m1 = tr.commit().parent(b).parent(c).create();
RevCommit m2 = tr.commit().parent(a).parent(m1).create();
- SortedSetMultimap<ObjectId, String> groups = collectGroups(
- newWalk(m2, branchTip),
- patchSets(),
- groups());
+ SortedSetMultimap<ObjectId, String> groups =
+ collectGroups(newWalk(m2, branchTip), patchSets(), groups());
assertThat(groups).containsEntry(a, a.name());
assertThat(groups).containsEntry(b, a.name());
@@ -249,8 +215,7 @@
}
@Test
- public void mergeCommitWithDuplicatedParentGetsParentsGroup()
- throws Exception {
+ public void mergeCommitWithDuplicatedParentGetsParentsGroup() throws Exception {
RevCommit branchTip = tr.commit().create();
RevCommit a = tr.commit().parent(branchTip).create();
RevCommit m = tr.commit().parent(a).parent(a).create();
@@ -258,18 +223,15 @@
assertThat(m.getParentCount()).isEqualTo(2);
assertThat(m.getParent(0)).isEqualTo(m.getParent(1));
- SortedSetMultimap<ObjectId, String> groups = collectGroups(
- newWalk(m, branchTip),
- patchSets(),
- groups());
+ SortedSetMultimap<ObjectId, String> groups =
+ collectGroups(newWalk(m, branchTip), patchSets(), groups());
assertThat(groups).containsEntry(a, a.name());
assertThat(groups).containsEntry(m, a.name());
}
@Test
- public void mergeCommitWithOneNewParentAndTwoExistingPatchSets()
- throws Exception {
+ public void mergeCommitWithOneNewParentAndTwoExistingPatchSets() throws Exception {
RevCommit branchTip = tr.commit().create();
RevCommit a = tr.commit().parent(branchTip).create();
RevCommit b = tr.commit().parent(branchTip).create();
@@ -278,20 +240,16 @@
String group1 = "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef";
String group2 = "1234567812345678123456781234567812345678";
- SortedSetMultimap<ObjectId, String> groups = collectGroups(
- newWalk(m, branchTip),
- patchSets()
- .put(a, psId(1, 1))
- .put(b, psId(2, 1)),
- groups()
- .put(psId(1, 1), group1)
- .put(psId(2, 1), group2));
+ SortedSetMultimap<ObjectId, String> groups =
+ collectGroups(
+ newWalk(m, branchTip),
+ patchSets().put(a, psId(1, 1)).put(b, psId(2, 1)),
+ groups().put(psId(1, 1), group1).put(psId(2, 1), group2));
assertThat(groups).containsEntry(a, group1);
assertThat(groups).containsEntry(b, group2);
assertThat(groups).containsEntry(c, group2);
- assertThat(groups.asMap())
- .containsEntry(m, ImmutableSet.of(group1, group2));
+ assertThat(groups.asMap()).containsEntry(m, ImmutableSet.of(group1, group2));
}
@Test
@@ -306,15 +264,16 @@
rw.markStart(rw.parseCommit(d));
// Schema upgrade case: all commits are existing patch sets, but none have
// groups assigned yet.
- SortedSetMultimap<ObjectId, String> groups = collectGroups(
- rw,
- patchSets()
- .put(branchTip, psId(1, 1))
- .put(a, psId(2, 1))
- .put(b, psId(3, 1))
- .put(c, psId(4, 1))
- .put(d, psId(5, 1)),
- groups());
+ SortedSetMultimap<ObjectId, String> groups =
+ collectGroups(
+ rw,
+ patchSets()
+ .put(branchTip, psId(1, 1))
+ .put(a, psId(2, 1))
+ .put(b, psId(3, 1))
+ .put(c, psId(4, 1))
+ .put(d, psId(5, 1)),
+ groups());
assertThat(groups).containsEntry(a, a.name());
assertThat(groups).containsEntry(b, a.name());
@@ -343,8 +302,7 @@
ImmutableListMultimap.Builder<ObjectId, PatchSet.Id> patchSetsBySha,
ImmutableListMultimap.Builder<PatchSet.Id, String> groupLookup)
throws Exception {
- GroupCollector gc =
- new GroupCollector(patchSetsBySha.build(), groupLookup.build());
+ GroupCollector gc = new GroupCollector(patchSetsBySha.build(), groupLookup.build());
RevCommit c;
while ((c = rw.next()) != null) {
gc.visit(c);
@@ -354,8 +312,7 @@
// Helper methods for constructing various map arguments, to avoid lots of
// type specifications.
- private static ImmutableListMultimap.Builder<ObjectId, PatchSet.Id>
- patchSets() {
+ private static ImmutableListMultimap.Builder<ObjectId, PatchSet.Id> patchSets() {
return ImmutableListMultimap.builder();
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/git/GroupListTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/git/GroupListTest.java
index 6cdf6c9..30f0ed5 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/git/GroupListTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/git/GroupListTest.java
@@ -28,19 +28,18 @@
import com.google.gerrit.common.data.GroupReference;
import com.google.gerrit.reviewdb.client.AccountGroup;
import com.google.gerrit.reviewdb.client.Project;
-
-import org.junit.Before;
-import org.junit.Test;
-
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.Set;
+import org.junit.Before;
+import org.junit.Test;
public class GroupListTest {
private static final Project.NameKey PROJECT = new Project.NameKey("project");
private static final String TEXT =
- "# UUID \tGroup Name\n" + "#\n"
+ "# UUID \tGroup Name\n"
+ + "#\n"
+ "d96b998f8a66ff433af50befb975d0e2bb6e0999\tNon-Interactive Users\n"
+ "ebe31c01aec2c9ac3b3c03e87a47450829ff4310\tAdministrators\n";
@@ -55,8 +54,7 @@
@Test
public void byUUID() throws Exception {
- AccountGroup.UUID uuid =
- new AccountGroup.UUID("d96b998f8a66ff433af50befb975d0e2bb6e0999");
+ AccountGroup.UUID uuid = new AccountGroup.UUID("d96b998f8a66ff433af50befb975d0e2bb6e0999");
GroupReference groupReference = groupList.byUUID(uuid);
@@ -81,8 +79,7 @@
Collection<GroupReference> result = groupList.references();
assertEquals(2, result.size());
- AccountGroup.UUID uuid =
- new AccountGroup.UUID("ebe31c01aec2c9ac3b3c03e87a47450829ff4310");
+ AccountGroup.UUID uuid = new AccountGroup.UUID("ebe31c01aec2c9ac3b3c03e87a47450829ff4310");
GroupReference expected = new GroupReference(uuid, "Administrators");
assertTrue(result.contains(expected));
@@ -93,8 +90,7 @@
Set<AccountGroup.UUID> result = groupList.uuids();
assertEquals(2, result.size());
- AccountGroup.UUID expected =
- new AccountGroup.UUID("ebe31c01aec2c9ac3b3c03e87a47450829ff4310");
+ AccountGroup.UUID expected = new AccountGroup.UUID("ebe31c01aec2c9ac3b3c03e87a47450829ff4310");
assertTrue(result.contains(expected));
}
@@ -110,13 +106,11 @@
@Test
public void retainAll() throws Exception {
- AccountGroup.UUID uuid =
- new AccountGroup.UUID("d96b998f8a66ff433af50befb975d0e2bb6e0999");
+ AccountGroup.UUID uuid = new AccountGroup.UUID("d96b998f8a66ff433af50befb975d0e2bb6e0999");
groupList.retainUUIDs(Collections.singleton(uuid));
assertNotNull(groupList.byUUID(uuid));
- assertNull(groupList.byUUID(new AccountGroup.UUID(
- "ebe31c01aec2c9ac3b3c03e87a47450829ff4310")));
+ assertNull(groupList.byUUID(new AccountGroup.UUID("ebe31c01aec2c9ac3b3c03e87a47450829ff4310")));
}
@Test
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/git/LabelNormalizerTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/git/LabelNormalizerTest.java
index aa23e50..eabccf7 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/git/LabelNormalizerTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/git/LabelNormalizerTest.java
@@ -51,14 +51,12 @@
import com.google.inject.Injector;
import com.google.inject.Provider;
import com.google.inject.util.Providers;
-
+import java.util.List;
import org.eclipse.jgit.lib.Repository;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
-import java.util.List;
-
/** Unit tests for {@link LabelNormalizer}. */
public class LabelNormalizerTest {
@Inject private AccountManager accountManager;
@@ -88,21 +86,21 @@
db = schemaFactory.open();
schemaCreator.create(db);
- userId = accountManager.authenticate(AuthRequest.forUser("user"))
- .getAccountId();
+ userId = accountManager.authenticate(AuthRequest.forUser("user")).getAccountId();
user = userFactory.create(userId);
- requestContext.setContext(new RequestContext() {
- @Override
- public CurrentUser getUser() {
- return user;
- }
+ requestContext.setContext(
+ new RequestContext() {
+ @Override
+ public CurrentUser getUser() {
+ return user;
+ }
- @Override
- public Provider<ReviewDb> getReviewDbProvider() {
- return Providers.of(db);
- }
- });
+ @Override
+ public Provider<ReviewDb> getReviewDbProvider() {
+ return Providers.of(db);
+ }
+ });
configureProject();
setUpChange();
@@ -115,20 +113,20 @@
sec.removePermission(forLabel(label));
}
}
- LabelType lt = category("Verified",
- value(1, "Verified"),
- value(0, "No score"),
- value(-1, "Fails"));
+ LabelType lt =
+ category("Verified", value(1, "Verified"), value(0, "No score"), value(-1, "Fails"));
pc.getLabelSections().put(lt.getName(), lt);
save(pc);
}
private void setUpChange() throws Exception {
- change = new Change(
- new Change.Key("Iabcd1234abcd1234abcd1234abcd1234abcd1234"),
- new Change.Id(1), userId,
- new Branch.NameKey(allProjects, "refs/heads/master"),
- TimeUtil.nowTs());
+ change =
+ new Change(
+ new Change.Key("Iabcd1234abcd1234abcd1234abcd1234abcd1234"),
+ new Change.Id(1),
+ userId,
+ new Branch.NameKey(allProjects, "refs/heads/master"),
+ TimeUtil.nowTs());
PatchSetInfo ps = new PatchSetInfo(new PatchSet.Id(change.getId(), 1));
ps.setSubject("Test change");
change.setCurrentPatchSet(ps);
@@ -156,11 +154,8 @@
PatchSetApproval cr = psa(userId, "Code-Review", 2);
PatchSetApproval v = psa(userId, "Verified", 1);
- assertEquals(Result.create(
- list(v),
- list(copy(cr, 1)),
- list()),
- norm.normalize(change, list(cr, v)));
+ assertEquals(
+ Result.create(list(v), list(copy(cr, 1)), list()), norm.normalize(change, list(cr, v)));
}
@Test
@@ -172,10 +167,8 @@
PatchSetApproval cr = psa(userId, "Code-Review", 5);
PatchSetApproval v = psa(userId, "Verified", 5);
- assertEquals(Result.create(
- list(),
- list(copy(cr, 2), copy(v, 1)),
- list()),
+ assertEquals(
+ Result.create(list(), list(copy(cr, 2), copy(v, 1)), list()),
norm.normalize(change, list(cr, v)));
}
@@ -183,11 +176,7 @@
public void emptyPermissionRangeOmitsResult() throws Exception {
PatchSetApproval cr = psa(userId, "Code-Review", 1);
PatchSetApproval v = psa(userId, "Verified", 1);
- assertEquals(Result.create(
- list(),
- list(),
- list(cr, v)),
- norm.normalize(change, list(cr, v)));
+ assertEquals(Result.create(list(), list(), list(cr, v)), norm.normalize(change, list(cr, v)));
}
@Test
@@ -198,11 +187,7 @@
PatchSetApproval cr = psa(userId, "Code-Review", 0);
PatchSetApproval v = psa(userId, "Verified", 0);
- assertEquals(Result.create(
- list(cr),
- list(),
- list(v)),
- norm.normalize(change, list(cr, v)));
+ assertEquals(Result.create(list(cr), list(), list(v)), norm.normalize(change, list(cr, v)));
}
private ProjectConfig loadAllProjects() throws Exception {
@@ -214,8 +199,7 @@
}
private void save(ProjectConfig pc) throws Exception {
- try (MetaDataUpdate md =
- metaDataUpdateFactory.create(pc.getProject().getNameKey(), user)) {
+ try (MetaDataUpdate md = metaDataUpdateFactory.create(pc.getProject().getNameKey(), user)) {
pc.commit(md);
projectCache.evict(pc.getProject().getNameKey());
}
@@ -223,19 +207,18 @@
private PatchSetApproval psa(Account.Id accountId, String label, int value) {
return new PatchSetApproval(
- new PatchSetApproval.Key(
- change.currentPatchSetId(), accountId, new LabelId(label)),
- (short) value, TimeUtil.nowTs());
+ new PatchSetApproval.Key(change.currentPatchSetId(), accountId, new LabelId(label)),
+ (short) value,
+ TimeUtil.nowTs());
}
private PatchSetApproval copy(PatchSetApproval src, int newValue) {
- PatchSetApproval result =
- new PatchSetApproval(src.getKey().getParentKey(), src);
+ PatchSetApproval result = new PatchSetApproval(src.getKey().getParentKey(), src);
result.setValue((short) newValue);
return result;
}
private static List<PatchSetApproval> list(PatchSetApproval... psas) {
- return ImmutableList.<PatchSetApproval> copyOf(psas);
+ return ImmutableList.<PatchSetApproval>copyOf(psas);
}
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/git/LocalDiskRepositoryManagerTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/git/LocalDiskRepositoryManagerTest.java
index e30e3fc..286f694 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/git/LocalDiskRepositoryManagerTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/git/LocalDiskRepositoryManagerTest.java
@@ -23,7 +23,9 @@
import com.google.gerrit.testutil.TempFileUtil;
import com.google.gwtorm.client.KeyUtil;
import com.google.gwtorm.server.StandardKeyEncoder;
-
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
import org.easymock.EasyMockSupport;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
import org.eclipse.jgit.lib.Config;
@@ -35,10 +37,6 @@
import org.junit.Before;
import org.junit.Test;
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.Path;
-
public class LocalDiskRepositoryManagerTest extends EasyMockSupport {
static {
@@ -116,8 +114,7 @@
}
@Test(expected = RepositoryNotFoundException.class)
- public void testProjectCreationWithPathSegmentEndingByDotGit()
- throws Exception {
+ public void testProjectCreationWithPathSegmentEndingByDotGit() throws Exception {
repoManager.createRepository(new Project.NameKey("a/b.git/projectA"));
}
@@ -175,8 +172,7 @@
@Test(expected = IllegalStateException.class)
public void testProjectRecreationAfterRestart() throws Exception {
repoManager.createRepository(new Project.NameKey("a"));
- LocalDiskRepositoryManager newRepoManager =
- new LocalDiskRepositoryManager(site, cfg);
+ LocalDiskRepositoryManager newRepoManager = new LocalDiskRepositoryManager(site, cfg);
newRepoManager.createRepository(new Project.NameKey("a"));
}
@@ -212,13 +208,11 @@
Project.NameKey name = new Project.NameKey("a");
repoManager.createRepository(name);
- LocalDiskRepositoryManager newRepoManager =
- new LocalDiskRepositoryManager(site, cfg);
+ LocalDiskRepositoryManager newRepoManager = new LocalDiskRepositoryManager(site, cfg);
newRepoManager.createRepository(new Project.NameKey("A"));
}
- private void createSymLink(Project.NameKey project, String link)
- throws IOException {
+ private void createSymLink(Project.NameKey project, String link) throws IOException {
Path base = repoManager.getBasePath(project);
Path projectDir = base.resolve(project.get() + ".git");
Path symlink = base.resolve(link);
@@ -244,12 +238,10 @@
repoManager.getBasePath(null).resolve(".git").toFile().mkdir();
// create an invalid repo name
createRepository(repoManager.getBasePath(null), "project?A");
- assertThat(repoManager.list())
- .containsExactly(projectA, projectB, projectC);
+ assertThat(repoManager.list()).containsExactly(projectA, projectB, projectC);
}
- private void createRepository(Path directory, String projectName)
- throws IOException {
+ private void createRepository(Path directory, String projectName) throws IOException {
String n = projectName + Constants.DOT_GIT_EXT;
FileKey loc = FileKey.exact(directory.resolve(n).toFile(), FS.DETECTED);
try (Repository db = RepositoryCache.open(loc, false)) {
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/git/MultiBaseLocalDiskRepositoryManagerTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/git/MultiBaseLocalDiskRepositoryManagerTest.java
index accf778..74515ae 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/git/MultiBaseLocalDiskRepositoryManagerTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/git/MultiBaseLocalDiskRepositoryManagerTest.java
@@ -25,7 +25,12 @@
import com.google.gerrit.server.config.SitePaths;
import com.google.gerrit.testutil.GerritBaseTests;
import com.google.gerrit.testutil.TempFileUtil;
-
+import java.io.IOException;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.SortedSet;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.lib.Constants;
@@ -37,13 +42,6 @@
import org.junit.Before;
import org.junit.Test;
-import java.io.IOException;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.SortedSet;
-
public class MultiBaseLocalDiskRepositoryManagerTest extends GerritBaseTests {
private Config cfg;
private SitePaths site;
@@ -59,8 +57,7 @@
configMock = createNiceMock(RepositoryConfig.class);
expect(configMock.getAllBasePaths()).andReturn(new ArrayList<Path>()).anyTimes();
replay(configMock);
- repoManager =
- new MultiBaseLocalDiskRepositoryManager(site, cfg, configMock);
+ repoManager = new MultiBaseLocalDiskRepositoryManager(site, cfg, configMock);
}
@After
@@ -70,25 +67,22 @@
@Test
public void defaultRepositoryLocation()
- throws RepositoryCaseMismatchException, RepositoryNotFoundException,
- IOException {
+ throws RepositoryCaseMismatchException, RepositoryNotFoundException, IOException {
Project.NameKey someProjectKey = new Project.NameKey("someProject");
Repository repo = repoManager.createRepository(someProjectKey);
assertThat(repo.getDirectory()).isNotNull();
assertThat(repo.getDirectory().exists()).isTrue();
- assertThat(repo.getDirectory().getParent()).isEqualTo(
- repoManager.getBasePath(someProjectKey).toAbsolutePath().toString());
+ assertThat(repo.getDirectory().getParent())
+ .isEqualTo(repoManager.getBasePath(someProjectKey).toAbsolutePath().toString());
repo = repoManager.openRepository(someProjectKey);
assertThat(repo.getDirectory()).isNotNull();
assertThat(repo.getDirectory().exists()).isTrue();
- assertThat(repo.getDirectory().getParent()).isEqualTo(
- repoManager.getBasePath(someProjectKey).toAbsolutePath().toString());
+ assertThat(repo.getDirectory().getParent())
+ .isEqualTo(repoManager.getBasePath(someProjectKey).toAbsolutePath().toString());
- assertThat(
- repoManager.getBasePath(someProjectKey).toAbsolutePath().toString())
- .isEqualTo(
- repoManager.getBasePath(someProjectKey).toAbsolutePath().toString());
+ assertThat(repoManager.getBasePath(someProjectKey).toAbsolutePath().toString())
+ .isEqualTo(repoManager.getBasePath(someProjectKey).toAbsolutePath().toString());
SortedSet<Project.NameKey> repoList = repoManager.list();
assertThat(repoList.size()).isEqualTo(1);
@@ -101,27 +95,22 @@
Path alternateBasePath = TempFileUtil.createTempDirectory().toPath();
Project.NameKey someProjectKey = new Project.NameKey("someProject");
reset(configMock);
- expect(configMock.getBasePath(someProjectKey)).andReturn(alternateBasePath)
- .anyTimes();
- expect(configMock.getAllBasePaths())
- .andReturn(Arrays.asList(alternateBasePath)).anyTimes();
+ expect(configMock.getBasePath(someProjectKey)).andReturn(alternateBasePath).anyTimes();
+ expect(configMock.getAllBasePaths()).andReturn(Arrays.asList(alternateBasePath)).anyTimes();
replay(configMock);
Repository repo = repoManager.createRepository(someProjectKey);
assertThat(repo.getDirectory()).isNotNull();
assertThat(repo.getDirectory().exists()).isTrue();
- assertThat(repo.getDirectory().getParent())
- .isEqualTo(alternateBasePath.toString());
+ assertThat(repo.getDirectory().getParent()).isEqualTo(alternateBasePath.toString());
repo = repoManager.openRepository(someProjectKey);
assertThat(repo.getDirectory()).isNotNull();
assertThat(repo.getDirectory().exists()).isTrue();
- assertThat(repo.getDirectory().getParent())
- .isEqualTo(alternateBasePath.toString());
+ assertThat(repo.getDirectory().getParent()).isEqualTo(alternateBasePath.toString());
- assertThat(
- repoManager.getBasePath(someProjectKey).toAbsolutePath().toString())
- .isEqualTo(alternateBasePath.toString());
+ assertThat(repoManager.getBasePath(someProjectKey).toAbsolutePath().toString())
+ .isEqualTo(alternateBasePath.toString());
SortedSet<Project.NameKey> repoList = repoManager.list();
assertThat(repoList.size()).isEqualTo(1);
@@ -133,28 +122,22 @@
public void listReturnRepoFromProperLocation() throws IOException {
Project.NameKey basePathProject = new Project.NameKey("basePathProject");
Project.NameKey altPathProject = new Project.NameKey("altPathProject");
- Project.NameKey misplacedProject1 =
- new Project.NameKey("misplacedProject1");
- Project.NameKey misplacedProject2 =
- new Project.NameKey("misplacedProject2");
+ Project.NameKey misplacedProject1 = new Project.NameKey("misplacedProject1");
+ Project.NameKey misplacedProject2 = new Project.NameKey("misplacedProject2");
Path alternateBasePath = TempFileUtil.createTempDirectory().toPath();
reset(configMock);
- expect(configMock.getBasePath(altPathProject)).andReturn(alternateBasePath)
- .anyTimes();
- expect(configMock.getBasePath(misplacedProject2))
- .andReturn(alternateBasePath).anyTimes();
- expect(configMock.getAllBasePaths())
- .andReturn(Arrays.asList(alternateBasePath)).anyTimes();
+ expect(configMock.getBasePath(altPathProject)).andReturn(alternateBasePath).anyTimes();
+ expect(configMock.getBasePath(misplacedProject2)).andReturn(alternateBasePath).anyTimes();
+ expect(configMock.getAllBasePaths()).andReturn(Arrays.asList(alternateBasePath)).anyTimes();
replay(configMock);
repoManager.createRepository(basePathProject);
repoManager.createRepository(altPathProject);
// create the misplaced ones without the repomanager otherwise they would
// end up at the proper place.
- createRepository(repoManager.getBasePath(basePathProject),
- misplacedProject2);
+ createRepository(repoManager.getBasePath(basePathProject), misplacedProject2);
createRepository(alternateBasePath, misplacedProject1);
SortedSet<Project.NameKey> repoList = repoManager.list();
@@ -163,8 +146,7 @@
.isEqualTo(new Project.NameKey[] {altPathProject, basePathProject});
}
- private void createRepository(Path directory, Project.NameKey projectName)
- throws IOException {
+ private void createRepository(Path directory, Project.NameKey projectName) throws IOException {
String n = projectName.get() + Constants.DOT_GIT_EXT;
FileKey loc = FileKey.exact(directory.resolve(n).toFile(), FS.DETECTED);
try (Repository db = RepositoryCache.open(loc, false)) {
@@ -175,10 +157,8 @@
@Test(expected = IllegalStateException.class)
public void testRelativeAlternateLocation() {
configMock = createNiceMock(RepositoryConfig.class);
- expect(configMock.getAllBasePaths())
- .andReturn(Arrays.asList(Paths.get("repos"))).anyTimes();
+ expect(configMock.getAllBasePaths()).andReturn(Arrays.asList(Paths.get("repos"))).anyTimes();
replay(configMock);
- repoManager =
- new MultiBaseLocalDiskRepositoryManager(site, cfg, configMock);
+ repoManager = new MultiBaseLocalDiskRepositoryManager(site, cfg, configMock);
}
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/git/ProjectConfigTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/git/ProjectConfigTest.java
index 94220f6..d4577c5 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/git/ProjectConfigTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/git/ProjectConfigTest.java
@@ -28,7 +28,9 @@
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.reviewdb.client.RefNames;
import com.google.gerrit.server.extensions.events.GitReferenceUpdated;
-
+import java.io.IOException;
+import java.util.Collections;
+import java.util.Map;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.errors.IncorrectObjectTypeException;
import org.eclipse.jgit.errors.MissingObjectException;
@@ -44,27 +46,30 @@
import org.junit.Before;
import org.junit.Test;
-import java.io.IOException;
-import java.util.Collections;
-import java.util.Map;
-
public class ProjectConfigTest extends LocalDiskRepositoryTestCase {
private static final String LABEL_SCORES_CONFIG =
- " copyMinScore = " + !LabelType.DEF_COPY_MIN_SCORE + "\n" //
- + " copyMaxScore = " + !LabelType.DEF_COPY_MAX_SCORE + "\n" //
- + " copyAllScoresOnMergeFirstParentUpdate = "
- + !LabelType.DEF_COPY_ALL_SCORES_ON_MERGE_FIRST_PARENT_UPDATE + "\n" //
- + " copyAllScoresOnTrivialRebase = "
- + !LabelType.DEF_COPY_ALL_SCORES_ON_TRIVIAL_REBASE + "\n" //
- + " copyAllScoresIfNoCodeChange = "
- + !LabelType.DEF_COPY_ALL_SCORES_IF_NO_CODE_CHANGE + "\n" //
- + " copyAllScoresIfNoChange = "
- + !LabelType.DEF_COPY_ALL_SCORES_IF_NO_CHANGE + "\n";
+ " copyMinScore = "
+ + !LabelType.DEF_COPY_MIN_SCORE
+ + "\n" //
+ + " copyMaxScore = "
+ + !LabelType.DEF_COPY_MAX_SCORE
+ + "\n" //
+ + " copyAllScoresOnMergeFirstParentUpdate = "
+ + !LabelType.DEF_COPY_ALL_SCORES_ON_MERGE_FIRST_PARENT_UPDATE
+ + "\n" //
+ + " copyAllScoresOnTrivialRebase = "
+ + !LabelType.DEF_COPY_ALL_SCORES_ON_TRIVIAL_REBASE
+ + "\n" //
+ + " copyAllScoresIfNoCodeChange = "
+ + !LabelType.DEF_COPY_ALL_SCORES_IF_NO_CODE_CHANGE
+ + "\n" //
+ + " copyAllScoresIfNoChange = "
+ + !LabelType.DEF_COPY_ALL_SCORES_IF_NO_CHANGE
+ + "\n";
- private final GroupReference developers = new GroupReference(
- new AccountGroup.UUID("X"), "Developers");
- private final GroupReference staff = new GroupReference(
- new AccountGroup.UUID("Y"), "Staff");
+ private final GroupReference developers =
+ new GroupReference(new AccountGroup.UUID("X"), "Developers");
+ private final GroupReference staff = new GroupReference(new AccountGroup.UUID("Y"), "Staff");
private Repository db;
private TestRepository<Repository> util;
@@ -79,24 +84,29 @@
@Test
public void readConfig() throws Exception {
- RevCommit rev = util.commit(util.tree( //
- util.file("groups", util.blob(group(developers))), //
- util.file("project.config", util.blob(""//
- + "[access \"refs/heads/*\"]\n" //
- + " exclusiveGroupPermissions = read submit create\n" //
- + " submit = group Developers\n" //
- + " push = group Developers\n" //
- + " read = group Developers\n" //
- + "[accounts]\n" //
- + " sameGroupVisibility = deny group Developers\n" //
- + " sameGroupVisibility = block group Staff\n" //
- + "[contributor-agreement \"Individual\"]\n" //
- + " description = A simple description\n" //
- + " accepted = group Developers\n" //
- + " accepted = group Staff\n" //
- + " autoVerify = group Developers\n" //
- + " agreementUrl = http://www.example.com/agree\n")) //
- ));
+ RevCommit rev =
+ util.commit(
+ util.tree( //
+ util.file("groups", util.blob(group(developers))), //
+ util.file(
+ "project.config",
+ util.blob(
+ "" //
+ + "[access \"refs/heads/*\"]\n" //
+ + " exclusiveGroupPermissions = read submit create\n" //
+ + " submit = group Developers\n" //
+ + " push = group Developers\n" //
+ + " read = group Developers\n" //
+ + "[accounts]\n" //
+ + " sameGroupVisibility = deny group Developers\n" //
+ + " sameGroupVisibility = block group Staff\n" //
+ + "[contributor-agreement \"Individual\"]\n" //
+ + " description = A simple description\n" //
+ + " accepted = group Developers\n" //
+ + " accepted = group Staff\n" //
+ + " autoVerify = group Developers\n" //
+ + " agreementUrl = http://www.example.com/agree\n")) //
+ ));
ProjectConfig cfg = read(rev);
assertThat(cfg.getAccountsSection().getSameGroupVisibility()).hasSize(2);
@@ -126,66 +136,85 @@
@Test
public void readConfigLabelDefaultValue() throws Exception {
- RevCommit rev = util.commit(util.tree( //
- util.file("groups", util.blob(group(developers))), //
- util.file("project.config", util.blob(""//
- + "[label \"CustomLabel\"]\n" //
- + " value = -1 Negative\n" //
- + " value = 0 No Score\n" //
- + " value = 1 Positive\n")) //
- ));
+ RevCommit rev =
+ util.commit(
+ util.tree( //
+ util.file("groups", util.blob(group(developers))), //
+ util.file(
+ "project.config",
+ util.blob(
+ "" //
+ + "[label \"CustomLabel\"]\n" //
+ + " value = -1 Negative\n" //
+ + " value = 0 No Score\n" //
+ + " value = 1 Positive\n")) //
+ ));
ProjectConfig cfg = read(rev);
Map<String, LabelType> labels = cfg.getLabelSections();
Short dv = labels.entrySet().iterator().next().getValue().getDefaultValue();
- assertThat((int)dv).isEqualTo(0);
+ assertThat((int) dv).isEqualTo(0);
}
@Test
public void readConfigLabelDefaultValueInRange() throws Exception {
- RevCommit rev = util.commit(util.tree( //
- util.file("groups", util.blob(group(developers))), //
- util.file("project.config", util.blob(""//
- + "[label \"CustomLabel\"]\n" //
- + " value = -1 Negative\n" //
- + " value = 0 No Score\n" //
- + " value = 1 Positive\n" //
- + " defaultValue = -1\n")) //
- ));
+ RevCommit rev =
+ util.commit(
+ util.tree( //
+ util.file("groups", util.blob(group(developers))), //
+ util.file(
+ "project.config",
+ util.blob(
+ "" //
+ + "[label \"CustomLabel\"]\n" //
+ + " value = -1 Negative\n" //
+ + " value = 0 No Score\n" //
+ + " value = 1 Positive\n" //
+ + " defaultValue = -1\n")) //
+ ));
ProjectConfig cfg = read(rev);
Map<String, LabelType> labels = cfg.getLabelSections();
Short dv = labels.entrySet().iterator().next().getValue().getDefaultValue();
- assertThat((int)dv).isEqualTo(-1);
+ assertThat((int) dv).isEqualTo(-1);
}
@Test
public void readConfigLabelDefaultValueNotInRange() throws Exception {
- RevCommit rev = util.commit(util.tree( //
- util.file("groups", util.blob(group(developers))), //
- util.file("project.config", util.blob(""//
- + "[label \"CustomLabel\"]\n" //
- + " value = -1 Negative\n" //
- + " value = 0 No Score\n" //
- + " value = 1 Positive\n" //
- + " defaultValue = -2\n")) //
- ));
+ RevCommit rev =
+ util.commit(
+ util.tree( //
+ util.file("groups", util.blob(group(developers))), //
+ util.file(
+ "project.config",
+ util.blob(
+ "" //
+ + "[label \"CustomLabel\"]\n" //
+ + " value = -1 Negative\n" //
+ + " value = 0 No Score\n" //
+ + " value = 1 Positive\n" //
+ + " defaultValue = -2\n")) //
+ ));
ProjectConfig cfg = read(rev);
assertThat(cfg.getValidationErrors()).hasSize(1);
assertThat(Iterables.getOnlyElement(cfg.getValidationErrors()).getMessage())
- .isEqualTo("project.config: Invalid defaultValue \"-2\" "
- + "for label \"CustomLabel\"");
+ .isEqualTo("project.config: Invalid defaultValue \"-2\" " + "for label \"CustomLabel\"");
}
@Test
public void readConfigLabelScores() throws Exception {
- RevCommit rev = util.commit(util.tree( //
- util.file("groups", util.blob(group(developers))), //
- util.file("project.config", util.blob(""//
- + "[label \"CustomLabel\"]\n" //
- + LABEL_SCORES_CONFIG)) //
- ));
+ RevCommit rev =
+ util.commit(
+ util.tree( //
+ util.file("groups", util.blob(group(developers))), //
+ util.file(
+ "project.config",
+ util.blob(
+ "" //
+ + "[label \"CustomLabel\"]\n" //
+ + LABEL_SCORES_CONFIG)) //
+ ));
ProjectConfig cfg = read(rev);
Map<String, LabelType> labels = cfg.getLabelSections();
@@ -193,42 +222,47 @@
assertThat(type.isCopyMinScore()).isNotEqualTo(LabelType.DEF_COPY_MIN_SCORE);
assertThat(type.isCopyMaxScore()).isNotEqualTo(LabelType.DEF_COPY_MAX_SCORE);
assertThat(type.isCopyAllScoresOnMergeFirstParentUpdate())
- .isNotEqualTo(LabelType.DEF_COPY_ALL_SCORES_ON_MERGE_FIRST_PARENT_UPDATE);
+ .isNotEqualTo(LabelType.DEF_COPY_ALL_SCORES_ON_MERGE_FIRST_PARENT_UPDATE);
assertThat(type.isCopyAllScoresOnTrivialRebase())
- .isNotEqualTo(LabelType.DEF_COPY_ALL_SCORES_ON_TRIVIAL_REBASE);
+ .isNotEqualTo(LabelType.DEF_COPY_ALL_SCORES_ON_TRIVIAL_REBASE);
assertThat(type.isCopyAllScoresIfNoCodeChange())
- .isNotEqualTo(LabelType.DEF_COPY_ALL_SCORES_IF_NO_CODE_CHANGE);
+ .isNotEqualTo(LabelType.DEF_COPY_ALL_SCORES_IF_NO_CODE_CHANGE);
assertThat(type.isCopyAllScoresIfNoChange())
- .isNotEqualTo(LabelType.DEF_COPY_ALL_SCORES_IF_NO_CHANGE);
+ .isNotEqualTo(LabelType.DEF_COPY_ALL_SCORES_IF_NO_CHANGE);
}
@Test
public void editConfig() throws Exception {
- RevCommit rev = util.commit(util.tree( //
- util.file("groups", util.blob(group(developers))), //
- util.file("project.config", util.blob(""//
- + "[access \"refs/heads/*\"]\n" //
- + " exclusiveGroupPermissions = read submit\n" //
- + " submit = group Developers\n" //
- + " upload = group Developers\n" //
- + " read = group Developers\n" //
- + "[accounts]\n" //
- + " sameGroupVisibility = deny group Developers\n" //
- + " sameGroupVisibility = block group Staff\n" //
- + "[contributor-agreement \"Individual\"]\n" //
- + " description = A simple description\n" //
- + " accepted = group Developers\n" //
- + " autoVerify = group Developers\n" //
- + " agreementUrl = http://www.example.com/agree\n" //
- + "[label \"CustomLabel\"]\n" //
- + LABEL_SCORES_CONFIG)) //
- ));
+ RevCommit rev =
+ util.commit(
+ util.tree( //
+ util.file("groups", util.blob(group(developers))), //
+ util.file(
+ "project.config",
+ util.blob(
+ "" //
+ + "[access \"refs/heads/*\"]\n" //
+ + " exclusiveGroupPermissions = read submit\n" //
+ + " submit = group Developers\n" //
+ + " upload = group Developers\n" //
+ + " read = group Developers\n" //
+ + "[accounts]\n" //
+ + " sameGroupVisibility = deny group Developers\n" //
+ + " sameGroupVisibility = block group Staff\n" //
+ + "[contributor-agreement \"Individual\"]\n" //
+ + " description = A simple description\n" //
+ + " accepted = group Developers\n" //
+ + " autoVerify = group Developers\n" //
+ + " agreementUrl = http://www.example.com/agree\n" //
+ + "[label \"CustomLabel\"]\n" //
+ + LABEL_SCORES_CONFIG)) //
+ ));
update(rev);
ProjectConfig cfg = read(rev);
AccessSection section = cfg.getAccessSection("refs/heads/*");
- cfg.getAccountsSection().setSameGroupVisibility(
- Collections.singletonList(new PermissionRule(cfg.resolve(staff))));
+ cfg.getAccountsSection()
+ .setSameGroupVisibility(Collections.singletonList(new PermissionRule(cfg.resolve(staff))));
Permission submit = section.getPermission(Permission.SUBMIT);
submit.add(new PermissionRule(cfg.resolve(staff)));
ContributorAgreement ca = cfg.getContributorAgreement("Individual");
@@ -236,36 +270,43 @@
ca.setAutoVerify(null);
ca.setDescription("A new description");
rev = commit(cfg);
- assertThat(text(rev, "project.config")).isEqualTo(""//
- + "[access \"refs/heads/*\"]\n" //
- + " exclusiveGroupPermissions = read submit\n" //
- + " submit = group Developers\n" //
- + "\tsubmit = group Staff\n" //
- + " upload = group Developers\n" //
- + " read = group Developers\n"//
- + "[accounts]\n" //
- + " sameGroupVisibility = group Staff\n" //
- + "[contributor-agreement \"Individual\"]\n" //
- + " description = A new description\n" //
- + " accepted = group Staff\n" //
- + " agreementUrl = http://www.example.com/agree\n"
- + "[label \"CustomLabel\"]\n" //
- + LABEL_SCORES_CONFIG
- + "\tfunction = MaxWithBlock\n" // label gets this function when it is created
- + "\tdefaultValue = 0\n"); // label gets this value when it is created
+ assertThat(text(rev, "project.config"))
+ .isEqualTo(
+ "" //
+ + "[access \"refs/heads/*\"]\n" //
+ + " exclusiveGroupPermissions = read submit\n" //
+ + " submit = group Developers\n" //
+ + "\tsubmit = group Staff\n" //
+ + " upload = group Developers\n" //
+ + " read = group Developers\n" //
+ + "[accounts]\n" //
+ + " sameGroupVisibility = group Staff\n" //
+ + "[contributor-agreement \"Individual\"]\n" //
+ + " description = A new description\n" //
+ + " accepted = group Staff\n" //
+ + " agreementUrl = http://www.example.com/agree\n"
+ + "[label \"CustomLabel\"]\n" //
+ + LABEL_SCORES_CONFIG
+ + "\tfunction = MaxWithBlock\n" // label gets this function when it is created
+ + "\tdefaultValue = 0\n"); // label gets this value when it is created
}
@Test
public void editConfigMissingGroupTableEntry() throws Exception {
- RevCommit rev = util.commit(util.tree( //
- util.file("groups", util.blob(group(developers))), //
- util.file("project.config", util.blob(""//
- + "[access \"refs/heads/*\"]\n" //
- + " exclusiveGroupPermissions = read submit\n" //
- + " submit = group People Who Can Submit\n" //
- + " upload = group Developers\n" //
- + " read = group Developers\n")) //
- ));
+ RevCommit rev =
+ util.commit(
+ util.tree( //
+ util.file("groups", util.blob(group(developers))), //
+ util.file(
+ "project.config",
+ util.blob(
+ "" //
+ + "[access \"refs/heads/*\"]\n" //
+ + " exclusiveGroupPermissions = read submit\n" //
+ + " submit = group People Who Can Submit\n" //
+ + " upload = group Developers\n" //
+ + " read = group Developers\n")) //
+ ));
update(rev);
ProjectConfig cfg = read(rev);
@@ -273,28 +314,27 @@
Permission submit = section.getPermission(Permission.SUBMIT);
submit.add(new PermissionRule(cfg.resolve(staff)));
rev = commit(cfg);
- assertThat(text(rev, "project.config")).isEqualTo(""//
- + "[access \"refs/heads/*\"]\n" //
- + " exclusiveGroupPermissions = read submit\n" //
- + " submit = group People Who Can Submit\n" //
- + "\tsubmit = group Staff\n" //
- + " upload = group Developers\n" //
- + " read = group Developers\n");
+ assertThat(text(rev, "project.config"))
+ .isEqualTo(
+ "" //
+ + "[access \"refs/heads/*\"]\n" //
+ + " exclusiveGroupPermissions = read submit\n" //
+ + " submit = group People Who Can Submit\n" //
+ + "\tsubmit = group Staff\n" //
+ + " upload = group Developers\n" //
+ + " read = group Developers\n");
}
- private ProjectConfig read(RevCommit rev) throws IOException,
- ConfigInvalidException {
+ private ProjectConfig read(RevCommit rev) throws IOException, ConfigInvalidException {
ProjectConfig cfg = new ProjectConfig(new Project.NameKey("test"));
cfg.load(db, rev);
return cfg;
}
- private RevCommit commit(ProjectConfig cfg) throws IOException,
- MissingObjectException, IncorrectObjectTypeException {
- try (MetaDataUpdate md = new MetaDataUpdate(
- GitReferenceUpdated.DISABLED,
- cfg.getProject().getNameKey(),
- db)) {
+ private RevCommit commit(ProjectConfig cfg)
+ throws IOException, MissingObjectException, IncorrectObjectTypeException {
+ try (MetaDataUpdate md =
+ new MetaDataUpdate(GitReferenceUpdated.DISABLED, cfg.getProject().getNameKey(), db)) {
util.tick(5);
util.setAuthorAndCommitter(md.getCommitBuilder());
md.setMessage("Edit\n");
@@ -311,9 +351,9 @@
u.setNewObjectId(rev);
Result result = u.forceUpdate();
assert_()
- .withFailureMessage("Cannot update ref for test: " + result)
- .that(result)
- .isAnyOf(Result.FAST_FORWARD, Result.FORCED, Result.NEW, Result.NO_CHANGE);
+ .withFailureMessage("Cannot update ref for test: " + result)
+ .that(result)
+ .isAnyOf(Result.FAST_FORWARD, Result.FORCED, Result.NEW, Result.NO_CHANGE);
}
private String text(RevCommit rev, String path) throws Exception {
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/git/QueryListTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/git/QueryListTest.java
index d022d3e..8d0f909 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/git/QueryListTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/git/QueryListTest.java
@@ -18,11 +18,9 @@
import static org.easymock.EasyMock.createNiceMock;
import static org.easymock.EasyMock.replay;
-import junit.framework.TestCase;
-
-import org.junit.Test;
-
import java.io.IOException;
+import junit.framework.TestCase;
+import org.junit.Test;
public class QueryListTest extends TestCase {
public static final String Q_P = "project:foo";
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/index/SchemaUtilTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/index/SchemaUtilTest.java
index e6447da..1dc6a469 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/index/SchemaUtilTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/index/SchemaUtilTest.java
@@ -20,12 +20,10 @@
import static com.google.gerrit.server.index.SchemaUtil.schema;
import com.google.gerrit.testutil.GerritBaseTests;
-
+import java.util.Map;
import org.eclipse.jgit.lib.PersonIdent;
import org.junit.Test;
-import java.util.Map;
-
public class SchemaUtilTest extends GerritBaseTests {
static class TestSchemas {
static final Schema<String> V1 = schema();
@@ -40,8 +38,7 @@
@Test
public void schemasFromClassBuildsMap() {
- Map<Integer, Schema<String>> all =
- SchemaUtil.schemasFromClass(TestSchemas.class, String.class);
+ Map<Integer, Schema<String>> all = SchemaUtil.schemasFromClass(TestSchemas.class, String.class);
assertThat(all.keySet()).containsExactly(1, 2, 4);
assertThat(all.get(1)).isEqualTo(TestSchemas.V1);
assertThat(all.get(2)).isEqualTo(TestSchemas.V2);
@@ -56,18 +53,22 @@
// PersonIdent allows empty email, which should be extracted as the empty
// string. However, it converts empty names to null internally.
assertThat(getPersonParts(new PersonIdent("", ""))).containsExactly("");
- assertThat(getPersonParts(new PersonIdent("foo bar", "")))
- .containsExactly("foo", "bar", "");
+ assertThat(getPersonParts(new PersonIdent("foo bar", ""))).containsExactly("foo", "bar", "");
assertThat(getPersonParts(new PersonIdent("", "foo@example.com")))
+ .containsExactly("foo@example.com", "foo", "example.com", "example", "com");
+ assertThat(getPersonParts(new PersonIdent("foO J. bAr", "bA-z@exAmple.cOm")))
.containsExactly(
- "foo@example.com", "foo", "example.com", "example", "com");
- assertThat(
- getPersonParts(new PersonIdent("foO J. bAr", "bA-z@exAmple.cOm")))
- .containsExactly(
- "foo", "j", "bar",
- "ba-z@example.com", "ba-z", "ba", "z",
- "example.com", "example", "com");
+ "foo",
+ "j",
+ "bar",
+ "ba-z@example.com",
+ "ba-z",
+ "ba",
+ "z",
+ "example.com",
+ "example",
+ "com");
}
@Test
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/index/change/ChangeFieldTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/index/change/ChangeFieldTest.java
index 693abfb..3a4db30 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/index/change/ChangeFieldTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/index/change/ChangeFieldTest.java
@@ -28,14 +28,12 @@
import com.google.gerrit.server.notedb.ReviewerStateInternal;
import com.google.gerrit.testutil.GerritBaseTests;
import com.google.gerrit.testutil.TestTimeUtil;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
import java.sql.Timestamp;
import java.util.List;
import java.util.concurrent.TimeUnit;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
public class ChangeFieldTest extends GerritBaseTests {
@Before
@@ -50,8 +48,7 @@
@Test
public void reviewerFieldValues() {
- Table<ReviewerStateInternal, Account.Id, Timestamp> t =
- HashBasedTable.create();
+ Table<ReviewerStateInternal, Account.Id, Timestamp> t = HashBasedTable.create();
Timestamp t1 = TimeUtil.nowTs();
t.put(ReviewerStateInternal.REVIEWER, new Account.Id(1), t1);
Timestamp t2 = TimeUtil.nowTs();
@@ -59,14 +56,11 @@
ReviewerSet reviewers = ReviewerSet.fromTable(t);
List<String> values = ChangeField.getReviewerFieldValues(reviewers);
- assertThat(values).containsExactly(
- "REVIEWER,1",
- "REVIEWER,1," + t1.getTime(),
- "CC,2",
- "CC,2," + t2.getTime());
+ assertThat(values)
+ .containsExactly(
+ "REVIEWER,1", "REVIEWER,1," + t1.getTime(), "CC,2", "CC,2," + t2.getTime());
- assertThat(ChangeField.parseReviewerFieldValues(values))
- .isEqualTo(reviewers);
+ assertThat(ChangeField.parseReviewerFieldValues(values)).isEqualTo(reviewers);
}
@Test
@@ -79,12 +73,7 @@
label(SubmitRecord.Label.Status.MAY, "Label-1", null),
label(SubmitRecord.Label.Status.OK, "Label-2", 1))),
new Account.Id(1)))
- .containsExactly(
- "OK",
- "MAY,label-1",
- "OK,label-2",
- "OK,label-2,0",
- "OK,label-2,1");
+ .containsExactly("OK", "MAY,label-1", "OK,label-2", "OK,label-2,0", "OK,label-2,1");
}
@Test
@@ -97,8 +86,7 @@
label(SubmitRecord.Label.Status.OK, "Label-2", 1)));
}
- private static SubmitRecord record(SubmitRecord.Status status,
- SubmitRecord.Label... labels) {
+ private static SubmitRecord record(SubmitRecord.Status status, SubmitRecord.Label... labels) {
SubmitRecord r = new SubmitRecord();
r.status = status;
if (labels.length > 0) {
@@ -107,8 +95,8 @@
return r;
}
- private static SubmitRecord.Label label(SubmitRecord.Label.Status status,
- String label, Integer appliedBy) {
+ private static SubmitRecord.Label label(
+ SubmitRecord.Label.Status status, String label, Integer appliedBy) {
SubmitRecord.Label l = new SubmitRecord.Label();
l.status = status;
l.label = label;
@@ -120,9 +108,11 @@
private static void assertStoredRecordRoundTrip(SubmitRecord... records) {
List<SubmitRecord> recordList = ImmutableList.copyOf(records);
- List<String> stored = ChangeField.storedSubmitRecords(recordList).stream()
- .map(s -> new String(s, UTF_8))
- .collect(toList());
+ List<String> stored =
+ ChangeField.storedSubmitRecords(recordList)
+ .stream()
+ .map(s -> new String(s, UTF_8))
+ .collect(toList());
assertThat(ChangeField.parseSubmitRecords(stored))
.named("JSON %s" + stored)
.isEqualTo(recordList);
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/index/change/ChangeIndexRewriterTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/index/change/ChangeIndexRewriterTest.java
index acf6b14..1724c51 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/index/change/ChangeIndexRewriterTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/index/change/ChangeIndexRewriterTest.java
@@ -38,13 +38,11 @@
import com.google.gerrit.server.query.change.ChangeStatusPredicate;
import com.google.gerrit.server.query.change.OrSource;
import com.google.gerrit.testutil.GerritBaseTests;
-
-import org.junit.Before;
-import org.junit.Test;
-
import java.util.Arrays;
import java.util.EnumSet;
import java.util.Set;
+import org.junit.Before;
+import org.junit.Test;
public class ChangeIndexRewriterTest extends GerritBaseTests {
private static final IndexConfig CONFIG = IndexConfig.createDefault();
@@ -60,8 +58,7 @@
indexes = new ChangeIndexCollection();
indexes.setSearchIndex(index);
queryBuilder = new FakeQueryBuilder(indexes);
- rewrite = new ChangeIndexRewriter(indexes,
- IndexConfig.create(0, 0, 3));
+ rewrite = new ChangeIndexRewriter(indexes, IndexConfig.create(0, 0, 3));
}
@Test
@@ -101,19 +98,13 @@
Predicate<ChangeData> in = parse("foo:a file:b");
Predicate<ChangeData> out = rewrite(in);
assertThat(AndChangeSource.class).isSameAs(out.getClass());
- assertThat(out.getChildren())
- .containsExactly(
- query(in.getChild(1)),
- in.getChild(0))
- .inOrder();
+ assertThat(out.getChildren()).containsExactly(query(in.getChild(1)), in.getChild(0)).inOrder();
}
@Test
public void threeLevelTreeWithAllIndexPredicates() throws Exception {
- Predicate<ChangeData> in =
- parse("-status:abandoned (file:a OR file:b)");
- assertThat(rewrite.rewrite(in, options(0, DEFAULT_MAX_QUERY_LIMIT)))
- .isEqualTo(query(in));
+ Predicate<ChangeData> in = parse("-status:abandoned (file:a OR file:b)");
+ assertThat(rewrite.rewrite(in, options(0, DEFAULT_MAX_QUERY_LIMIT))).isEqualTo(query(in));
}
@Test
@@ -121,24 +112,16 @@
Predicate<ChangeData> in = parse("-foo:a (file:b OR file:c)");
Predicate<ChangeData> out = rewrite(in);
assertThat(out.getClass()).isSameAs(AndChangeSource.class);
- assertThat(out.getChildren())
- .containsExactly(
- query(in.getChild(1)),
- in.getChild(0))
- .inOrder();
+ assertThat(out.getChildren()).containsExactly(query(in.getChild(1)), in.getChild(0)).inOrder();
}
@Test
public void multipleIndexPredicates() throws Exception {
- Predicate<ChangeData> in =
- parse("file:a OR foo:b OR file:c OR foo:d");
+ Predicate<ChangeData> in = parse("file:a OR foo:b OR file:c OR foo:d");
Predicate<ChangeData> out = rewrite(in);
assertThat(out.getClass()).isSameAs(OrSource.class);
assertThat(out.getChildren())
- .containsExactly(
- query(or(in.getChild(0), in.getChild(2))),
- in.getChild(1),
- in.getChild(3))
+ .containsExactly(query(or(in.getChild(0), in.getChild(2))), in.getChild(1), in.getChild(3))
.inOrder();
}
@@ -148,49 +131,37 @@
Predicate<ChangeData> out = rewrite(in);
assertThat(AndChangeSource.class).isSameAs(out.getClass());
assertThat(out.getChildren())
- .containsExactly(
- query(and(in.getChild(0), in.getChild(2))),
- in.getChild(1))
+ .containsExactly(query(and(in.getChild(0), in.getChild(2))), in.getChild(1))
.inOrder();
}
@Test
public void duplicateCompoundNonIndexOnlyPredicates() throws Exception {
- Predicate<ChangeData> in =
- parse("(status:new OR status:draft) bar:p file:a");
+ Predicate<ChangeData> in = parse("(status:new OR status:draft) bar:p file:a");
Predicate<ChangeData> out = rewrite(in);
assertThat(out.getClass()).isEqualTo(AndChangeSource.class);
assertThat(out.getChildren())
- .containsExactly(
- query(and(in.getChild(0), in.getChild(2))),
- in.getChild(1))
+ .containsExactly(query(and(in.getChild(0), in.getChild(2))), in.getChild(1))
.inOrder();
}
@Test
public void duplicateCompoundIndexOnlyPredicates() throws Exception {
- Predicate<ChangeData> in =
- parse("(status:new OR file:a) bar:p file:b");
+ Predicate<ChangeData> in = parse("(status:new OR file:a) bar:p file:b");
Predicate<ChangeData> out = rewrite(in);
assertThat(out.getClass()).isEqualTo(AndChangeSource.class);
assertThat(out.getChildren())
- .containsExactly(
- query(and(in.getChild(0), in.getChild(2))),
- in.getChild(1))
+ .containsExactly(query(and(in.getChild(0), in.getChild(2))), in.getChild(1))
.inOrder();
}
@Test
- public void optionsArgumentOverridesAllLimitPredicates()
- throws Exception {
+ public void optionsArgumentOverridesAllLimitPredicates() throws Exception {
Predicate<ChangeData> in = parse("limit:1 file:a limit:3");
Predicate<ChangeData> out = rewrite(in, options(0, 5));
assertThat(out.getClass()).isEqualTo(AndChangeSource.class);
assertThat(out.getChildren())
- .containsExactly(
- query(in.getChild(1), 5),
- parse("limit:5"),
- parse("limit:5"))
+ .containsExactly(query(in.getChild(1), 5), parse("limit:5"), parse("limit:5"))
.inOrder();
}
@@ -200,28 +171,23 @@
Predicate<ChangeData> f = parse("file:a");
Predicate<ChangeData> l = parse("limit:" + n);
Predicate<ChangeData> in = andSource(f, l);
- assertThat(rewrite.rewrite(in, options(0, n)))
- .isEqualTo(andSource(query(f, 3), l));
- assertThat(rewrite.rewrite(in, options(1, n)))
- .isEqualTo(andSource(query(f, 4), l));
- assertThat(rewrite.rewrite(in, options(2, n)))
- .isEqualTo(andSource(query(f, 5), l));
+ assertThat(rewrite.rewrite(in, options(0, n))).isEqualTo(andSource(query(f, 3), l));
+ assertThat(rewrite.rewrite(in, options(1, n))).isEqualTo(andSource(query(f, 4), l));
+ assertThat(rewrite.rewrite(in, options(2, n))).isEqualTo(andSource(query(f, 5), l));
}
@Test
public void getPossibleStatus() throws Exception {
assertThat(status("file:a")).isEqualTo(EnumSet.allOf(Change.Status.class));
assertThat(status("is:new")).containsExactly(NEW);
- assertThat(status("-is:new"))
- .containsExactly(DRAFT, MERGED, ABANDONED);
+ assertThat(status("-is:new")).containsExactly(DRAFT, MERGED, ABANDONED);
assertThat(status("is:new OR is:merged")).containsExactly(NEW, MERGED);
assertThat(status("is:new is:merged")).isEmpty();
assertThat(status("(is:new is:draft) (is:merged)")).isEmpty();
assertThat(status("(is:new is:draft) (is:merged)")).isEmpty();
- assertThat(status("(is:new is:draft) OR (is:merged)"))
- .containsExactly(MERGED);
+ assertThat(status("(is:new is:draft) OR (is:merged)")).containsExactly(MERGED);
}
@Test
@@ -232,11 +198,7 @@
indexes.setSearchIndex(new FakeChangeIndex(FakeChangeIndex.V1));
Predicate<ChangeData> out = rewrite(in);
assertThat(out).isInstanceOf(AndPredicate.class);
- assertThat(out.getChildren())
- .containsExactly(
- query(in.getChild(0)),
- in.getChild(1))
- .inOrder();
+ assertThat(out.getChildren()).containsExactly(query(in.getChild(0)), in.getChild(1)).inOrder();
}
@Test
@@ -275,29 +237,25 @@
return new AndChangeSource(Arrays.asList(preds));
}
- private Predicate<ChangeData> rewrite(Predicate<ChangeData> in)
- throws QueryParseException {
+ private Predicate<ChangeData> rewrite(Predicate<ChangeData> in) throws QueryParseException {
return rewrite.rewrite(in, options(0, DEFAULT_MAX_QUERY_LIMIT));
}
- private Predicate<ChangeData> rewrite(Predicate<ChangeData> in,
- QueryOptions opts) throws QueryParseException {
+ private Predicate<ChangeData> rewrite(Predicate<ChangeData> in, QueryOptions opts)
+ throws QueryParseException {
return rewrite.rewrite(in, opts);
}
- private IndexedChangeQuery query(Predicate<ChangeData> p)
- throws QueryParseException {
+ private IndexedChangeQuery query(Predicate<ChangeData> p) throws QueryParseException {
return query(p, DEFAULT_MAX_QUERY_LIMIT);
}
- private IndexedChangeQuery query(Predicate<ChangeData> p, int limit)
- throws QueryParseException {
+ private IndexedChangeQuery query(Predicate<ChangeData> p, int limit) throws QueryParseException {
return new IndexedChangeQuery(index, p, options(0, limit));
}
private static QueryOptions options(int start, int limit) {
- return IndexedChangeQuery.createOptions(CONFIG, start, limit,
- ImmutableSet.<String> of());
+ return IndexedChangeQuery.createOptions(CONFIG, start, limit, ImmutableSet.<String>of());
}
private Set<Change.Status> status(String query) throws QueryParseException {
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/index/change/FakeChangeIndex.java b/gerrit-server/src/test/java/com/google/gerrit/server/index/change/FakeChangeIndex.java
index 43039f8..8189c81 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/index/change/FakeChangeIndex.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/index/change/FakeChangeIndex.java
@@ -25,20 +25,15 @@
import com.google.gerrit.server.query.change.ChangeDataSource;
import com.google.gwtorm.server.OrmException;
import com.google.gwtorm.server.ResultSet;
-
import org.junit.Ignore;
@Ignore
public class FakeChangeIndex implements ChangeIndex {
- static Schema<ChangeData> V1 = new Schema<>(1,
- ImmutableList.<FieldDef<ChangeData, ?>> of(
- ChangeField.STATUS));
+ static Schema<ChangeData> V1 =
+ new Schema<>(1, ImmutableList.<FieldDef<ChangeData, ?>>of(ChangeField.STATUS));
- static Schema<ChangeData> V2 = new Schema<>(2,
- ImmutableList.of(
- ChangeField.STATUS,
- ChangeField.PATH,
- ChangeField.UPDATED));
+ static Schema<ChangeData> V2 =
+ new Schema<>(2, ImmutableList.of(ChangeField.STATUS, ChangeField.PATH, ChangeField.UPDATED));
private static class Source implements ChangeDataSource {
private final Predicate<ChangeData> p;
@@ -101,8 +96,7 @@
}
@Override
- public void close() {
- }
+ public void close() {}
@Override
public void markReady(boolean ready) {
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/index/change/FakeQueryBuilder.java b/gerrit-server/src/test/java/com/google/gerrit/server/index/change/FakeQueryBuilder.java
index e59067a..3652ec7 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/index/change/FakeQueryBuilder.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/index/change/FakeQueryBuilder.java
@@ -18,19 +18,17 @@
import com.google.gerrit.server.query.Predicate;
import com.google.gerrit.server.query.change.ChangeData;
import com.google.gerrit.server.query.change.ChangeQueryBuilder;
-
import org.junit.Ignore;
@Ignore
public class FakeQueryBuilder extends ChangeQueryBuilder {
FakeQueryBuilder(ChangeIndexCollection indexes) {
super(
- new FakeQueryBuilder.Definition<>(
- FakeQueryBuilder.class),
- new ChangeQueryBuilder.Arguments(null, null, null, null, null, null,
- null, null, null, null, null, null, null, null, null, null, null,
- null, null, null, null, indexes, null, null, null, null, null, null,
- null, null));
+ new FakeQueryBuilder.Definition<>(FakeQueryBuilder.class),
+ new ChangeQueryBuilder.Arguments(
+ null, null, null, null, null, null, null, null, null, null, null, null, null, null,
+ null, null, null, null, null, null, null, indexes, null, null, null, null, null, null,
+ null, null));
}
@Operator
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/index/change/StalenessCheckerTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/index/change/StalenessCheckerTest.java
index adfd1fe..4eef629 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/index/change/StalenessCheckerTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/index/change/StalenessCheckerTest.java
@@ -35,15 +35,13 @@
import com.google.gerrit.testutil.InMemoryRepositoryManager;
import com.google.gwtorm.protobuf.CodecFactory;
import com.google.gwtorm.protobuf.ProtobufCodec;
-
+import java.util.stream.Stream;
import org.eclipse.jgit.junit.TestRepository;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Repository;
import org.junit.Before;
import org.junit.Test;
-import java.util.stream.Stream;
-
public class StalenessCheckerTest extends GerritBaseTests {
private static final String SHA1 = "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef";
private static final String SHA2 = "badc0feebadc0feebadc0feebadc0feebadc0fee";
@@ -53,8 +51,7 @@
private static final Change.Id C = new Change.Id(1234);
- private static final ProtobufCodec<Change> CHANGE_CODEC =
- CodecFactory.encoder(Change.class);
+ private static final ProtobufCodec<Change> CHANGE_CODEC = CodecFactory.encoder(Change.class);
private GitRepositoryManager repoManager;
private Repository r1;
@@ -105,15 +102,11 @@
public void refStateToByteArray() {
assertThat(
new String(
- RefState.create("refs/heads/foo", ObjectId.fromString(SHA1))
- .toByteArray(P1),
+ RefState.create("refs/heads/foo", ObjectId.fromString(SHA1)).toByteArray(P1),
UTF_8))
.isEqualTo(P1 + ":refs/heads/foo:" + SHA1);
assertThat(
- new String(
- RefState.create("refs/heads/foo", (ObjectId) null)
- .toByteArray(P1),
- UTF_8))
+ new String(RefState.create("refs/heads/foo", (ObjectId) null).toByteArray(P1), UTF_8))
.isEqualTo(P1 + ":refs/heads/foo:" + ObjectId.zeroId().name());
}
@@ -146,8 +139,7 @@
p = r.get(P2).get(0);
assertThat(p.pattern()).isEqualTo("refs/heads/foo/*/bar");
assertThat(p.prefix()).isEqualTo("refs/heads/foo/");
- assertThat(p.regex().pattern())
- .isEqualTo("^\\Qrefs/heads/foo/\\E.*\\Q/bar\\E$");
+ assertThat(p.regex().pattern()).isEqualTo("^\\Qrefs/heads/foo/\\E.*\\Q/bar\\E$");
assertThat(p.match("refs/heads/foo//bar")).isTrue();
assertThat(p.match("refs/heads/foo/x/bar")).isTrue();
assertThat(p.match("refs/heads/foo/x/y/bar")).isTrue();
@@ -156,8 +148,7 @@
p = r.get(P2).get(1);
assertThat(p.pattern()).isEqualTo("refs/heads/foo/*-baz/*/quux");
assertThat(p.prefix()).isEqualTo("refs/heads/foo/");
- assertThat(p.regex().pattern())
- .isEqualTo("^\\Qrefs/heads/foo/\\E.*\\Q-baz/\\E.*\\Q/quux\\E$");
+ assertThat(p.regex().pattern()).isEqualTo("^\\Qrefs/heads/foo/\\E.*\\Q-baz/\\E.*\\Q/quux\\E$");
assertThat(p.match("refs/heads/foo/-baz//quux")).isTrue();
assertThat(p.match("refs/heads/foo/x-baz/x/quux")).isTrue();
assertThat(p.match("refs/heads/foo/x/y-baz/x/y/quux")).isTrue();
@@ -166,8 +157,7 @@
@Test
public void refStatePatternToByteArray() {
- assertThat(
- new String(RefStatePattern.create("refs/*").toByteArray(P1), UTF_8))
+ assertThat(new String(RefStatePattern.create("refs/*").toByteArray(P1), UTF_8))
.isEqualTo(P1 + ":refs/*");
}
@@ -190,7 +180,8 @@
// Not stale.
assertThat(
refsAreStale(
- repoManager, C,
+ repoManager,
+ C,
ImmutableSetMultimap.of(
P1, RefState.create(ref1, id1.name()),
P2, RefState.create(ref2, id2.name())),
@@ -200,7 +191,8 @@
// Wrong ref value.
assertThat(
refsAreStale(
- repoManager, C,
+ repoManager,
+ C,
ImmutableSetMultimap.of(
P1, RefState.create(ref1, SHA1),
P2, RefState.create(ref2, id2.name())),
@@ -210,7 +202,8 @@
// Swapped repos.
assertThat(
refsAreStale(
- repoManager, C,
+ repoManager,
+ C,
ImmutableSetMultimap.of(
P1, RefState.create(ref1, id2.name()),
P2, RefState.create(ref2, id1.name())),
@@ -223,7 +216,8 @@
tr1.update(ref3, id3);
assertThat(
refsAreStale(
- repoManager, C,
+ repoManager,
+ C,
ImmutableSetMultimap.of(
P1, RefState.create(ref1, id1.name()),
P1, RefState.create(ref3, id3.name())),
@@ -233,16 +227,17 @@
// Ignore ref not mentioned.
assertThat(
refsAreStale(
- repoManager, C,
- ImmutableSetMultimap.of(
- P1, RefState.create(ref1, id1.name())),
+ repoManager,
+ C,
+ ImmutableSetMultimap.of(P1, RefState.create(ref1, id1.name())),
ImmutableListMultimap.of()))
.isFalse();
// One ref wrong.
assertThat(
refsAreStale(
- repoManager, C,
+ repoManager,
+ C,
ImmutableSetMultimap.of(
P1, RefState.create(ref1, id1.name()),
P1, RefState.create(ref3, SHA1)),
@@ -258,11 +253,10 @@
// ref1 is only ref matching pattern.
assertThat(
refsAreStale(
- repoManager, C,
- ImmutableSetMultimap.of(
- P1, RefState.create(ref1, id1.name())),
- ImmutableListMultimap.of(
- P1, RefStatePattern.create("refs/heads/*"))))
+ repoManager,
+ C,
+ ImmutableSetMultimap.of(P1, RefState.create(ref1, id1.name())),
+ ImmutableListMultimap.of(P1, RefStatePattern.create("refs/heads/*"))))
.isFalse();
// Now ref2 matches pattern, so stale unless ref2 is present in state map.
@@ -270,20 +264,19 @@
ObjectId id2 = tr1.update(ref2, tr1.commit().message("commit 2"));
assertThat(
refsAreStale(
- repoManager, C,
- ImmutableSetMultimap.of(
- P1, RefState.create(ref1, id1.name())),
- ImmutableListMultimap.of(
- P1, RefStatePattern.create("refs/heads/*"))))
+ repoManager,
+ C,
+ ImmutableSetMultimap.of(P1, RefState.create(ref1, id1.name())),
+ ImmutableListMultimap.of(P1, RefStatePattern.create("refs/heads/*"))))
.isTrue();
assertThat(
refsAreStale(
- repoManager, C,
+ repoManager,
+ C,
ImmutableSetMultimap.of(
P1, RefState.create(ref1, id1.name()),
P1, RefState.create(ref2, id2.name())),
- ImmutableListMultimap.of(
- P1, RefStatePattern.create("refs/heads/*"))))
+ ImmutableListMultimap.of(P1, RefStatePattern.create("refs/heads/*"))))
.isFalse();
}
@@ -296,11 +289,10 @@
// ref1 is only ref matching pattern.
assertThat(
refsAreStale(
- repoManager, C,
- ImmutableSetMultimap.of(
- P1, RefState.create(ref1, id1.name())),
- ImmutableListMultimap.of(
- P1, RefStatePattern.create("refs/*/foo"))))
+ repoManager,
+ C,
+ ImmutableSetMultimap.of(P1, RefState.create(ref1, id1.name())),
+ ImmutableListMultimap.of(P1, RefStatePattern.create("refs/*/foo"))))
.isFalse();
// Now ref2 matches pattern, so stale unless ref2 is present in state map.
@@ -308,20 +300,19 @@
ObjectId id3 = tr1.update(ref3, tr1.commit().message("commit 3"));
assertThat(
refsAreStale(
- repoManager, C,
- ImmutableSetMultimap.of(
- P1, RefState.create(ref1, id1.name())),
- ImmutableListMultimap.of(
- P1, RefStatePattern.create("refs/*/foo"))))
+ repoManager,
+ C,
+ ImmutableSetMultimap.of(P1, RefState.create(ref1, id1.name())),
+ ImmutableListMultimap.of(P1, RefStatePattern.create("refs/*/foo"))))
.isTrue();
assertThat(
refsAreStale(
- repoManager, C,
+ repoManager,
+ C,
ImmutableSetMultimap.of(
P1, RefState.create(ref1, id1.name()),
P1, RefState.create(ref3, id3.name())),
- ImmutableListMultimap.of(
- P1, RefStatePattern.create("refs/*/foo"))))
+ ImmutableListMultimap.of(P1, RefStatePattern.create("refs/*/foo"))))
.isFalse();
}
@@ -330,30 +321,22 @@
Change indexChange = newChange(P1, new Account.Id(1));
indexChange.setNoteDbState(SHA1);
- assertThat(StalenessChecker.reviewDbChangeIsStale(indexChange, null))
- .isFalse();
+ assertThat(StalenessChecker.reviewDbChangeIsStale(indexChange, null)).isFalse();
Change noteDbPrimary = clone(indexChange);
noteDbPrimary.setNoteDbState(NoteDbChangeState.NOTE_DB_PRIMARY_STATE);
- assertThat(
- StalenessChecker.reviewDbChangeIsStale(indexChange, noteDbPrimary))
- .isFalse();
+ assertThat(StalenessChecker.reviewDbChangeIsStale(indexChange, noteDbPrimary)).isFalse();
- assertThat(
- StalenessChecker.reviewDbChangeIsStale(
- indexChange, clone(indexChange)))
- .isFalse();
+ assertThat(StalenessChecker.reviewDbChangeIsStale(indexChange, clone(indexChange))).isFalse();
// Can't easily change row version to check true case.
}
private static Iterable<byte[]> byteArrays(String... strs) {
- return Stream.of(strs).map(s -> s != null ? s.getBytes(UTF_8) : null)
- .collect(toList());
+ return Stream.of(strs).map(s -> s != null ? s.getBytes(UTF_8) : null).collect(toList());
}
private static Change clone(Change change) {
return CHANGE_CODEC.decode(CHANGE_CODEC.encodeToByteArray(change));
}
-
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/ioutil/BasicSerializationTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/ioutil/BasicSerializationTest.java
index f6bdeac..800413b 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/ioutil/BasicSerializationTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/ioutil/BasicSerializationTest.java
@@ -23,12 +23,11 @@
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
-import org.junit.Test;
-
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
+import org.junit.Test;
public class BasicSerializationTest {
@Test
@@ -60,20 +59,17 @@
assertEquals(0L, readFixInt64(r(b(0, 0, 0, 0, 0, 0, 0, 0))));
assertEquals(3L, readFixInt64(r(b(0, 0, 0, 0, 0, 0, 0, 3))));
- assertEquals(0xdeadbeefL, readFixInt64(r(b(0, 0, 0, 0, 0xde, 0xad, 0xbe,
- 0xef))));
+ assertEquals(0xdeadbeefL, readFixInt64(r(b(0, 0, 0, 0, 0xde, 0xad, 0xbe, 0xef))));
- assertEquals(0x0310adefL, readFixInt64(r(b(0, 0, 0, 0, 0x03, 0x10, 0xad,
- 0xef))));
+ assertEquals(0x0310adefL, readFixInt64(r(b(0, 0, 0, 0, 0x03, 0x10, 0xad, 0xef))));
- assertEquals(0xc0ffee78deadbeefL, readFixInt64(r(b(0xc0, 0xff, 0xee, 0x78,
- 0xde, 0xad, 0xbe, 0xef))));
+ assertEquals(
+ 0xc0ffee78deadbeefL, readFixInt64(r(b(0xc0, 0xff, 0xee, 0x78, 0xde, 0xad, 0xbe, 0xef))));
- assertEquals(0x00000000ffffffffL, readFixInt64(r(b(0, 0, 0, 0, 0xff, 0xff,
- 0xff, 0xff))));
+ assertEquals(0x00000000ffffffffL, readFixInt64(r(b(0, 0, 0, 0, 0xff, 0xff, 0xff, 0xff))));
- assertEquals(0xffffffffffffffffL, readFixInt64(r(b(0xff, 0xff, 0xff, 0xff,
- 0xff, 0xff, 0xff, 0xff))));
+ assertEquals(
+ 0xffffffffffffffffL, readFixInt64(r(b(0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff))));
}
@Test
@@ -109,8 +105,7 @@
public void testReadString() throws IOException {
assertNull(readString(r(b(0))));
assertEquals("a", readString(r(b(1, 'a'))));
- assertEquals("coffee4",
- readString(r(b(7, 'c', 'o', 'f', 'f', 'e', 'e', '4'))));
+ assertEquals("coffee4", readString(r(b(7, 'c', 'o', 'f', 'f', 'e', 'e', '4'))));
}
@Test
@@ -134,8 +129,7 @@
assertOutput(b(7, 'c', 'o', 'f', 'f', 'e', 'e', '4'), out);
}
- private static void assertOutput(final byte[] expect,
- final ByteArrayOutputStream out) {
+ private static void assertOutput(final byte[] expect, final ByteArrayOutputStream out) {
final byte[] buf = out.toByteArray();
for (int i = 0; i < expect.length; i++) {
assertEquals(expect[i], buf[i]);
@@ -155,7 +149,9 @@
}
private static byte[] b(int a, int b, int c, int d, int e, int f, int g, int h) {
- return new byte[] {(byte) a, (byte) b, (byte) c, (byte) d, //
- (byte) e, (byte) f, (byte) g, (byte) h,};
+ return new byte[] {
+ (byte) a, (byte) b, (byte) c, (byte) d, //
+ (byte) e, (byte) f, (byte) g, (byte) h,
+ };
}
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/ioutil/ColumnFormatterTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/ioutil/ColumnFormatterTest.java
index 51abe2b..fe642ba 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/ioutil/ColumnFormatterTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/ioutil/ColumnFormatterTest.java
@@ -14,16 +14,15 @@
package com.google.gerrit.server.ioutil;
+import java.io.PrintWriter;
+import java.io.StringWriter;
import org.junit.Assert;
import org.junit.Test;
-import java.io.PrintWriter;
-import java.io.StringWriter;
-
public class ColumnFormatterTest {
/**
- * Holds an in-memory {@link java.io.PrintWriter} object and allows
- * comparisons of its contents to a supplied string via an assert statement.
+ * Holds an in-memory {@link java.io.PrintWriter} object and allows comparisons of its contents to
+ * a supplied string via an assert statement.
*/
static class PrintWriterComparator {
private PrintWriter printWriter;
@@ -44,14 +43,11 @@
}
}
- /**
- * Test that only lines with at least one column of text emit output.
- */
+ /** Test that only lines with at least one column of text emit output. */
@Test
public void emptyLine() {
final PrintWriterComparator comparator = new PrintWriterComparator();
- final ColumnFormatter formatter =
- new ColumnFormatter(comparator.getPrintWriter(), '\t');
+ final ColumnFormatter formatter = new ColumnFormatter(comparator.getPrintWriter(), '\t');
formatter.addColumn("foo");
formatter.addColumn("bar");
formatter.nextLine();
@@ -63,14 +59,11 @@
comparator.assertEquals("foo\tbar\nfoo\tbar\n");
}
- /**
- * Test that there is no output if no columns are ever added.
- */
+ /** Test that there is no output if no columns are ever added. */
@Test
public void emptyOutput() {
final PrintWriterComparator comparator = new PrintWriterComparator();
- final ColumnFormatter formatter =
- new ColumnFormatter(comparator.getPrintWriter(), '\t');
+ final ColumnFormatter formatter = new ColumnFormatter(comparator.getPrintWriter(), '\t');
formatter.nextLine();
formatter.nextLine();
formatter.finish();
@@ -78,44 +71,40 @@
}
/**
- * Test that there is no output (nor any exceptions) if we finalize
- * the output immediately after the creation of the {@link ColumnFormatter}.
+ * Test that there is no output (nor any exceptions) if we finalize the output immediately after
+ * the creation of the {@link ColumnFormatter}.
*/
@Test
public void noNextLine() {
final PrintWriterComparator comparator = new PrintWriterComparator();
- final ColumnFormatter formatter =
- new ColumnFormatter(comparator.getPrintWriter(), '\t');
+ final ColumnFormatter formatter = new ColumnFormatter(comparator.getPrintWriter(), '\t');
formatter.finish();
comparator.assertEquals("");
}
/**
- * Test that the text in added columns is escaped while the column separator
- * (which of course shouldn't be escaped) is left alone.
+ * Test that the text in added columns is escaped while the column separator (which of course
+ * shouldn't be escaped) is left alone.
*/
@Test
public void escapingTakesPlace() {
final PrintWriterComparator comparator = new PrintWriterComparator();
- final ColumnFormatter formatter =
- new ColumnFormatter(comparator.getPrintWriter(), '\t');
+ final ColumnFormatter formatter = new ColumnFormatter(comparator.getPrintWriter(), '\t');
formatter.addColumn("foo");
- formatter.addColumn(
- "\tan indented multi-line\ntext");
+ formatter.addColumn("\tan indented multi-line\ntext");
formatter.nextLine();
formatter.finish();
comparator.assertEquals("foo\t\\tan indented multi-line\\ntext\n");
}
/**
- * Test that we get the correct output with multi-line input where the number
- * of columns in each line varies.
+ * Test that we get the correct output with multi-line input where the number of columns in each
+ * line varies.
*/
@Test
public void multiLineDifferentColumnCount() {
final PrintWriterComparator comparator = new PrintWriterComparator();
- final ColumnFormatter formatter =
- new ColumnFormatter(comparator.getPrintWriter(), '\t');
+ final ColumnFormatter formatter = new ColumnFormatter(comparator.getPrintWriter(), '\t');
formatter.addColumn("foo");
formatter.addColumn("bar");
formatter.addColumn("baz");
@@ -127,14 +116,11 @@
comparator.assertEquals("foo\tbar\tbaz\nfoo\tbar\n");
}
- /**
- * Test that we get the correct output with a single column of input.
- */
+ /** Test that we get the correct output with a single column of input. */
@Test
public void oneColumn() {
final PrintWriterComparator comparator = new PrintWriterComparator();
- final ColumnFormatter formatter =
- new ColumnFormatter(comparator.getPrintWriter(), '\t');
+ final ColumnFormatter formatter = new ColumnFormatter(comparator.getPrintWriter(), '\t');
formatter.addColumn("foo");
formatter.nextLine();
formatter.finish();
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/mail/AddressTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/mail/AddressTest.java
index 6d33f50..2909df7 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/mail/AddressTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/mail/AddressTest.java
@@ -18,7 +18,6 @@
import static org.junit.Assert.fail;
import com.google.gerrit.testutil.GerritBaseTests;
-
import org.junit.Test;
public class AddressTest extends GerritBaseTests {
@@ -133,14 +132,13 @@
@Test
public void toHeaderString_NameEmail6() {
- assertThat(format("A \u20ac B", "a@a"))
- .isEqualTo("=?UTF-8?Q?A_=E2=82=AC_B?= <a@a>");
+ assertThat(format("A \u20ac B", "a@a")).isEqualTo("=?UTF-8?Q?A_=E2=82=AC_B?= <a@a>");
}
@Test
public void toHeaderString_NameEmail7() {
assertThat(format("A \u20ac B (Code Review)", "a@a"))
- .isEqualTo("=?UTF-8?Q?A_=E2=82=AC_B_=28Code_Review=29?= <a@a>");
+ .isEqualTo("=?UTF-8?Q?A_=E2=82=AC_B_=28Code_Review=29?= <a@a>");
}
@Test
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/mail/ValidatorTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/mail/ValidatorTest.java
index 4d7bf08..0620b24 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/mail/ValidatorTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/mail/ValidatorTest.java
@@ -18,12 +18,10 @@
import static com.google.common.truth.Truth.assert_;
import com.google.gerrit.server.mail.send.OutgoingEmailValidator;
-
-import org.junit.Test;
-
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
+import org.junit.Test;
public class ValidatorTest {
private static final String UNSUPPORTED_PREFIX = "#! ";
@@ -35,8 +33,7 @@
@Test
public void validateTopLevelDomains() throws Exception {
- try (InputStream in =
- this.getClass().getResourceAsStream("tlds-alpha-by-domain.txt")) {
+ try (InputStream in = this.getClass().getResourceAsStream("tlds-alpha-by-domain.txt")) {
if (in == null) {
throw new Exception("TLD list not found");
}
@@ -48,18 +45,17 @@
continue;
}
if (tld.startsWith(UNSUPPORTED_PREFIX)) {
- String test = "test@example."
- + tld.toLowerCase().substring(UNSUPPORTED_PREFIX.length());
+ String test = "test@example." + tld.toLowerCase().substring(UNSUPPORTED_PREFIX.length());
assert_()
- .withFailureMessage("expected invalid TLD \"" + test + "\"")
- .that(OutgoingEmailValidator.isValid(test))
- .isFalse();
+ .withFailureMessage("expected invalid TLD \"" + test + "\"")
+ .that(OutgoingEmailValidator.isValid(test))
+ .isFalse();
} else {
String test = "test@example." + tld.toLowerCase();
assert_()
- .withFailureMessage("failed to validate TLD \"" + test + "\"")
- .that(OutgoingEmailValidator.isValid(test))
- .isTrue();
+ .withFailureMessage("failed to validate TLD \"" + test + "\"")
+ .that(OutgoingEmailValidator.isValid(test))
+ .isTrue();
}
}
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/AbstractParserTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/AbstractParserTest.java
index dc1c054..3efae43 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/AbstractParserTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/AbstractParserTest.java
@@ -19,47 +19,48 @@
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.reviewdb.client.Comment;
import com.google.gerrit.server.mail.Address;
-
-import org.joda.time.DateTime;
-import org.junit.Ignore;
-
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
+import org.joda.time.DateTime;
+import org.junit.Ignore;
@Ignore
public class AbstractParserTest {
- protected static final String changeURL =
- "https://gerrit-review.googlesource.com/#/changes/123";
+ protected static final String changeURL = "https://gerrit-review.googlesource.com/#/changes/123";
- protected static void assertChangeMessage(String message,
- MailComment comment) {
+ protected static void assertChangeMessage(String message, MailComment comment) {
assertThat(comment.fileName).isNull();
assertThat(comment.message).isEqualTo(message);
assertThat(comment.inReplyTo).isNull();
assertThat(comment.type).isEqualTo(MailComment.CommentType.CHANGE_MESSAGE);
}
- protected static void assertInlineComment(String message, MailComment comment,
- Comment inReplyTo) {
+ protected static void assertInlineComment(
+ String message, MailComment comment, Comment inReplyTo) {
assertThat(comment.fileName).isNull();
assertThat(comment.message).isEqualTo(message);
assertThat(comment.inReplyTo).isEqualTo(inReplyTo);
assertThat(comment.type).isEqualTo(MailComment.CommentType.INLINE_COMMENT);
}
- protected static void assertFileComment(String message, MailComment comment,
- String file) {
+ protected static void assertFileComment(String message, MailComment comment, String file) {
assertThat(comment.fileName).isEqualTo(file);
assertThat(comment.message).isEqualTo(message);
assertThat(comment.inReplyTo).isNull();
assertThat(comment.type).isEqualTo(MailComment.CommentType.FILE_COMMENT);
}
- protected static Comment newComment(String uuid, String file,
- String message, int line) {
- Comment c = new Comment(new Comment.Key(uuid, file, 1),
- new Account.Id(0), new Timestamp(0L), (short) 0, message, "", false);
+ protected static Comment newComment(String uuid, String file, String message, int line) {
+ Comment c =
+ new Comment(
+ new Comment.Key(uuid, file, 1),
+ new Account.Id(0),
+ new Timestamp(0L),
+ (short) 0,
+ message,
+ "",
+ false);
c.lineNbr = line;
return c;
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/GenericHtmlParserTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/GenericHtmlParserTest.java
index 7eadf01..faf7451 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/GenericHtmlParserTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/GenericHtmlParserTest.java
@@ -17,71 +17,96 @@
/** Test parser for a generic Html email client response */
public class GenericHtmlParserTest extends HtmlParserTest {
@Override
- protected String newHtmlBody(String changeMessage, String c1,
- String c2, String c3, String f1, String f2, String fc1) {
- String email = "" +
- "<div dir=\"ltr\">" + (changeMessage != null ? changeMessage : "") +
- "<div class=\"extra\"><br><div class=\"quote\">" +
- "On Fri, Nov 18, 2016 at 11:15 AM, foobar (Gerrit) noreply@gerrit.com" +
- "<span dir=\"ltr\"><<a href=\"mailto:noreply@gerrit.com\" " +
- "target=\"_blank\">noreply@gerrit.com</a>></span> wrote:<br>" +
- "<blockquote class=\"quote\" " +
- "<p>foobar <strong>posted comments</strong> on this change.</p>" +
- "<p><a href=\"" + changeURL + "/1\" " +
- "target=\"_blank\">View Change</a></p><div>Patch Set 2: CR-1\n" +
- "\n" +
- "(3 comments)</div><ul><li>" +
- "<p>" + // File #1: test.txt
- "<a href=\"" + changeURL + "/1/gerrit-server/test.txt\">" +
- "File gerrit-server/<wbr>test.txt:</a></p>" +
- commentBlock(f1) +
- "<li><p>" +
- "<a href=\"" + changeURL + "/1/gerrit-server/test.txt\">" +
- "Patch Set #2:</a> </p>" +
- "<blockquote><pre>Some inline comment from Gerrit</pre>" +
- "</blockquote><p>Some comment on file 1</p>" +
- "</li>" +
- commentBlock(fc1) +
- "<li><p>" +
- "<a href=\"" + changeURL + "/1/gerrit-server/test.txt@2\">" +
- "Patch Set #2, Line 31:</a> </p>" +
- "<blockquote><pre>Some inline comment from Gerrit</pre>" +
- "</blockquote><p>Some text from original comment</p>" +
- "</li>" +
- commentBlock(c1) +
- "" + // Inline comment #2
- "<li><p>" +
- "<a href=\"" + changeURL + "/1/gerrit-server/test.txt@3\">" +
- "Patch Set #2, Line 47:</a> </p>" +
- "<blockquote><pre>Some comment posted on Gerrit</pre>" +
- "</blockquote><p>Some more comments from Gerrit</p>" +
- "</li>" +
- commentBlock(c2) +
- "<li><p>" +
- "<a href=\"" + changeURL + "/1/gerrit-server/test.txt@115\">" +
- "Patch Set #2, Line 115:</a> <code>some code</code></p>" +
- "<p>some comment</p></li></ul></li>" +
- "" +
- "<li><p>" + // File #2: test.txt
- "<a href=\"" + changeURL + "/1/gerrit-server/readme.txt\">" +
- "File gerrit-server/<wbr>readme.txt:</a></p>" +
- commentBlock(f2) +
- "<li><p>" +
- "<a href=\"" + changeURL + "/1/gerrit-server/readme.txt@3\">" +
- "Patch Set #2, Line 31:</a> </p>" +
- "<blockquote><pre>Some inline comment from Gerrit</pre>" +
- "</blockquote><p>Some text from original comment</p>" +
- "</li>" +
- commentBlock(c3) +
- "" + // Inline comment #2
- "</ul></li></ul>" +
- "" + // Footer
- "<p>To view, visit <a href=\"" + changeURL + "/1\">this change</a>. " +
- "To unsubscribe, visit <a href=\"https://someurl\">settings</a>." +
- "</p><p>Gerrit-MessageType: comment<br>" +
- "Footer omitted</p>" +
- "<div><div></div></div>" +
- "<p>Gerrit-HasComments: Yes</p></blockquote></div><br></div></div>";
+ protected String newHtmlBody(
+ String changeMessage, String c1, String c2, String c3, String f1, String f2, String fc1) {
+ String email =
+ ""
+ + "<div dir=\"ltr\">"
+ + (changeMessage != null ? changeMessage : "")
+ + "<div class=\"extra\"><br><div class=\"quote\">"
+ + "On Fri, Nov 18, 2016 at 11:15 AM, foobar (Gerrit) noreply@gerrit.com"
+ + "<span dir=\"ltr\"><<a href=\"mailto:noreply@gerrit.com\" "
+ + "target=\"_blank\">noreply@gerrit.com</a>></span> wrote:<br>"
+ + "<blockquote class=\"quote\" "
+ + "<p>foobar <strong>posted comments</strong> on this change.</p>"
+ + "<p><a href=\""
+ + changeURL
+ + "/1\" "
+ + "target=\"_blank\">View Change</a></p><div>Patch Set 2: CR-1\n"
+ + "\n"
+ + "(3 comments)</div><ul><li>"
+ + "<p>"
+ + // File #1: test.txt
+ "<a href=\""
+ + changeURL
+ + "/1/gerrit-server/test.txt\">"
+ + "File gerrit-server/<wbr>test.txt:</a></p>"
+ + commentBlock(f1)
+ + "<li><p>"
+ + "<a href=\""
+ + changeURL
+ + "/1/gerrit-server/test.txt\">"
+ + "Patch Set #2:</a> </p>"
+ + "<blockquote><pre>Some inline comment from Gerrit</pre>"
+ + "</blockquote><p>Some comment on file 1</p>"
+ + "</li>"
+ + commentBlock(fc1)
+ + "<li><p>"
+ + "<a href=\""
+ + changeURL
+ + "/1/gerrit-server/test.txt@2\">"
+ + "Patch Set #2, Line 31:</a> </p>"
+ + "<blockquote><pre>Some inline comment from Gerrit</pre>"
+ + "</blockquote><p>Some text from original comment</p>"
+ + "</li>"
+ + commentBlock(c1)
+ + ""
+ + // Inline comment #2
+ "<li><p>"
+ + "<a href=\""
+ + changeURL
+ + "/1/gerrit-server/test.txt@3\">"
+ + "Patch Set #2, Line 47:</a> </p>"
+ + "<blockquote><pre>Some comment posted on Gerrit</pre>"
+ + "</blockquote><p>Some more comments from Gerrit</p>"
+ + "</li>"
+ + commentBlock(c2)
+ + "<li><p>"
+ + "<a href=\""
+ + changeURL
+ + "/1/gerrit-server/test.txt@115\">"
+ + "Patch Set #2, Line 115:</a> <code>some code</code></p>"
+ + "<p>some comment</p></li></ul></li>"
+ + ""
+ + "<li><p>"
+ + // File #2: test.txt
+ "<a href=\""
+ + changeURL
+ + "/1/gerrit-server/readme.txt\">"
+ + "File gerrit-server/<wbr>readme.txt:</a></p>"
+ + commentBlock(f2)
+ + "<li><p>"
+ + "<a href=\""
+ + changeURL
+ + "/1/gerrit-server/readme.txt@3\">"
+ + "Patch Set #2, Line 31:</a> </p>"
+ + "<blockquote><pre>Some inline comment from Gerrit</pre>"
+ + "</blockquote><p>Some text from original comment</p>"
+ + "</li>"
+ + commentBlock(c3)
+ + ""
+ + // Inline comment #2
+ "</ul></li></ul>"
+ + ""
+ + // Footer
+ "<p>To view, visit <a href=\""
+ + changeURL
+ + "/1\">this change</a>. "
+ + "To unsubscribe, visit <a href=\"https://someurl\">settings</a>."
+ + "</p><p>Gerrit-MessageType: comment<br>"
+ + "Footer omitted</p>"
+ + "<div><div></div></div>"
+ + "<p>Gerrit-HasComments: Yes</p></blockquote></div><br></div></div>";
return email;
}
@@ -89,7 +114,8 @@
if (comment == null) {
return "";
}
- return "</ul></li></ul></blockquote><div>" + comment +
- "</div><blockquote class=\"quote\"><ul><li><ul>";
+ return "</ul></li></ul></blockquote><div>"
+ + comment
+ + "</div><blockquote class=\"quote\"><ul><li><ul>";
}
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/GmailHtmlParserTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/GmailHtmlParserTest.java
index 7000e46..d253af5 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/GmailHtmlParserTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/GmailHtmlParserTest.java
@@ -16,71 +16,96 @@
public class GmailHtmlParserTest extends HtmlParserTest {
@Override
- protected String newHtmlBody(String changeMessage, String c1,
- String c2, String c3, String f1, String f2, String fc1) {
- String email = "" +
- "<div dir=\"ltr\">" + (changeMessage != null ? changeMessage : "") +
- "<div class=\"gmail_extra\"><br><div class=\"gmail_quote\">" +
- "On Fri, Nov 18, 2016 at 11:15 AM, foobar (Gerrit) noreply@gerrit.com" +
- "<span dir=\"ltr\"><<a href=\"mailto:noreply@gerrit.com\" " +
- "target=\"_blank\">noreply@gerrit.com</a>></span> wrote:<br>" +
- "<blockquote class=\"gmail_quote\" " +
- "<p>foobar <strong>posted comments</strong> on this change.</p>" +
- "<p><a href=\"" + changeURL + "/1\" " +
- "target=\"_blank\">View Change</a></p><div>Patch Set 2: CR-1\n" +
- "\n" +
- "(3 comments)</div><ul><li>" +
- "<p>" + // File #1: test.txt
- "<a href=\"" + changeURL + "/1/gerrit-server/test.txt\">" +
- "File gerrit-server/<wbr>test.txt:</a></p>" +
- commentBlock(f1) +
- "<li><p>" +
- "<a href=\"" + changeURL + "/1/gerrit-server/test.txt\">" +
- "Patch Set #2:</a> </p>" +
- "<blockquote><pre>Some inline comment from Gerrit</pre>" +
- "</blockquote><p>Some comment on file 1</p>" +
- "</li>" +
- commentBlock(fc1) +
- "<li><p>" +
- "<a href=\"" + changeURL + "/1/gerrit-server/test.txt@2\">" +
- "Patch Set #2, Line 31:</a> </p>" +
- "<blockquote><pre>Some inline comment from Gerrit</pre>" +
- "</blockquote><p>Some text from original comment</p>" +
- "</li>" +
- commentBlock(c1) +
- "" + // Inline comment #2
- "<li><p>" +
- "<a href=\"" + changeURL + "/1/gerrit-server/test.txt@3\">" +
- "Patch Set #2, Line 47:</a> </p>" +
- "<blockquote><pre>Some comment posted on Gerrit</pre>" +
- "</blockquote><p>Some more comments from Gerrit</p>" +
- "</li>" +
- commentBlock(c2) +
- "<li><p>" +
- "<a href=\"" + changeURL + "/1/gerrit-server/test.txt@115\">" +
- "Patch Set #2, Line 115:</a> <code>some code</code></p>" +
- "<p>some comment</p></li></ul></li>" +
- "" +
- "<li><p>" + // File #2: test.txt
- "<a href=\"" + changeURL + "/1/gerrit-server/readme.txt\">" +
- "File gerrit-server/<wbr>readme.txt:</a></p>" +
- commentBlock(f2) +
- "<li><p>" +
- "<a href=\"" + changeURL + "/1/gerrit-server/readme.txt@3\">" +
- "Patch Set #2, Line 31:</a> </p>" +
- "<blockquote><pre>Some inline comment from Gerrit</pre>" +
- "</blockquote><p>Some text from original comment</p>" +
- "</li>" +
- commentBlock(c3) +
- "" + // Inline comment #2
- "</ul></li></ul>" +
- "" + // Footer
- "<p>To view, visit <a href=\"" + changeURL + "/1\">this change</a>. " +
- "To unsubscribe, visit <a href=\"https://someurl\">settings</a>." +
- "</p><p>Gerrit-MessageType: comment<br>" +
- "Footer omitted</p>" +
- "<div><div></div></div>" +
- "<p>Gerrit-HasComments: Yes</p></blockquote></div><br></div></div>";
+ protected String newHtmlBody(
+ String changeMessage, String c1, String c2, String c3, String f1, String f2, String fc1) {
+ String email =
+ ""
+ + "<div dir=\"ltr\">"
+ + (changeMessage != null ? changeMessage : "")
+ + "<div class=\"gmail_extra\"><br><div class=\"gmail_quote\">"
+ + "On Fri, Nov 18, 2016 at 11:15 AM, foobar (Gerrit) noreply@gerrit.com"
+ + "<span dir=\"ltr\"><<a href=\"mailto:noreply@gerrit.com\" "
+ + "target=\"_blank\">noreply@gerrit.com</a>></span> wrote:<br>"
+ + "<blockquote class=\"gmail_quote\" "
+ + "<p>foobar <strong>posted comments</strong> on this change.</p>"
+ + "<p><a href=\""
+ + changeURL
+ + "/1\" "
+ + "target=\"_blank\">View Change</a></p><div>Patch Set 2: CR-1\n"
+ + "\n"
+ + "(3 comments)</div><ul><li>"
+ + "<p>"
+ + // File #1: test.txt
+ "<a href=\""
+ + changeURL
+ + "/1/gerrit-server/test.txt\">"
+ + "File gerrit-server/<wbr>test.txt:</a></p>"
+ + commentBlock(f1)
+ + "<li><p>"
+ + "<a href=\""
+ + changeURL
+ + "/1/gerrit-server/test.txt\">"
+ + "Patch Set #2:</a> </p>"
+ + "<blockquote><pre>Some inline comment from Gerrit</pre>"
+ + "</blockquote><p>Some comment on file 1</p>"
+ + "</li>"
+ + commentBlock(fc1)
+ + "<li><p>"
+ + "<a href=\""
+ + changeURL
+ + "/1/gerrit-server/test.txt@2\">"
+ + "Patch Set #2, Line 31:</a> </p>"
+ + "<blockquote><pre>Some inline comment from Gerrit</pre>"
+ + "</blockquote><p>Some text from original comment</p>"
+ + "</li>"
+ + commentBlock(c1)
+ + ""
+ + // Inline comment #2
+ "<li><p>"
+ + "<a href=\""
+ + changeURL
+ + "/1/gerrit-server/test.txt@3\">"
+ + "Patch Set #2, Line 47:</a> </p>"
+ + "<blockquote><pre>Some comment posted on Gerrit</pre>"
+ + "</blockquote><p>Some more comments from Gerrit</p>"
+ + "</li>"
+ + commentBlock(c2)
+ + "<li><p>"
+ + "<a href=\""
+ + changeURL
+ + "/1/gerrit-server/test.txt@115\">"
+ + "Patch Set #2, Line 115:</a> <code>some code</code></p>"
+ + "<p>some comment</p></li></ul></li>"
+ + ""
+ + "<li><p>"
+ + // File #2: test.txt
+ "<a href=\""
+ + changeURL
+ + "/1/gerrit-server/readme.txt\">"
+ + "File gerrit-server/<wbr>readme.txt:</a></p>"
+ + commentBlock(f2)
+ + "<li><p>"
+ + "<a href=\""
+ + changeURL
+ + "/1/gerrit-server/readme.txt@3\">"
+ + "Patch Set #2, Line 31:</a> </p>"
+ + "<blockquote><pre>Some inline comment from Gerrit</pre>"
+ + "</blockquote><p>Some text from original comment</p>"
+ + "</li>"
+ + commentBlock(c3)
+ + ""
+ + // Inline comment #2
+ "</ul></li></ul>"
+ + ""
+ + // Footer
+ "<p>To view, visit <a href=\""
+ + changeURL
+ + "/1\">this change</a>. "
+ + "To unsubscribe, visit <a href=\"https://someurl\">settings</a>."
+ + "</p><p>Gerrit-MessageType: comment<br>"
+ + "Footer omitted</p>"
+ + "<div><div></div></div>"
+ + "<p>Gerrit-HasComments: Yes</p></blockquote></div><br></div></div>";
return email;
}
@@ -88,7 +113,8 @@
if (comment == null) {
return "";
}
- return "</ul></li></ul></blockquote><div>" + comment +
- "</div><blockquote class=\"gmail_quote\"><ul><li><ul>";
+ return "</ul></li></ul></blockquote><div>"
+ + comment
+ + "</div><blockquote class=\"gmail_quote\"><ul><li><ul>";
}
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/HtmlParserTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/HtmlParserTest.java
index 198e827..7d729bc 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/HtmlParserTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/HtmlParserTest.java
@@ -17,23 +17,19 @@
import static com.google.common.truth.Truth.assertThat;
import com.google.gerrit.reviewdb.client.Comment;
-
+import java.util.List;
import org.junit.Ignore;
import org.junit.Test;
-import java.util.List;
-
@Ignore
public abstract class HtmlParserTest extends AbstractParserTest {
@Test
public void simpleChangeMessage() {
MailMessage.Builder b = newMailMessageBuilder();
- b.htmlContent(newHtmlBody("Looks good to me", null, null,
- null, null, null, null));
+ b.htmlContent(newHtmlBody("Looks good to me", null, null, null, null, null, null));
List<Comment> comments = defaultComments();
- List<MailComment> parsedComments =
- HtmlParser.parse(b.build(), comments, "");
+ List<MailComment> parsedComments = HtmlParser.parse(b.build(), comments, "");
assertThat(parsedComments).hasSize(1);
assertChangeMessage("Looks good to me", parsedComments.get(0));
@@ -42,39 +38,45 @@
@Test
public void simpleInlineComments() {
MailMessage.Builder b = newMailMessageBuilder();
- b.htmlContent(newHtmlBody("Looks good to me",
- "I have a comment on this.", null, "Also have a comment here.",
- null, null, null));
+ b.htmlContent(
+ newHtmlBody(
+ "Looks good to me",
+ "I have a comment on this.",
+ null,
+ "Also have a comment here.",
+ null,
+ null,
+ null));
List<Comment> comments = defaultComments();
- List<MailComment> parsedComments =
- HtmlParser.parse(b.build(), comments, changeURL);
+ List<MailComment> parsedComments = HtmlParser.parse(b.build(), comments, changeURL);
assertThat(parsedComments).hasSize(3);
assertChangeMessage("Looks good to me", parsedComments.get(0));
- assertInlineComment("I have a comment on this.", parsedComments.get(1),
- comments.get(1));
- assertInlineComment("Also have a comment here.", parsedComments.get(2),
- comments.get(3));
+ assertInlineComment("I have a comment on this.", parsedComments.get(1), comments.get(1));
+ assertInlineComment("Also have a comment here.", parsedComments.get(2), comments.get(3));
}
@Test
public void simpleFileComment() {
MailMessage.Builder b = newMailMessageBuilder();
- b.htmlContent(newHtmlBody("Looks good to me",
- null, null, "Also have a comment here.",
- "This is a nice file", null, null));
+ b.htmlContent(
+ newHtmlBody(
+ "Looks good to me",
+ null,
+ null,
+ "Also have a comment here.",
+ "This is a nice file",
+ null,
+ null));
List<Comment> comments = defaultComments();
- List<MailComment> parsedComments =
- HtmlParser.parse(b.build(), comments, changeURL);
+ List<MailComment> parsedComments = HtmlParser.parse(b.build(), comments, changeURL);
assertThat(parsedComments).hasSize(3);
assertChangeMessage("Looks good to me", parsedComments.get(0));
- assertFileComment("This is a nice file", parsedComments.get(1),
- comments.get(1).key.filename);
- assertInlineComment("Also have a comment here.", parsedComments.get(2),
- comments.get(3));
+ assertFileComment("This is a nice file", parsedComments.get(1), comments.get(1).key.filename);
+ assertInlineComment("Also have a comment here.", parsedComments.get(2), comments.get(3));
}
@Test
@@ -83,8 +85,7 @@
b.htmlContent(newHtmlBody(null, null, null, null, null, null, null));
List<Comment> comments = defaultComments();
- List<MailComment> parsedComments =
- HtmlParser.parse(b.build(), comments, changeURL);
+ List<MailComment> parsedComments = HtmlParser.parse(b.build(), comments, changeURL);
assertThat(parsedComments).isEmpty();
}
@@ -92,18 +93,16 @@
@Test
public void noChangeMessage() {
MailMessage.Builder b = newMailMessageBuilder();
- b.htmlContent(newHtmlBody(null, null, null,
- "Also have a comment here.", "This is a nice file", null, null));
+ b.htmlContent(
+ newHtmlBody(
+ null, null, null, "Also have a comment here.", "This is a nice file", null, null));
List<Comment> comments = defaultComments();
- List<MailComment> parsedComments =
- HtmlParser.parse(b.build(), comments, changeURL);
+ List<MailComment> parsedComments = HtmlParser.parse(b.build(), comments, changeURL);
assertThat(parsedComments).hasSize(2);
- assertFileComment("This is a nice file", parsedComments.get(0),
- comments.get(1).key.filename);
- assertInlineComment("Also have a comment here.", parsedComments.get(1),
- comments.get(3));
+ assertFileComment("This is a nice file", parsedComments.get(0), comments.get(1).key.filename);
+ assertInlineComment("Also have a comment here.", parsedComments.get(1), comments.get(3));
}
/**
@@ -118,6 +117,6 @@
* @param fc1 Comment in reply to a comment on file 1.
* @return A string with all inline comments and the original quoted email.
*/
- protected abstract String newHtmlBody(String changeMessage, String c1,
- String c2, String c3, String f1, String f2, String fc1);
+ protected abstract String newHtmlBody(
+ String changeMessage, String c1, String c2, String c3, String f1, String f2, String fc1);
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/MetadataParserTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/MetadataParserTest.java
index 67f3e46..2c60b5d 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/MetadataParserTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/MetadataParserTest.java
@@ -20,7 +20,6 @@
import com.google.gerrit.server.mail.Address;
import com.google.gerrit.server.mail.MetadataName;
-
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.junit.Test;
@@ -35,13 +34,11 @@
b.dateReceived(new DateTime());
b.subject("");
- b.addAdditionalHeader(
- toHeaderWithDelimiter(MetadataName.CHANGE_ID) + "cid");
+ b.addAdditionalHeader(toHeaderWithDelimiter(MetadataName.CHANGE_ID) + "cid");
b.addAdditionalHeader(toHeaderWithDelimiter(MetadataName.PATCH_SET) + "1");
+ b.addAdditionalHeader(toHeaderWithDelimiter(MetadataName.MESSAGE_TYPE) + "comment");
b.addAdditionalHeader(
- toHeaderWithDelimiter(MetadataName.MESSAGE_TYPE) +"comment");
- b.addAdditionalHeader(toHeaderWithDelimiter(MetadataName.TIMESTAMP) +
- "Tue, 25 Oct 2016 02:11:35 -0700");
+ toHeaderWithDelimiter(MetadataName.TIMESTAMP) + "Tue, 25 Oct 2016 02:11:35 -0700");
Address author = new Address("Diffy", "test@gerritcodereview.com");
b.from(author);
@@ -51,8 +48,8 @@
assertThat(meta.changeId).isEqualTo("cid");
assertThat(meta.patchSet).isEqualTo(1);
assertThat(meta.messageType).isEqualTo("comment");
- assertThat(meta.timestamp.getTime()).isEqualTo(
- new DateTime(2016, 10, 25, 9, 11, 35, 0, DateTimeZone.UTC).getMillis());
+ assertThat(meta.timestamp.getTime())
+ .isEqualTo(new DateTime(2016, 10, 25, 9, 11, 35, 0, DateTimeZone.UTC).getMillis());
}
@Test
@@ -65,14 +62,11 @@
b.subject("");
StringBuilder stringBuilder = new StringBuilder();
+ stringBuilder.append(toFooterWithDelimiter(MetadataName.CHANGE_ID) + "cid" + "\n");
+ stringBuilder.append(toFooterWithDelimiter(MetadataName.PATCH_SET) + "1" + "\n");
+ stringBuilder.append(toFooterWithDelimiter(MetadataName.MESSAGE_TYPE) + "comment" + "\n");
stringBuilder.append(
- toFooterWithDelimiter(MetadataName.CHANGE_ID) + "cid" + "\n");
- stringBuilder.append(
- toFooterWithDelimiter(MetadataName.PATCH_SET) + "1" + "\n");
- stringBuilder.append(
- toFooterWithDelimiter(MetadataName.MESSAGE_TYPE) + "comment" + "\n");
- stringBuilder.append(toFooterWithDelimiter(MetadataName.TIMESTAMP) +
- "Tue, 25 Oct 2016 02:11:35 -0700" + "\n");
+ toFooterWithDelimiter(MetadataName.TIMESTAMP) + "Tue, 25 Oct 2016 02:11:35 -0700" + "\n");
b.textContent(stringBuilder.toString());
Address author = new Address("Diffy", "test@gerritcodereview.com");
@@ -83,8 +77,8 @@
assertThat(meta.changeId).isEqualTo("cid");
assertThat(meta.patchSet).isEqualTo(1);
assertThat(meta.messageType).isEqualTo("comment");
- assertThat(meta.timestamp.getTime()).isEqualTo(
- new DateTime(2016, 10, 25, 9, 11, 35, 0, DateTimeZone.UTC).getMillis());
+ assertThat(meta.timestamp.getTime())
+ .isEqualTo(new DateTime(2016, 10, 25, 9, 11, 35, 0, DateTimeZone.UTC).getMillis());
}
@Test
@@ -97,14 +91,15 @@
b.subject("");
StringBuilder stringBuilder = new StringBuilder();
- stringBuilder.append("<p>" +
- toFooterWithDelimiter(MetadataName.CHANGE_ID) + "cid" + "</p>");
- stringBuilder.append("<p>" + toFooterWithDelimiter(MetadataName.PATCH_SET) +
- "1" + "</p>");
- stringBuilder.append("<p>" +
- toFooterWithDelimiter(MetadataName.MESSAGE_TYPE) + "comment" + "</p>");
- stringBuilder.append("<p>" + toFooterWithDelimiter(MetadataName.TIMESTAMP) +
- "Tue, 25 Oct 2016 02:11:35 -0700" + "</p>");
+ stringBuilder.append("<p>" + toFooterWithDelimiter(MetadataName.CHANGE_ID) + "cid" + "</p>");
+ stringBuilder.append("<p>" + toFooterWithDelimiter(MetadataName.PATCH_SET) + "1" + "</p>");
+ stringBuilder.append(
+ "<p>" + toFooterWithDelimiter(MetadataName.MESSAGE_TYPE) + "comment" + "</p>");
+ stringBuilder.append(
+ "<p>"
+ + toFooterWithDelimiter(MetadataName.TIMESTAMP)
+ + "Tue, 25 Oct 2016 02:11:35 -0700"
+ + "</p>");
b.htmlContent(stringBuilder.toString());
Address author = new Address("Diffy", "test@gerritcodereview.com");
@@ -115,7 +110,7 @@
assertThat(meta.changeId).isEqualTo("cid");
assertThat(meta.patchSet).isEqualTo(1);
assertThat(meta.messageType).isEqualTo("comment");
- assertThat(meta.timestamp.getTime()).isEqualTo(
- new DateTime(2016, 10, 25, 9, 11, 35, 0, DateTimeZone.UTC).getMillis());
+ assertThat(meta.timestamp.getTime())
+ .isEqualTo(new DateTime(2016, 10, 25, 9, 11, 35, 0, DateTimeZone.UTC).getMillis());
}
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/RawMailParserTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/RawMailParserTest.java
index 2e5b4c2..4efa817 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/RawMailParserTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/RawMailParserTest.java
@@ -24,40 +24,39 @@
import com.google.gerrit.server.mail.receive.data.RawMailMessage;
import com.google.gerrit.server.mail.receive.data.SimpleTextMessage;
import com.google.gerrit.testutil.GerritBaseTests;
-
import org.junit.Test;
public class RawMailParserTest extends GerritBaseTests {
@Test
public void parseEmail() throws Exception {
- RawMailMessage[] messages = new RawMailMessage[] {
- new SimpleTextMessage(),
- new Base64HeaderMessage(),
- new QuotedPrintableHeaderMessage(),
- new HtmlMimeMessage(),
- new AttachmentMessage(),
- new NonUTF8Message(),
- };
+ RawMailMessage[] messages =
+ new RawMailMessage[] {
+ new SimpleTextMessage(),
+ new Base64HeaderMessage(),
+ new QuotedPrintableHeaderMessage(),
+ new HtmlMimeMessage(),
+ new AttachmentMessage(),
+ new NonUTF8Message(),
+ };
for (RawMailMessage rawMailMessage : messages) {
if (rawMailMessage.rawChars() != null) {
// Assert Character to Mail Parser
- MailMessage parsedMailMessage =
- RawMailParser.parse(rawMailMessage.rawChars());
+ MailMessage parsedMailMessage = RawMailParser.parse(rawMailMessage.rawChars());
assertMail(parsedMailMessage, rawMailMessage.expectedMailMessage());
}
if (rawMailMessage.raw() != null) {
// Assert String to Mail Parser
- MailMessage parsedMailMessage = RawMailParser
- .parse(rawMailMessage.raw());
+ MailMessage parsedMailMessage = RawMailParser.parse(rawMailMessage.raw());
assertMail(parsedMailMessage, rawMailMessage.expectedMailMessage());
}
}
}
/**
- * This method makes it easier to debug failing tests by checking each
- * property individual instead of calling equals as it will immediately
- * reveal the property that diverges between the two objects.
+ * This method makes it easier to debug failing tests by checking each property individual instead
+ * of calling equals as it will immediately reveal the property that diverges between the two
+ * objects.
+ *
* @param have MailMessage retrieved from the parser
* @param want MailMessage that would be expected
*/
@@ -66,8 +65,7 @@
assertThat(have.to()).isEqualTo(want.to());
assertThat(have.from()).isEqualTo(want.from());
assertThat(have.cc()).isEqualTo(want.cc());
- assertThat(have.dateReceived().getMillis())
- .isEqualTo(want.dateReceived().getMillis());
+ assertThat(have.dateReceived().getMillis()).isEqualTo(want.dateReceived().getMillis());
assertThat(have.additionalHeaders()).isEqualTo(want.additionalHeaders());
assertThat(have.subject()).isEqualTo(want.subject());
assertThat(have.textContent()).isEqualTo(want.textContent());
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/TextParserTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/TextParserTest.java
index 7a55653..b23b341 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/TextParserTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/TextParserTest.java
@@ -17,23 +17,22 @@
import static com.google.common.truth.Truth.assertThat;
import com.google.gerrit.reviewdb.client.Comment;
-
+import java.util.List;
import org.junit.Test;
-import java.util.List;
-
public class TextParserTest extends AbstractParserTest {
- private static final String quotedFooter = "" +
- "> To view, visit https://gerrit-review.googlesource.com/123\n" +
- "> To unsubscribe, visit https://gerrit-review.googlesource.com\n" +
- "> \n" +
- "> Gerrit-MessageType: comment\n" +
- "> Gerrit-Change-Id: Ie1234021bf1e8d1425641af58fd648fc011db153\n" +
- "> Gerrit-PatchSet: 1\n" +
- "> Gerrit-Project: gerrit\n" +
- "> Gerrit-Branch: master\n" +
- "> Gerrit-Owner: Foo Bar <foo@bar.com>\n" +
- "> Gerrit-HasComments: Yes";
+ private static final String quotedFooter =
+ ""
+ + "> To view, visit https://gerrit-review.googlesource.com/123\n"
+ + "> To unsubscribe, visit https://gerrit-review.googlesource.com\n"
+ + "> \n"
+ + "> Gerrit-MessageType: comment\n"
+ + "> Gerrit-Change-Id: Ie1234021bf1e8d1425641af58fd648fc011db153\n"
+ + "> Gerrit-PatchSet: 1\n"
+ + "> Gerrit-Project: gerrit\n"
+ + "> Gerrit-Branch: master\n"
+ + "> Gerrit-Owner: Foo Bar <foo@bar.com>\n"
+ + "> Gerrit-HasComments: Yes";
@Test
public void simpleChangeMessage() {
@@ -41,8 +40,7 @@
b.textContent("Looks good to me\n" + quotedFooter);
List<Comment> comments = defaultComments();
- List<MailComment> parsedComments =
- TextParser.parse(b.build(), comments, changeURL);
+ List<MailComment> parsedComments = TextParser.parse(b.build(), comments, changeURL);
assertThat(parsedComments).hasSize(1);
assertChangeMessage("Looks good to me", parsedComments.get(0));
@@ -51,50 +49,56 @@
@Test
public void simpleInlineComments() {
MailMessage.Builder b = newMailMessageBuilder();
- b.textContent(newPlaintextBody("Looks good to me",
- "I have a comment on this.", null, "Also have a comment here.",
- null, null, null) + quotedFooter);
+ b.textContent(
+ newPlaintextBody(
+ "Looks good to me",
+ "I have a comment on this.",
+ null,
+ "Also have a comment here.",
+ null,
+ null,
+ null)
+ + quotedFooter);
List<Comment> comments = defaultComments();
- List<MailComment> parsedComments =
- TextParser.parse(b.build(), comments, changeURL);
+ List<MailComment> parsedComments = TextParser.parse(b.build(), comments, changeURL);
assertThat(parsedComments).hasSize(3);
assertChangeMessage("Looks good to me", parsedComments.get(0));
- assertInlineComment("I have a comment on this.", parsedComments.get(1),
- comments.get(1));
- assertInlineComment("Also have a comment here.", parsedComments.get(2),
- comments.get(3));
+ assertInlineComment("I have a comment on this.", parsedComments.get(1), comments.get(1));
+ assertInlineComment("Also have a comment here.", parsedComments.get(2), comments.get(3));
}
@Test
public void simpleFileComment() {
MailMessage.Builder b = newMailMessageBuilder();
- b.textContent(newPlaintextBody("Looks good to me",
- null, null, "Also have a comment here.",
- "This is a nice file", null, null) + quotedFooter);
+ b.textContent(
+ newPlaintextBody(
+ "Looks good to me",
+ null,
+ null,
+ "Also have a comment here.",
+ "This is a nice file",
+ null,
+ null)
+ + quotedFooter);
List<Comment> comments = defaultComments();
- List<MailComment> parsedComments =
- TextParser.parse(b.build(), comments, changeURL);
+ List<MailComment> parsedComments = TextParser.parse(b.build(), comments, changeURL);
assertThat(parsedComments).hasSize(3);
assertChangeMessage("Looks good to me", parsedComments.get(0));
- assertFileComment("This is a nice file", parsedComments.get(1),
- comments.get(1).key.filename);
- assertInlineComment("Also have a comment here.", parsedComments.get(2),
- comments.get(3));
+ assertFileComment("This is a nice file", parsedComments.get(1), comments.get(1).key.filename);
+ assertInlineComment("Also have a comment here.", parsedComments.get(2), comments.get(3));
}
@Test
public void noComments() {
MailMessage.Builder b = newMailMessageBuilder();
- b.textContent(newPlaintextBody(null, null, null, null, null, null, null) +
- quotedFooter);
+ b.textContent(newPlaintextBody(null, null, null, null, null, null, null) + quotedFooter);
List<Comment> comments = defaultComments();
- List<MailComment> parsedComments =
- TextParser.parse(b.build(), comments, changeURL);
+ List<MailComment> parsedComments = TextParser.parse(b.build(), comments, changeURL);
assertThat(parsedComments).isEmpty();
}
@@ -102,55 +106,63 @@
@Test
public void noChangeMessage() {
MailMessage.Builder b = newMailMessageBuilder();
- b.textContent(newPlaintextBody(null, null, null,
- "Also have a comment here.", "This is a nice file", null, null) +
- quotedFooter);
+ b.textContent(
+ newPlaintextBody(
+ null, null, null, "Also have a comment here.", "This is a nice file", null, null)
+ + quotedFooter);
List<Comment> comments = defaultComments();
- List<MailComment> parsedComments =
- TextParser.parse(b.build(), comments, changeURL);
+ List<MailComment> parsedComments = TextParser.parse(b.build(), comments, changeURL);
assertThat(parsedComments).hasSize(2);
- assertFileComment("This is a nice file", parsedComments.get(0),
- comments.get(1).key.filename);
- assertInlineComment("Also have a comment here.", parsedComments.get(1),
- comments.get(3));
+ assertFileComment("This is a nice file", parsedComments.get(0), comments.get(1).key.filename);
+ assertInlineComment("Also have a comment here.", parsedComments.get(1), comments.get(3));
}
@Test
public void allCommentsGmail() {
MailMessage.Builder b = newMailMessageBuilder();
- b.textContent((newPlaintextBody("Looks good to me",
- null, null, "Also have a comment here.",
- "This is a nice file", null, null) + quotedFooter)
- .replace("> ", ">> "));
+ b.textContent(
+ (newPlaintextBody(
+ "Looks good to me",
+ null,
+ null,
+ "Also have a comment here.",
+ "This is a nice file",
+ null,
+ null)
+ + quotedFooter)
+ .replace("> ", ">> "));
List<Comment> comments = defaultComments();
- List<MailComment> parsedComments =
- TextParser.parse(b.build(), comments, changeURL);
+ List<MailComment> parsedComments = TextParser.parse(b.build(), comments, changeURL);
assertThat(parsedComments).hasSize(3);
assertChangeMessage("Looks good to me", parsedComments.get(0));
- assertFileComment("This is a nice file", parsedComments.get(1),
- comments.get(1).key.filename);
- assertInlineComment("Also have a comment here.", parsedComments.get(2),
- comments.get(3));
+ assertFileComment("This is a nice file", parsedComments.get(1), comments.get(1).key.filename);
+ assertInlineComment("Also have a comment here.", parsedComments.get(2), comments.get(3));
}
@Test
public void replyToFileComment() {
MailMessage.Builder b = newMailMessageBuilder();
- b.textContent(newPlaintextBody("Looks good to me", null, null, null, null,
- null, "Comment in reply to file comment") + quotedFooter);
+ b.textContent(
+ newPlaintextBody(
+ "Looks good to me",
+ null,
+ null,
+ null,
+ null,
+ null,
+ "Comment in reply to file comment")
+ + quotedFooter);
List<Comment> comments = defaultComments();
- List<MailComment> parsedComments =
- TextParser.parse(b.build(), comments, changeURL);
+ List<MailComment> parsedComments = TextParser.parse(b.build(), comments, changeURL);
assertThat(parsedComments).hasSize(2);
assertChangeMessage("Looks good to me", parsedComments.get(0));
- assertInlineComment("Comment in reply to file comment",
- parsedComments.get(1), comments.get(0));
+ assertInlineComment("Comment in reply to file comment", parsedComments.get(1), comments.get(0));
}
/**
@@ -165,55 +177,69 @@
* @param fc1 Comment in reply to a comment of file 1.
* @return A string with all inline comments and the original quoted email.
*/
- private static String newPlaintextBody(String changeMessage, String c1,
- String c2, String c3, String f1, String f2, String fc1) {
- return (changeMessage == null ? "" : changeMessage + "\n") +
- "> Foo Bar has posted comments on this change. ( \n" +
- "> " + changeURL +"/1 )\n" +
- "> \n" +
- "> Change subject: Test change\n" +
- "> ...............................................................\n" +
- "> \n" +
- "> \n" +
- "> Patch Set 1: Code-Review+1\n" +
- "> \n" +
- "> (3 comments)\n" +
- "> \n" +
- "> " + changeURL + "/1/gerrit-server/test.txt\n" +
- "> File \n" +
- "> gerrit-server/test.txt:\n" +
- (f1 == null ? "" : f1 + "\n") +
- "> \n" +
- "> Patch Set #4:\n" +
- "> " + changeURL + "/1/gerrit-server/test.txt\n" +
- "> \n" +
- "> Some comment" +
- "> \n" +
- (fc1 == null ? "" : fc1 + "\n") +
- "> " + changeURL + "/1/gerrit-server/test.txt@2\n" +
- "> PS1, Line 2: throw new Exception(\"Object has unsupported: \" +\n" +
- "> : entry.getValue() +\n" +
- "> : \" must be java.util.Date\");\n" +
- "> Should entry.getKey() be included in this message?\n" +
- "> \n" +
- (c1 == null ? "" : c1 + "\n") +
- "> \n" +
- "> " + changeURL + "/1/gerrit-server/test.txt@3\n" +
- "> PS1, Line 3: throw new Exception(\"Object has: \" +\n" +
- "> : entry.getValue().getClass() +\n" +
- "> : \" must be java.util.Date\");\n" +
- "> same here\n" +
- "> \n" +
- (c2 == null ? "" : c2 + "\n") +
- "> \n" +
- "> " + changeURL + "/1/gerrit-server/readme.txt\n" +
- "> File \n" +
- "> gerrit-server/readme.txt:\n" +
- (f2 == null ? "" : f2 + "\n") +
- "> \n" +
- "> " + changeURL + "/1/gerrit-server/readme.txt@3\n" +
- "> PS1, Line 3: E\n" +
- "> Should this be EEE like in other places?\n" +
- (c3 == null ? "" : c3 + "\n");
+ private static String newPlaintextBody(
+ String changeMessage, String c1, String c2, String c3, String f1, String f2, String fc1) {
+ return (changeMessage == null ? "" : changeMessage + "\n")
+ + "> Foo Bar has posted comments on this change. ( \n"
+ + "> "
+ + changeURL
+ + "/1 )\n"
+ + "> \n"
+ + "> Change subject: Test change\n"
+ + "> ...............................................................\n"
+ + "> \n"
+ + "> \n"
+ + "> Patch Set 1: Code-Review+1\n"
+ + "> \n"
+ + "> (3 comments)\n"
+ + "> \n"
+ + "> "
+ + changeURL
+ + "/1/gerrit-server/test.txt\n"
+ + "> File \n"
+ + "> gerrit-server/test.txt:\n"
+ + (f1 == null ? "" : f1 + "\n")
+ + "> \n"
+ + "> Patch Set #4:\n"
+ + "> "
+ + changeURL
+ + "/1/gerrit-server/test.txt\n"
+ + "> \n"
+ + "> Some comment"
+ + "> \n"
+ + (fc1 == null ? "" : fc1 + "\n")
+ + "> "
+ + changeURL
+ + "/1/gerrit-server/test.txt@2\n"
+ + "> PS1, Line 2: throw new Exception(\"Object has unsupported: \" +\n"
+ + "> : entry.getValue() +\n"
+ + "> : \" must be java.util.Date\");\n"
+ + "> Should entry.getKey() be included in this message?\n"
+ + "> \n"
+ + (c1 == null ? "" : c1 + "\n")
+ + "> \n"
+ + "> "
+ + changeURL
+ + "/1/gerrit-server/test.txt@3\n"
+ + "> PS1, Line 3: throw new Exception(\"Object has: \" +\n"
+ + "> : entry.getValue().getClass() +\n"
+ + "> : \" must be java.util.Date\");\n"
+ + "> same here\n"
+ + "> \n"
+ + (c2 == null ? "" : c2 + "\n")
+ + "> \n"
+ + "> "
+ + changeURL
+ + "/1/gerrit-server/readme.txt\n"
+ + "> File \n"
+ + "> gerrit-server/readme.txt:\n"
+ + (f2 == null ? "" : f2 + "\n")
+ + "> \n"
+ + "> "
+ + changeURL
+ + "/1/gerrit-server/readme.txt@3\n"
+ + "> PS1, Line 3: E\n"
+ + "> Should this be EEE like in other places?\n"
+ + (c3 == null ? "" : c3 + "\n");
}
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/data/AttachmentMessage.java b/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/data/AttachmentMessage.java
index 390209a..2c418ec 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/data/AttachmentMessage.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/data/AttachmentMessage.java
@@ -14,52 +14,48 @@
package com.google.gerrit.server.mail.receive.data;
-
import com.google.gerrit.server.mail.Address;
import com.google.gerrit.server.mail.receive.MailMessage;
-
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.junit.Ignore;
-/**
- * Tests that all mime parts that are neither text/plain, nor text/html are
- * dropped.
- */
+/** Tests that all mime parts that are neither text/plain, nor text/html are dropped. */
@Ignore
public class AttachmentMessage extends RawMailMessage {
- private static String raw = "MIME-Version: 1.0\n" +
- "Date: Tue, 25 Oct 2016 02:11:35 -0700\n" +
- "Message-ID: <CAM7sg=3meaAVUxW3KXeJEVs8sv_ADw1BnvpcHHiYVR2TQQi__w" +
- "@mail.gmail.com>\n" +
- "Subject: Test Subject\n" +
- "From: Patrick Hiesel <hiesel@google.com>\n" +
- "To: Patrick Hiesel <hiesel@google.com>\n" +
- "Content-Type: multipart/mixed; boundary=001a114e019a56962d054062708f\n" +
- "\n" +
- "--001a114e019a56962d054062708f\n" +
- "Content-Type: multipart/alternative; boundary=001a114e019a5696250540" +
- "62708d\n" +
- "\n" +
- "--001a114e019a569625054062708d\n" +
- "Content-Type: text/plain; charset=UTF-8\n" +
- "\n" +
- "Contains unwanted attachment" +
- "\n" +
- "--001a114e019a569625054062708d\n" +
- "Content-Type: text/html; charset=UTF-8\n" +
- "\n" +
- "<div dir=\"ltr\">Contains unwanted attachment</div>" +
- "\n" +
- "--001a114e019a569625054062708d--\n" +
- "--001a114e019a56962d054062708f\n" +
- "Content-Type: text/plain; charset=US-ASCII; name=\"test.txt\"\n" +
- "Content-Disposition: attachment; filename=\"test.txt\"\n" +
- "Content-Transfer-Encoding: base64\n" +
- "X-Attachment-Id: f_iv264bt50\n" +
- "\n" +
- "VEVTVAo=\n" +
- "--001a114e019a56962d054062708f--";
+ private static String raw =
+ "MIME-Version: 1.0\n"
+ + "Date: Tue, 25 Oct 2016 02:11:35 -0700\n"
+ + "Message-ID: <CAM7sg=3meaAVUxW3KXeJEVs8sv_ADw1BnvpcHHiYVR2TQQi__w"
+ + "@mail.gmail.com>\n"
+ + "Subject: Test Subject\n"
+ + "From: Patrick Hiesel <hiesel@google.com>\n"
+ + "To: Patrick Hiesel <hiesel@google.com>\n"
+ + "Content-Type: multipart/mixed; boundary=001a114e019a56962d054062708f\n"
+ + "\n"
+ + "--001a114e019a56962d054062708f\n"
+ + "Content-Type: multipart/alternative; boundary=001a114e019a5696250540"
+ + "62708d\n"
+ + "\n"
+ + "--001a114e019a569625054062708d\n"
+ + "Content-Type: text/plain; charset=UTF-8\n"
+ + "\n"
+ + "Contains unwanted attachment"
+ + "\n"
+ + "--001a114e019a569625054062708d\n"
+ + "Content-Type: text/html; charset=UTF-8\n"
+ + "\n"
+ + "<div dir=\"ltr\">Contains unwanted attachment</div>"
+ + "\n"
+ + "--001a114e019a569625054062708d--\n"
+ + "--001a114e019a56962d054062708f\n"
+ + "Content-Type: text/plain; charset=US-ASCII; name=\"test.txt\"\n"
+ + "Content-Disposition: attachment; filename=\"test.txt\"\n"
+ + "Content-Transfer-Encoding: base64\n"
+ + "X-Attachment-Id: f_iv264bt50\n"
+ + "\n"
+ + "VEVTVAo=\n"
+ + "--001a114e019a56962d054062708f--";
@Override
public String raw() {
@@ -76,16 +72,14 @@
System.out.println("\uD83D\uDE1B test");
MailMessage.Builder expect = MailMessage.builder();
expect
- .id("<CAM7sg=3meaAVUxW3KXeJEVs8sv_ADw1BnvpcHHiYVR2TQQi__w" +
- "@mail.gmail.com>")
+ .id("<CAM7sg=3meaAVUxW3KXeJEVs8sv_ADw1BnvpcHHiYVR2TQQi__w" + "@mail.gmail.com>")
.from(new Address("Patrick Hiesel", "hiesel@google.com"))
.addTo(new Address("Patrick Hiesel", "hiesel@google.com"))
.textContent("Contains unwanted attachment")
.htmlContent("<div dir=\"ltr\">Contains unwanted attachment</div>")
.subject("Test Subject")
.addAdditionalHeader("MIME-Version: 1.0")
- .dateReceived(
- new DateTime(2016, 10, 25, 9, 11, 35, 0, DateTimeZone.UTC));
+ .dateReceived(new DateTime(2016, 10, 25, 9, 11, 35, 0, DateTimeZone.UTC));
return expect.build();
}
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/data/Base64HeaderMessage.java b/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/data/Base64HeaderMessage.java
index 5511e75..affa3bd 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/data/Base64HeaderMessage.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/data/Base64HeaderMessage.java
@@ -16,26 +16,25 @@
import com.google.gerrit.server.mail.Address;
import com.google.gerrit.server.mail.receive.MailMessage;
-
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.junit.Ignore;
-/**
- * Tests parsing a Base64 encoded subject.
- */
+/** Tests parsing a Base64 encoded subject. */
@Ignore
public class Base64HeaderMessage extends RawMailMessage {
private static String textContent = "Some Text";
- private static String raw = "" +
- "Date: Tue, 25 Oct 2016 02:11:35 -0700\n" +
- "Message-ID: <001a114da7ae26e2eb053fe0c29c@google.com>\n" +
- "Subject: =?UTF-8?B?8J+YmyB0ZXN0?=\n" +
- "From: \"Jonathan Nieder (Gerrit)\" <noreply-gerritcodereview-" +
- "CtTy0igsBrnvL7dKoWEIEg@google.com>\n" +
- "To: ekempin <ekempin@google.com>\n" +
- "Content-Type: text/plain; charset=UTF-8; format=flowed; delsp=yes\n" +
- "\n" + textContent;
+ private static String raw =
+ ""
+ + "Date: Tue, 25 Oct 2016 02:11:35 -0700\n"
+ + "Message-ID: <001a114da7ae26e2eb053fe0c29c@google.com>\n"
+ + "Subject: =?UTF-8?B?8J+YmyB0ZXN0?=\n"
+ + "From: \"Jonathan Nieder (Gerrit)\" <noreply-gerritcodereview-"
+ + "CtTy0igsBrnvL7dKoWEIEg@google.com>\n"
+ + "To: ekempin <ekempin@google.com>\n"
+ + "Content-Type: text/plain; charset=UTF-8; format=flowed; delsp=yes\n"
+ + "\n"
+ + textContent;
@Override
public String raw() {
@@ -52,13 +51,14 @@
MailMessage.Builder expect = MailMessage.builder();
expect
.id("<001a114da7ae26e2eb053fe0c29c@google.com>")
- .from(new Address("Jonathan Nieder (Gerrit)",
- "noreply-gerritcodereview-CtTy0igsBrnvL7dKoWEIEg@google.com"))
- .addTo(new Address("ekempin","ekempin@google.com"))
+ .from(
+ new Address(
+ "Jonathan Nieder (Gerrit)",
+ "noreply-gerritcodereview-CtTy0igsBrnvL7dKoWEIEg@google.com"))
+ .addTo(new Address("ekempin", "ekempin@google.com"))
.textContent(textContent)
.subject("\uD83D\uDE1B test")
- .dateReceived(
- new DateTime(2016, 10, 25, 9, 11, 35, 0, DateTimeZone.UTC));
+ .dateReceived(new DateTime(2016, 10, 25, 9, 11, 35, 0, DateTimeZone.UTC));
return expect.build();
}
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/data/HtmlMimeMessage.java b/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/data/HtmlMimeMessage.java
index 2ed096e..c19e618 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/data/HtmlMimeMessage.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/data/HtmlMimeMessage.java
@@ -16,63 +16,63 @@
import com.google.gerrit.server.mail.Address;
import com.google.gerrit.server.mail.receive.MailMessage;
-
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.junit.Ignore;
-/**
- * Tests a message containing mime/alternative (text + html) content.
- */
+/** Tests a message containing mime/alternative (text + html) content. */
@Ignore
public class HtmlMimeMessage extends RawMailMessage {
private static String textContent = "Simple test";
// htmlContent is encoded in quoted-printable
- private static String htmlContent = "<div dir=3D\"ltr\">Test <span style" +
- "=3D\"background-color:rgb(255,255,0)\">Messa=\n" +
- "ge</span> in <u>HTML=C2=A0</u><a href=3D\"https://en.wikipedia.org/" +
- "wiki/%C3%=\n9Cmlaut_(band)\" class=3D\"gmail-mw-redirect\" title=3D\"" +
- "=C3=9Cmlaut (band)\" st=\nyle=3D\"text-decoration:none;color:rgb(11," +
- "0,128);background-image:none;backg=\nround-position:initial;background" +
- "-size:initial;background-repeat:initial;ba=\nckground-origin:initial;" +
- "background-clip:initial;font-family:sans-serif;font=\n" +
- "-size:14px\">=C3=9C</a></div>";
+ private static String htmlContent =
+ "<div dir=3D\"ltr\">Test <span style"
+ + "=3D\"background-color:rgb(255,255,0)\">Messa=\n"
+ + "ge</span> in <u>HTML=C2=A0</u><a href=3D\"https://en.wikipedia.org/"
+ + "wiki/%C3%=\n9Cmlaut_(band)\" class=3D\"gmail-mw-redirect\" title=3D\""
+ + "=C3=9Cmlaut (band)\" st=\nyle=3D\"text-decoration:none;color:rgb(11,"
+ + "0,128);background-image:none;backg=\nround-position:initial;background"
+ + "-size:initial;background-repeat:initial;ba=\nckground-origin:initial;"
+ + "background-clip:initial;font-family:sans-serif;font=\n"
+ + "-size:14px\">=C3=9C</a></div>";
- private static String unencodedHtmlContent = "" +
- "<div dir=\"ltr\">Test <span style=\"background-color:rgb(255,255,0)\">" +
- "Message</span> in <u>HTML </u><a href=\"https://en.wikipedia.org/wiki/" +
- "%C3%9Cmlaut_(band)\" class=\"gmail-mw-redirect\" title=\"Ümlaut " +
- "(band)\" style=\"text-decoration:none;color:rgb(11,0,128);" +
- "background-image:none;background-position:initial;background-size:" +
- "initial;background-repeat:initial;background-origin:initial;background" +
- "-clip:initial;font-family:sans-serif;font-size:14px\">Ü</a></div>";
+ private static String unencodedHtmlContent =
+ ""
+ + "<div dir=\"ltr\">Test <span style=\"background-color:rgb(255,255,0)\">"
+ + "Message</span> in <u>HTML </u><a href=\"https://en.wikipedia.org/wiki/"
+ + "%C3%9Cmlaut_(band)\" class=\"gmail-mw-redirect\" title=\"Ümlaut "
+ + "(band)\" style=\"text-decoration:none;color:rgb(11,0,128);"
+ + "background-image:none;background-position:initial;background-size:"
+ + "initial;background-repeat:initial;background-origin:initial;background"
+ + "-clip:initial;font-family:sans-serif;font-size:14px\">Ü</a></div>";
- private static String raw = "" +
- "MIME-Version: 1.0\n" +
- "Date: Tue, 25 Oct 2016 02:11:35 -0700\n" +
- "Message-ID: <001a114cd8be55b4ab053face5cd@google.com>\n" +
- "Subject: Change in gerrit[master]: Implement receiver class structure " +
- "and bindings\n" +
- "From: \"ekempin (Gerrit)\" <noreply-gerritcodereview-qUgXfQecoDLHwp0Ml" +
- "dAzig@google.com>\n" +
- "To: Patrick Hiesel <hiesel@google.com>\n" +
- "Cc: ekempin <ekempin@google.com>\n" +
- "Content-Type: multipart/alternative; boundary=001a114cd8b" +
- "e55b486053face5ca\n" +
- "\n" +
- "--001a114cd8be55b486053face5ca\n" +
- "Content-Type: text/plain; charset=UTF-8; format=flowed; delsp=yes\n" +
- "\n" +
- textContent +
- "\n" +
- "--001a114cd8be55b486053face5ca\n" +
- "Content-Type: text/html; charset=UTF-8\n" +
- "Content-Transfer-Encoding: quoted-printable\n" +
- "\n" +
- htmlContent +
- "\n" +
- "--001a114cd8be55b486053face5ca--";
+ private static String raw =
+ ""
+ + "MIME-Version: 1.0\n"
+ + "Date: Tue, 25 Oct 2016 02:11:35 -0700\n"
+ + "Message-ID: <001a114cd8be55b4ab053face5cd@google.com>\n"
+ + "Subject: Change in gerrit[master]: Implement receiver class structure "
+ + "and bindings\n"
+ + "From: \"ekempin (Gerrit)\" <noreply-gerritcodereview-qUgXfQecoDLHwp0Ml"
+ + "dAzig@google.com>\n"
+ + "To: Patrick Hiesel <hiesel@google.com>\n"
+ + "Cc: ekempin <ekempin@google.com>\n"
+ + "Content-Type: multipart/alternative; boundary=001a114cd8b"
+ + "e55b486053face5ca\n"
+ + "\n"
+ + "--001a114cd8be55b486053face5ca\n"
+ + "Content-Type: text/plain; charset=UTF-8; format=flowed; delsp=yes\n"
+ + "\n"
+ + textContent
+ + "\n"
+ + "--001a114cd8be55b486053face5ca\n"
+ + "Content-Type: text/html; charset=UTF-8\n"
+ + "Content-Transfer-Encoding: quoted-printable\n"
+ + "\n"
+ + htmlContent
+ + "\n"
+ + "--001a114cd8be55b486053face5ca--";
@Override
public String raw() {
@@ -89,17 +89,16 @@
MailMessage.Builder expect = MailMessage.builder();
expect
.id("<001a114cd8be55b4ab053face5cd@google.com>")
- .from(new Address("ekempin (Gerrit)",
- "noreply-gerritcodereview-qUgXfQecoDLHwp0MldAzig@google.com"))
- .addCc(new Address("ekempin","ekempin@google.com"))
- .addTo(new Address("Patrick Hiesel","hiesel@google.com"))
+ .from(
+ new Address(
+ "ekempin (Gerrit)", "noreply-gerritcodereview-qUgXfQecoDLHwp0MldAzig@google.com"))
+ .addCc(new Address("ekempin", "ekempin@google.com"))
+ .addTo(new Address("Patrick Hiesel", "hiesel@google.com"))
.textContent(textContent)
.htmlContent(unencodedHtmlContent)
- .subject("Change in gerrit[master]: Implement " +
- "receiver class structure and bindings")
+ .subject("Change in gerrit[master]: Implement " + "receiver class structure and bindings")
.addAdditionalHeader("MIME-Version: 1.0")
- .dateReceived(
- new DateTime(2016, 10, 25, 9, 11, 35, 0, DateTimeZone.UTC));
+ .dateReceived(new DateTime(2016, 10, 25, 9, 11, 35, 0, DateTimeZone.UTC));
return expect.build();
}
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/data/NonUTF8Message.java b/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/data/NonUTF8Message.java
index 1472049..9f2af0d 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/data/NonUTF8Message.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/data/NonUTF8Message.java
@@ -15,26 +15,25 @@
import com.google.gerrit.server.mail.Address;
import com.google.gerrit.server.mail.receive.MailMessage;
-
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.junit.Ignore;
-/**
- * Tests that non-UTF8 encodings are handled correctly.
- */
+/** Tests that non-UTF8 encodings are handled correctly. */
@Ignore
public class NonUTF8Message extends RawMailMessage {
private static String textContent = "Some Text";
- private static String raw = "" +
- "Date: Tue, 25 Oct 2016 02:11:35 -0700\n" +
- "Message-ID: <001a114da7ae26e2eb053fe0c29c@google.com>\n" +
- "Subject: =?UTF-8?B?8J+YmyB0ZXN0?=\n" +
- "From: \"Jonathan Nieder (Gerrit)\" <noreply-gerritcodereview-" +
- "CtTy0igsBrnvL7dKoWEIEg@google.com>\n" +
- "To: ekempin <ekempin@google.com>\n" +
- "Content-Type: text/plain; charset=UTF-8; format=flowed; delsp=yes\n" +
- "\n" + textContent;
+ private static String raw =
+ ""
+ + "Date: Tue, 25 Oct 2016 02:11:35 -0700\n"
+ + "Message-ID: <001a114da7ae26e2eb053fe0c29c@google.com>\n"
+ + "Subject: =?UTF-8?B?8J+YmyB0ZXN0?=\n"
+ + "From: \"Jonathan Nieder (Gerrit)\" <noreply-gerritcodereview-"
+ + "CtTy0igsBrnvL7dKoWEIEg@google.com>\n"
+ + "To: ekempin <ekempin@google.com>\n"
+ + "Content-Type: text/plain; charset=UTF-8; format=flowed; delsp=yes\n"
+ + "\n"
+ + textContent;
@Override
public String raw() {
@@ -56,13 +55,14 @@
MailMessage.Builder expect = MailMessage.builder();
expect
.id("<001a114da7ae26e2eb053fe0c29c@google.com>")
- .from(new Address("Jonathan Nieder (Gerrit)",
- "noreply-gerritcodereview-CtTy0igsBrnvL7dKoWEIEg@google.com"))
- .addTo(new Address("ekempin","ekempin@google.com"))
+ .from(
+ new Address(
+ "Jonathan Nieder (Gerrit)",
+ "noreply-gerritcodereview-CtTy0igsBrnvL7dKoWEIEg@google.com"))
+ .addTo(new Address("ekempin", "ekempin@google.com"))
.textContent(textContent)
.subject("\uD83D\uDE1B test")
- .dateReceived(
- new DateTime(2016, 10, 25, 9, 11, 35, 0, DateTimeZone.UTC));
+ .dateReceived(new DateTime(2016, 10, 25, 9, 11, 35, 0, DateTimeZone.UTC));
return expect.build();
}
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/data/QuotedPrintableHeaderMessage.java b/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/data/QuotedPrintableHeaderMessage.java
index f694447..2c17859 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/data/QuotedPrintableHeaderMessage.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/data/QuotedPrintableHeaderMessage.java
@@ -16,26 +16,25 @@
import com.google.gerrit.server.mail.Address;
import com.google.gerrit.server.mail.receive.MailMessage;
-
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.junit.Ignore;
-/**
- * Tests parsing a quoted printable encoded subject
- */
+/** Tests parsing a quoted printable encoded subject */
@Ignore
public class QuotedPrintableHeaderMessage extends RawMailMessage {
private static String textContent = "Some Text";
- private static String raw = "" +
- "Date: Tue, 25 Oct 2016 02:11:35 -0700\n" +
- "Message-ID: <001a114da7ae26e2eb053fe0c29c@google.com>\n" +
- "Subject: =?UTF-8?Q?=C3=A2me vulgaire?=\n" +
- "From: \"Jonathan Nieder (Gerrit)\" <noreply-gerritcodereview-" +
- "CtTy0igsBrnvL7dKoWEIEg@google.com>\n" +
- "To: ekempin <ekempin@google.com>\n" +
- "Content-Type: text/plain; charset=UTF-8; format=flowed; delsp=yes\n" +
- "\n" + textContent;
+ private static String raw =
+ ""
+ + "Date: Tue, 25 Oct 2016 02:11:35 -0700\n"
+ + "Message-ID: <001a114da7ae26e2eb053fe0c29c@google.com>\n"
+ + "Subject: =?UTF-8?Q?=C3=A2me vulgaire?=\n"
+ + "From: \"Jonathan Nieder (Gerrit)\" <noreply-gerritcodereview-"
+ + "CtTy0igsBrnvL7dKoWEIEg@google.com>\n"
+ + "To: ekempin <ekempin@google.com>\n"
+ + "Content-Type: text/plain; charset=UTF-8; format=flowed; delsp=yes\n"
+ + "\n"
+ + textContent;
@Override
public String raw() {
@@ -53,13 +52,14 @@
MailMessage.Builder expect = MailMessage.builder();
expect
.id("<001a114da7ae26e2eb053fe0c29c@google.com>")
- .from(new Address("Jonathan Nieder (Gerrit)",
- "noreply-gerritcodereview-CtTy0igsBrnvL7dKoWEIEg@google.com"))
- .addTo(new Address("ekempin","ekempin@google.com"))
+ .from(
+ new Address(
+ "Jonathan Nieder (Gerrit)",
+ "noreply-gerritcodereview-CtTy0igsBrnvL7dKoWEIEg@google.com"))
+ .addTo(new Address("ekempin", "ekempin@google.com"))
.textContent(textContent)
.subject("âme vulgaire")
- .dateReceived(
- new DateTime(2016, 10, 25, 9, 11, 35, 0, DateTimeZone.UTC));
+ .dateReceived(new DateTime(2016, 10, 25, 9, 11, 35, 0, DateTimeZone.UTC));
return expect.build();
}
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/data/RawMailMessage.java b/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/data/RawMailMessage.java
index 8afa8cc..2af82ad 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/data/RawMailMessage.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/data/RawMailMessage.java
@@ -15,16 +15,14 @@
package com.google.gerrit.server.mail.receive.data;
import com.google.gerrit.server.mail.receive.MailMessage;
-
import org.junit.Ignore;
-/**
- * Base class for all email parsing tests.
- */
+/** Base class for all email parsing tests. */
@Ignore
public abstract class RawMailMessage {
// Raw content to feed the parser
public abstract String raw();
+
public abstract int[] rawChars();
// Parsed representation for asserting the expected parser output
public abstract MailMessage expectedMailMessage();
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/data/SimpleTextMessage.java b/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/data/SimpleTextMessage.java
index 179c514..8fc1dbc 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/data/SimpleTextMessage.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/mail/receive/data/SimpleTextMessage.java
@@ -16,88 +16,88 @@
import com.google.gerrit.server.mail.Address;
import com.google.gerrit.server.mail.receive.MailMessage;
-
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.junit.Ignore;
-/**
- * Tests parsing a simple text message with different headers.
- */
+/** Tests parsing a simple text message with different headers. */
@Ignore
public class SimpleTextMessage extends RawMailMessage {
- private static String textContent = "" +
- "Jonathan Nieder has posted comments on this change. ( \n" +
- "https://gerrit-review.googlesource.com/90018 )\n" +
- "\n" +
- "Change subject: (Re)enable voting buttons for merged changes\n" +
- "...........................................................\n" +
- "\n" +
- "\n" +
- "Patch Set 2:\n" +
- "\n" +
- "This is producing NPEs server-side and 500s for the client. \n" +
- "when I try to load this change:\n" +
- "\n" +
- " Error in GET /changes/90018/detail?O=10004\n" +
- " com.google.gwtorm.OrmException: java.lang.NullPointerException\n" +
- "\tat com.google.gerrit.change.ChangeJson.format(ChangeJson.java:303)\n" +
- "\tat com.google.gerrit.change.ChangeJson.format(ChangeJson.java:285)\n" +
- "\tat com.google.gerrit.change.ChangeJson.format(ChangeJson.java:263)\n" +
- "\tat com.google.gerrit.change.GetChange.apply(GetChange.java:50)\n" +
- "\tat com.google.gerrit.change.GetDetail.apply(GetDetail.java:51)\n" +
- "\tat com.google.gerrit.change.GetDetail.apply(GetDetail.java:26)\n" +
- "\tat \n" +
- "com.google.gerrit.RestApiServlet.service(RestApiServlet.java:367)\n" +
- "\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:717)\n" +
- "[...]\n" +
- " Caused by: java.lang.NullPointerException\n" +
- "\tat \n" +
- "com.google.gerrit.ChangeJson.setLabelScores(ChangeJson.java:670)\n" +
- "\tat \n" +
- "com.google.gerrit.ChangeJson.labelsFor(ChangeJson.java:845)\n" +
- "\tat \n" +
- "com.google.gerrit.change.ChangeJson.labelsFor(ChangeJson.java:598)\n" +
- "\tat \n" +
- "com.google.gerrit.change.ChangeJson.toChange(ChangeJson.java:499)\n" +
- "\tat com.google.gerrit.change.ChangeJson.format(ChangeJson.java:294)\n" +
- "\t... 105 more\n" +
- "-- \n" +
- "To view, visit https://gerrit-review.googlesource.com/90018\n" +
- "To unsubscribe, visit https://gerrit-review.googlesource.com\n" +
- "\n" +
- "Gerrit-MessageType: comment\n" +
- "Gerrit-Change-Id: Iba501e00bee77be3bd0ced72f88fd04ba0accaed\n" +
- "Gerrit-PatchSet: 2\n" +
- "Gerrit-Project: gerrit\n" +
- "Gerrit-Branch: master\n" +
- "Gerrit-Owner: ekempin <ekempin@google.com>\n" +
- "Gerrit-Reviewer: Dave Borowitz <dborowitz@google.com>\n" +
- "Gerrit-Reviewer: Edwin Kempin <ekempin@google.com>\n" +
- "Gerrit-Reviewer: GerritForge CI <gerritforge@gmail.com>\n" +
- "Gerrit-Reviewer: Jonathan Nieder <jrn@google.com>\n" +
- "Gerrit-Reviewer: Patrick Hiesel <hiesel@google.com>\n" +
- "Gerrit-Reviewer: ekempin <ekempin@google.com>\n" +
- "Gerrit-HasComments: No";
+ private static String textContent =
+ ""
+ + "Jonathan Nieder has posted comments on this change. ( \n"
+ + "https://gerrit-review.googlesource.com/90018 )\n"
+ + "\n"
+ + "Change subject: (Re)enable voting buttons for merged changes\n"
+ + "...........................................................\n"
+ + "\n"
+ + "\n"
+ + "Patch Set 2:\n"
+ + "\n"
+ + "This is producing NPEs server-side and 500s for the client. \n"
+ + "when I try to load this change:\n"
+ + "\n"
+ + " Error in GET /changes/90018/detail?O=10004\n"
+ + " com.google.gwtorm.OrmException: java.lang.NullPointerException\n"
+ + "\tat com.google.gerrit.change.ChangeJson.format(ChangeJson.java:303)\n"
+ + "\tat com.google.gerrit.change.ChangeJson.format(ChangeJson.java:285)\n"
+ + "\tat com.google.gerrit.change.ChangeJson.format(ChangeJson.java:263)\n"
+ + "\tat com.google.gerrit.change.GetChange.apply(GetChange.java:50)\n"
+ + "\tat com.google.gerrit.change.GetDetail.apply(GetDetail.java:51)\n"
+ + "\tat com.google.gerrit.change.GetDetail.apply(GetDetail.java:26)\n"
+ + "\tat \n"
+ + "com.google.gerrit.RestApiServlet.service(RestApiServlet.java:367)\n"
+ + "\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:717)\n"
+ + "[...]\n"
+ + " Caused by: java.lang.NullPointerException\n"
+ + "\tat \n"
+ + "com.google.gerrit.ChangeJson.setLabelScores(ChangeJson.java:670)\n"
+ + "\tat \n"
+ + "com.google.gerrit.ChangeJson.labelsFor(ChangeJson.java:845)\n"
+ + "\tat \n"
+ + "com.google.gerrit.change.ChangeJson.labelsFor(ChangeJson.java:598)\n"
+ + "\tat \n"
+ + "com.google.gerrit.change.ChangeJson.toChange(ChangeJson.java:499)\n"
+ + "\tat com.google.gerrit.change.ChangeJson.format(ChangeJson.java:294)\n"
+ + "\t... 105 more\n"
+ + "-- \n"
+ + "To view, visit https://gerrit-review.googlesource.com/90018\n"
+ + "To unsubscribe, visit https://gerrit-review.googlesource.com\n"
+ + "\n"
+ + "Gerrit-MessageType: comment\n"
+ + "Gerrit-Change-Id: Iba501e00bee77be3bd0ced72f88fd04ba0accaed\n"
+ + "Gerrit-PatchSet: 2\n"
+ + "Gerrit-Project: gerrit\n"
+ + "Gerrit-Branch: master\n"
+ + "Gerrit-Owner: ekempin <ekempin@google.com>\n"
+ + "Gerrit-Reviewer: Dave Borowitz <dborowitz@google.com>\n"
+ + "Gerrit-Reviewer: Edwin Kempin <ekempin@google.com>\n"
+ + "Gerrit-Reviewer: GerritForge CI <gerritforge@gmail.com>\n"
+ + "Gerrit-Reviewer: Jonathan Nieder <jrn@google.com>\n"
+ + "Gerrit-Reviewer: Patrick Hiesel <hiesel@google.com>\n"
+ + "Gerrit-Reviewer: ekempin <ekempin@google.com>\n"
+ + "Gerrit-HasComments: No";
- private static String raw = "" +
- "Authentication-Results: mx.google.com; dkim=pass header.i=" +
- "@google.com;\n" +
- "Date: Tue, 25 Oct 2016 02:11:35 -0700\n" +
- "In-Reply-To: <gerrit.1477487889000.Iba501e00bee77be3bd0ced" +
- "72f88fd04ba0accaed@gerrit-review.googlesource.com>\n" +
- "References: <gerrit.1477487889000.Iba501e00bee77be3bd0ced72f8" +
- "8fd04ba0accaed@gerrit-review.googlesource.com>\n" +
- "Message-ID: <001a114da7ae26e2eb053fe0c29c@google.com>\n" +
- "Subject: Change in gerrit[master]: (Re)enable voting buttons for " +
- "merged changes\n" +
- "From: \"Jonathan Nieder (Gerrit)\" <noreply-gerritcodereview-CtTy0" +
- "igsBrnvL7dKoWEIEg@google.com>\n" +
- "To: ekempin <ekempin@google.com>\n" +
- "Cc: Dave Borowitz <dborowitz@google.com>, Jonathan Nieder " +
- "<jrn@google.com>, Patrick Hiesel <hiesel@google.com>\n" +
- "Content-Type: text/plain; charset=UTF-8; format=flowed; delsp=yes\n" +
- "\n" + textContent;
+ private static String raw =
+ ""
+ + "Authentication-Results: mx.google.com; dkim=pass header.i="
+ + "@google.com;\n"
+ + "Date: Tue, 25 Oct 2016 02:11:35 -0700\n"
+ + "In-Reply-To: <gerrit.1477487889000.Iba501e00bee77be3bd0ced"
+ + "72f88fd04ba0accaed@gerrit-review.googlesource.com>\n"
+ + "References: <gerrit.1477487889000.Iba501e00bee77be3bd0ced72f8"
+ + "8fd04ba0accaed@gerrit-review.googlesource.com>\n"
+ + "Message-ID: <001a114da7ae26e2eb053fe0c29c@google.com>\n"
+ + "Subject: Change in gerrit[master]: (Re)enable voting buttons for "
+ + "merged changes\n"
+ + "From: \"Jonathan Nieder (Gerrit)\" <noreply-gerritcodereview-CtTy0"
+ + "igsBrnvL7dKoWEIEg@google.com>\n"
+ + "To: ekempin <ekempin@google.com>\n"
+ + "Cc: Dave Borowitz <dborowitz@google.com>, Jonathan Nieder "
+ + "<jrn@google.com>, Patrick Hiesel <hiesel@google.com>\n"
+ + "Content-Type: text/plain; charset=UTF-8; format=flowed; delsp=yes\n"
+ + "\n"
+ + textContent;
@Override
public String raw() {
@@ -114,23 +114,25 @@
MailMessage.Builder expect = MailMessage.builder();
expect
.id("<001a114da7ae26e2eb053fe0c29c@google.com>")
- .from(new Address("Jonathan Nieder (Gerrit)",
- "noreply-gerritcodereview-CtTy0igsBrnvL7dKoWEIEg@google.com"))
- .addTo(new Address("ekempin","ekempin@google.com"))
+ .from(
+ new Address(
+ "Jonathan Nieder (Gerrit)",
+ "noreply-gerritcodereview-CtTy0igsBrnvL7dKoWEIEg@google.com"))
+ .addTo(new Address("ekempin", "ekempin@google.com"))
.addCc(new Address("Dave Borowitz", "dborowitz@google.com"))
.addCc(new Address("Jonathan Nieder", "jrn@google.com"))
.addCc(new Address("Patrick Hiesel", "hiesel@google.com"))
.textContent(textContent)
- .subject("Change in gerrit[master]: (Re)enable voting"
- + " buttons for merged changes")
- .dateReceived(
- new DateTime(2016, 10, 25, 9, 11, 35, 0, DateTimeZone.UTC))
- .addAdditionalHeader("Authentication-Results: mx.google.com; " +
- "dkim=pass header.i=@google.com;")
- .addAdditionalHeader("In-Reply-To: <gerrit.1477487889000.Iba501e00bee" +
- "77be3bd0ced72f88fd04ba0accaed@gerrit-review.googlesource.com>")
- .addAdditionalHeader("References: <gerrit.1477487889000.Iba501e00bee" +
- "77be3bd0ced72f88fd04ba0accaed@gerrit-review.googlesource.com>");
+ .subject("Change in gerrit[master]: (Re)enable voting" + " buttons for merged changes")
+ .dateReceived(new DateTime(2016, 10, 25, 9, 11, 35, 0, DateTimeZone.UTC))
+ .addAdditionalHeader(
+ "Authentication-Results: mx.google.com; " + "dkim=pass header.i=@google.com;")
+ .addAdditionalHeader(
+ "In-Reply-To: <gerrit.1477487889000.Iba501e00bee"
+ + "77be3bd0ced72f88fd04ba0accaed@gerrit-review.googlesource.com>")
+ .addAdditionalHeader(
+ "References: <gerrit.1477487889000.Iba501e00bee"
+ + "77be3bd0ced72f88fd04ba0accaed@gerrit-review.googlesource.com>");
return expect.build();
}
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/mail/send/CommentFormatterTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/mail/send/CommentFormatterTest.java
index ad06832..f4fbc78 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/mail/send/CommentFormatterTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/mail/send/CommentFormatterTest.java
@@ -20,13 +20,12 @@
import static com.google.gerrit.server.mail.send.CommentFormatter.BlockType.PRE_FORMATTED;
import static com.google.gerrit.server.mail.send.CommentFormatter.BlockType.QUOTE;
+import java.util.List;
import org.junit.Test;
-import java.util.List;
-
public class CommentFormatterTest {
- private void assertBlock(List<CommentFormatter.Block> list, int index,
- CommentFormatter.BlockType type, String text) {
+ private void assertBlock(
+ List<CommentFormatter.Block> list, int index, CommentFormatter.BlockType type, String text) {
CommentFormatter.Block block = list.get(index);
assertThat(block.type).isEqualTo(type);
assertThat(block.text).isEqualTo(text);
@@ -34,8 +33,8 @@
assertThat(block.quotedBlocks).isNull();
}
- private void assertListBlock(List<CommentFormatter.Block> list, int index,
- int itemIndex, String text) {
+ private void assertListBlock(
+ List<CommentFormatter.Block> list, int index, int itemIndex, String text) {
CommentFormatter.Block block = list.get(index);
assertThat(block.type).isEqualTo(LIST);
assertThat(block.items.get(itemIndex)).isEqualTo(text);
@@ -43,8 +42,7 @@
assertThat(block.quotedBlocks).isNull();
}
- private void assertQuoteBlock(List<CommentFormatter.Block> list, int index,
- int size) {
+ private void assertQuoteBlock(List<CommentFormatter.Block> list, int index, int size) {
CommentFormatter.Block block = list.get(index);
assertThat(block.type).isEqualTo(QUOTE);
assertThat(block.items).isNull();
@@ -128,8 +126,8 @@
assertThat(result).hasSize(1);
assertQuoteBlock(result, 0, 1);
- assertBlock(result.get(0).quotedBlocks, 0, PARAGRAPH,
- "Quote line 1\nQuote line 2\nQuote line 3\n");
+ assertBlock(
+ result.get(0).quotedBlocks, 0, PARAGRAPH, "Quote line 1\nQuote line 2\nQuote line 3\n");
}
@Test
@@ -204,26 +202,26 @@
@Test
public void parseMixedBlockTypes() {
- String comment = "Paragraph\nacross\na\nfew\nlines."
- + "\n\n"
- + "> Quote\n> across\n> not many lines."
- + "\n\n"
- + "Another paragraph"
- + "\n\n"
- + "* Series\n* of\n* list\n* items"
- + "\n\n"
- + "Yet another paragraph"
- + "\n\n"
- + "\tPreformatted text."
- + "\n\n"
- + "Parting words.";
+ String comment =
+ "Paragraph\nacross\na\nfew\nlines."
+ + "\n\n"
+ + "> Quote\n> across\n> not many lines."
+ + "\n\n"
+ + "Another paragraph"
+ + "\n\n"
+ + "* Series\n* of\n* list\n* items"
+ + "\n\n"
+ + "Yet another paragraph"
+ + "\n\n"
+ + "\tPreformatted text."
+ + "\n\n"
+ + "Parting words.";
List<CommentFormatter.Block> result = CommentFormatter.parse(comment);
assertThat(result).hasSize(7);
assertBlock(result, 0, PARAGRAPH, "Paragraph\nacross\na\nfew\nlines.");
assertQuoteBlock(result, 1, 1);
- assertBlock(result.get(1).quotedBlocks, 0, PARAGRAPH,
- "Quote\nacross\nnot many lines.");
+ assertBlock(result.get(1).quotedBlocks, 0, PARAGRAPH, "Quote\nacross\nnot many lines.");
assertBlock(result, 2, PARAGRAPH, "Another paragraph");
assertListBlock(result, 3, 0, "Series");
assertListBlock(result, 3, 1, "of");
@@ -270,9 +268,10 @@
@Test
public void bulletList4() {
- String comment = "To see this bug, you have to:\n" //
- + "* Be on IMAP or EAS (not on POP)\n"//
- + "* Be very unlucky\n";
+ String comment =
+ "To see this bug, you have to:\n" //
+ + "* Be on IMAP or EAS (not on POP)\n" //
+ + "* Be very unlucky\n";
List<CommentFormatter.Block> result = CommentFormatter.parse(comment);
assertThat(result).hasSize(2);
@@ -283,10 +282,11 @@
@Test
public void bulletList5() {
- String comment = "To see this bug,\n" //
- + "you have to:\n" //
- + "* Be on IMAP or EAS (not on POP)\n"//
- + "* Be very unlucky\n";
+ String comment =
+ "To see this bug,\n" //
+ + "you have to:\n" //
+ + "* Be on IMAP or EAS (not on POP)\n" //
+ + "* Be very unlucky\n";
List<CommentFormatter.Block> result = CommentFormatter.parse(comment);
assertThat(result).hasSize(2);
@@ -378,8 +378,7 @@
assertThat(result).hasSize(2);
assertQuoteBlock(result, 0, 1);
- assertBlock(result.get(0).quotedBlocks, 0, PARAGRAPH,
- "I'm happy\nwith quotes!");
+ assertBlock(result.get(0).quotedBlocks, 0, PARAGRAPH, "I'm happy\nwith quotes!");
assertBlock(result, 1, PARAGRAPH, "See above.");
}
@@ -391,8 +390,7 @@
assertThat(result).hasSize(3);
assertBlock(result, 0, PARAGRAPH, "See this said:");
assertQuoteBlock(result, 1, 1);
- assertBlock(result.get(1).quotedBlocks, 0, PARAGRAPH,
- "a quoted\nstring block");
+ assertBlock(result.get(1).quotedBlocks, 0, PARAGRAPH, "a quoted\nstring block");
assertBlock(result, 2, PARAGRAPH, "OK?");
}
@@ -404,41 +402,39 @@
assertThat(result).hasSize(1);
assertQuoteBlock(result, 0, 2);
assertQuoteBlock(result.get(0).quotedBlocks, 0, 1);
- assertBlock(result.get(0).quotedBlocks.get(0).quotedBlocks, 0, PARAGRAPH,
- "prior");
+ assertBlock(result.get(0).quotedBlocks.get(0).quotedBlocks, 0, PARAGRAPH, "prior");
assertBlock(result.get(0).quotedBlocks, 1, PARAGRAPH, "next\n");
}
@Test
public void largeMixedQuote() {
String comment =
- "> > Paragraph 1.\n" +
- "> > \n" +
- "> > > Paragraph 2.\n" +
- "> > \n" +
- "> > Paragraph 3.\n" +
- "> > \n" +
- "> > pre line 1;\n" +
- "> > pre line 2;\n" +
- "> > \n" +
- "> > Paragraph 4.\n" +
- "> > \n" +
- "> > * List item 1.\n" +
- "> > * List item 2.\n" +
- "> > \n" +
- "> > Paragraph 5.\n" +
- "> \n" +
- "> Paragraph 6.\n" +
- "\n" +
- "Paragraph 7.\n";
+ "> > Paragraph 1.\n"
+ + "> > \n"
+ + "> > > Paragraph 2.\n"
+ + "> > \n"
+ + "> > Paragraph 3.\n"
+ + "> > \n"
+ + "> > pre line 1;\n"
+ + "> > pre line 2;\n"
+ + "> > \n"
+ + "> > Paragraph 4.\n"
+ + "> > \n"
+ + "> > * List item 1.\n"
+ + "> > * List item 2.\n"
+ + "> > \n"
+ + "> > Paragraph 5.\n"
+ + "> \n"
+ + "> Paragraph 6.\n"
+ + "\n"
+ + "Paragraph 7.\n";
List<CommentFormatter.Block> result = CommentFormatter.parse(comment);
assertThat(result).hasSize(2);
assertQuoteBlock(result, 0, 2);
assertQuoteBlock(result.get(0).quotedBlocks, 0, 7);
- List<CommentFormatter.Block> bigQuote =
- result.get(0).quotedBlocks.get(0).quotedBlocks;
+ List<CommentFormatter.Block> bigQuote = result.get(0).quotedBlocks.get(0).quotedBlocks;
assertBlock(bigQuote, 0, PARAGRAPH, "Paragraph 1.");
assertQuoteBlock(bigQuote, 1, 1);
assertBlock(bigQuote.get(1).quotedBlocks, 0, PARAGRAPH, "Paragraph 2.");
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/mail/send/FromAddressGeneratorProviderTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/mail/send/FromAddressGeneratorProviderTest.java
index 33e34b6..ca8dc0c6 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/mail/send/FromAddressGeneratorProviderTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/mail/send/FromAddressGeneratorProviderTest.java
@@ -30,17 +30,15 @@
import com.google.gerrit.server.account.WatchConfig.NotifyType;
import com.google.gerrit.server.account.WatchConfig.ProjectWatchKey;
import com.google.gerrit.server.mail.Address;
-
-import org.eclipse.jgit.lib.Config;
-import org.eclipse.jgit.lib.PersonIdent;
-import org.junit.Before;
-import org.junit.Test;
-
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
+import org.eclipse.jgit.lib.Config;
+import org.eclipse.jgit.lib.PersonIdent;
+import org.junit.Before;
+import org.junit.Test;
public class FromAddressGeneratorProviderTest {
private Config config;
@@ -55,8 +53,7 @@
}
private FromAddressGenerator create() {
- return new FromAddressGeneratorProvider(config, "Anonymous Coward", ident,
- accountCache).get();
+ return new FromAddressGeneratorProvider(config, "Anonymous Coward", ident, accountCache).get();
}
private void setFrom(final String newFrom) {
@@ -390,8 +387,10 @@
final Account account = new Account(userId, TimeUtil.nowTs());
account.setFullName(name);
account.setPreferredEmail(email);
- return new AccountState(account, Collections.<AccountGroup.UUID> emptySet(),
- Collections.<AccountExternalId> emptySet(),
+ return new AccountState(
+ account,
+ Collections.<AccountGroup.UUID>emptySet(),
+ Collections.<AccountExternalId>emptySet(),
new HashMap<ProjectWatchKey, Set<NotifyType>>());
}
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/notedb/AbstractChangeNotesTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/notedb/AbstractChangeNotesTest.java
index d827e6c..be153c9 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/notedb/AbstractChangeNotesTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/notedb/AbstractChangeNotesTest.java
@@ -64,7 +64,8 @@
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.util.Providers;
-
+import java.sql.Timestamp;
+import java.util.TimeZone;
import org.eclipse.jgit.internal.storage.dfs.InMemoryRepository;
import org.eclipse.jgit.junit.TestRepository;
import org.eclipse.jgit.lib.Config;
@@ -75,9 +76,6 @@
import org.junit.Ignore;
import org.junit.runner.RunWith;
-import java.sql.Timestamp;
-import java.util.TimeZone;
-
@Ignore
@RunWith(ConfigSuite.class)
public abstract class AbstractChangeNotesTest extends GerritBaseTests {
@@ -95,14 +93,11 @@
return cfg;
}
- @ConfigSuite.Parameter
- public Config testConfig;
+ @ConfigSuite.Parameter public Config testConfig;
- private static final TimeZone TZ =
- TimeZone.getTimeZone("America/Los_Angeles");
+ private static final TimeZone TZ = TimeZone.getTimeZone("America/Los_Angeles");
- private static final NotesMigration MIGRATION =
- new TestNotesMigration().setAllEnabled(true);
+ private static final NotesMigration MIGRATION = new TestNotesMigration().setAllEnabled(true);
protected Account.Id otherUserId;
protected FakeAccountCache accountCache;
@@ -116,21 +111,15 @@
protected RevWalk rw;
protected TestRepository<InMemoryRepository> tr;
- @Inject
- protected IdentifiedUser.GenericFactory userFactory;
+ @Inject protected IdentifiedUser.GenericFactory userFactory;
- @Inject
- protected NoteDbUpdateManager.Factory updateManagerFactory;
+ @Inject protected NoteDbUpdateManager.Factory updateManagerFactory;
- @Inject
- protected AllUsersName allUsers;
+ @Inject protected AllUsersName allUsers;
- @Inject
- protected AbstractChangeNotes.Args args;
+ @Inject protected AbstractChangeNotes.Args args;
- @Inject
- @GerritServerId
- private String serverId;
+ @Inject @GerritServerId private String serverId;
protected Injector injector;
private String systemTimeZone;
@@ -139,8 +128,7 @@
public void setUp() throws Exception {
setTimeForTesting();
- serverIdent = new PersonIdent(
- "Gerrit Server", "noreply@gerrit.com", TimeUtil.nowTs(), TZ);
+ serverIdent = new PersonIdent("Gerrit Server", "noreply@gerrit.com", TimeUtil.nowTs(), TZ);
project = new Project.NameKey("test-project");
repoManager = new InMemoryRepositoryManager();
repo = repoManager.createRepository(project);
@@ -156,38 +144,41 @@
ou.setPreferredEmail("other@account.com");
accountCache.put(ou);
- injector = Guice.createInjector(new FactoryModule() {
- @Override
- public void configure() {
- install(new GitModule());
- install(NoteDbModule.forTest(testConfig));
- bind(AllUsersName.class).toProvider(AllUsersNameProvider.class);
- bind(String.class).annotatedWith(GerritServerId.class)
- .toInstance("gerrit");
- bind(NotesMigration.class).toInstance(MIGRATION);
- bind(GitRepositoryManager.class).toInstance(repoManager);
- bind(ProjectCache.class).toProvider(Providers.<ProjectCache> of(null));
- bind(CapabilityControl.Factory.class)
- .toProvider(Providers.<CapabilityControl.Factory> of(null));
- bind(Config.class).annotatedWith(GerritServerConfig.class)
- .toInstance(testConfig);
- bind(String.class).annotatedWith(AnonymousCowardName.class)
- .toProvider(AnonymousCowardNameProvider.class);
- bind(String.class).annotatedWith(CanonicalWebUrl.class)
- .toInstance("http://localhost:8080/");
- bind(Boolean.class).annotatedWith(DisableReverseDnsLookup.class)
- .toInstance(Boolean.FALSE);
- bind(Realm.class).to(FakeRealm.class);
- bind(GroupBackend.class).to(SystemGroupBackend.class).in(SINGLETON);
- bind(AccountCache.class).toInstance(accountCache);
- bind(PersonIdent.class).annotatedWith(GerritPersonIdent.class)
- .toInstance(serverIdent);
- bind(GitReferenceUpdated.class)
- .toInstance(GitReferenceUpdated.DISABLED);
- bind(MetricMaker.class).to(DisabledMetricMaker.class);
- bind(ReviewDb.class).toProvider(Providers.<ReviewDb> of(null));
- }
- });
+ injector =
+ Guice.createInjector(
+ new FactoryModule() {
+ @Override
+ public void configure() {
+ install(new GitModule());
+ install(NoteDbModule.forTest(testConfig));
+ bind(AllUsersName.class).toProvider(AllUsersNameProvider.class);
+ bind(String.class).annotatedWith(GerritServerId.class).toInstance("gerrit");
+ bind(NotesMigration.class).toInstance(MIGRATION);
+ bind(GitRepositoryManager.class).toInstance(repoManager);
+ bind(ProjectCache.class).toProvider(Providers.<ProjectCache>of(null));
+ bind(CapabilityControl.Factory.class)
+ .toProvider(Providers.<CapabilityControl.Factory>of(null));
+ bind(Config.class).annotatedWith(GerritServerConfig.class).toInstance(testConfig);
+ bind(String.class)
+ .annotatedWith(AnonymousCowardName.class)
+ .toProvider(AnonymousCowardNameProvider.class);
+ bind(String.class)
+ .annotatedWith(CanonicalWebUrl.class)
+ .toInstance("http://localhost:8080/");
+ bind(Boolean.class)
+ .annotatedWith(DisableReverseDnsLookup.class)
+ .toInstance(Boolean.FALSE);
+ bind(Realm.class).to(FakeRealm.class);
+ bind(GroupBackend.class).to(SystemGroupBackend.class).in(SINGLETON);
+ bind(AccountCache.class).toInstance(accountCache);
+ bind(PersonIdent.class)
+ .annotatedWith(GerritPersonIdent.class)
+ .toInstance(serverIdent);
+ bind(GitReferenceUpdated.class).toInstance(GitReferenceUpdated.DISABLED);
+ bind(MetricMaker.class).to(DisabledMetricMaker.class);
+ bind(ReviewDb.class).toProvider(Providers.<ReviewDb>of(null));
+ }
+ });
injector.injectMembers(this);
repoManager.createRepository(allUsers);
@@ -217,8 +208,7 @@
return c;
}
- protected ChangeUpdate newUpdate(Change c, CurrentUser user)
- throws Exception {
+ protected ChangeUpdate newUpdate(Change c, CurrentUser user) throws Exception {
ChangeUpdate update = TestChanges.newUpdate(injector, c, user);
update.setPatchSetId(c.currentPatchSetId());
update.setAllowWriteToNewRef(true);
@@ -229,8 +219,8 @@
return new ChangeNotes(args, c).load();
}
- protected static SubmitRecord submitRecord(String status,
- String errorMessage, SubmitRecord.Label... labels) {
+ protected static SubmitRecord submitRecord(
+ String status, String errorMessage, SubmitRecord.Label... labels) {
SubmitRecord rec = new SubmitRecord();
rec.status = SubmitRecord.Status.valueOf(status);
rec.errorMessage = errorMessage;
@@ -240,8 +230,8 @@
return rec;
}
- protected static SubmitRecord.Label submitLabel(String name, String status,
- Account.Id appliedBy) {
+ protected static SubmitRecord.Label submitLabel(
+ String name, String status, Account.Id appliedBy) {
SubmitRecord.Label label = new SubmitRecord.Label();
label.label = name;
label.status = SubmitRecord.Label.Status.valueOf(status);
@@ -249,24 +239,33 @@
return label;
}
- protected Comment newComment(PatchSet.Id psId, String filename, String UUID,
- CommentRange range, int line, IdentifiedUser commenter, String parentUUID,
- Timestamp t, String message, short side, String commitSHA1,
+ protected Comment newComment(
+ PatchSet.Id psId,
+ String filename,
+ String UUID,
+ CommentRange range,
+ int line,
+ IdentifiedUser commenter,
+ String parentUUID,
+ Timestamp t,
+ String message,
+ short side,
+ String commitSHA1,
boolean unresolved) {
- Comment c = new Comment(
- new Comment.Key(UUID, filename, psId.get()),
- commenter.getAccountId(),
- t,
- side,
- message,
- serverId,
- unresolved);
+ Comment c =
+ new Comment(
+ new Comment.Key(UUID, filename, psId.get()),
+ commenter.getAccountId(),
+ t,
+ side,
+ message,
+ serverId,
+ unresolved);
c.lineNbr = line;
c.parentUuid = parentUUID;
c.revId = commitSHA1;
c.setRange(range);
return c;
-
}
protected static Timestamp truncate(Timestamp ts) {
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/notedb/ChangeBundleTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/notedb/ChangeBundleTest.java
index f9c2c42..a3f8a76 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/notedb/ChangeBundleTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/notedb/ChangeBundleTest.java
@@ -45,31 +45,28 @@
import com.google.gerrit.testutil.TestTimeUtil;
import com.google.gwtorm.protobuf.CodecFactory;
import com.google.gwtorm.protobuf.ProtobufCodec;
-
-import org.joda.time.DateTime;
-import org.joda.time.DateTimeZone;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.TimeZone;
+import org.joda.time.DateTime;
+import org.joda.time.DateTimeZone;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
public class ChangeBundleTest extends GerritBaseTests {
- private static final ProtobufCodec<Change> CHANGE_CODEC =
- CodecFactory.encoder(Change.class);
+ private static final ProtobufCodec<Change> CHANGE_CODEC = CodecFactory.encoder(Change.class);
private static final ProtobufCodec<ChangeMessage> CHANGE_MESSAGE_CODEC =
CodecFactory.encoder(ChangeMessage.class);
private static final ProtobufCodec<PatchSet> PATCH_SET_CODEC =
CodecFactory.encoder(PatchSet.class);
- private static final ProtobufCodec<PatchSetApproval>
- PATCH_SET_APPROVAL_CODEC = CodecFactory.encoder(PatchSetApproval.class);
- private static final ProtobufCodec<PatchLineComment>
- PATCH_LINE_COMMENT_CODEC = CodecFactory.encoder(PatchLineComment.class);
+ private static final ProtobufCodec<PatchSetApproval> PATCH_SET_APPROVAL_CODEC =
+ CodecFactory.encoder(PatchSetApproval.class);
+ private static final ProtobufCodec<PatchLineComment> PATCH_LINE_COMMENT_CODEC =
+ CodecFactory.encoder(PatchLineComment.class);
private String systemTimeZoneProperty;
private TimeZone systemTimeZone;
@@ -98,8 +95,7 @@
}
private void superWindowResolution() {
- TestTimeUtil.setClockStep(
- ChangeRebuilderImpl.MAX_WINDOW_MS * 2, MILLISECONDS);
+ TestTimeUtil.setClockStep(ChangeRebuilderImpl.MAX_WINDOW_MS * 2, MILLISECONDS);
TimeUtil.nowTs();
}
@@ -114,61 +110,73 @@
int id1 = c1.getId().get();
Change c2 = TestChanges.newChange(project, accountId);
int id2 = c2.getId().get();
- ChangeBundle b1 = new ChangeBundle(c1, messages(), patchSets(), approvals(),
- comments(), reviewers(), REVIEW_DB);
- ChangeBundle b2 = new ChangeBundle(c2, messages(), patchSets(), approvals(),
- comments(), reviewers(), REVIEW_DB);
+ ChangeBundle b1 =
+ new ChangeBundle(
+ c1, messages(), patchSets(), approvals(), comments(), reviewers(), REVIEW_DB);
+ ChangeBundle b2 =
+ new ChangeBundle(
+ c2, messages(), patchSets(), approvals(), comments(), reviewers(), REVIEW_DB);
- assertDiffs(b1, b2,
+ assertDiffs(
+ b1,
+ b2,
"changeId differs for Changes: {" + id1 + "} != {" + id2 + "}",
- "createdOn differs for Changes:"
- + " {2009-09-30 17:00:00.0} != {2009-09-30 17:00:06.0}",
+ "createdOn differs for Changes:" + " {2009-09-30 17:00:00.0} != {2009-09-30 17:00:06.0}",
"effective last updated time differs for Changes:"
+ " {2009-09-30 17:00:00.0} != {2009-09-30 17:00:06.0}");
}
@Test
public void diffChangesSameId() throws Exception {
- Change c1 = TestChanges.newChange(
- new Project.NameKey("project"), new Account.Id(100));
+ Change c1 = TestChanges.newChange(new Project.NameKey("project"), new Account.Id(100));
Change c2 = clone(c1);
- ChangeBundle b1 = new ChangeBundle(c1, messages(), patchSets(), approvals(),
- comments(), reviewers(), REVIEW_DB);
- ChangeBundle b2 = new ChangeBundle(c2, messages(), patchSets(), approvals(),
- comments(), reviewers(), REVIEW_DB);
+ ChangeBundle b1 =
+ new ChangeBundle(
+ c1, messages(), patchSets(), approvals(), comments(), reviewers(), REVIEW_DB);
+ ChangeBundle b2 =
+ new ChangeBundle(
+ c2, messages(), patchSets(), approvals(), comments(), reviewers(), REVIEW_DB);
assertNoDiffs(b1, b2);
c2.setTopic("topic");
- assertDiffs(b1, b2,
- "topic differs for Change.Id " + c1.getId() + ": {null} != {topic}");
+ assertDiffs(b1, b2, "topic differs for Change.Id " + c1.getId() + ": {null} != {topic}");
}
@Test
public void diffChangesMixedSourcesAllowsSlop() throws Exception {
subWindowResolution();
- Change c1 = TestChanges.newChange(
- new Project.NameKey("project"), new Account.Id(100));
+ Change c1 = TestChanges.newChange(new Project.NameKey("project"), new Account.Id(100));
Change c2 = clone(c1);
c2.setCreatedOn(TimeUtil.nowTs());
c2.setLastUpdatedOn(TimeUtil.nowTs());
// Both are ReviewDb, exact timestamp match is required.
- ChangeBundle b1 = new ChangeBundle(c1, messages(), patchSets(),
- approvals(), comments(), reviewers(), REVIEW_DB);
- ChangeBundle b2 = new ChangeBundle(c2, messages(), patchSets(),
- approvals(), comments(), reviewers(), REVIEW_DB);
- assertDiffs(b1, b2,
- "createdOn differs for Change.Id " + c1.getId() + ":"
+ ChangeBundle b1 =
+ new ChangeBundle(
+ c1, messages(), patchSets(), approvals(), comments(), reviewers(), REVIEW_DB);
+ ChangeBundle b2 =
+ new ChangeBundle(
+ c2, messages(), patchSets(), approvals(), comments(), reviewers(), REVIEW_DB);
+ assertDiffs(
+ b1,
+ b2,
+ "createdOn differs for Change.Id "
+ + c1.getId()
+ + ":"
+ " {2009-09-30 17:00:01.0} != {2009-09-30 17:00:02.0}",
- "effective last updated time differs for Change.Id " + c1.getId() + ":"
+ "effective last updated time differs for Change.Id "
+ + c1.getId()
+ + ":"
+ " {2009-09-30 17:00:01.0} != {2009-09-30 17:00:03.0}");
// One NoteDb, slop is allowed.
- b1 = new ChangeBundle(c1, messages(), patchSets(), approvals(),
- comments(), reviewers(), NOTE_DB);
- b2 = new ChangeBundle(c2, messages(), patchSets(), approvals(),
- comments(), reviewers(), REVIEW_DB);
+ b1 =
+ new ChangeBundle(
+ c1, messages(), patchSets(), approvals(), comments(), reviewers(), NOTE_DB);
+ b2 =
+ new ChangeBundle(
+ c2, messages(), patchSets(), approvals(), comments(), reviewers(), REVIEW_DB);
assertNoDiffs(b1, b2);
assertNoDiffs(b2, b1);
@@ -176,194 +184,215 @@
superWindowResolution();
Change c3 = clone(c1);
c3.setLastUpdatedOn(TimeUtil.nowTs());
- b1 = new ChangeBundle(c1, messages(), patchSets(), approvals(),
- comments(), reviewers(), NOTE_DB);
- ChangeBundle b3 = new ChangeBundle(c3, messages(), patchSets(), approvals(),
- comments(), reviewers(), REVIEW_DB);
- String msg = "effective last updated time differs for Change.Id "
- + c1.getId() + " in NoteDb vs. ReviewDb:"
- + " {2009-09-30 17:00:01.0} != {2009-09-30 17:00:10.0}";
+ b1 =
+ new ChangeBundle(
+ c1, messages(), patchSets(), approvals(), comments(), reviewers(), NOTE_DB);
+ ChangeBundle b3 =
+ new ChangeBundle(
+ c3, messages(), patchSets(), approvals(), comments(), reviewers(), REVIEW_DB);
+ String msg =
+ "effective last updated time differs for Change.Id "
+ + c1.getId()
+ + " in NoteDb vs. ReviewDb:"
+ + " {2009-09-30 17:00:01.0} != {2009-09-30 17:00:10.0}";
assertDiffs(b1, b3, msg);
assertDiffs(b3, b1, msg);
}
@Test
- public void diffChangesIgnoresOriginalSubjectInReviewDb()
- throws Exception {
- Change c1 = TestChanges.newChange(
- new Project.NameKey("project"), new Account.Id(100));
+ public void diffChangesIgnoresOriginalSubjectInReviewDb() throws Exception {
+ Change c1 = TestChanges.newChange(new Project.NameKey("project"), new Account.Id(100));
c1.setCurrentPatchSet(c1.currentPatchSetId(), "Subject", "Original A");
Change c2 = clone(c1);
- c2.setCurrentPatchSet(
- c2.currentPatchSetId(), c1.getSubject(), "Original B");
+ c2.setCurrentPatchSet(c2.currentPatchSetId(), c1.getSubject(), "Original B");
// Both ReviewDb, exact match required.
- ChangeBundle b1 = new ChangeBundle(c1, messages(), patchSets(), approvals(),
- comments(), reviewers(), REVIEW_DB);
- ChangeBundle b2 = new ChangeBundle(c2, messages(), patchSets(), approvals(),
- comments(), reviewers(), REVIEW_DB);
- assertDiffs(b1, b2,
- "originalSubject differs for Change.Id " + c1.getId() + ":"
+ ChangeBundle b1 =
+ new ChangeBundle(
+ c1, messages(), patchSets(), approvals(), comments(), reviewers(), REVIEW_DB);
+ ChangeBundle b2 =
+ new ChangeBundle(
+ c2, messages(), patchSets(), approvals(), comments(), reviewers(), REVIEW_DB);
+ assertDiffs(
+ b1,
+ b2,
+ "originalSubject differs for Change.Id "
+ + c1.getId()
+ + ":"
+ " {Original A} != {Original B}");
// Both NoteDb, exact match required.
- b1 = new ChangeBundle(c1, messages(), patchSets(), approvals(), comments(),
- reviewers(), NOTE_DB);
- b2 = new ChangeBundle(c2, messages(), patchSets(), approvals(), comments(),
- reviewers(), NOTE_DB);
- assertDiffs(b1, b2,
- "originalSubject differs for Change.Id " + c1.getId() + ":"
+ b1 =
+ new ChangeBundle(
+ c1, messages(), patchSets(), approvals(), comments(), reviewers(), NOTE_DB);
+ b2 =
+ new ChangeBundle(
+ c2, messages(), patchSets(), approvals(), comments(), reviewers(), NOTE_DB);
+ assertDiffs(
+ b1,
+ b2,
+ "originalSubject differs for Change.Id "
+ + c1.getId()
+ + ":"
+ " {Original A} != {Original B}");
// One ReviewDb, one NoteDb, original subject is ignored.
- b1 = new ChangeBundle(c1, messages(), patchSets(), approvals(), comments(),
- reviewers(), REVIEW_DB);
- b2 = new ChangeBundle(c2, messages(), patchSets(), approvals(), comments(),
- reviewers(), NOTE_DB);
+ b1 =
+ new ChangeBundle(
+ c1, messages(), patchSets(), approvals(), comments(), reviewers(), REVIEW_DB);
+ b2 =
+ new ChangeBundle(
+ c2, messages(), patchSets(), approvals(), comments(), reviewers(), NOTE_DB);
assertNoDiffs(b1, b2);
assertNoDiffs(b2, b1);
}
@Test
- public void diffChangesConsidersEmptyReviewDbTopicEquivalentToNullInNoteDb()
- throws Exception {
- Change c1 = TestChanges.newChange(
- new Project.NameKey("project"), new Account.Id(100));
+ public void diffChangesConsidersEmptyReviewDbTopicEquivalentToNullInNoteDb() throws Exception {
+ Change c1 = TestChanges.newChange(new Project.NameKey("project"), new Account.Id(100));
c1.setTopic("");
Change c2 = clone(c1);
c2.setTopic(null);
// Both ReviewDb, exact match required.
- ChangeBundle b1 = new ChangeBundle(c1, messages(), patchSets(), approvals(),
- comments(), reviewers(), REVIEW_DB);
- ChangeBundle b2 = new ChangeBundle(c2, messages(), patchSets(), approvals(),
- comments(), reviewers(), REVIEW_DB);
- assertDiffs(b1, b2,
- "topic differs for Change.Id " + c1.getId() + ":"
- + " {} != {null}");
+ ChangeBundle b1 =
+ new ChangeBundle(
+ c1, messages(), patchSets(), approvals(), comments(), reviewers(), REVIEW_DB);
+ ChangeBundle b2 =
+ new ChangeBundle(
+ c2, messages(), patchSets(), approvals(), comments(), reviewers(), REVIEW_DB);
+ assertDiffs(b1, b2, "topic differs for Change.Id " + c1.getId() + ":" + " {} != {null}");
// Topic ignored if ReviewDb is empty and NoteDb is null.
- b1 = new ChangeBundle(c1, messages(), patchSets(), approvals(), comments(),
- reviewers(), REVIEW_DB);
- b2 = new ChangeBundle(c2, messages(), patchSets(), approvals(), comments(),
- reviewers(), NOTE_DB);
+ b1 =
+ new ChangeBundle(
+ c1, messages(), patchSets(), approvals(), comments(), reviewers(), REVIEW_DB);
+ b2 =
+ new ChangeBundle(
+ c2, messages(), patchSets(), approvals(), comments(), reviewers(), NOTE_DB);
assertNoDiffs(b1, b2);
// Exact match still required if NoteDb has empty value (not realistic).
- b1 = new ChangeBundle(c1, messages(), patchSets(), approvals(), comments(),
- reviewers(), NOTE_DB);
- b2 = new ChangeBundle(c2, messages(), patchSets(), approvals(), comments(),
- reviewers(), REVIEW_DB);
- assertDiffs(b1, b2,
- "topic differs for Change.Id " + c1.getId() + ":"
- + " {} != {null}");
+ b1 =
+ new ChangeBundle(
+ c1, messages(), patchSets(), approvals(), comments(), reviewers(), NOTE_DB);
+ b2 =
+ new ChangeBundle(
+ c2, messages(), patchSets(), approvals(), comments(), reviewers(), REVIEW_DB);
+ assertDiffs(b1, b2, "topic differs for Change.Id " + c1.getId() + ":" + " {} != {null}");
// Null is not equal to a non-empty string.
Change c3 = clone(c1);
c3.setTopic("topic");
- b1 = new ChangeBundle(c3, messages(), patchSets(), approvals(), comments(),
- reviewers(), REVIEW_DB);
- b2 = new ChangeBundle(c2, messages(), patchSets(), approvals(), comments(),
- reviewers(), NOTE_DB);
- assertDiffs(b1, b2,
- "topic differs for Change.Id " + c1.getId() + ":"
- + " {topic} != {null}");
+ b1 =
+ new ChangeBundle(
+ c3, messages(), patchSets(), approvals(), comments(), reviewers(), REVIEW_DB);
+ b2 =
+ new ChangeBundle(
+ c2, messages(), patchSets(), approvals(), comments(), reviewers(), NOTE_DB);
+ assertDiffs(b1, b2, "topic differs for Change.Id " + c1.getId() + ":" + " {topic} != {null}");
// Null is equal to a string that is all whitespace.
Change c4 = clone(c1);
c4.setTopic(" ");
- b1 = new ChangeBundle(c4, messages(), patchSets(), approvals(), comments(),
- reviewers(), REVIEW_DB);
- b2 = new ChangeBundle(c2, messages(), patchSets(), approvals(), comments(),
- reviewers(), NOTE_DB);
+ b1 =
+ new ChangeBundle(
+ c4, messages(), patchSets(), approvals(), comments(), reviewers(), REVIEW_DB);
+ b2 =
+ new ChangeBundle(
+ c2, messages(), patchSets(), approvals(), comments(), reviewers(), NOTE_DB);
assertNoDiffs(b1, b2);
assertNoDiffs(b2, b1);
}
@Test
- public void diffChangesIgnoresLeadingWhitespaceInReviewDbTopics()
- throws Exception {
- Change c1 = TestChanges.newChange(
- new Project.NameKey("project"), new Account.Id(100));
+ public void diffChangesIgnoresLeadingWhitespaceInReviewDbTopics() throws Exception {
+ Change c1 = TestChanges.newChange(new Project.NameKey("project"), new Account.Id(100));
c1.setTopic(" abc");
Change c2 = clone(c1);
c2.setTopic("abc");
// Both ReviewDb, exact match required.
- ChangeBundle b1 = new ChangeBundle(c1, messages(), patchSets(), approvals(),
- comments(), reviewers(), REVIEW_DB);
- ChangeBundle b2 = new ChangeBundle(c2, messages(), patchSets(), approvals(),
- comments(), reviewers(), REVIEW_DB);
- assertDiffs(b1, b2,
- "topic differs for Change.Id " + c1.getId() + ":"
- + " { abc} != {abc}");
+ ChangeBundle b1 =
+ new ChangeBundle(
+ c1, messages(), patchSets(), approvals(), comments(), reviewers(), REVIEW_DB);
+ ChangeBundle b2 =
+ new ChangeBundle(
+ c2, messages(), patchSets(), approvals(), comments(), reviewers(), REVIEW_DB);
+ assertDiffs(b1, b2, "topic differs for Change.Id " + c1.getId() + ":" + " { abc} != {abc}");
// Leading whitespace in ReviewDb topic is ignored.
- b1 = new ChangeBundle(c1, messages(), patchSets(), approvals(), comments(),
- reviewers(), REVIEW_DB);
- b2 = new ChangeBundle(c2, messages(), patchSets(), approvals(), comments(),
- reviewers(), NOTE_DB);
+ b1 =
+ new ChangeBundle(
+ c1, messages(), patchSets(), approvals(), comments(), reviewers(), REVIEW_DB);
+ b2 =
+ new ChangeBundle(
+ c2, messages(), patchSets(), approvals(), comments(), reviewers(), NOTE_DB);
assertNoDiffs(b1, b2);
assertNoDiffs(b2, b1);
// Must match except for the leading whitespace.
Change c3 = clone(c1);
c3.setTopic("cba");
- b1 = new ChangeBundle(c1, messages(), patchSets(), approvals(), comments(),
- reviewers(), REVIEW_DB);
- b2 = new ChangeBundle(c3, messages(), patchSets(), approvals(), comments(),
- reviewers(), NOTE_DB);
- assertDiffs(b1, b2,
- "topic differs for Change.Id " + c1.getId() + ":"
- + " { abc} != {cba}");
+ b1 =
+ new ChangeBundle(
+ c1, messages(), patchSets(), approvals(), comments(), reviewers(), REVIEW_DB);
+ b2 =
+ new ChangeBundle(
+ c3, messages(), patchSets(), approvals(), comments(), reviewers(), NOTE_DB);
+ assertDiffs(b1, b2, "topic differs for Change.Id " + c1.getId() + ":" + " { abc} != {cba}");
}
@Test
- public void diffChangesTakesMaxEntityTimestampFromReviewDb()
- throws Exception {
- Change c1 = TestChanges.newChange(
- new Project.NameKey("project"), new Account.Id(100));
+ public void diffChangesTakesMaxEntityTimestampFromReviewDb() throws Exception {
+ Change c1 = TestChanges.newChange(new Project.NameKey("project"), new Account.Id(100));
PatchSet ps = new PatchSet(c1.currentPatchSetId());
ps.setRevision(new RevId("deadbeefdeadbeefdeadbeefdeadbeefdeadbeef"));
ps.setUploader(accountId);
ps.setCreatedOn(TimeUtil.nowTs());
- PatchSetApproval a = new PatchSetApproval(
- new PatchSetApproval.Key(
- c1.currentPatchSetId(), accountId, new LabelId("Code-Review")),
- (short) 1,
- TimeUtil.nowTs());
+ PatchSetApproval a =
+ new PatchSetApproval(
+ new PatchSetApproval.Key(c1.currentPatchSetId(), accountId, new LabelId("Code-Review")),
+ (short) 1,
+ TimeUtil.nowTs());
Change c2 = clone(c1);
c2.setLastUpdatedOn(a.getGranted());
// Both ReviewDb, exact match required.
- ChangeBundle b1 = new ChangeBundle(c1, messages(), patchSets(ps),
- approvals(a), comments(), reviewers(), REVIEW_DB);
- ChangeBundle b2 = new ChangeBundle(c2, messages(), patchSets(ps),
- approvals(a), comments(), reviewers(), REVIEW_DB);
- assertDiffs(b1, b2,
- "effective last updated time differs for Change.Id " + c1.getId() + ":"
+ ChangeBundle b1 =
+ new ChangeBundle(
+ c1, messages(), patchSets(ps), approvals(a), comments(), reviewers(), REVIEW_DB);
+ ChangeBundle b2 =
+ new ChangeBundle(
+ c2, messages(), patchSets(ps), approvals(a), comments(), reviewers(), REVIEW_DB);
+ assertDiffs(
+ b1,
+ b2,
+ "effective last updated time differs for Change.Id "
+ + c1.getId()
+ + ":"
+ " {2009-09-30 17:00:00.0} != {2009-09-30 17:00:12.0}");
// NoteDb allows latest timestamp from all entities in bundle.
- b2 = new ChangeBundle(c2, messages(), patchSets(ps),
- approvals(a), comments(), reviewers(), NOTE_DB);
+ b2 =
+ new ChangeBundle(
+ c2, messages(), patchSets(ps), approvals(a), comments(), reviewers(), NOTE_DB);
assertNoDiffs(b1, b2);
}
@Test
public void diffChangesIgnoresChangeTimestampIfAnyOtherEntitiesExist() {
- Change c1 = TestChanges.newChange(
- new Project.NameKey("project"), new Account.Id(100));
+ Change c1 = TestChanges.newChange(new Project.NameKey("project"), new Account.Id(100));
PatchSet ps = new PatchSet(c1.currentPatchSetId());
ps.setRevision(new RevId("deadbeefdeadbeefdeadbeefdeadbeefdeadbeef"));
ps.setUploader(accountId);
ps.setCreatedOn(TimeUtil.nowTs());
- PatchSetApproval a = new PatchSetApproval(
- new PatchSetApproval.Key(
- c1.currentPatchSetId(), accountId, new LabelId("Code-Review")),
- (short) 1,
- TimeUtil.nowTs());
+ PatchSetApproval a =
+ new PatchSetApproval(
+ new PatchSetApproval.Key(c1.currentPatchSetId(), accountId, new LabelId("Code-Review")),
+ (short) 1,
+ TimeUtil.nowTs());
c1.setLastUpdatedOn(a.getGranted());
Change c2 = clone(c1);
@@ -371,116 +400,144 @@
// ReviewDb has later lastUpdatedOn timestamp than NoteDb, allowed since
// NoteDb matches the latest timestamp of a non-Change entity.
- ChangeBundle b1 = new ChangeBundle(c2, messages(), patchSets(ps),
- approvals(a), comments(), reviewers(), REVIEW_DB);
- ChangeBundle b2 = new ChangeBundle(c1, messages(), patchSets(ps),
- approvals(a), comments(), reviewers(), NOTE_DB);
- assertThat(b1.getChange().getLastUpdatedOn())
- .isGreaterThan(b2.getChange().getLastUpdatedOn());
+ ChangeBundle b1 =
+ new ChangeBundle(
+ c2, messages(), patchSets(ps), approvals(a), comments(), reviewers(), REVIEW_DB);
+ ChangeBundle b2 =
+ new ChangeBundle(
+ c1, messages(), patchSets(ps), approvals(a), comments(), reviewers(), NOTE_DB);
+ assertThat(b1.getChange().getLastUpdatedOn()).isGreaterThan(b2.getChange().getLastUpdatedOn());
assertNoDiffs(b1, b2);
// Timestamps must actually match if Change is the only entity.
- b1 = new ChangeBundle(c2, messages(), patchSets(), approvals(), comments(),
- reviewers(), REVIEW_DB);
- b2 = new ChangeBundle(c1, messages(), patchSets(), approvals(), comments(),
- reviewers(), NOTE_DB);
- assertDiffs(b1, b2,
- "effective last updated time differs for Change.Id " + c1.getId()
+ b1 =
+ new ChangeBundle(
+ c2, messages(), patchSets(), approvals(), comments(), reviewers(), REVIEW_DB);
+ b2 =
+ new ChangeBundle(
+ c1, messages(), patchSets(), approvals(), comments(), reviewers(), NOTE_DB);
+ assertDiffs(
+ b1,
+ b2,
+ "effective last updated time differs for Change.Id "
+ + c1.getId()
+ " in NoteDb vs. ReviewDb:"
+ " {2009-09-30 17:00:12.0} != {2009-09-30 17:00:18.0}");
}
@Test
- public void diffChangesAllowsReviewDbSubjectToBePrefixOfNoteDbSubject()
- throws Exception {
- Change c1 = TestChanges.newChange(
- new Project.NameKey("project"), new Account.Id(100));
+ public void diffChangesAllowsReviewDbSubjectToBePrefixOfNoteDbSubject() throws Exception {
+ Change c1 = TestChanges.newChange(new Project.NameKey("project"), new Account.Id(100));
Change c2 = clone(c1);
- c2.setCurrentPatchSet(c1.currentPatchSetId(),
- c1.getSubject().substring(0, 10), c1.getOriginalSubject());
+ c2.setCurrentPatchSet(
+ c1.currentPatchSetId(), c1.getSubject().substring(0, 10), c1.getOriginalSubject());
assertThat(c2.getSubject()).isNotEqualTo(c1.getSubject());
// Both ReviewDb, exact match required.
- ChangeBundle b1 = new ChangeBundle(c1, messages(), patchSets(), approvals(),
- comments(), reviewers(), REVIEW_DB);
- ChangeBundle b2 = new ChangeBundle(c2, messages(), patchSets(), approvals(),
- comments(), reviewers(), REVIEW_DB);
- assertDiffs(b1, b2,
- "subject differs for Change.Id " + c1.getId() + ":"
- + " {Change subject} != {Change sub}");
+ ChangeBundle b1 =
+ new ChangeBundle(
+ c1, messages(), patchSets(), approvals(), comments(), reviewers(), REVIEW_DB);
+ ChangeBundle b2 =
+ new ChangeBundle(
+ c2, messages(), patchSets(), approvals(), comments(), reviewers(), REVIEW_DB);
+ assertDiffs(
+ b1,
+ b2,
+ "subject differs for Change.Id " + c1.getId() + ":" + " {Change subject} != {Change sub}");
// ReviewDb has shorter subject, allowed.
- b1 = new ChangeBundle(c1, messages(), patchSets(), approvals(),
- comments(), reviewers(), NOTE_DB);
- b2 = new ChangeBundle(c2, messages(), patchSets(), approvals(),
- comments(), reviewers(), REVIEW_DB);
+ b1 =
+ new ChangeBundle(
+ c1, messages(), patchSets(), approvals(), comments(), reviewers(), NOTE_DB);
+ b2 =
+ new ChangeBundle(
+ c2, messages(), patchSets(), approvals(), comments(), reviewers(), REVIEW_DB);
assertNoDiffs(b1, b2);
// NoteDb has shorter subject, not allowed.
- b1 = new ChangeBundle(c1, messages(), latest(c1), approvals(),
- comments(), reviewers(), REVIEW_DB);
- b2 = new ChangeBundle(c2, messages(), latest(c2), approvals(),
- comments(), reviewers(), NOTE_DB);
- assertDiffs(b1, b2,
- "subject differs for Change.Id " + c1.getId() + ":"
- + " {Change subject} != {Change sub}");
+ b1 =
+ new ChangeBundle(
+ c1, messages(), latest(c1), approvals(), comments(), reviewers(), REVIEW_DB);
+ b2 =
+ new ChangeBundle(c2, messages(), latest(c2), approvals(), comments(), reviewers(), NOTE_DB);
+ assertDiffs(
+ b1,
+ b2,
+ "subject differs for Change.Id " + c1.getId() + ":" + " {Change subject} != {Change sub}");
}
@Test
- public void diffChangesTrimsLeadingSpacesFromReviewDbComparingToNoteDb()
- throws Exception {
- Change c1 = TestChanges.newChange(
- new Project.NameKey("project"), new Account.Id(100));
+ public void diffChangesTrimsLeadingSpacesFromReviewDbComparingToNoteDb() throws Exception {
+ Change c1 = TestChanges.newChange(new Project.NameKey("project"), new Account.Id(100));
Change c2 = clone(c1);
- c2.setCurrentPatchSet(c1.currentPatchSetId(),
- " " + c1.getSubject(), c1.getOriginalSubject());
+ c2.setCurrentPatchSet(c1.currentPatchSetId(), " " + c1.getSubject(), c1.getOriginalSubject());
// Both ReviewDb, exact match required.
- ChangeBundle b1 = new ChangeBundle(c1, messages(), patchSets(), approvals(),
- comments(), reviewers(), REVIEW_DB);
- ChangeBundle b2 = new ChangeBundle(c2, messages(), patchSets(), approvals(),
- comments(), reviewers(), REVIEW_DB);
- assertDiffs(b1, b2,
- "subject differs for Change.Id " + c1.getId() + ":"
+ ChangeBundle b1 =
+ new ChangeBundle(
+ c1, messages(), patchSets(), approvals(), comments(), reviewers(), REVIEW_DB);
+ ChangeBundle b2 =
+ new ChangeBundle(
+ c2, messages(), patchSets(), approvals(), comments(), reviewers(), REVIEW_DB);
+ assertDiffs(
+ b1,
+ b2,
+ "subject differs for Change.Id "
+ + c1.getId()
+ + ":"
+ " {Change subject} != { Change subject}");
// ReviewDb is missing leading spaces, allowed.
- b1 = new ChangeBundle(c1, messages(), patchSets(), approvals(),
- comments(), reviewers(), NOTE_DB);
- b2 = new ChangeBundle(c2, messages(), patchSets(), approvals(),
- comments(), reviewers(), REVIEW_DB);
+ b1 =
+ new ChangeBundle(
+ c1, messages(), patchSets(), approvals(), comments(), reviewers(), NOTE_DB);
+ b2 =
+ new ChangeBundle(
+ c2, messages(), patchSets(), approvals(), comments(), reviewers(), REVIEW_DB);
assertNoDiffs(b1, b2);
assertNoDiffs(b2, b1);
}
@Test
- public void diffChangesDoesntTrimLeadingNonSpaceWhitespaceFromSubject()
- throws Exception {
- Change c1 = TestChanges.newChange(
- new Project.NameKey("project"), new Account.Id(100));
+ public void diffChangesDoesntTrimLeadingNonSpaceWhitespaceFromSubject() throws Exception {
+ Change c1 = TestChanges.newChange(new Project.NameKey("project"), new Account.Id(100));
Change c2 = clone(c1);
- c2.setCurrentPatchSet(c1.currentPatchSetId(),
- "\t" + c1.getSubject(), c1.getOriginalSubject());
+ c2.setCurrentPatchSet(c1.currentPatchSetId(), "\t" + c1.getSubject(), c1.getOriginalSubject());
// Both ReviewDb.
- ChangeBundle b1 = new ChangeBundle(c1, messages(), patchSets(), approvals(),
- comments(), reviewers(), REVIEW_DB);
- ChangeBundle b2 = new ChangeBundle(c2, messages(), patchSets(), approvals(),
- comments(), reviewers(), REVIEW_DB);
- assertDiffs(b1, b2,
- "subject differs for Change.Id " + c1.getId() + ":"
+ ChangeBundle b1 =
+ new ChangeBundle(
+ c1, messages(), patchSets(), approvals(), comments(), reviewers(), REVIEW_DB);
+ ChangeBundle b2 =
+ new ChangeBundle(
+ c2, messages(), patchSets(), approvals(), comments(), reviewers(), REVIEW_DB);
+ assertDiffs(
+ b1,
+ b2,
+ "subject differs for Change.Id "
+ + c1.getId()
+ + ":"
+ " {Change subject} != {\tChange subject}");
// One NoteDb.
- b1 = new ChangeBundle(c1, messages(), latest(c1), approvals(),
- comments(), reviewers(), NOTE_DB);
- b2 = new ChangeBundle(c2, messages(), latest(c2), approvals(),
- comments(), reviewers(), REVIEW_DB);
- assertDiffs(b1, b2,
- "subject differs for Change.Id " + c1.getId() + ":"
+ b1 =
+ new ChangeBundle(c1, messages(), latest(c1), approvals(), comments(), reviewers(), NOTE_DB);
+ b2 =
+ new ChangeBundle(
+ c2, messages(), latest(c2), approvals(), comments(), reviewers(), REVIEW_DB);
+ assertDiffs(
+ b1,
+ b2,
+ "subject differs for Change.Id "
+ + c1.getId()
+ + ":"
+ " {Change subject} != {\tChange subject}");
- assertDiffs(b2, b1,
- "subject differs for Change.Id " + c1.getId() + ":"
+ assertDiffs(
+ b2,
+ b1,
+ "subject differs for Change.Id "
+ + c1.getId()
+ + ":"
+ " {\tChange subject} != {Change subject}");
}
@@ -493,43 +550,56 @@
c2.setCurrentPatchSet(c2.currentPatchSetId(), "Subject", "Subject");
// Both ReviewDb.
- ChangeBundle b1 = new ChangeBundle(c1, messages(), patchSets(), approvals(),
- comments(), reviewers(), REVIEW_DB);
- ChangeBundle b2 = new ChangeBundle(c2, messages(), patchSets(), approvals(),
- comments(), reviewers(), REVIEW_DB);
- assertDiffs(b1, b2,
- "originalSubject differs for Change.Id " + c1.getId() + ":"
+ ChangeBundle b1 =
+ new ChangeBundle(
+ c1, messages(), patchSets(), approvals(), comments(), reviewers(), REVIEW_DB);
+ ChangeBundle b2 =
+ new ChangeBundle(
+ c2, messages(), patchSets(), approvals(), comments(), reviewers(), REVIEW_DB);
+ assertDiffs(
+ b1,
+ b2,
+ "originalSubject differs for Change.Id "
+ + c1.getId()
+ + ":"
+ " {Subject\r \r Rest of message.} != {Subject}",
- "subject differs for Change.Id " + c1.getId() + ":"
+ "subject differs for Change.Id "
+ + c1.getId()
+ + ":"
+ " {Subject\r \r Rest of message.} != {Subject}");
// NoteDb has correct subject without "\r ".
- b1 = new ChangeBundle(c1, messages(), patchSets(), approvals(),
- comments(), reviewers(), REVIEW_DB);
- b2 = new ChangeBundle(c2, messages(), patchSets(), approvals(),
- comments(), reviewers(), NOTE_DB);
+ b1 =
+ new ChangeBundle(
+ c1, messages(), patchSets(), approvals(), comments(), reviewers(), REVIEW_DB);
+ b2 =
+ new ChangeBundle(
+ c2, messages(), patchSets(), approvals(), comments(), reviewers(), NOTE_DB);
assertNoDiffs(b1, b2);
assertNoDiffs(b2, b1);
}
@Test
- public void diffChangesIgnoresInvalidCurrentPatchSetIdInReviewDb()
- throws Exception {
- Change c1 = TestChanges.newChange(
- new Project.NameKey("project"), new Account.Id(100));
+ public void diffChangesIgnoresInvalidCurrentPatchSetIdInReviewDb() throws Exception {
+ Change c1 = TestChanges.newChange(new Project.NameKey("project"), new Account.Id(100));
Change c2 = clone(c1);
- c2.setCurrentPatchSet(new PatchSet.Id(c2.getId(), 0), "Unrelated subject",
- c2.getOriginalSubject());
+ c2.setCurrentPatchSet(
+ new PatchSet.Id(c2.getId(), 0), "Unrelated subject", c2.getOriginalSubject());
// Both ReviewDb.
- ChangeBundle b1 = new ChangeBundle(c1, messages(), patchSets(),
- approvals(), comments(), reviewers(), REVIEW_DB);
- ChangeBundle b2 = new ChangeBundle(c2, messages(), patchSets(),
- approvals(), comments(), reviewers(), REVIEW_DB);
- assertDiffs(b1, b2,
- "currentPatchSetId differs for Change.Id " + c1.getId() + ":"
- + " {1} != {0}",
- "subject differs for Change.Id " + c1.getId() + ":"
+ ChangeBundle b1 =
+ new ChangeBundle(
+ c1, messages(), patchSets(), approvals(), comments(), reviewers(), REVIEW_DB);
+ ChangeBundle b2 =
+ new ChangeBundle(
+ c2, messages(), patchSets(), approvals(), comments(), reviewers(), REVIEW_DB);
+ assertDiffs(
+ b1,
+ b2,
+ "currentPatchSetId differs for Change.Id " + c1.getId() + ":" + " {1} != {0}",
+ "subject differs for Change.Id "
+ + c1.getId()
+ + ":"
+ " {Change subject} != {Unrelated subject}");
// One NoteDb.
@@ -537,10 +607,12 @@
// This is based on a real corrupt change where all patch sets were deleted
// but the Change entity stuck around, resulting in a currentPatchSetId of 0
// after converting to NoteDb.
- b1 = new ChangeBundle(c1, messages(), patchSets(), approvals(), comments(),
- reviewers(), REVIEW_DB);
- b2 = new ChangeBundle(c2, messages(), patchSets(), approvals(), comments(),
- reviewers(), NOTE_DB);
+ b1 =
+ new ChangeBundle(
+ c1, messages(), patchSets(), approvals(), comments(), reviewers(), REVIEW_DB);
+ b2 =
+ new ChangeBundle(
+ c2, messages(), patchSets(), approvals(), comments(), reviewers(), NOTE_DB);
assertNoDiffs(b1, b2);
assertNoDiffs(b2, b1);
}
@@ -549,40 +621,63 @@
public void diffChangeMessageKeySets() throws Exception {
Change c = TestChanges.newChange(project, accountId);
int id = c.getId().get();
- ChangeMessage cm1 = new ChangeMessage(
- new ChangeMessage.Key(c.getId(), "uuid1"),
- accountId, TimeUtil.nowTs(), c.currentPatchSetId());
- ChangeMessage cm2 = new ChangeMessage(
- new ChangeMessage.Key(c.getId(), "uuid2"),
- accountId, TimeUtil.nowTs(), c.currentPatchSetId());
- ChangeBundle b1 = new ChangeBundle(c, messages(cm1), latest(c), approvals(),
- comments(), reviewers(), REVIEW_DB);
- ChangeBundle b2 = new ChangeBundle(c, messages(cm2), latest(c), approvals(),
- comments(), reviewers(), REVIEW_DB);
+ ChangeMessage cm1 =
+ new ChangeMessage(
+ new ChangeMessage.Key(c.getId(), "uuid1"),
+ accountId,
+ TimeUtil.nowTs(),
+ c.currentPatchSetId());
+ ChangeMessage cm2 =
+ new ChangeMessage(
+ new ChangeMessage.Key(c.getId(), "uuid2"),
+ accountId,
+ TimeUtil.nowTs(),
+ c.currentPatchSetId());
+ ChangeBundle b1 =
+ new ChangeBundle(
+ c, messages(cm1), latest(c), approvals(), comments(), reviewers(), REVIEW_DB);
+ ChangeBundle b2 =
+ new ChangeBundle(
+ c, messages(cm2), latest(c), approvals(), comments(), reviewers(), REVIEW_DB);
- assertDiffs(b1, b2,
+ assertDiffs(
+ b1,
+ b2,
"ChangeMessage.Key sets differ:"
- + " [" + id + ",uuid1] only in A; [" + id + ",uuid2] only in B");
+ + " ["
+ + id
+ + ",uuid1] only in A; ["
+ + id
+ + ",uuid2] only in B");
}
@Test
public void diffChangeMessages() throws Exception {
Change c = TestChanges.newChange(project, accountId);
- ChangeMessage cm1 = new ChangeMessage(
- new ChangeMessage.Key(c.getId(), "uuid"),
- accountId, TimeUtil.nowTs(), c.currentPatchSetId());
+ ChangeMessage cm1 =
+ new ChangeMessage(
+ new ChangeMessage.Key(c.getId(), "uuid"),
+ accountId,
+ TimeUtil.nowTs(),
+ c.currentPatchSetId());
cm1.setMessage("message 1");
ChangeMessage cm2 = clone(cm1);
- ChangeBundle b1 = new ChangeBundle(c, messages(cm1), latest(c), approvals(),
- comments(), reviewers(), REVIEW_DB);
- ChangeBundle b2 = new ChangeBundle(c, messages(cm2), latest(c), approvals(),
- comments(), reviewers(), REVIEW_DB);
+ ChangeBundle b1 =
+ new ChangeBundle(
+ c, messages(cm1), latest(c), approvals(), comments(), reviewers(), REVIEW_DB);
+ ChangeBundle b2 =
+ new ChangeBundle(
+ c, messages(cm2), latest(c), approvals(), comments(), reviewers(), REVIEW_DB);
assertNoDiffs(b1, b2);
cm2.setMessage("message 2");
- assertDiffs(b1, b2,
- "message differs for ChangeMessage.Key " + c.getId() + ",uuid:"
+ assertDiffs(
+ b1,
+ b2,
+ "message differs for ChangeMessage.Key "
+ + c.getId()
+ + ",uuid:"
+ " {message 1} != {message 2}");
}
@@ -590,27 +685,40 @@
public void diffChangeMessagesIgnoresUuids() throws Exception {
Change c = TestChanges.newChange(project, accountId);
int id = c.getId().get();
- ChangeMessage cm1 = new ChangeMessage(
- new ChangeMessage.Key(c.getId(), "uuid1"),
- accountId, TimeUtil.nowTs(), c.currentPatchSetId());
+ ChangeMessage cm1 =
+ new ChangeMessage(
+ new ChangeMessage.Key(c.getId(), "uuid1"),
+ accountId,
+ TimeUtil.nowTs(),
+ c.currentPatchSetId());
cm1.setMessage("message 1");
ChangeMessage cm2 = clone(cm1);
cm2.getKey().set("uuid2");
- ChangeBundle b1 = new ChangeBundle(c, messages(cm1), latest(c), approvals(),
- comments(), reviewers(), REVIEW_DB);
- ChangeBundle b2 = new ChangeBundle(c, messages(cm2), latest(c), approvals(),
- comments(), reviewers(), REVIEW_DB);
+ ChangeBundle b1 =
+ new ChangeBundle(
+ c, messages(cm1), latest(c), approvals(), comments(), reviewers(), REVIEW_DB);
+ ChangeBundle b2 =
+ new ChangeBundle(
+ c, messages(cm2), latest(c), approvals(), comments(), reviewers(), REVIEW_DB);
// Both are ReviewDb, exact UUID match is required.
- assertDiffs(b1, b2,
+ assertDiffs(
+ b1,
+ b2,
"ChangeMessage.Key sets differ:"
- + " [" + id + ",uuid1] only in A; [" + id + ",uuid2] only in B");
+ + " ["
+ + id
+ + ",uuid1] only in A; ["
+ + id
+ + ",uuid2] only in B");
// One NoteDb, UUIDs are ignored.
- b1 = new ChangeBundle(c, messages(cm1), latest(c), approvals(), comments(),
- reviewers(), REVIEW_DB);
- b2 = new ChangeBundle(c, messages(cm2), latest(c), approvals(), comments(),
- reviewers(), NOTE_DB);
+ b1 =
+ new ChangeBundle(
+ c, messages(cm1), latest(c), approvals(), comments(), reviewers(), REVIEW_DB);
+ b2 =
+ new ChangeBundle(
+ c, messages(cm2), latest(c), approvals(), comments(), reviewers(), NOTE_DB);
assertNoDiffs(b1, b2);
}
@@ -618,91 +726,128 @@
public void diffChangeMessagesWithDifferentCounts() throws Exception {
Change c = TestChanges.newChange(project, accountId);
int id = c.getId().get();
- ChangeMessage cm1 = new ChangeMessage(
- new ChangeMessage.Key(c.getId(), "uuid1"),
- accountId, TimeUtil.nowTs(), c.currentPatchSetId());
+ ChangeMessage cm1 =
+ new ChangeMessage(
+ new ChangeMessage.Key(c.getId(), "uuid1"),
+ accountId,
+ TimeUtil.nowTs(),
+ c.currentPatchSetId());
cm1.setMessage("message 1");
- ChangeMessage cm2 = new ChangeMessage(
- new ChangeMessage.Key(c.getId(), "uuid2"),
- accountId, TimeUtil.nowTs(), c.currentPatchSetId());
+ ChangeMessage cm2 =
+ new ChangeMessage(
+ new ChangeMessage.Key(c.getId(), "uuid2"),
+ accountId,
+ TimeUtil.nowTs(),
+ c.currentPatchSetId());
cm1.setMessage("message 2");
// Both ReviewDb: Uses same keySet diff as other types.
- ChangeBundle b1 = new ChangeBundle(c, messages(cm1, cm2), latest(c),
- approvals(), comments(), reviewers(), REVIEW_DB);
- ChangeBundle b2 = new ChangeBundle(c, messages(cm1), latest(c), approvals(),
- comments(), reviewers(), REVIEW_DB);
- assertDiffs(b1, b2,
- "ChangeMessage.Key sets differ: [" + id
- + ",uuid2] only in A; [] only in B");
+ ChangeBundle b1 =
+ new ChangeBundle(
+ c, messages(cm1, cm2), latest(c), approvals(), comments(), reviewers(), REVIEW_DB);
+ ChangeBundle b2 =
+ new ChangeBundle(
+ c, messages(cm1), latest(c), approvals(), comments(), reviewers(), REVIEW_DB);
+ assertDiffs(
+ b1, b2, "ChangeMessage.Key sets differ: [" + id + ",uuid2] only in A; [] only in B");
// One NoteDb: UUIDs in keys can't be used for comparison, just diff counts.
- b1 = new ChangeBundle(c, messages(cm1, cm2), latest(c), approvals(),
- comments(), reviewers(), REVIEW_DB);
- b2 = new ChangeBundle(c, messages(cm1), latest(c), approvals(), comments(),
- reviewers(), NOTE_DB);
- assertDiffs(b1, b2,
- "ChangeMessages differ for Change.Id " + id + "\n"
- + "Only in A:\n " + cm2);
- assertDiffs(b2, b1,
- "ChangeMessages differ for Change.Id " + id + "\n"
- + "Only in B:\n " + cm2);
+ b1 =
+ new ChangeBundle(
+ c, messages(cm1, cm2), latest(c), approvals(), comments(), reviewers(), REVIEW_DB);
+ b2 =
+ new ChangeBundle(
+ c, messages(cm1), latest(c), approvals(), comments(), reviewers(), NOTE_DB);
+ assertDiffs(
+ b1, b2, "ChangeMessages differ for Change.Id " + id + "\n" + "Only in A:\n " + cm2);
+ assertDiffs(
+ b2, b1, "ChangeMessages differ for Change.Id " + id + "\n" + "Only in B:\n " + cm2);
}
@Test
public void diffChangeMessagesMixedSourcesWithDifferences() throws Exception {
Change c = TestChanges.newChange(project, accountId);
int id = c.getId().get();
- ChangeMessage cm1 = new ChangeMessage(
- new ChangeMessage.Key(c.getId(), "uuid1"),
- accountId, TimeUtil.nowTs(), c.currentPatchSetId());
+ ChangeMessage cm1 =
+ new ChangeMessage(
+ new ChangeMessage.Key(c.getId(), "uuid1"),
+ accountId,
+ TimeUtil.nowTs(),
+ c.currentPatchSetId());
cm1.setMessage("message 1");
ChangeMessage cm2 = clone(cm1);
cm2.setMessage("message 2");
ChangeMessage cm3 = clone(cm1);
cm3.getKey().set("uuid2"); // Differs only in UUID.
- ChangeBundle b1 = new ChangeBundle(c, messages(cm1, cm3), latest(c),
- approvals(), comments(), reviewers(), REVIEW_DB);
- ChangeBundle b2 = new ChangeBundle(c, messages(cm2, cm3), latest(c),
- approvals(), comments(), reviewers(), NOTE_DB);
+ ChangeBundle b1 =
+ new ChangeBundle(
+ c, messages(cm1, cm3), latest(c), approvals(), comments(), reviewers(), REVIEW_DB);
+ ChangeBundle b2 =
+ new ChangeBundle(
+ c, messages(cm2, cm3), latest(c), approvals(), comments(), reviewers(), NOTE_DB);
// Implementation happens to pair up cm1 in b1 with cm3 in b2 because it
// depends on iteration order and doesn't care about UUIDs. The important
// thing is that there's some diff.
- assertDiffs(b1, b2,
- "ChangeMessages differ for Change.Id " + id + "\n"
- + "Only in A:\n " + cm3 + "\n"
- + "Only in B:\n " + cm2);
- assertDiffs(b2, b1,
- "ChangeMessages differ for Change.Id " + id + "\n"
- + "Only in A:\n " + cm2 + "\n"
- + "Only in B:\n " + cm3);
+ assertDiffs(
+ b1,
+ b2,
+ "ChangeMessages differ for Change.Id "
+ + id
+ + "\n"
+ + "Only in A:\n "
+ + cm3
+ + "\n"
+ + "Only in B:\n "
+ + cm2);
+ assertDiffs(
+ b2,
+ b1,
+ "ChangeMessages differ for Change.Id "
+ + id
+ + "\n"
+ + "Only in A:\n "
+ + cm2
+ + "\n"
+ + "Only in B:\n "
+ + cm3);
}
@Test
public void diffChangeMessagesMixedSourcesAllowsSlop() throws Exception {
subWindowResolution();
Change c = TestChanges.newChange(project, accountId);
- ChangeMessage cm1 = new ChangeMessage(
- new ChangeMessage.Key(c.getId(), "uuid1"),
- accountId, TimeUtil.nowTs(), c.currentPatchSetId());
+ ChangeMessage cm1 =
+ new ChangeMessage(
+ new ChangeMessage.Key(c.getId(), "uuid1"),
+ accountId,
+ TimeUtil.nowTs(),
+ c.currentPatchSetId());
ChangeMessage cm2 = clone(cm1);
cm2.setWrittenOn(TimeUtil.nowTs());
// Both are ReviewDb, exact timestamp match is required.
- ChangeBundle b1 = new ChangeBundle(c, messages(cm1), latest(c), approvals(),
- comments(), reviewers(), REVIEW_DB);
- ChangeBundle b2 = new ChangeBundle(c, messages(cm2), latest(c), approvals(),
- comments(), reviewers(), REVIEW_DB);
- assertDiffs(b1, b2,
- "writtenOn differs for ChangeMessage.Key " + c.getId() + ",uuid1:"
+ ChangeBundle b1 =
+ new ChangeBundle(
+ c, messages(cm1), latest(c), approvals(), comments(), reviewers(), REVIEW_DB);
+ ChangeBundle b2 =
+ new ChangeBundle(
+ c, messages(cm2), latest(c), approvals(), comments(), reviewers(), REVIEW_DB);
+ assertDiffs(
+ b1,
+ b2,
+ "writtenOn differs for ChangeMessage.Key "
+ + c.getId()
+ + ",uuid1:"
+ " {2009-09-30 17:00:02.0} != {2009-09-30 17:00:03.0}");
// One NoteDb, slop is allowed.
- b1 = new ChangeBundle(c, messages(cm1), latest(c), approvals(), comments(),
- reviewers(), NOTE_DB);
- b2 = new ChangeBundle(c, messages(cm2), latest(c), approvals(), comments(),
- reviewers(), REVIEW_DB);
+ b1 =
+ new ChangeBundle(
+ c, messages(cm1), latest(c), approvals(), comments(), reviewers(), NOTE_DB);
+ b2 =
+ new ChangeBundle(
+ c, messages(cm2), latest(c), approvals(), comments(), reviewers(), REVIEW_DB);
assertNoDiffs(b1, b2);
assertNoDiffs(b2, b1);
@@ -710,63 +855,107 @@
superWindowResolution();
ChangeMessage cm3 = clone(cm1);
cm3.setWrittenOn(TimeUtil.nowTs());
- b1 = new ChangeBundle(c, messages(cm1), latest(c), approvals(), comments(),
- reviewers(), NOTE_DB);
- ChangeBundle b3 = new ChangeBundle(c, messages(cm3), latest(c), approvals(),
- comments(), reviewers(), REVIEW_DB);
+ b1 =
+ new ChangeBundle(
+ c, messages(cm1), latest(c), approvals(), comments(), reviewers(), NOTE_DB);
+ ChangeBundle b3 =
+ new ChangeBundle(
+ c, messages(cm3), latest(c), approvals(), comments(), reviewers(), REVIEW_DB);
int id = c.getId().get();
- assertDiffs(b1, b3,
- "ChangeMessages differ for Change.Id " + id + "\n"
- + "Only in A:\n " + cm1 + "\n"
- + "Only in B:\n " + cm3);
- assertDiffs(b3, b1,
- "ChangeMessages differ for Change.Id " + id + "\n"
- + "Only in A:\n " + cm3 + "\n"
- + "Only in B:\n " + cm1);
+ assertDiffs(
+ b1,
+ b3,
+ "ChangeMessages differ for Change.Id "
+ + id
+ + "\n"
+ + "Only in A:\n "
+ + cm1
+ + "\n"
+ + "Only in B:\n "
+ + cm3);
+ assertDiffs(
+ b3,
+ b1,
+ "ChangeMessages differ for Change.Id "
+ + id
+ + "\n"
+ + "Only in A:\n "
+ + cm3
+ + "\n"
+ + "Only in B:\n "
+ + cm1);
}
@Test
- public void diffChangeMessagesAllowsNullPatchSetIdFromReviewDb()
- throws Exception {
+ public void diffChangeMessagesAllowsNullPatchSetIdFromReviewDb() throws Exception {
Change c = TestChanges.newChange(project, accountId);
int id = c.getId().get();
- ChangeMessage cm1 = new ChangeMessage(
- new ChangeMessage.Key(c.getId(), "uuid"),
- accountId, TimeUtil.nowTs(), c.currentPatchSetId());
+ ChangeMessage cm1 =
+ new ChangeMessage(
+ new ChangeMessage.Key(c.getId(), "uuid"),
+ accountId,
+ TimeUtil.nowTs(),
+ c.currentPatchSetId());
cm1.setMessage("message 1");
ChangeMessage cm2 = clone(cm1);
cm2.setPatchSetId(null);
- ChangeBundle b1 = new ChangeBundle(c, messages(cm1), latest(c), approvals(),
- comments(), reviewers(), REVIEW_DB);
- ChangeBundle b2 = new ChangeBundle(c, messages(cm2), latest(c), approvals(),
- comments(), reviewers(), REVIEW_DB);
+ ChangeBundle b1 =
+ new ChangeBundle(
+ c, messages(cm1), latest(c), approvals(), comments(), reviewers(), REVIEW_DB);
+ ChangeBundle b2 =
+ new ChangeBundle(
+ c, messages(cm2), latest(c), approvals(), comments(), reviewers(), REVIEW_DB);
// Both are ReviewDb, exact patch set ID match is required.
- assertDiffs(b1, b2,
- "patchset differs for ChangeMessage.Key " + c.getId() + ",uuid:"
- + " {" + id + ",1} != {null}");
+ assertDiffs(
+ b1,
+ b2,
+ "patchset differs for ChangeMessage.Key "
+ + c.getId()
+ + ",uuid:"
+ + " {"
+ + id
+ + ",1} != {null}");
// Null patch set ID on ReviewDb is ignored.
- b1 = new ChangeBundle(c, messages(cm1), latest(c), approvals(), comments(),
- reviewers(), NOTE_DB);
- b2 = new ChangeBundle(c, messages(cm2), latest(c), approvals(), comments(),
- reviewers(), REVIEW_DB);
+ b1 =
+ new ChangeBundle(
+ c, messages(cm1), latest(c), approvals(), comments(), reviewers(), NOTE_DB);
+ b2 =
+ new ChangeBundle(
+ c, messages(cm2), latest(c), approvals(), comments(), reviewers(), REVIEW_DB);
assertNoDiffs(b1, b2);
// Null patch set ID on NoteDb is not ignored (but is not realistic).
- b1 = new ChangeBundle(c, messages(cm1), latest(c), approvals(), comments(),
- reviewers(), REVIEW_DB);
- b2 = new ChangeBundle(c, messages(cm2), latest(c), approvals(), comments(),
- reviewers(), NOTE_DB);
- assertDiffs(b1, b2,
- "ChangeMessages differ for Change.Id " + id + "\n"
- + "Only in A:\n " + cm1 + "\n"
- + "Only in B:\n " + cm2);
- assertDiffs(b2, b1,
- "ChangeMessages differ for Change.Id " + id + "\n"
- + "Only in A:\n " + cm2 + "\n"
- + "Only in B:\n " + cm1);
+ b1 =
+ new ChangeBundle(
+ c, messages(cm1), latest(c), approvals(), comments(), reviewers(), REVIEW_DB);
+ b2 =
+ new ChangeBundle(
+ c, messages(cm2), latest(c), approvals(), comments(), reviewers(), NOTE_DB);
+ assertDiffs(
+ b1,
+ b2,
+ "ChangeMessages differ for Change.Id "
+ + id
+ + "\n"
+ + "Only in A:\n "
+ + cm1
+ + "\n"
+ + "Only in B:\n "
+ + cm2);
+ assertDiffs(
+ b2,
+ b1,
+ "ChangeMessages differ for Change.Id "
+ + id
+ + "\n"
+ + "Only in A:\n "
+ + cm2
+ + "\n"
+ + "Only in B:\n "
+ + cm1);
}
@Test
@@ -783,14 +972,15 @@
ps2.setUploader(accountId);
ps2.setCreatedOn(TimeUtil.nowTs());
- ChangeBundle b1 = new ChangeBundle(c, messages(), patchSets(ps2),
- approvals(), comments(), reviewers(), REVIEW_DB);
- ChangeBundle b2 = new ChangeBundle(c, messages(), patchSets(ps1, ps2),
- approvals(), comments(), reviewers(), REVIEW_DB);
+ ChangeBundle b1 =
+ new ChangeBundle(
+ c, messages(), patchSets(ps2), approvals(), comments(), reviewers(), REVIEW_DB);
+ ChangeBundle b2 =
+ new ChangeBundle(
+ c, messages(), patchSets(ps1, ps2), approvals(), comments(), reviewers(), REVIEW_DB);
- assertDiffs(b1, b2,
- "PatchSet.Id sets differ:"
- + " [] only in A; [" + c.getId() + ",1] only in B");
+ assertDiffs(
+ b1, b2, "PatchSet.Id sets differ:" + " [] only in A; [" + c.getId() + ",1] only in B");
}
@Test
@@ -801,16 +991,22 @@
ps1.setUploader(accountId);
ps1.setCreatedOn(TimeUtil.nowTs());
PatchSet ps2 = clone(ps1);
- ChangeBundle b1 = new ChangeBundle(c, messages(), patchSets(ps1),
- approvals(), comments(), reviewers(), REVIEW_DB);
- ChangeBundle b2 = new ChangeBundle(c, messages(), patchSets(ps2),
- approvals(), comments(), reviewers(), REVIEW_DB);
+ ChangeBundle b1 =
+ new ChangeBundle(
+ c, messages(), patchSets(ps1), approvals(), comments(), reviewers(), REVIEW_DB);
+ ChangeBundle b2 =
+ new ChangeBundle(
+ c, messages(), patchSets(ps2), approvals(), comments(), reviewers(), REVIEW_DB);
assertNoDiffs(b1, b2);
ps2.setRevision(new RevId("badc0feebadc0feebadc0feebadc0feebadc0fee"));
- assertDiffs(b1, b2,
- "revision differs for PatchSet.Id " + c.getId() + ",1:"
+ assertDiffs(
+ b1,
+ b2,
+ "revision differs for PatchSet.Id "
+ + c.getId()
+ + ",1:"
+ " {RevId{deadbeefdeadbeefdeadbeefdeadbeefdeadbeef}}"
+ " != {RevId{badc0feebadc0feebadc0feebadc0feebadc0fee}}");
}
@@ -827,39 +1023,50 @@
ps2.setCreatedOn(TimeUtil.nowTs());
// Both are ReviewDb, exact timestamp match is required.
- ChangeBundle b1 = new ChangeBundle(c, messages(), patchSets(ps1),
- approvals(), comments(), reviewers(), REVIEW_DB);
- ChangeBundle b2 = new ChangeBundle(c, messages(), patchSets(ps2),
- approvals(), comments(), reviewers(), REVIEW_DB);
- assertDiffs(b1, b2,
- "createdOn differs for PatchSet.Id " + c.getId() + ",1:"
+ ChangeBundle b1 =
+ new ChangeBundle(
+ c, messages(), patchSets(ps1), approvals(), comments(), reviewers(), REVIEW_DB);
+ ChangeBundle b2 =
+ new ChangeBundle(
+ c, messages(), patchSets(ps2), approvals(), comments(), reviewers(), REVIEW_DB);
+ assertDiffs(
+ b1,
+ b2,
+ "createdOn differs for PatchSet.Id "
+ + c.getId()
+ + ",1:"
+ " {2009-09-30 17:00:02.0} != {2009-09-30 17:00:03.0}");
// One NoteDb, slop is allowed.
- b1 = new ChangeBundle(c, messages(), patchSets(ps1), approvals(),
- comments(), reviewers(), NOTE_DB);
- b2 = new ChangeBundle(c, messages(), patchSets(ps2), approvals(),
- comments(), reviewers(), REVIEW_DB);
+ b1 =
+ new ChangeBundle(
+ c, messages(), patchSets(ps1), approvals(), comments(), reviewers(), NOTE_DB);
+ b2 =
+ new ChangeBundle(
+ c, messages(), patchSets(ps2), approvals(), comments(), reviewers(), REVIEW_DB);
assertNoDiffs(b1, b2);
// But not too much slop.
superWindowResolution();
PatchSet ps3 = clone(ps1);
ps3.setCreatedOn(TimeUtil.nowTs());
- b1 = new ChangeBundle(c, messages(), patchSets(ps1), approvals(),
- comments(), reviewers(), NOTE_DB);
- ChangeBundle b3 = new ChangeBundle(c, messages(), patchSets(ps3),
- approvals(), comments(), reviewers(), REVIEW_DB);
- String msg = "createdOn differs for PatchSet.Id " + c.getId()
- + ",1 in NoteDb vs. ReviewDb:"
- + " {2009-09-30 17:00:02.0} != {2009-09-30 17:00:10.0}";
+ b1 =
+ new ChangeBundle(
+ c, messages(), patchSets(ps1), approvals(), comments(), reviewers(), NOTE_DB);
+ ChangeBundle b3 =
+ new ChangeBundle(
+ c, messages(), patchSets(ps3), approvals(), comments(), reviewers(), REVIEW_DB);
+ String msg =
+ "createdOn differs for PatchSet.Id "
+ + c.getId()
+ + ",1 in NoteDb vs. ReviewDb:"
+ + " {2009-09-30 17:00:02.0} != {2009-09-30 17:00:10.0}";
assertDiffs(b1, b3, msg);
assertDiffs(b3, b1, msg);
}
@Test
- public void diffPatchSetsIgnoresTrailingNewlinesInPushCertificate()
- throws Exception {
+ public void diffPatchSetsIgnoresTrailingNewlinesInPushCertificate() throws Exception {
subWindowResolution();
Change c = TestChanges.newChange(project, accountId);
PatchSet ps1 = new PatchSet(c.currentPatchSetId());
@@ -870,17 +1077,21 @@
PatchSet ps2 = clone(ps1);
ps2.setPushCertificate(ps2.getPushCertificate() + "\n\n");
- ChangeBundle b1 = new ChangeBundle(c, messages(), patchSets(ps1),
- approvals(), comments(), reviewers(), NOTE_DB);
- ChangeBundle b2 = new ChangeBundle(c, messages(), patchSets(ps2),
- approvals(), comments(), reviewers(), REVIEW_DB);
+ ChangeBundle b1 =
+ new ChangeBundle(
+ c, messages(), patchSets(ps1), approvals(), comments(), reviewers(), NOTE_DB);
+ ChangeBundle b2 =
+ new ChangeBundle(
+ c, messages(), patchSets(ps2), approvals(), comments(), reviewers(), REVIEW_DB);
assertNoDiffs(b1, b2);
assertNoDiffs(b2, b1);
- b1 = new ChangeBundle(c, messages(), patchSets(ps1), approvals(),
- comments(), reviewers(), REVIEW_DB);
- b2 = new ChangeBundle(c, messages(), patchSets(ps2), approvals(),
- comments(), reviewers(), NOTE_DB);
+ b1 =
+ new ChangeBundle(
+ c, messages(), patchSets(ps1), approvals(), comments(), reviewers(), REVIEW_DB);
+ b2 =
+ new ChangeBundle(
+ c, messages(), patchSets(ps2), approvals(), comments(), reviewers(), NOTE_DB);
assertNoDiffs(b1, b2);
assertNoDiffs(b2, b1);
}
@@ -899,187 +1110,240 @@
ps2.setCreatedOn(TimeUtil.nowTs());
assertThat(ps2.getId().get()).isGreaterThan(c.currentPatchSetId().get());
- ChangeMessage cm1 = new ChangeMessage(
- new ChangeMessage.Key(c.getId(), "uuid1"),
- accountId, TimeUtil.nowTs(), c.currentPatchSetId());
- ChangeMessage cm2 = new ChangeMessage(
- new ChangeMessage.Key(c.getId(), "uuid2"),
- accountId, TimeUtil.nowTs(), c.currentPatchSetId());
+ ChangeMessage cm1 =
+ new ChangeMessage(
+ new ChangeMessage.Key(c.getId(), "uuid1"),
+ accountId,
+ TimeUtil.nowTs(),
+ c.currentPatchSetId());
+ ChangeMessage cm2 =
+ new ChangeMessage(
+ new ChangeMessage.Key(c.getId(), "uuid2"),
+ accountId,
+ TimeUtil.nowTs(),
+ c.currentPatchSetId());
- PatchSetApproval a1 = new PatchSetApproval(
- new PatchSetApproval.Key(
- ps1.getId(), accountId, new LabelId("Code-Review")),
- (short) 1,
- TimeUtil.nowTs());
- PatchSetApproval a2 = new PatchSetApproval(
- new PatchSetApproval.Key(
- ps2.getId(), accountId, new LabelId("Code-Review")),
- (short) 1,
- TimeUtil.nowTs());
+ PatchSetApproval a1 =
+ new PatchSetApproval(
+ new PatchSetApproval.Key(ps1.getId(), accountId, new LabelId("Code-Review")),
+ (short) 1,
+ TimeUtil.nowTs());
+ PatchSetApproval a2 =
+ new PatchSetApproval(
+ new PatchSetApproval.Key(ps2.getId(), accountId, new LabelId("Code-Review")),
+ (short) 1,
+ TimeUtil.nowTs());
// Both ReviewDb.
- ChangeBundle b1 = new ChangeBundle(c, messages(cm1), patchSets(ps1),
- approvals(a1), comments(), reviewers(), REVIEW_DB);
- ChangeBundle b2 = new ChangeBundle(c, messages(cm1, cm2),
- patchSets(ps1, ps2), approvals(a1, a2), comments(), reviewers(),
- REVIEW_DB);
- assertDiffs(b1, b2,
- "ChangeMessage.Key sets differ: [] only in A; [" + cm2.getKey()
- + "] only in B",
- "PatchSet.Id sets differ:"
- + " [] only in A; [" + ps2.getId() + "] only in B",
- "PatchSetApproval.Key sets differ:"
- + " [] only in A; [" + a2.getKey() + "] only in B");
+ ChangeBundle b1 =
+ new ChangeBundle(
+ c, messages(cm1), patchSets(ps1), approvals(a1), comments(), reviewers(), REVIEW_DB);
+ ChangeBundle b2 =
+ new ChangeBundle(
+ c,
+ messages(cm1, cm2),
+ patchSets(ps1, ps2),
+ approvals(a1, a2),
+ comments(),
+ reviewers(),
+ REVIEW_DB);
+ assertDiffs(
+ b1,
+ b2,
+ "ChangeMessage.Key sets differ: [] only in A; [" + cm2.getKey() + "] only in B",
+ "PatchSet.Id sets differ:" + " [] only in A; [" + ps2.getId() + "] only in B",
+ "PatchSetApproval.Key sets differ:" + " [] only in A; [" + a2.getKey() + "] only in B");
// One NoteDb.
- b1 = new ChangeBundle(c, messages(cm1), patchSets(ps1), approvals(a1),
- comments(), reviewers(), NOTE_DB);
- b2 = new ChangeBundle(c, messages(cm1, cm2), patchSets(ps1, ps2), approvals(a1, a2),
- comments(), reviewers(), REVIEW_DB);
- assertDiffs(b1, b2,
- "ChangeMessages differ for Change.Id " + c.getId() + "\n"
- + "Only in B:\n " + cm2,
- "PatchSet.Id sets differ:"
- + " [] only in A; [" + ps2.getId() + "] only in B",
- "PatchSetApproval.Key sets differ:"
- + " [] only in A; [" + a2.getKey() + "] only in B");
+ b1 =
+ new ChangeBundle(
+ c, messages(cm1), patchSets(ps1), approvals(a1), comments(), reviewers(), NOTE_DB);
+ b2 =
+ new ChangeBundle(
+ c,
+ messages(cm1, cm2),
+ patchSets(ps1, ps2),
+ approvals(a1, a2),
+ comments(),
+ reviewers(),
+ REVIEW_DB);
+ assertDiffs(
+ b1,
+ b2,
+ "ChangeMessages differ for Change.Id " + c.getId() + "\n" + "Only in B:\n " + cm2,
+ "PatchSet.Id sets differ:" + " [] only in A; [" + ps2.getId() + "] only in B",
+ "PatchSetApproval.Key sets differ:" + " [] only in A; [" + a2.getKey() + "] only in B");
// Both NoteDb.
- b1 = new ChangeBundle(c, messages(cm1), patchSets(ps1), approvals(a1),
- comments(), reviewers(), NOTE_DB);
- b2 = new ChangeBundle(c, messages(cm1, cm2), patchSets(ps1, ps2), approvals(a1, a2),
- comments(), reviewers(), NOTE_DB);
- assertDiffs(b1, b2,
- "ChangeMessages differ for Change.Id " + c.getId() + "\n"
- + "Only in B:\n " + cm2,
- "PatchSet.Id sets differ:"
- + " [] only in A; [" + ps2.getId() + "] only in B",
- "PatchSetApproval.Key sets differ:"
- + " [] only in A; [" + a2.getKey() + "] only in B");
+ b1 =
+ new ChangeBundle(
+ c, messages(cm1), patchSets(ps1), approvals(a1), comments(), reviewers(), NOTE_DB);
+ b2 =
+ new ChangeBundle(
+ c,
+ messages(cm1, cm2),
+ patchSets(ps1, ps2),
+ approvals(a1, a2),
+ comments(),
+ reviewers(),
+ NOTE_DB);
+ assertDiffs(
+ b1,
+ b2,
+ "ChangeMessages differ for Change.Id " + c.getId() + "\n" + "Only in B:\n " + cm2,
+ "PatchSet.Id sets differ:" + " [] only in A; [" + ps2.getId() + "] only in B",
+ "PatchSetApproval.Key sets differ:" + " [] only in A; [" + a2.getKey() + "] only in B");
}
@Test
public void diffPatchSetApprovalKeySets() throws Exception {
Change c = TestChanges.newChange(project, accountId);
int id = c.getId().get();
- PatchSetApproval a1 = new PatchSetApproval(
- new PatchSetApproval.Key(
- c.currentPatchSetId(), accountId, new LabelId("Code-Review")),
- (short) 1,
- TimeUtil.nowTs());
- PatchSetApproval a2 = new PatchSetApproval(
- new PatchSetApproval.Key(
- c.currentPatchSetId(), accountId, new LabelId("Verified")),
- (short) 1,
- TimeUtil.nowTs());
+ PatchSetApproval a1 =
+ new PatchSetApproval(
+ new PatchSetApproval.Key(c.currentPatchSetId(), accountId, new LabelId("Code-Review")),
+ (short) 1,
+ TimeUtil.nowTs());
+ PatchSetApproval a2 =
+ new PatchSetApproval(
+ new PatchSetApproval.Key(c.currentPatchSetId(), accountId, new LabelId("Verified")),
+ (short) 1,
+ TimeUtil.nowTs());
- ChangeBundle b1 = new ChangeBundle(c, messages(), latest(c), approvals(a1),
- comments(), reviewers(), REVIEW_DB);
- ChangeBundle b2 = new ChangeBundle(c, messages(), latest(c), approvals(a2),
- comments(), reviewers(), REVIEW_DB);
+ ChangeBundle b1 =
+ new ChangeBundle(
+ c, messages(), latest(c), approvals(a1), comments(), reviewers(), REVIEW_DB);
+ ChangeBundle b2 =
+ new ChangeBundle(
+ c, messages(), latest(c), approvals(a2), comments(), reviewers(), REVIEW_DB);
- assertDiffs(b1, b2,
+ assertDiffs(
+ b1,
+ b2,
"PatchSetApproval.Key sets differ:"
- + " [" + id + "%2C1,100,Code-Review] only in A;"
- + " [" + id + "%2C1,100,Verified] only in B");
+ + " ["
+ + id
+ + "%2C1,100,Code-Review] only in A;"
+ + " ["
+ + id
+ + "%2C1,100,Verified] only in B");
}
@Test
public void diffPatchSetApprovals() throws Exception {
Change c = TestChanges.newChange(project, accountId);
- PatchSetApproval a1 = new PatchSetApproval(
- new PatchSetApproval.Key(
- c.currentPatchSetId(), accountId, new LabelId("Code-Review")),
- (short) 1,
- TimeUtil.nowTs());
+ PatchSetApproval a1 =
+ new PatchSetApproval(
+ new PatchSetApproval.Key(c.currentPatchSetId(), accountId, new LabelId("Code-Review")),
+ (short) 1,
+ TimeUtil.nowTs());
PatchSetApproval a2 = clone(a1);
- ChangeBundle b1 = new ChangeBundle(c, messages(), latest(c), approvals(a1),
- comments(), reviewers(), REVIEW_DB);
- ChangeBundle b2 = new ChangeBundle(c, messages(), latest(c), approvals(a2),
- comments(), reviewers(), REVIEW_DB);
+ ChangeBundle b1 =
+ new ChangeBundle(
+ c, messages(), latest(c), approvals(a1), comments(), reviewers(), REVIEW_DB);
+ ChangeBundle b2 =
+ new ChangeBundle(
+ c, messages(), latest(c), approvals(a2), comments(), reviewers(), REVIEW_DB);
assertNoDiffs(b1, b2);
a2.setValue((short) -1);
- assertDiffs(b1, b2,
+ assertDiffs(
+ b1,
+ b2,
"value differs for PatchSetApproval.Key "
- + c.getId() + "%2C1,100,Code-Review: {1} != {-1}");
+ + c.getId()
+ + "%2C1,100,Code-Review: {1} != {-1}");
}
@Test
- public void diffPatchSetApprovalsMixedSourcesAllowsSlop()
- throws Exception {
+ public void diffPatchSetApprovalsMixedSourcesAllowsSlop() throws Exception {
Change c = TestChanges.newChange(project, accountId);
subWindowResolution();
- PatchSetApproval a1 = new PatchSetApproval(
- new PatchSetApproval.Key(
- c.currentPatchSetId(), accountId, new LabelId("Code-Review")),
- (short) 1,
- roundToSecond(TimeUtil.nowTs()));
+ PatchSetApproval a1 =
+ new PatchSetApproval(
+ new PatchSetApproval.Key(c.currentPatchSetId(), accountId, new LabelId("Code-Review")),
+ (short) 1,
+ roundToSecond(TimeUtil.nowTs()));
PatchSetApproval a2 = clone(a1);
a2.setGranted(TimeUtil.nowTs());
// Both are ReviewDb, exact timestamp match is required.
- ChangeBundle b1 = new ChangeBundle(c, messages(), latest(c), approvals(a1),
- comments(), reviewers(), REVIEW_DB);
- ChangeBundle b2 = new ChangeBundle(c, messages(), latest(c), approvals(a2),
- comments(), reviewers(), REVIEW_DB);
- assertDiffs(b1, b2,
+ ChangeBundle b1 =
+ new ChangeBundle(
+ c, messages(), latest(c), approvals(a1), comments(), reviewers(), REVIEW_DB);
+ ChangeBundle b2 =
+ new ChangeBundle(
+ c, messages(), latest(c), approvals(a2), comments(), reviewers(), REVIEW_DB);
+ assertDiffs(
+ b1,
+ b2,
"granted differs for PatchSetApproval.Key "
- + c.getId() + "%2C1,100,Code-Review:"
+ + c.getId()
+ + "%2C1,100,Code-Review:"
+ " {2009-09-30 17:00:07.0} != {2009-09-30 17:00:08.0}");
// One NoteDb, slop is allowed.
- b1 = new ChangeBundle(c, messages(), latest(c), approvals(a1), comments(),
- reviewers(), NOTE_DB);
- b2 = new ChangeBundle(c, messages(), latest(c), approvals(a2), comments(),
- reviewers(), REVIEW_DB);
+ b1 =
+ new ChangeBundle(c, messages(), latest(c), approvals(a1), comments(), reviewers(), NOTE_DB);
+ b2 =
+ new ChangeBundle(
+ c, messages(), latest(c), approvals(a2), comments(), reviewers(), REVIEW_DB);
assertNoDiffs(b1, b2);
// But not too much slop.
superWindowResolution();
PatchSetApproval a3 = clone(a1);
a3.setGranted(TimeUtil.nowTs());
- b1 = new ChangeBundle(c, messages(), latest(c), approvals(a1), comments(),
- reviewers(), NOTE_DB);
- ChangeBundle b3 = new ChangeBundle(c, messages(), latest(c), approvals(a3),
- comments(), reviewers(), REVIEW_DB);
- String msg = "granted differs for PatchSetApproval.Key "
- + c.getId() + "%2C1,100,Code-Review in NoteDb vs. ReviewDb:"
- + " {2009-09-30 17:00:07.0} != {2009-09-30 17:00:15.0}";
+ b1 =
+ new ChangeBundle(c, messages(), latest(c), approvals(a1), comments(), reviewers(), NOTE_DB);
+ ChangeBundle b3 =
+ new ChangeBundle(
+ c, messages(), latest(c), approvals(a3), comments(), reviewers(), REVIEW_DB);
+ String msg =
+ "granted differs for PatchSetApproval.Key "
+ + c.getId()
+ + "%2C1,100,Code-Review in NoteDb vs. ReviewDb:"
+ + " {2009-09-30 17:00:07.0} != {2009-09-30 17:00:15.0}";
assertDiffs(b1, b3, msg);
assertDiffs(b3, b1, msg);
}
@Test
- public void diffPatchSetApprovalsAllowsTruncatedTimestampInNoteDb()
- throws Exception {
+ public void diffPatchSetApprovalsAllowsTruncatedTimestampInNoteDb() throws Exception {
Change c = TestChanges.newChange(project, accountId);
- PatchSetApproval a1 = new PatchSetApproval(
- new PatchSetApproval.Key(
- c.currentPatchSetId(), accountId, new LabelId("Code-Review")),
- (short) 1,
- c.getCreatedOn());
+ PatchSetApproval a1 =
+ new PatchSetApproval(
+ new PatchSetApproval.Key(c.currentPatchSetId(), accountId, new LabelId("Code-Review")),
+ (short) 1,
+ c.getCreatedOn());
PatchSetApproval a2 = clone(a1);
- a2.setGranted(new Timestamp(new DateTime(
- 1900, 1, 1, 0, 0, 0, DateTimeZone.forTimeZone(TimeZone.getDefault()))
- .getMillis()));
+ a2.setGranted(
+ new Timestamp(
+ new DateTime(1900, 1, 1, 0, 0, 0, DateTimeZone.forTimeZone(TimeZone.getDefault()))
+ .getMillis()));
// Both are ReviewDb, exact match is required.
- ChangeBundle b1 = new ChangeBundle(c, messages(), latest(c), approvals(a1),
- comments(), reviewers(), REVIEW_DB);
- ChangeBundle b2 = new ChangeBundle(c, messages(), latest(c), approvals(a2),
- comments(), reviewers(), REVIEW_DB);
- assertDiffs(b1, b2,
+ ChangeBundle b1 =
+ new ChangeBundle(
+ c, messages(), latest(c), approvals(a1), comments(), reviewers(), REVIEW_DB);
+ ChangeBundle b2 =
+ new ChangeBundle(
+ c, messages(), latest(c), approvals(a2), comments(), reviewers(), REVIEW_DB);
+ assertDiffs(
+ b1,
+ b2,
"granted differs for PatchSetApproval.Key "
- + c.getId() + "%2C1,100,Code-Review:"
+ + c.getId()
+ + "%2C1,100,Code-Review:"
+ " {2009-09-30 17:00:00.0} != {1900-01-01 00:00:00.0}");
// Truncating NoteDb timestamp is allowed.
- b1 = new ChangeBundle(c, messages(), latest(c), approvals(a1), comments(),
- reviewers(), NOTE_DB);
- b2 = new ChangeBundle(c, messages(), latest(c), approvals(a2), comments(),
- reviewers(), REVIEW_DB);
+ b1 =
+ new ChangeBundle(c, messages(), latest(c), approvals(a1), comments(), reviewers(), NOTE_DB);
+ b2 =
+ new ChangeBundle(
+ c, messages(), latest(c), approvals(a2), comments(), reviewers(), REVIEW_DB);
assertNoDiffs(b1, b2);
assertNoDiffs(b2, b1);
}
@@ -1091,16 +1355,13 @@
ReviewerSet r1 = reviewers(REVIEWER, new Account.Id(1), now);
ReviewerSet r2 = reviewers(REVIEWER, new Account.Id(2), now);
- ChangeBundle b1 = new ChangeBundle(c, messages(), latest(c), approvals(),
- comments(), r1, REVIEW_DB);
- ChangeBundle b2 = new ChangeBundle(c, messages(), latest(c), approvals(),
- comments(), r2, REVIEW_DB);
+ ChangeBundle b1 =
+ new ChangeBundle(c, messages(), latest(c), approvals(), comments(), r1, REVIEW_DB);
+ ChangeBundle b2 =
+ new ChangeBundle(c, messages(), latest(c), approvals(), comments(), r2, REVIEW_DB);
assertNoDiffs(b1, b1);
assertNoDiffs(b2, b2);
- assertDiffs(b1, b2,
- "reviewer sets differ:"
- + " [1] only in A;"
- + " [2] only in B");
+ assertDiffs(b1, b2, "reviewer sets differ:" + " [1] only in A;" + " [2] only in B");
}
@Test
@@ -1109,10 +1370,10 @@
ReviewerSet r1 = reviewers(REVIEWER, new Account.Id(1), TimeUtil.nowTs());
ReviewerSet r2 = reviewers(CC, new Account.Id(1), TimeUtil.nowTs());
- ChangeBundle b1 = new ChangeBundle(c, messages(), latest(c), approvals(),
- comments(), r1, REVIEW_DB);
- ChangeBundle b2 = new ChangeBundle(c, messages(), latest(c), approvals(),
- comments(), r2, REVIEW_DB);
+ ChangeBundle b1 =
+ new ChangeBundle(c, messages(), latest(c), approvals(), comments(), r1, REVIEW_DB);
+ ChangeBundle b2 =
+ new ChangeBundle(c, messages(), latest(c), approvals(), comments(), r2, REVIEW_DB);
assertNoDiffs(b1, b1);
assertNoDiffs(b2, b2);
}
@@ -1121,108 +1382,147 @@
public void diffPatchLineCommentKeySets() throws Exception {
Change c = TestChanges.newChange(project, accountId);
int id = c.getId().get();
- PatchLineComment c1 = new PatchLineComment(
- new PatchLineComment.Key(
- new Patch.Key(c.currentPatchSetId(), "filename1"), "uuid1"),
- 5, accountId, null, TimeUtil.nowTs());
- PatchLineComment c2 = new PatchLineComment(
- new PatchLineComment.Key(
- new Patch.Key(c.currentPatchSetId(), "filename2"), "uuid2"),
- 5, accountId, null, TimeUtil.nowTs());
+ PatchLineComment c1 =
+ new PatchLineComment(
+ new PatchLineComment.Key(new Patch.Key(c.currentPatchSetId(), "filename1"), "uuid1"),
+ 5,
+ accountId,
+ null,
+ TimeUtil.nowTs());
+ PatchLineComment c2 =
+ new PatchLineComment(
+ new PatchLineComment.Key(new Patch.Key(c.currentPatchSetId(), "filename2"), "uuid2"),
+ 5,
+ accountId,
+ null,
+ TimeUtil.nowTs());
- ChangeBundle b1 = new ChangeBundle(c, messages(), latest(c), approvals(),
- comments(c1), reviewers(), REVIEW_DB);
- ChangeBundle b2 = new ChangeBundle(c, messages(), latest(c), approvals(),
- comments(c2), reviewers(), REVIEW_DB);
+ ChangeBundle b1 =
+ new ChangeBundle(
+ c, messages(), latest(c), approvals(), comments(c1), reviewers(), REVIEW_DB);
+ ChangeBundle b2 =
+ new ChangeBundle(
+ c, messages(), latest(c), approvals(), comments(c2), reviewers(), REVIEW_DB);
- assertDiffs(b1, b2,
+ assertDiffs(
+ b1,
+ b2,
"PatchLineComment.Key sets differ:"
- + " [" + id + ",1,filename1,uuid1] only in A;"
- + " [" + id + ",1,filename2,uuid2] only in B");
+ + " ["
+ + id
+ + ",1,filename1,uuid1] only in A;"
+ + " ["
+ + id
+ + ",1,filename2,uuid2] only in B");
}
@Test
public void diffPatchLineComments() throws Exception {
Change c = TestChanges.newChange(project, accountId);
- PatchLineComment c1 = new PatchLineComment(
- new PatchLineComment.Key(
- new Patch.Key(c.currentPatchSetId(), "filename"), "uuid"),
- 5, accountId, null, TimeUtil.nowTs());
+ PatchLineComment c1 =
+ new PatchLineComment(
+ new PatchLineComment.Key(new Patch.Key(c.currentPatchSetId(), "filename"), "uuid"),
+ 5,
+ accountId,
+ null,
+ TimeUtil.nowTs());
PatchLineComment c2 = clone(c1);
- ChangeBundle b1 = new ChangeBundle(c, messages(), latest(c), approvals(),
- comments(c1), reviewers(), REVIEW_DB);
- ChangeBundle b2 = new ChangeBundle(c, messages(), latest(c), approvals(),
- comments(c2), reviewers(), REVIEW_DB);
+ ChangeBundle b1 =
+ new ChangeBundle(
+ c, messages(), latest(c), approvals(), comments(c1), reviewers(), REVIEW_DB);
+ ChangeBundle b2 =
+ new ChangeBundle(
+ c, messages(), latest(c), approvals(), comments(c2), reviewers(), REVIEW_DB);
assertNoDiffs(b1, b2);
c2.setStatus(PatchLineComment.Status.PUBLISHED);
- assertDiffs(b1, b2,
- "status differs for PatchLineComment.Key "
- + c.getId() + ",1,filename,uuid: {d} != {P}");
+ assertDiffs(
+ b1,
+ b2,
+ "status differs for PatchLineComment.Key " + c.getId() + ",1,filename,uuid: {d} != {P}");
}
@Test
- public void diffPatchLineCommentsMixedSourcesAllowsSlop()
- throws Exception {
+ public void diffPatchLineCommentsMixedSourcesAllowsSlop() throws Exception {
subWindowResolution();
Change c = TestChanges.newChange(project, accountId);
- PatchLineComment c1 = new PatchLineComment(
- new PatchLineComment.Key(
- new Patch.Key(c.currentPatchSetId(), "filename"), "uuid"),
- 5, accountId, null, roundToSecond(TimeUtil.nowTs()));
+ PatchLineComment c1 =
+ new PatchLineComment(
+ new PatchLineComment.Key(new Patch.Key(c.currentPatchSetId(), "filename"), "uuid"),
+ 5,
+ accountId,
+ null,
+ roundToSecond(TimeUtil.nowTs()));
PatchLineComment c2 = clone(c1);
c2.setWrittenOn(TimeUtil.nowTs());
// Both are ReviewDb, exact timestamp match is required.
- ChangeBundle b1 = new ChangeBundle(c, messages(), latest(c), approvals(),
- comments(c1), reviewers(), REVIEW_DB);
- ChangeBundle b2 = new ChangeBundle(c, messages(), latest(c), approvals(),
- comments(c2), reviewers(), REVIEW_DB);
- assertDiffs(b1, b2,
+ ChangeBundle b1 =
+ new ChangeBundle(
+ c, messages(), latest(c), approvals(), comments(c1), reviewers(), REVIEW_DB);
+ ChangeBundle b2 =
+ new ChangeBundle(
+ c, messages(), latest(c), approvals(), comments(c2), reviewers(), REVIEW_DB);
+ assertDiffs(
+ b1,
+ b2,
"writtenOn differs for PatchLineComment.Key "
- + c.getId() + ",1,filename,uuid:"
+ + c.getId()
+ + ",1,filename,uuid:"
+ " {2009-09-30 17:00:02.0} != {2009-09-30 17:00:03.0}");
// One NoteDb, slop is allowed.
- b1 = new ChangeBundle(c, messages(), latest(c), approvals(), comments(c1),
- reviewers(), NOTE_DB);
- b2 = new ChangeBundle(c, messages(), latest(c), approvals(), comments(c2),
- reviewers(), REVIEW_DB);
+ b1 =
+ new ChangeBundle(c, messages(), latest(c), approvals(), comments(c1), reviewers(), NOTE_DB);
+ b2 =
+ new ChangeBundle(
+ c, messages(), latest(c), approvals(), comments(c2), reviewers(), REVIEW_DB);
assertNoDiffs(b1, b2);
// But not too much slop.
superWindowResolution();
PatchLineComment c3 = clone(c1);
c3.setWrittenOn(TimeUtil.nowTs());
- b1 = new ChangeBundle(c, messages(), latest(c), approvals(), comments(c1),
- reviewers(), NOTE_DB);
- ChangeBundle b3 = new ChangeBundle(c, messages(), latest(c), approvals(),
- comments(c3), reviewers(), REVIEW_DB);
- String msg = "writtenOn differs for PatchLineComment.Key " + c.getId()
- + ",1,filename,uuid in NoteDb vs. ReviewDb:"
- + " {2009-09-30 17:00:02.0} != {2009-09-30 17:00:10.0}";
+ b1 =
+ new ChangeBundle(c, messages(), latest(c), approvals(), comments(c1), reviewers(), NOTE_DB);
+ ChangeBundle b3 =
+ new ChangeBundle(
+ c, messages(), latest(c), approvals(), comments(c3), reviewers(), REVIEW_DB);
+ String msg =
+ "writtenOn differs for PatchLineComment.Key "
+ + c.getId()
+ + ",1,filename,uuid in NoteDb vs. ReviewDb:"
+ + " {2009-09-30 17:00:02.0} != {2009-09-30 17:00:10.0}";
assertDiffs(b1, b3, msg);
assertDiffs(b3, b1, msg);
}
@Test
- public void diffPatchLineCommentsIgnoresCommentsOnInvalidPatchSet()
- throws Exception {
+ public void diffPatchLineCommentsIgnoresCommentsOnInvalidPatchSet() throws Exception {
Change c = TestChanges.newChange(project, accountId);
- PatchLineComment c1 = new PatchLineComment(
- new PatchLineComment.Key(
- new Patch.Key(c.currentPatchSetId(), "filename1"), "uuid1"),
- 5, accountId, null, TimeUtil.nowTs());
- PatchLineComment c2 = new PatchLineComment(
- new PatchLineComment.Key(
- new Patch.Key(new PatchSet.Id(c.getId(), 0), "filename2"), "uuid2"),
- 5, accountId, null, TimeUtil.nowTs());
+ PatchLineComment c1 =
+ new PatchLineComment(
+ new PatchLineComment.Key(new Patch.Key(c.currentPatchSetId(), "filename1"), "uuid1"),
+ 5,
+ accountId,
+ null,
+ TimeUtil.nowTs());
+ PatchLineComment c2 =
+ new PatchLineComment(
+ new PatchLineComment.Key(
+ new Patch.Key(new PatchSet.Id(c.getId(), 0), "filename2"), "uuid2"),
+ 5,
+ accountId,
+ null,
+ TimeUtil.nowTs());
- ChangeBundle b1 = new ChangeBundle(c, messages(), latest(c), approvals(),
- comments(c1, c2), reviewers(), REVIEW_DB);
- ChangeBundle b2 = new ChangeBundle(c, messages(), latest(c), approvals(),
- comments(c1), reviewers(), REVIEW_DB);
+ ChangeBundle b1 =
+ new ChangeBundle(
+ c, messages(), latest(c), approvals(), comments(c1, c2), reviewers(), REVIEW_DB);
+ ChangeBundle b2 =
+ new ChangeBundle(
+ c, messages(), latest(c), approvals(), comments(c1), reviewers(), REVIEW_DB);
assertNoDiffs(b1, b2);
}
@@ -1231,8 +1531,7 @@
assertThat(b.differencesFrom(a)).isEmpty();
}
- private static void assertDiffs(ChangeBundle a, ChangeBundle b, String first,
- String... rest) {
+ private static void assertDiffs(ChangeBundle a, ChangeBundle b, String first, String... rest) {
List<String> actual = a.differencesFrom(b);
if (actual.size() == 1 && rest.length == 0) {
// This error message is much easier to read.
@@ -1266,11 +1565,9 @@
private static ReviewerSet reviewers(Object... ents) {
checkArgument(ents.length % 3 == 0);
- Table<ReviewerStateInternal, Account.Id, Timestamp> t =
- HashBasedTable.create();
+ Table<ReviewerStateInternal, Account.Id, Timestamp> t = HashBasedTable.create();
for (int i = 0; i < ents.length; i += 3) {
- t.put((ReviewerStateInternal) ents[i], (Account.Id) ents[i + 1],
- (Timestamp) ents[i + 2]);
+ t.put((ReviewerStateInternal) ents[i], (Account.Id) ents[i + 1], (Timestamp) ents[i + 2]);
}
return ReviewerSet.fromTable(t);
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/notedb/ChangeNotesParserTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/notedb/ChangeNotesParserTest.java
index a4f3438..abc87d4 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/notedb/ChangeNotesParserTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/notedb/ChangeNotesParserTest.java
@@ -19,7 +19,6 @@
import com.google.gerrit.common.TimeUtil;
import com.google.gerrit.reviewdb.client.Change;
import com.google.gerrit.server.notedb.ChangeNotesCommit.ChangeNotesRevWalk;
-
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.internal.storage.dfs.InMemoryRepository;
import org.eclipse.jgit.junit.TestRepository;
@@ -49,434 +48,426 @@
@Test
public void parseAuthor() throws Exception {
- assertParseSucceeds("Update change\n"
- + "\n"
- + "Branch: refs/heads/master\n"
- + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
- + "Patch-set: 1\n"
- + "Subject: This is a test change\n");
- assertParseFails(writeCommit("Update change\n"
- + "\n"
- + "Patch-set: 1\n",
- new PersonIdent("Change Owner", "owner@example.com",
- serverIdent.getWhen(), serverIdent.getTimeZone())));
- assertParseFails(writeCommit("Update change\n"
- + "\n"
- + "Patch-set: 1\n",
- new PersonIdent("Change Owner", "x@gerrit",
- serverIdent.getWhen(), serverIdent.getTimeZone())));
- assertParseFails(writeCommit("Update change\n"
- + "\n"
- + "Patch-set: 1\n",
- new PersonIdent("Change\n\u1234<Owner>", "\n\nx<@>\u0002gerrit",
- serverIdent.getWhen(), serverIdent.getTimeZone())));
+ assertParseSucceeds(
+ "Update change\n"
+ + "\n"
+ + "Branch: refs/heads/master\n"
+ + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
+ + "Patch-set: 1\n"
+ + "Subject: This is a test change\n");
+ assertParseFails(
+ writeCommit(
+ "Update change\n" + "\n" + "Patch-set: 1\n",
+ new PersonIdent(
+ "Change Owner",
+ "owner@example.com",
+ serverIdent.getWhen(),
+ serverIdent.getTimeZone())));
+ assertParseFails(
+ writeCommit(
+ "Update change\n" + "\n" + "Patch-set: 1\n",
+ new PersonIdent(
+ "Change Owner", "x@gerrit", serverIdent.getWhen(), serverIdent.getTimeZone())));
+ assertParseFails(
+ writeCommit(
+ "Update change\n" + "\n" + "Patch-set: 1\n",
+ new PersonIdent(
+ "Change\n\u1234<Owner>",
+ "\n\nx<@>\u0002gerrit",
+ serverIdent.getWhen(),
+ serverIdent.getTimeZone())));
}
@Test
public void parseStatus() throws Exception {
- assertParseSucceeds("Update change\n"
- + "\n"
- + "Branch: refs/heads/master\n"
- + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
- + "Patch-set: 1\n"
- + "Status: NEW\n"
- + "Subject: This is a test change\n");
- assertParseSucceeds("Update change\n"
- + "\n"
- + "Branch: refs/heads/master\n"
- + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
- + "Patch-set: 1\n"
- + "Status: new\n"
- + "Subject: This is a test change\n");
- assertParseFails("Update change\n"
- + "\n"
- + "Patch-set: 1\n"
- + "Status: OOPS\n");
- assertParseFails("Update change\n"
- + "\n"
- + "Patch-set: 1\n"
- + "Status: NEW\n"
- + "Status: NEW\n");
+ assertParseSucceeds(
+ "Update change\n"
+ + "\n"
+ + "Branch: refs/heads/master\n"
+ + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
+ + "Patch-set: 1\n"
+ + "Status: NEW\n"
+ + "Subject: This is a test change\n");
+ assertParseSucceeds(
+ "Update change\n"
+ + "\n"
+ + "Branch: refs/heads/master\n"
+ + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
+ + "Patch-set: 1\n"
+ + "Status: new\n"
+ + "Subject: This is a test change\n");
+ assertParseFails("Update change\n" + "\n" + "Patch-set: 1\n" + "Status: OOPS\n");
+ assertParseFails(
+ "Update change\n" + "\n" + "Patch-set: 1\n" + "Status: NEW\n" + "Status: NEW\n");
}
@Test
public void parsePatchSetId() throws Exception {
- assertParseSucceeds("Update change\n"
- + "\n"
- + "Branch: refs/heads/master\n"
- + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
- + "Patch-set: 1\n"
- + "Subject: This is a test change\n");
- assertParseFails("Update change\n"
- + "\n");
- assertParseFails("Update change\n"
- + "\n"
- + "Patch-set: 1\n"
- + "Patch-set: 1\n");
- assertParseSucceeds("Update change\n"
- + "\n"
- + "Branch: refs/heads/master\n"
- + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
- + "Patch-set: 1\n"
- + "Subject: This is a test change\n");
- assertParseFails("Update change\n"
- + "\n"
- + "Patch-set: x\n");
+ assertParseSucceeds(
+ "Update change\n"
+ + "\n"
+ + "Branch: refs/heads/master\n"
+ + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
+ + "Patch-set: 1\n"
+ + "Subject: This is a test change\n");
+ assertParseFails("Update change\n" + "\n");
+ assertParseFails("Update change\n" + "\n" + "Patch-set: 1\n" + "Patch-set: 1\n");
+ assertParseSucceeds(
+ "Update change\n"
+ + "\n"
+ + "Branch: refs/heads/master\n"
+ + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
+ + "Patch-set: 1\n"
+ + "Subject: This is a test change\n");
+ assertParseFails("Update change\n" + "\n" + "Patch-set: x\n");
}
@Test
public void parseApproval() throws Exception {
- assertParseSucceeds("Update change\n"
- + "\n"
- + "Branch: refs/heads/master\n"
- + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
- + "Patch-set: 1\n"
- + "Label: Label1=+1\n"
- + "Label: Label2=1\n"
- + "Label: Label3=0\n"
- + "Label: Label4=-1\n"
- + "Subject: This is a test change\n");
- assertParseSucceeds("Update change\n"
- + "\n"
- + "Branch: refs/heads/master\n"
- + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
- + "Patch-set: 1\n"
- + "Label: -Label1\n"
- + "Label: -Label1 Other Account <2@gerrit>\n"
- + "Subject: This is a test change\n");
- assertParseFails("Update change\n"
- + "\n"
- + "Patch-set: 1\n"
- + "Label: Label1=X\n");
- assertParseFails("Update change\n"
- + "\n"
- + "Patch-set: 1\n"
- + "Label: Label1 = 1\n");
- assertParseFails("Update change\n"
- + "\n"
- + "Patch-set: 1\n"
- + "Label: X+Y\n");
- assertParseFails("Update change\n"
- + "\n"
- + "Patch-set: 1\n"
- + "Label: Label1 Other Account <2@gerrit>\n");
- assertParseFails("Update change\n"
- + "\n"
- + "Patch-set: 1\n"
- + "Label: -Label!1\n");
- assertParseFails("Update change\n"
- + "\n"
- + "Patch-set: 1\n"
- + "Label: -Label!1 Other Account <2@gerrit>\n");
+ assertParseSucceeds(
+ "Update change\n"
+ + "\n"
+ + "Branch: refs/heads/master\n"
+ + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
+ + "Patch-set: 1\n"
+ + "Label: Label1=+1\n"
+ + "Label: Label2=1\n"
+ + "Label: Label3=0\n"
+ + "Label: Label4=-1\n"
+ + "Subject: This is a test change\n");
+ assertParseSucceeds(
+ "Update change\n"
+ + "\n"
+ + "Branch: refs/heads/master\n"
+ + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
+ + "Patch-set: 1\n"
+ + "Label: -Label1\n"
+ + "Label: -Label1 Other Account <2@gerrit>\n"
+ + "Subject: This is a test change\n");
+ assertParseFails("Update change\n" + "\n" + "Patch-set: 1\n" + "Label: Label1=X\n");
+ assertParseFails("Update change\n" + "\n" + "Patch-set: 1\n" + "Label: Label1 = 1\n");
+ assertParseFails("Update change\n" + "\n" + "Patch-set: 1\n" + "Label: X+Y\n");
+ assertParseFails(
+ "Update change\n" + "\n" + "Patch-set: 1\n" + "Label: Label1 Other Account <2@gerrit>\n");
+ assertParseFails("Update change\n" + "\n" + "Patch-set: 1\n" + "Label: -Label!1\n");
+ assertParseFails(
+ "Update change\n" + "\n" + "Patch-set: 1\n" + "Label: -Label!1 Other Account <2@gerrit>\n");
}
@Test
public void parseSubmitRecords() throws Exception {
- assertParseSucceeds("Update change\n"
- + "\n"
- + "Branch: refs/heads/master\n"
- + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
- + "Patch-set: 1\n"
- + "Subject: This is a test change\n"
- + "Submitted-with: NOT_READY\n"
- + "Submitted-with: OK: Verified: Change Owner <1@gerrit>\n"
- + "Submitted-with: NEED: Code-Review\n"
- + "Submitted-with: NOT_READY\n"
- + "Submitted-with: OK: Verified: Change Owner <1@gerrit>\n"
- + "Submitted-with: NEED: Alternative-Code-Review\n");
- assertParseFails("Update change\n"
- + "\n"
- + "Patch-set: 1\n"
- + "Submitted-with: OOPS\n");
- assertParseFails("Update change\n"
- + "\n"
- + "Patch-set: 1\n"
- + "Submitted-with: NEED: X+Y\n");
- assertParseFails("Update change\n"
- + "\n"
- + "Patch-set: 1\n"
- + "Submitted-with: OK: X+Y: Change Owner <1@gerrit>\n");
- assertParseFails("Update change\n"
- + "\n"
- + "Patch-set: 1\n"
- + "Submitted-with: OK: Code-Review: 1@gerrit\n");
+ assertParseSucceeds(
+ "Update change\n"
+ + "\n"
+ + "Branch: refs/heads/master\n"
+ + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
+ + "Patch-set: 1\n"
+ + "Subject: This is a test change\n"
+ + "Submitted-with: NOT_READY\n"
+ + "Submitted-with: OK: Verified: Change Owner <1@gerrit>\n"
+ + "Submitted-with: NEED: Code-Review\n"
+ + "Submitted-with: NOT_READY\n"
+ + "Submitted-with: OK: Verified: Change Owner <1@gerrit>\n"
+ + "Submitted-with: NEED: Alternative-Code-Review\n");
+ assertParseFails("Update change\n" + "\n" + "Patch-set: 1\n" + "Submitted-with: OOPS\n");
+ assertParseFails("Update change\n" + "\n" + "Patch-set: 1\n" + "Submitted-with: NEED: X+Y\n");
+ assertParseFails(
+ "Update change\n"
+ + "\n"
+ + "Patch-set: 1\n"
+ + "Submitted-with: OK: X+Y: Change Owner <1@gerrit>\n");
+ assertParseFails(
+ "Update change\n"
+ + "\n"
+ + "Patch-set: 1\n"
+ + "Submitted-with: OK: Code-Review: 1@gerrit\n");
}
@Test
public void parseSubmissionId() throws Exception {
- assertParseSucceeds("Update change\n"
- + "\n"
- + "Branch: refs/heads/master\n"
- + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
- + "Patch-set: 1\n"
- + "Subject: This is a test change\n"
- + "Submission-id: 1-1453387607626-96fabc25");
- assertParseFails("Update change\n"
- + "\n"
- + "Patch-set: 1\n"
- + "Submission-id: 1-1453387607626-96fabc25\n"
- + "Submission-id: 1-1453387901516-5d1e2450");
+ assertParseSucceeds(
+ "Update change\n"
+ + "\n"
+ + "Branch: refs/heads/master\n"
+ + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
+ + "Patch-set: 1\n"
+ + "Subject: This is a test change\n"
+ + "Submission-id: 1-1453387607626-96fabc25");
+ assertParseFails(
+ "Update change\n"
+ + "\n"
+ + "Patch-set: 1\n"
+ + "Submission-id: 1-1453387607626-96fabc25\n"
+ + "Submission-id: 1-1453387901516-5d1e2450");
}
@Test
public void parseReviewer() throws Exception {
- assertParseSucceeds("Update change\n"
- + "\n"
- + "Branch: refs/heads/master\n"
- + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
- + "Patch-set: 1\n"
- + "Reviewer: Change Owner <1@gerrit>\n"
- + "CC: Other Account <2@gerrit>\n"
- + "Subject: This is a test change\n");
- assertParseFails("Update change\n"
- + "\n"
- + "Patch-set: 1\n"
- + "Reviewer: 1@gerrit\n");
+ assertParseSucceeds(
+ "Update change\n"
+ + "\n"
+ + "Branch: refs/heads/master\n"
+ + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
+ + "Patch-set: 1\n"
+ + "Reviewer: Change Owner <1@gerrit>\n"
+ + "CC: Other Account <2@gerrit>\n"
+ + "Subject: This is a test change\n");
+ assertParseFails("Update change\n" + "\n" + "Patch-set: 1\n" + "Reviewer: 1@gerrit\n");
}
@Test
public void parseTopic() throws Exception {
- assertParseSucceeds("Update change\n"
- + "\n"
- + "Branch: refs/heads/master\n"
- + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
- + "Patch-set: 1\n"
- + "Topic: Some Topic\n"
- + "Subject: This is a test change\n");
- assertParseSucceeds("Update change\n"
- + "\n"
- + "Branch: refs/heads/master\n"
- + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
- + "Patch-set: 1\n"
- + "Topic:\n"
- + "Subject: This is a test change\n");
- assertParseFails("Update change\n"
- + "\n"
- + "Patch-set: 1\n"
- + "Topic: Some Topic\n"
- + "Topic: Other Topic");
+ assertParseSucceeds(
+ "Update change\n"
+ + "\n"
+ + "Branch: refs/heads/master\n"
+ + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
+ + "Patch-set: 1\n"
+ + "Topic: Some Topic\n"
+ + "Subject: This is a test change\n");
+ assertParseSucceeds(
+ "Update change\n"
+ + "\n"
+ + "Branch: refs/heads/master\n"
+ + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
+ + "Patch-set: 1\n"
+ + "Topic:\n"
+ + "Subject: This is a test change\n");
+ assertParseFails(
+ "Update change\n" + "\n" + "Patch-set: 1\n" + "Topic: Some Topic\n" + "Topic: Other Topic");
}
@Test
public void parseBranch() throws Exception {
- assertParseSucceeds("Update change\n"
- + "\n"
- + "Branch: refs/heads/master\n"
- + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
- + "Patch-set: 1\n"
- + "Subject: This is a test change\n");
- assertParseSucceeds("Update change\n"
- + "\n"
- + "Branch: master\n"
- + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
- + "Patch-set: 1\n"
- + "Subject: This is a test change\n");
- assertParseFails("Update change\n"
- + "\n"
- + "Patch-set: 1\n"
- + "Branch: refs/heads/master\n"
- + "Branch: refs/heads/stable");
+ assertParseSucceeds(
+ "Update change\n"
+ + "\n"
+ + "Branch: refs/heads/master\n"
+ + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
+ + "Patch-set: 1\n"
+ + "Subject: This is a test change\n");
+ assertParseSucceeds(
+ "Update change\n"
+ + "\n"
+ + "Branch: master\n"
+ + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
+ + "Patch-set: 1\n"
+ + "Subject: This is a test change\n");
+ assertParseFails(
+ "Update change\n"
+ + "\n"
+ + "Patch-set: 1\n"
+ + "Branch: refs/heads/master\n"
+ + "Branch: refs/heads/stable");
}
@Test
public void parseChangeId() throws Exception {
- assertParseSucceeds("Update change\n"
- + "\n"
- + "Branch: refs/heads/master\n"
- + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
- + "Patch-set: 1\n"
- + "Subject: This is a test change\n");
- assertParseFails("Update change\n"
- + "\n"
- + "Patch-set: 1\n"
- + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
- + "Change-id: I159532ef4844d7c18f7f3fd37a0b275590d41b1b");
+ assertParseSucceeds(
+ "Update change\n"
+ + "\n"
+ + "Branch: refs/heads/master\n"
+ + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
+ + "Patch-set: 1\n"
+ + "Subject: This is a test change\n");
+ assertParseFails(
+ "Update change\n"
+ + "\n"
+ + "Patch-set: 1\n"
+ + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
+ + "Change-id: I159532ef4844d7c18f7f3fd37a0b275590d41b1b");
}
@Test
public void parseSubject() throws Exception {
- assertParseSucceeds("Update change\n"
- + "\n"
- + "Patch-set: 1\n"
- + "Branch: refs/heads/master\n"
- + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
- + "Subject: Some subject of a change\n");
- assertParseFails("Update change\n"
- + "\n"
- + "Patch-set: 1\n"
- + "Subject: Some subject of a change\n"
- + "Subject: Some other subject\n");
+ assertParseSucceeds(
+ "Update change\n"
+ + "\n"
+ + "Patch-set: 1\n"
+ + "Branch: refs/heads/master\n"
+ + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
+ + "Subject: Some subject of a change\n");
+ assertParseFails(
+ "Update change\n"
+ + "\n"
+ + "Patch-set: 1\n"
+ + "Subject: Some subject of a change\n"
+ + "Subject: Some other subject\n");
}
@Test
public void parseCommit() throws Exception {
- assertParseSucceeds("Update change\n"
- + "\n"
- + "Patch-set: 2\n"
- + "Branch: refs/heads/master\n"
- + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
- + "Subject: Some subject of a change\n"
- + "Commit: abcd1234abcd1234abcd1234abcd1234abcd1234");
- assertParseFails("Update change\n"
- + "\n"
- + "Patch-set: 2\n"
- + "Branch: refs/heads/master\n"
- + "Subject: Some subject of a change\n"
- + "Commit: abcd1234abcd1234abcd1234abcd1234abcd1234\n"
- + "Commit: deadbeefdeadbeefdeadbeefdeadbeefdeadbeef");
- assertParseFails("Update patch set 1\n"
- + "Uploaded patch set 1.\n"
- + "Patch-set: 2\n"
- + "Branch: refs/heads/master\n"
- + "Subject: Some subject of a change\n"
- + "Commit: beef");
+ assertParseSucceeds(
+ "Update change\n"
+ + "\n"
+ + "Patch-set: 2\n"
+ + "Branch: refs/heads/master\n"
+ + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
+ + "Subject: Some subject of a change\n"
+ + "Commit: abcd1234abcd1234abcd1234abcd1234abcd1234");
+ assertParseFails(
+ "Update change\n"
+ + "\n"
+ + "Patch-set: 2\n"
+ + "Branch: refs/heads/master\n"
+ + "Subject: Some subject of a change\n"
+ + "Commit: abcd1234abcd1234abcd1234abcd1234abcd1234\n"
+ + "Commit: deadbeefdeadbeefdeadbeefdeadbeefdeadbeef");
+ assertParseFails(
+ "Update patch set 1\n"
+ + "Uploaded patch set 1.\n"
+ + "Patch-set: 2\n"
+ + "Branch: refs/heads/master\n"
+ + "Subject: Some subject of a change\n"
+ + "Commit: beef");
}
@Test
public void parsePatchSetState() throws Exception {
- assertParseSucceeds("Update change\n"
- + "\n"
- + "Patch-set: 1 (PUBLISHED)\n"
- + "Branch: refs/heads/master\n"
- + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
- + "Subject: Some subject of a change\n");
- assertParseSucceeds("Update change\n"
- + "\n"
- + "Patch-set: 1 (DRAFT)\n"
- + "Branch: refs/heads/master\n"
- + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
- + "Subject: Some subject of a change\n");
- assertParseSucceeds("Update change\n"
- + "\n"
- + "Patch-set: 1 (DELETED)\n"
- + "Branch: refs/heads/master\n"
- + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
- + "Subject: Some subject of a change\n");
- assertParseFails("Update change\n"
- + "\n"
- + "Patch-set: 1 (NOT A STATUS)\n"
- + "Branch: refs/heads/master\n"
- + "Subject: Some subject of a change\n");
+ assertParseSucceeds(
+ "Update change\n"
+ + "\n"
+ + "Patch-set: 1 (PUBLISHED)\n"
+ + "Branch: refs/heads/master\n"
+ + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
+ + "Subject: Some subject of a change\n");
+ assertParseSucceeds(
+ "Update change\n"
+ + "\n"
+ + "Patch-set: 1 (DRAFT)\n"
+ + "Branch: refs/heads/master\n"
+ + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
+ + "Subject: Some subject of a change\n");
+ assertParseSucceeds(
+ "Update change\n"
+ + "\n"
+ + "Patch-set: 1 (DELETED)\n"
+ + "Branch: refs/heads/master\n"
+ + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
+ + "Subject: Some subject of a change\n");
+ assertParseFails(
+ "Update change\n"
+ + "\n"
+ + "Patch-set: 1 (NOT A STATUS)\n"
+ + "Branch: refs/heads/master\n"
+ + "Subject: Some subject of a change\n");
}
@Test
public void parsePatchSetGroups() throws Exception {
- assertParseSucceeds("Update change\n"
- + "\n"
- + "Patch-set: 2\n"
- + "Branch: refs/heads/master\n"
- + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
- + "Commit: abcd1234abcd1234abcd1234abcd1234abcd1234\n"
- + "Subject: Change subject\n"
- + "Groups: a,b,c\n");
- assertParseFails("Update change\n"
- + "\n"
- + "Patch-set: 2\n"
- + "Branch: refs/heads/master\n"
- + "Commit: abcd1234abcd1234abcd1234abcd1234abcd1234\n"
- + "Subject: Change subject\n"
- + "Groups: a,b,c\n"
- + "Groups: d,e,f\n");
+ assertParseSucceeds(
+ "Update change\n"
+ + "\n"
+ + "Patch-set: 2\n"
+ + "Branch: refs/heads/master\n"
+ + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
+ + "Commit: abcd1234abcd1234abcd1234abcd1234abcd1234\n"
+ + "Subject: Change subject\n"
+ + "Groups: a,b,c\n");
+ assertParseFails(
+ "Update change\n"
+ + "\n"
+ + "Patch-set: 2\n"
+ + "Branch: refs/heads/master\n"
+ + "Commit: abcd1234abcd1234abcd1234abcd1234abcd1234\n"
+ + "Subject: Change subject\n"
+ + "Groups: a,b,c\n"
+ + "Groups: d,e,f\n");
}
@Test
public void parseServerIdent() throws Exception {
- String msg = "Update change\n"
- + "\n"
- + "Patch-set: 1\n"
- + "Branch: refs/heads/master\n"
- + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
- + "Subject: Change subject\n";
+ String msg =
+ "Update change\n"
+ + "\n"
+ + "Patch-set: 1\n"
+ + "Branch: refs/heads/master\n"
+ + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
+ + "Subject: Change subject\n";
assertParseSucceeds(msg);
assertParseSucceeds(writeCommit(msg, serverIdent));
- msg = "Update change\n"
- + "\n"
- + "With a message."
- + "\n"
- + "Patch-set: 1\n"
- + "Branch: refs/heads/master\n"
- + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
- + "Subject: Change subject\n";
+ msg =
+ "Update change\n"
+ + "\n"
+ + "With a message."
+ + "\n"
+ + "Patch-set: 1\n"
+ + "Branch: refs/heads/master\n"
+ + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
+ + "Subject: Change subject\n";
assertParseSucceeds(msg);
assertParseSucceeds(writeCommit(msg, serverIdent));
- msg = "Update change\n"
- + "\n"
- + "Patch-set: 1\n"
- + "Branch: refs/heads/master\n"
- + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
- + "Subject: Change subject\n"
- + "Label: Label1=+1\n";
+ msg =
+ "Update change\n"
+ + "\n"
+ + "Patch-set: 1\n"
+ + "Branch: refs/heads/master\n"
+ + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
+ + "Subject: Change subject\n"
+ + "Label: Label1=+1\n";
assertParseSucceeds(msg);
assertParseFails(writeCommit(msg, serverIdent));
}
@Test
public void parseTag() throws Exception {
- assertParseSucceeds("Update change\n"
- + "\n"
- + "Patch-set: 1\n"
- + "Branch: refs/heads/master\n"
- + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
- + "Subject: Change subject\n"
- + "Tag:\n");
- assertParseSucceeds("Update change\n"
- + "\n"
- + "Patch-set: 1\n"
- + "Branch: refs/heads/master\n"
- + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
- + "Subject: Change subject\n"
- + "Tag: jenkins\n");
- assertParseFails("Update change\n"
- + "\n"
- + "Patch-set: 1\n"
- + "Branch: refs/heads/master\n"
- + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
- + "Subject: Change subject\n"
- + "Tag: ci\n"
- + "Tag: jenkins\n");
+ assertParseSucceeds(
+ "Update change\n"
+ + "\n"
+ + "Patch-set: 1\n"
+ + "Branch: refs/heads/master\n"
+ + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
+ + "Subject: Change subject\n"
+ + "Tag:\n");
+ assertParseSucceeds(
+ "Update change\n"
+ + "\n"
+ + "Patch-set: 1\n"
+ + "Branch: refs/heads/master\n"
+ + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
+ + "Subject: Change subject\n"
+ + "Tag: jenkins\n");
+ assertParseFails(
+ "Update change\n"
+ + "\n"
+ + "Patch-set: 1\n"
+ + "Branch: refs/heads/master\n"
+ + "Change-id: I577fb248e474018276351785930358ec0450e9f7\n"
+ + "Subject: Change subject\n"
+ + "Tag: ci\n"
+ + "Tag: jenkins\n");
}
@Test
public void caseInsensitiveFooters() throws Exception {
- assertParseSucceeds("Update change\n"
- + "\n"
- + "BRaNch: refs/heads/master\n"
- + "Change-ID: I577fb248e474018276351785930358ec0450e9f7\n"
- + "patcH-set: 1\n"
- + "subject: This is a test change\n");
+ assertParseSucceeds(
+ "Update change\n"
+ + "\n"
+ + "BRaNch: refs/heads/master\n"
+ + "Change-ID: I577fb248e474018276351785930358ec0450e9f7\n"
+ + "patcH-set: 1\n"
+ + "subject: This is a test change\n");
}
@Test
public void currentPatchSet() throws Exception {
- assertParseSucceeds("Update change\n"
- + "\n"
- + "Patch-set: 1\n"
- + "Current: true");
- assertParseSucceeds("Update change\n"
- + "\n"
- + "Patch-set: 1\n"
- + "Current: tRUe");
- assertParseFails("Update change\n"
- + "\n"
- + "Patch-set: 1\n"
- + "Current: false");
- assertParseFails("Update change\n"
- + "\n"
- + "Patch-set: 1\n"
- + "Current: blah");
+ assertParseSucceeds("Update change\n" + "\n" + "Patch-set: 1\n" + "Current: true");
+ assertParseSucceeds("Update change\n" + "\n" + "Patch-set: 1\n" + "Current: tRUe");
+ assertParseFails("Update change\n" + "\n" + "Patch-set: 1\n" + "Current: false");
+ assertParseFails("Update change\n" + "\n" + "Patch-set: 1\n" + "Current: blah");
}
private RevCommit writeCommit(String body) throws Exception {
ChangeNoteUtil noteUtil = injector.getInstance(ChangeNoteUtil.class);
- return writeCommit(body, noteUtil.newIdent(
- changeOwner.getAccount(), TimeUtil.nowTs(), serverIdent,
- "Anonymous Coward"));
+ return writeCommit(
+ body,
+ noteUtil.newIdent(
+ changeOwner.getAccount(), TimeUtil.nowTs(), serverIdent, "Anonymous Coward"));
}
- private RevCommit writeCommit(String body, PersonIdent author)
- throws Exception {
+ private RevCommit writeCommit(String body, PersonIdent author) throws Exception {
Change change = newChange();
ChangeNotes notes = newNotes(change).load();
try (ObjectInserter ins = testRepo.getRepository().newObjectInserter()) {
@@ -518,7 +509,6 @@
private ChangeNotesParser newParser(ObjectId tip) throws Exception {
walk.reset();
ChangeNoteUtil noteUtil = injector.getInstance(ChangeNoteUtil.class);
- return new ChangeNotesParser(
- newChange().getId(), tip, walk, noteUtil, args.metrics);
+ return new ChangeNotesParser(newChange().getId(), tip, walk, noteUtil, args.metrics);
}
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/notedb/ChangeNotesTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/notedb/ChangeNotesTest.java
index 3d7abb0..a4990c1 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/notedb/ChangeNotesTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/notedb/ChangeNotesTest.java
@@ -53,7 +53,11 @@
import com.google.gerrit.testutil.TestChanges;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
-
+import java.sql.Timestamp;
+import java.util.ArrayList;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.ObjectId;
@@ -65,21 +69,12 @@
import org.eclipse.jgit.revwalk.RevWalk;
import org.junit.Test;
-import java.sql.Timestamp;
-import java.util.ArrayList;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Map;
-
public class ChangeNotesTest extends AbstractChangeNotesTest {
- @Inject
- private DraftCommentNotes.Factory draftNotesFactory;
+ @Inject private DraftCommentNotes.Factory draftNotesFactory;
- @Inject
- private ChangeNoteUtil noteUtil;
+ @Inject private ChangeNoteUtil noteUtil;
- @Inject
- private @GerritServerId String serverId;
+ @Inject private @GerritServerId String serverId;
@Test
public void tagChangeMessage() throws Exception {
@@ -105,8 +100,7 @@
update.commit();
ChangeNotes notes = newNotes(c);
- assertThat(notes.getCurrentPatchSet().getDescription())
- .isEqualTo(description);
+ assertThat(notes.getCurrentPatchSet().getDescription()).isEqualTo(description);
description = "new, now more descriptive!";
update = newUpdate(c, changeOwner);
@@ -114,8 +108,7 @@
update.commit();
notes = newNotes(c);
- assertThat(notes.getCurrentPatchSet().getDescription())
- .isEqualTo(description);
+ assertThat(notes.getCurrentPatchSet().getDescription()).isEqualTo(description);
}
@Test
@@ -124,10 +117,21 @@
Change c = newChange();
RevCommit commit = tr.commit().message("PS2").create();
ChangeUpdate update = newUpdate(c, changeOwner);
- update.putComment(Status.PUBLISHED,
- newComment(c.currentPatchSetId(), "a.txt", "uuid1",
- new CommentRange(1, 2, 3, 4), 1, changeOwner, null,
- TimeUtil.nowTs(), "Comment", (short) 1, commit.name(), false));
+ update.putComment(
+ Status.PUBLISHED,
+ newComment(
+ c.currentPatchSetId(),
+ "a.txt",
+ "uuid1",
+ new CommentRange(1, 2, 3, 4),
+ 1,
+ changeOwner,
+ null,
+ TimeUtil.nowTs(),
+ "Comment",
+ (short) 1,
+ commit.name(),
+ false));
update.setTag(tag);
update.commit();
@@ -135,9 +139,7 @@
ImmutableListMultimap<RevId, Comment> comments = notes.getComments();
assertThat(comments).hasSize(1);
- assertThat(
- comments.entries().asList().get(0).getValue().tag)
- .isEqualTo(tag);
+ assertThat(comments.entries().asList().get(0).getValue().tag).isEqualTo(tag);
}
@Test
@@ -157,11 +159,9 @@
ChangeNotes notes = newNotes(c);
- ImmutableListMultimap<PatchSet.Id, PatchSetApproval> approvals =
- notes.getApprovals();
+ ImmutableListMultimap<PatchSet.Id, PatchSetApproval> approvals = notes.getApprovals();
assertThat(approvals).hasSize(1);
- assertThat(approvals.entries().asList().get(0).getValue().getTag())
- .isEqualTo(tag2);
+ assertThat(approvals.entries().asList().get(0).getValue().getTag()).isEqualTo(tag2);
}
@Test
@@ -179,10 +179,21 @@
RevCommit commit = tr.commit().message("PS2").create();
update = newUpdate(c, changeOwner);
- update.putComment(Status.PUBLISHED,
- newComment(c.currentPatchSetId(), "a.txt", "uuid1",
- new CommentRange(1, 2, 3, 4), 1, changeOwner, null,
- TimeUtil.nowTs(), "Comment", (short) 1, commit.name(), false));
+ update.putComment(
+ Status.PUBLISHED,
+ newComment(
+ c.currentPatchSetId(),
+ "a.txt",
+ "uuid1",
+ new CommentRange(1, 2, 3, 4),
+ 1,
+ changeOwner,
+ null,
+ TimeUtil.nowTs(),
+ "Comment",
+ (short) 1,
+ commit.name(),
+ false));
update.setChangeMessage("coverage verification");
update.setTag(coverageTag);
update.commit();
@@ -194,8 +205,7 @@
ChangeNotes notes = newNotes(c);
- ImmutableListMultimap<PatchSet.Id, PatchSetApproval> approvals =
- notes.getApprovals();
+ ImmutableListMultimap<PatchSet.Id, PatchSetApproval> approvals = notes.getApprovals();
assertThat(approvals).hasSize(1);
PatchSetApproval approval = approvals.entries().asList().get(0).getValue();
assertThat(approval.getTag()).isEqualTo(integrationTag);
@@ -203,8 +213,7 @@
ImmutableListMultimap<RevId, Comment> comments = notes.getComments();
assertThat(comments).hasSize(1);
- assertThat(comments.entries().asList().get(0).getValue().tag)
- .isEqualTo(coverageTag);
+ assertThat(comments.entries().asList().get(0).getValue().tag).isEqualTo(coverageTag);
ImmutableList<ChangeMessage> messages = notes.getChangeMessages();
assertThat(messages).hasSize(3);
@@ -222,10 +231,8 @@
update.commit();
ChangeNotes notes = newNotes(c);
- assertThat(notes.getApprovals().keySet())
- .containsExactly(c.currentPatchSetId());
- List<PatchSetApproval> psas =
- notes.getApprovals().get(c.currentPatchSetId());
+ assertThat(notes.getApprovals().keySet()).containsExactly(c.currentPatchSetId());
+ List<PatchSetApproval> psas = notes.getApprovals().get(c.currentPatchSetId());
assertThat(psas).hasSize(2);
assertThat(psas.get(0).getPatchSetId()).isEqualTo(c.currentPatchSetId());
@@ -282,8 +289,8 @@
update.commit();
ChangeNotes notes = newNotes(c);
- PatchSetApproval psa = Iterables.getOnlyElement(
- notes.getApprovals().get(c.currentPatchSetId()));
+ PatchSetApproval psa =
+ Iterables.getOnlyElement(notes.getApprovals().get(c.currentPatchSetId()));
assertThat(psa.getLabel()).isEqualTo("Code-Review");
assertThat(psa.getValue()).isEqualTo((short) -1);
@@ -292,8 +299,7 @@
update.commit();
notes = newNotes(c);
- psa = Iterables.getOnlyElement(
- notes.getApprovals().get(c.currentPatchSetId()));
+ psa = Iterables.getOnlyElement(notes.getApprovals().get(c.currentPatchSetId()));
assertThat(psa.getLabel()).isEqualTo("Code-Review");
assertThat(psa.getValue()).isEqualTo((short) 1);
}
@@ -310,10 +316,8 @@
update.commit();
ChangeNotes notes = newNotes(c);
- assertThat(notes.getApprovals().keySet())
- .containsExactly(c.currentPatchSetId());
- List<PatchSetApproval> psas =
- notes.getApprovals().get(c.currentPatchSetId());
+ assertThat(notes.getApprovals().keySet()).containsExactly(c.currentPatchSetId());
+ List<PatchSetApproval> psas = notes.getApprovals().get(c.currentPatchSetId());
assertThat(psas).hasSize(2);
assertThat(psas.get(0).getPatchSetId()).isEqualTo(c.currentPatchSetId());
@@ -337,8 +341,8 @@
update.commit();
ChangeNotes notes = newNotes(c);
- PatchSetApproval psa = Iterables.getOnlyElement(
- notes.getApprovals().get(c.currentPatchSetId()));
+ PatchSetApproval psa =
+ Iterables.getOnlyElement(notes.getApprovals().get(c.currentPatchSetId()));
assertThat(psa.getAccountId().get()).isEqualTo(1);
assertThat(psa.getLabel()).isEqualTo("Not-For-Long");
assertThat(psa.getValue()).isEqualTo((short) 1);
@@ -348,10 +352,11 @@
update.commit();
notes = newNotes(c);
- assertThat(notes.getApprovals()).containsExactlyEntriesIn(
- ImmutableListMultimap.of(
- psa.getPatchSetId(),
- new PatchSetApproval(psa.getKey(), (short) 0, update.getWhen())));
+ assertThat(notes.getApprovals())
+ .containsExactlyEntriesIn(
+ ImmutableListMultimap.of(
+ psa.getPatchSetId(),
+ new PatchSetApproval(psa.getKey(), (short) 0, update.getWhen())));
}
@Test
@@ -362,8 +367,8 @@
update.commit();
ChangeNotes notes = newNotes(c);
- PatchSetApproval psa = Iterables.getOnlyElement(
- notes.getApprovals().get(c.currentPatchSetId()));
+ PatchSetApproval psa =
+ Iterables.getOnlyElement(notes.getApprovals().get(c.currentPatchSetId()));
assertThat(psa.getAccountId()).isEqualTo(otherUserId);
assertThat(psa.getLabel()).isEqualTo("Not-For-Long");
assertThat(psa.getValue()).isEqualTo((short) 1);
@@ -373,10 +378,11 @@
update.commit();
notes = newNotes(c);
- assertThat(notes.getApprovals()).containsExactlyEntriesIn(
- ImmutableListMultimap.of(
- psa.getPatchSetId(),
- new PatchSetApproval(psa.getKey(), (short) 0, update.getWhen())));
+ assertThat(notes.getApprovals())
+ .containsExactlyEntriesIn(
+ ImmutableListMultimap.of(
+ psa.getPatchSetId(),
+ new PatchSetApproval(psa.getKey(), (short) 0, update.getWhen())));
// Add back approval on same label.
update = newUpdate(c, otherUser);
@@ -384,8 +390,7 @@
update.commit();
notes = newNotes(c);
- psa = Iterables.getOnlyElement(
- notes.getApprovals().get(c.currentPatchSetId()));
+ psa = Iterables.getOnlyElement(notes.getApprovals().get(c.currentPatchSetId()));
assertThat(psa.getAccountId()).isEqualTo(otherUserId);
assertThat(psa.getLabel()).isEqualTo("Not-For-Long");
assertThat(psa.getValue()).isEqualTo((short) 2);
@@ -400,18 +405,17 @@
update.commit();
ChangeNotes notes = newNotes(c);
- List<PatchSetApproval> approvals = ReviewDbUtil.intKeyOrdering()
- .onResultOf(PatchSetApproval::getAccountId)
- .sortedCopy(notes.getApprovals().get(c.currentPatchSetId()));
+ List<PatchSetApproval> approvals =
+ ReviewDbUtil.intKeyOrdering()
+ .onResultOf(PatchSetApproval::getAccountId)
+ .sortedCopy(notes.getApprovals().get(c.currentPatchSetId()));
assertThat(approvals).hasSize(2);
- assertThat(approvals.get(0).getAccountId())
- .isEqualTo(changeOwner.getAccountId());
+ assertThat(approvals.get(0).getAccountId()).isEqualTo(changeOwner.getAccountId());
assertThat(approvals.get(0).getLabel()).isEqualTo("Code-Review");
assertThat(approvals.get(0).getValue()).isEqualTo((short) 1);
- assertThat(approvals.get(1).getAccountId())
- .isEqualTo(otherUser.getAccountId());
+ assertThat(approvals.get(1).getAccountId()).isEqualTo(otherUser.getAccountId());
assertThat(approvals.get(1).getLabel()).isEqualTo("Code-Review");
assertThat(approvals.get(1).getValue()).isEqualTo((short) -1);
}
@@ -426,10 +430,14 @@
update.commit();
update = newUpdate(c, changeOwner);
- update.merge(submissionId, ImmutableList.of(
- submitRecord("NOT_READY", null,
- submitLabel("Verified", "OK", changeOwner.getAccountId()),
- submitLabel("Code-Review", "NEED", null))));
+ update.merge(
+ submissionId,
+ ImmutableList.of(
+ submitRecord(
+ "NOT_READY",
+ null,
+ submitLabel("Verified", "OK", changeOwner.getAccountId()),
+ submitLabel("Code-Review", "NEED", null))));
update.commit();
update = newUpdate(c, changeOwner);
@@ -437,8 +445,7 @@
update.commit();
ChangeNotes notes = newNotes(c);
- List<PatchSetApproval> approvals =
- Lists.newArrayList(notes.getApprovals().values());
+ List<PatchSetApproval> approvals = Lists.newArrayList(notes.getApprovals().values());
assertThat(approvals).hasSize(2);
assertThat(approvals.get(0).getLabel()).isEqualTo("Verified");
assertThat(approvals.get(0).getValue()).isEqualTo((short) 1);
@@ -460,10 +467,14 @@
Account.Id ownerId = changeOwner.getAccountId();
Account.Id otherId = otherUser.getAccountId();
update = newUpdate(c, otherUser);
- update.merge(submissionId, ImmutableList.of(
- submitRecord("NOT_READY", null,
- submitLabel("Verified", "OK", ownerId),
- submitLabel("Code-Review", "NEED", null))));
+ update.merge(
+ submissionId,
+ ImmutableList.of(
+ submitRecord(
+ "NOT_READY",
+ null,
+ submitLabel("Verified", "OK", ownerId),
+ submitLabel("Code-Review", "NEED", null))));
update.putApproval("Other-Label", (short) 1);
update.putApprovalFor(ownerId, "Code-Review", (short) 2);
update.commit();
@@ -474,8 +485,7 @@
ChangeNotes notes = newNotes(c);
- List<PatchSetApproval> approvals =
- Lists.newArrayList(notes.getApprovals().values());
+ List<PatchSetApproval> approvals = Lists.newArrayList(notes.getApprovals().values());
assertThat(approvals).hasSize(3);
assertThat(approvals.get(0).getAccountId()).isEqualTo(ownerId);
assertThat(approvals.get(0).getLabel()).isEqualTo("Verified");
@@ -501,11 +511,13 @@
ChangeNotes notes = newNotes(c);
Timestamp ts = new Timestamp(update.getWhen().getTime());
- assertThat(notes.getReviewers()).isEqualTo(ReviewerSet.fromTable(
- ImmutableTable.<ReviewerStateInternal, Account.Id, Timestamp>builder()
- .put(REVIEWER, new Account.Id(1), ts)
- .put(REVIEWER, new Account.Id(2), ts)
- .build()));
+ assertThat(notes.getReviewers())
+ .isEqualTo(
+ ReviewerSet.fromTable(
+ ImmutableTable.<ReviewerStateInternal, Account.Id, Timestamp>builder()
+ .put(REVIEWER, new Account.Id(1), ts)
+ .put(REVIEWER, new Account.Id(2), ts)
+ .build()));
}
@Test
@@ -518,11 +530,13 @@
ChangeNotes notes = newNotes(c);
Timestamp ts = new Timestamp(update.getWhen().getTime());
- assertThat(notes.getReviewers()).isEqualTo(ReviewerSet.fromTable(
- ImmutableTable.<ReviewerStateInternal, Account.Id, Timestamp>builder()
- .put(REVIEWER, new Account.Id(1), ts)
- .put(CC, new Account.Id(2), ts)
- .build()));
+ assertThat(notes.getReviewers())
+ .isEqualTo(
+ ReviewerSet.fromTable(
+ ImmutableTable.<ReviewerStateInternal, Account.Id, Timestamp>builder()
+ .put(REVIEWER, new Account.Id(1), ts)
+ .put(CC, new Account.Id(2), ts)
+ .build()));
}
@Test
@@ -534,8 +548,8 @@
ChangeNotes notes = newNotes(c);
Timestamp ts = new Timestamp(update.getWhen().getTime());
- assertThat(notes.getReviewers()).isEqualTo(ReviewerSet.fromTable(
- ImmutableTable.of(REVIEWER, new Account.Id(2), ts)));
+ assertThat(notes.getReviewers())
+ .isEqualTo(ReviewerSet.fromTable(ImmutableTable.of(REVIEWER, new Account.Id(2), ts)));
update = newUpdate(c, otherUser);
update.putReviewer(otherUser.getAccount().getId(), CC);
@@ -543,8 +557,8 @@
notes = newNotes(c);
ts = new Timestamp(update.getWhen().getTime());
- assertThat(notes.getReviewers()).isEqualTo(ReviewerSet.fromTable(
- ImmutableTable.of(CC, new Account.Id(2), ts)));
+ assertThat(notes.getReviewers())
+ .isEqualTo(ReviewerSet.fromTable(ImmutableTable.of(CC, new Account.Id(2), ts)));
}
@Test
@@ -563,13 +577,10 @@
update.commit();
ChangeNotes notes = newNotes(c);
- List<PatchSetApproval> psas =
- notes.getApprovals().get(c.currentPatchSetId());
+ List<PatchSetApproval> psas = notes.getApprovals().get(c.currentPatchSetId());
assertThat(psas).hasSize(2);
- assertThat(psas.get(0).getAccountId())
- .isEqualTo(changeOwner.getAccount().getId());
- assertThat(psas.get(1).getAccountId())
- .isEqualTo(otherUser.getAccount().getId());
+ assertThat(psas.get(0).getAccountId()).isEqualTo(changeOwner.getAccount().getId());
+ assertThat(psas.get(1).getAccountId()).isEqualTo(otherUser.getAccount().getId());
update = newUpdate(c, changeOwner);
update.removeReviewer(otherUser.getAccount().getId());
@@ -578,8 +589,7 @@
notes = newNotes(c);
psas = notes.getApprovals().get(c.currentPatchSetId());
assertThat(psas).hasSize(1);
- assertThat(psas.get(0).getAccountId())
- .isEqualTo(changeOwner.getAccount().getId());
+ assertThat(psas.get(0).getAccountId()).isEqualTo(changeOwner.getAccount().getId());
}
@Test
@@ -589,28 +599,39 @@
ChangeUpdate update = newUpdate(c, changeOwner);
update.setSubjectForCommit("Submit patch set 1");
- update.merge(submissionId, ImmutableList.of(
- submitRecord("NOT_READY", null,
- submitLabel("Verified", "OK", changeOwner.getAccountId()),
- submitLabel("Code-Review", "NEED", null)),
- submitRecord("NOT_READY", null,
- submitLabel("Verified", "OK", changeOwner.getAccountId()),
- submitLabel("Alternative-Code-Review", "NEED", null))));
+ update.merge(
+ submissionId,
+ ImmutableList.of(
+ submitRecord(
+ "NOT_READY",
+ null,
+ submitLabel("Verified", "OK", changeOwner.getAccountId()),
+ submitLabel("Code-Review", "NEED", null)),
+ submitRecord(
+ "NOT_READY",
+ null,
+ submitLabel("Verified", "OK", changeOwner.getAccountId()),
+ submitLabel("Alternative-Code-Review", "NEED", null))));
update.commit();
ChangeNotes notes = newNotes(c);
List<SubmitRecord> recs = notes.getSubmitRecords();
assertThat(recs).hasSize(2);
- assertThat(recs.get(0)).isEqualTo(
- submitRecord("NOT_READY", null,
- submitLabel("Verified", "OK", changeOwner.getAccountId()),
- submitLabel("Code-Review", "NEED", null)));
- assertThat(recs.get(1)).isEqualTo(
- submitRecord("NOT_READY", null,
- submitLabel("Verified", "OK", changeOwner.getAccountId()),
- submitLabel("Alternative-Code-Review", "NEED", null)));
- assertThat(notes.getChange().getSubmissionId())
- .isEqualTo(submissionId.toStringForStorage());
+ assertThat(recs.get(0))
+ .isEqualTo(
+ submitRecord(
+ "NOT_READY",
+ null,
+ submitLabel("Verified", "OK", changeOwner.getAccountId()),
+ submitLabel("Code-Review", "NEED", null)));
+ assertThat(recs.get(1))
+ .isEqualTo(
+ submitRecord(
+ "NOT_READY",
+ null,
+ submitLabel("Verified", "OK", changeOwner.getAccountId()),
+ submitLabel("Alternative-Code-Review", "NEED", null)));
+ assertThat(notes.getChange().getSubmissionId()).isEqualTo(submissionId.toStringForStorage());
}
@Test
@@ -619,25 +640,27 @@
RequestId submissionId = RequestId.forChange(c);
ChangeUpdate update = newUpdate(c, changeOwner);
update.setSubjectForCommit("Submit patch set 1");
- update.merge(submissionId, ImmutableList.of(
- submitRecord("OK", null,
- submitLabel("Code-Review", "OK", otherUser.getAccountId()))));
+ update.merge(
+ submissionId,
+ ImmutableList.of(
+ submitRecord("OK", null, submitLabel("Code-Review", "OK", otherUser.getAccountId()))));
update.commit();
incrementPatchSet(c);
update = newUpdate(c, changeOwner);
update.setSubjectForCommit("Submit patch set 2");
- update.merge(submissionId, ImmutableList.of(
- submitRecord("OK", null,
- submitLabel("Code-Review", "OK", changeOwner.getAccountId()))));
+ update.merge(
+ submissionId,
+ ImmutableList.of(
+ submitRecord(
+ "OK", null, submitLabel("Code-Review", "OK", changeOwner.getAccountId()))));
update.commit();
ChangeNotes notes = newNotes(c);
- assertThat(notes.getSubmitRecords()).containsExactly(
- submitRecord("OK", null,
- submitLabel("Code-Review", "OK", changeOwner.getAccountId())));
- assertThat(notes.getChange().getSubmissionId())
- .isEqualTo(submissionId.toStringForStorage());
+ assertThat(notes.getSubmitRecords())
+ .containsExactly(
+ submitRecord("OK", null, submitLabel("Code-Review", "OK", changeOwner.getAccountId())));
+ assertThat(notes.getChange().getSubmissionId()).isEqualTo(submissionId.toStringForStorage());
}
@Test
@@ -665,15 +688,8 @@
try (RevWalk rw = new RevWalk(repo)) {
RevCommit commit = rw.parseCommit(update.getResult());
rw.parseBody(commit);
- String strIdent =
- otherUser.getName()
- + " <"
- + otherUserId
- + "@"
- + serverId
- + ">";
- assertThat(commit.getFullMessage())
- .contains("Assignee: " + strIdent);
+ String strIdent = otherUser.getName() + " <" + otherUserId + "@" + serverId + ">";
+ assertThat(commit.getFullMessage()).contains("Assignee: " + strIdent);
}
}
@@ -692,8 +708,7 @@
update.commit();
notes = newNotes(c);
- assertThat(notes.getChange().getAssignee())
- .isEqualTo(changeOwner.getAccountId());
+ assertThat(notes.getChange().getAssignee()).isEqualTo(changeOwner.getAccountId());
}
@Test
@@ -807,8 +822,11 @@
String otherChangeId = "I577fb248e474018276351785930358ec0450e9f7";
update = newUpdate(c, changeOwner);
exception.expect(IllegalArgumentException.class);
- exception.expectMessage("The Change-Id was already set to " + c.getKey()
- + ", so we cannot set this Change-Id: " + otherChangeId);
+ exception.expectMessage(
+ "The Change-Id was already set to "
+ + c.getKey()
+ + ", so we cannot set this Change-Id: "
+ + otherChangeId);
update.setChangeId(otherChangeId);
}
@@ -817,8 +835,7 @@
Change c = newChange();
ChangeNotes notes = newNotes(c);
- Branch.NameKey expectedBranch =
- new Branch.NameKey(project, "refs/heads/master");
+ Branch.NameKey expectedBranch = new Branch.NameKey(project, "refs/heads/master");
assertThat(notes.getChange().getDest()).isEqualTo(expectedBranch);
// An update doesn't affect the branch
@@ -832,23 +849,21 @@
update = newUpdate(c, changeOwner);
update.setBranch(otherBranch);
update.commit();
- assertThat(newNotes(c).getChange().getDest()).isEqualTo(
- new Branch.NameKey(project, otherBranch));
+ assertThat(newNotes(c).getChange().getDest())
+ .isEqualTo(new Branch.NameKey(project, otherBranch));
}
@Test
public void ownerChangeNotes() throws Exception {
Change c = newChange();
- assertThat(newNotes(c).getChange().getOwner()).isEqualTo(
- changeOwner.getAccountId());
+ assertThat(newNotes(c).getChange().getOwner()).isEqualTo(changeOwner.getAccountId());
// An update doesn't affect the owner
ChangeUpdate update = newUpdate(c, otherUser);
update.setTopic("topic"); // Change something to get a new commit.
update.commit();
- assertThat(newNotes(c).getChange().getOwner()).isEqualTo(
- changeOwner.getAccountId());
+ assertThat(newNotes(c).getChange().getOwner()).isEqualTo(changeOwner.getAccountId());
}
@Test
@@ -922,10 +937,14 @@
// Finish off by merging the change.
update = newUpdate(c, changeOwner);
- update.merge(RequestId.forChange(c), ImmutableList.of(
- submitRecord("NOT_READY", null,
- submitLabel("Verified", "OK", changeOwner.getAccountId()),
- submitLabel("Alternative-Code-Review", "NEED", null))));
+ update.merge(
+ RequestId.forChange(c),
+ ImmutableList.of(
+ submitRecord(
+ "NOT_READY",
+ null,
+ submitLabel("Verified", "OK", changeOwner.getAccountId()),
+ submitLabel("Alternative-Code-Review", "NEED", null))));
update.commit();
Timestamp ts10 = newNotes(c).getChange().getLastUpdatedOn();
assertThat(ts10).isGreaterThan(ts9);
@@ -935,8 +954,7 @@
public void subjectLeadingWhitespaceChangeNotes() throws Exception {
Change c = TestChanges.newChange(project, changeOwner.getAccountId());
String trimmedSubj = c.getSubject();
- c.setCurrentPatchSet(c.currentPatchSetId(), " " + trimmedSubj,
- c.getOriginalSubject());
+ c.setCurrentPatchSet(c.currentPatchSetId(), " " + trimmedSubj, c.getOriginalSubject());
ChangeUpdate update = newUpdate(c, changeOwner);
update.setChangeId(c.getKey().get());
update.setBranch(c.getDest().get());
@@ -948,8 +966,7 @@
String tabSubj = "\t\t" + trimmedSubj;
c = TestChanges.newChange(project, changeOwner.getAccountId());
- c.setCurrentPatchSet(c.currentPatchSetId(), tabSubj,
- c.getOriginalSubject());
+ c.setCurrentPatchSet(c.currentPatchSetId(), tabSubj, c.getOriginalSubject());
update = newUpdate(c, changeOwner);
update.setChangeId(c.getKey().get());
update.setBranch(c.getDest().get());
@@ -978,9 +995,14 @@
notes = newNotes(c);
fail("Expected IOException");
} catch (OrmException e) {
- assertCause(e, ConfigInvalidException.class,
+ assertCause(
+ e,
+ ConfigInvalidException.class,
"Multiple revisions parsed for patch set 1:"
- + " RevId{" + commit.name() + "} and " + ps.getRevision().get());
+ + " RevId{"
+ + commit.name()
+ + "} and "
+ + ps.getRevision().get());
}
}
@@ -993,8 +1015,7 @@
PatchSet ps1 = notes.getCurrentPatchSet();
assertThat(notes.getChange().currentPatchSetId()).isEqualTo(ps1.getId());
assertThat(notes.getChange().getSubject()).isEqualTo("Change subject");
- assertThat(notes.getChange().getOriginalSubject())
- .isEqualTo("Change subject");
+ assertThat(notes.getChange().getOriginalSubject()).isEqualTo("Change subject");
assertThat(ps1.getId()).isEqualTo(new PatchSet.Id(c.getId(), 1));
assertThat(ps1.getUploader()).isEqualTo(changeOwner.getAccountId());
@@ -1004,14 +1025,12 @@
PatchSet ps2 = notes.getCurrentPatchSet();
assertThat(ps2.getId()).isEqualTo(new PatchSet.Id(c.getId(), 2));
assertThat(notes.getChange().getSubject()).isEqualTo("PS2");
- assertThat(notes.getChange().getOriginalSubject())
- .isEqualTo("Change subject");
+ assertThat(notes.getChange().getOriginalSubject()).isEqualTo("Change subject");
assertThat(notes.getChange().currentPatchSetId()).isEqualTo(ps2.getId());
assertThat(ps2.getRevision().get()).isNotEqualTo(ps1.getRevision());
assertThat(ps2.getRevision().get()).isEqualTo(commit.name());
assertThat(ps2.getUploader()).isEqualTo(otherUser.getAccountId());
- assertThat(ps2.getCreatedOn())
- .isEqualTo(notes.getChange().getLastUpdatedOn());
+ assertThat(ps2.getCreatedOn()).isEqualTo(notes.getChange().getLastUpdatedOn());
// comment on ps1, current patch set is still ps2
ChangeUpdate update = newUpdate(c, changeOwner);
@@ -1035,10 +1054,21 @@
update.setPatchSetState(PatchSetState.DRAFT);
update.putApproval("Code-Review", (short) 1);
update.setChangeMessage("This is a message");
- update.putComment(Status.PUBLISHED,
- newComment(c.currentPatchSetId(), "a.txt", "uuid1",
- new CommentRange(1, 2, 3, 4), 1, changeOwner, null,
- TimeUtil.nowTs(), "Comment", (short) 1, commit.name(), false));
+ update.putComment(
+ Status.PUBLISHED,
+ newComment(
+ c.currentPatchSetId(),
+ "a.txt",
+ "uuid1",
+ new CommentRange(1, 2, 3, 4),
+ 1,
+ changeOwner,
+ null,
+ TimeUtil.nowTs(),
+ "Comment",
+ (short) 1,
+ commit.name(),
+ false));
update.commit();
ChangeNotes notes = newNotes(c);
@@ -1083,8 +1113,7 @@
update.setGroups(ImmutableList.of("a", "b"));
update.commit();
notes = newNotes(c);
- assertThat(notes.getPatchSets().get(psId1).getGroups())
- .containsExactly("a", "b").inOrder();
+ assertThat(notes.getPatchSets().get(psId1).getGroups()).containsExactly("a", "b").inOrder();
incrementCurrentPatchSetFieldOnly(c);
PatchSet.Id psId2 = c.currentPatchSetId();
@@ -1093,21 +1122,20 @@
update.setGroups(ImmutableList.of("d"));
update.commit();
notes = newNotes(c);
- assertThat(notes.getPatchSets().get(psId2).getGroups())
- .containsExactly("d");
- assertThat(notes.getPatchSets().get(psId1).getGroups())
- .containsExactly("a", "b").inOrder();
+ assertThat(notes.getPatchSets().get(psId2).getGroups()).containsExactly("d");
+ assertThat(notes.getPatchSets().get(psId1).getGroups()).containsExactly("a", "b").inOrder();
}
@Test
public void pushCertificate() throws Exception {
- String pushCert = "certificate version 0.1\n"
- + "pusher This is not a real push cert\n"
- + "-----BEGIN PGP SIGNATURE-----\n"
- + "Version: GnuPG v1\n"
- + "\n"
- + "Nor is this a real signature.\n"
- + "-----END PGP SIGNATURE-----\n";
+ String pushCert =
+ "certificate version 0.1\n"
+ + "pusher This is not a real push cert\n"
+ + "-----BEGIN PGP SIGNATURE-----\n"
+ + "Version: GnuPG v1\n"
+ + "\n"
+ + "Nor is this a real signature.\n"
+ + "-----END PGP SIGNATURE-----\n";
// ps2 with push cert
Change c = newChange();
@@ -1134,9 +1162,21 @@
update = newUpdate(c, changeOwner);
update.setPatchSetId(psId2);
Timestamp ts = TimeUtil.nowTs();
- update.putComment(Status.PUBLISHED,
- newComment(psId2, "a.txt", "uuid1", new CommentRange(1, 2, 3, 4), 1,
- changeOwner, null, ts, "Comment", (short) 1, commit.name(), false));
+ update.putComment(
+ Status.PUBLISHED,
+ newComment(
+ psId2,
+ "a.txt",
+ "uuid1",
+ new CommentRange(1, 2, 3, 4),
+ 1,
+ changeOwner,
+ null,
+ ts,
+ "Comment",
+ (short) 1,
+ commit.name(),
+ false));
update.commit();
notes = newNotes(c);
@@ -1147,20 +1187,24 @@
assertThat(notes.getComments()).isNotEmpty();
if (!testJson()) {
- assertThat(readNote(notes, commit)).isEqualTo(
- pushCert
- + "Revision: " + commit.name() + "\n"
- + "Patch-set: 2\n"
- + "File: a.txt\n"
- + "\n"
- + "1:2-3:4\n"
- + ChangeNoteUtil.formatTime(serverIdent, ts) + "\n"
- + "Author: Change Owner <1@gerrit>\n"
- + "Unresolved: false\n"
- + "UUID: uuid1\n"
- + "Bytes: 7\n"
- + "Comment\n"
- + "\n");
+ assertThat(readNote(notes, commit))
+ .isEqualTo(
+ pushCert
+ + "Revision: "
+ + commit.name()
+ + "\n"
+ + "Patch-set: 2\n"
+ + "File: a.txt\n"
+ + "\n"
+ + "1:2-3:4\n"
+ + ChangeNoteUtil.formatTime(serverIdent, ts)
+ + "\n"
+ + "Author: Change Owner <1@gerrit>\n"
+ + "Unresolved: false\n"
+ + "UUID: uuid1\n"
+ + "Bytes: 7\n"
+ + "Comment\n"
+ + "\n");
}
}
@@ -1180,25 +1224,21 @@
ChangeUpdate update2 = newUpdate(c, otherUser);
update2.putApproval("Code-Review", (short) 2);
- try (NoteDbUpdateManager updateManager =
- updateManagerFactory.create(project)) {
+ try (NoteDbUpdateManager updateManager = updateManagerFactory.create(project)) {
updateManager.add(update1);
updateManager.add(update2);
updateManager.execute();
}
ChangeNotes notes = newNotes(c);
- List<PatchSetApproval> psas =
- notes.getApprovals().get(c.currentPatchSetId());
+ List<PatchSetApproval> psas = notes.getApprovals().get(c.currentPatchSetId());
assertThat(psas).hasSize(2);
- assertThat(psas.get(0).getAccountId())
- .isEqualTo(changeOwner.getAccount().getId());
+ assertThat(psas.get(0).getAccountId()).isEqualTo(changeOwner.getAccount().getId());
assertThat(psas.get(0).getLabel()).isEqualTo("Verified");
assertThat(psas.get(0).getValue()).isEqualTo((short) 1);
- assertThat(psas.get(1).getAccountId())
- .isEqualTo(otherUser.getAccount().getId());
+ assertThat(psas.get(1).getAccountId()).isEqualTo(otherUser.getAccount().getId());
assertThat(psas.get(1).getLabel()).isEqualTo("Code-Review");
assertThat(psas.get(1).getValue()).isEqualTo((short) 2);
}
@@ -1213,11 +1253,21 @@
Timestamp time1 = TimeUtil.nowTs();
PatchSet.Id psId = c.currentPatchSetId();
RevCommit tipCommit;
- try (NoteDbUpdateManager updateManager =
- updateManagerFactory.create(project)) {
- Comment comment1 = newComment(psId, "file1",
- uuid1, range1, range1.getEndLine(), otherUser, null, time1, message1,
- (short) 0, "abcd1234abcd1234abcd1234abcd1234abcd1234", false);
+ try (NoteDbUpdateManager updateManager = updateManagerFactory.create(project)) {
+ Comment comment1 =
+ newComment(
+ psId,
+ "file1",
+ uuid1,
+ range1,
+ range1.getEndLine(),
+ otherUser,
+ null,
+ time1,
+ message1,
+ (short) 0,
+ "abcd1234abcd1234abcd1234abcd1234abcd1234",
+ false);
update1.setPatchSetId(psId);
update1.putComment(Status.PUBLISHED, comment1);
updateManager.add(update1);
@@ -1239,16 +1289,16 @@
assertThat(commitWithComments).isNotNull();
try (ChangeNotesRevWalk rw = ChangeNotesCommit.newRevWalk(repo)) {
- ChangeNotesParser notesWithComments = new ChangeNotesParser(
- c.getId(), commitWithComments.copy(), rw, noteUtil, args.metrics);
+ ChangeNotesParser notesWithComments =
+ new ChangeNotesParser(c.getId(), commitWithComments.copy(), rw, noteUtil, args.metrics);
ChangeNotesState state = notesWithComments.parseAll();
assertThat(state.approvals()).isEmpty();
assertThat(state.publishedComments()).hasSize(1);
}
try (ChangeNotesRevWalk rw = ChangeNotesCommit.newRevWalk(repo)) {
- ChangeNotesParser notesWithApprovals = new ChangeNotesParser(c.getId(),
- commitWithApprovals.copy(), rw, noteUtil, args.metrics);
+ ChangeNotesParser notesWithApprovals =
+ new ChangeNotesParser(c.getId(), commitWithApprovals.copy(), rw, noteUtil, args.metrics);
ChangeNotesState state = notesWithApprovals.parseAll();
assertThat(state.approvals()).hasSize(1);
assertThat(state.publishedComments()).hasSize(1);
@@ -1270,8 +1320,7 @@
Ref initial2 = repo.exactRef(update2.getRefName());
assertThat(initial2).isNotNull();
- try (NoteDbUpdateManager updateManager =
- updateManagerFactory.create(project)) {
+ try (NoteDbUpdateManager updateManager = updateManagerFactory.create(project)) {
updateManager.add(update1);
updateManager.add(update2);
updateManager.execute();
@@ -1284,12 +1333,12 @@
assertThat(ref2.getObjectId()).isEqualTo(update2.getResult());
assertThat(ref2.getObjectId()).isNotEqualTo(initial2.getObjectId());
- PatchSetApproval approval1 = newNotes(c1).getApprovals()
- .get(c1.currentPatchSetId()).iterator().next();
+ PatchSetApproval approval1 =
+ newNotes(c1).getApprovals().get(c1.currentPatchSetId()).iterator().next();
assertThat(approval1.getLabel()).isEqualTo("Verified");
- PatchSetApproval approval2 = newNotes(c2).getApprovals()
- .get(c2.currentPatchSetId()).iterator().next();
+ PatchSetApproval approval2 =
+ newNotes(c2).getApprovals().get(c2.currentPatchSetId()).iterator().next();
assertThat(approval2.getLabel()).isEqualTo("Code-Review");
}
@@ -1303,8 +1352,7 @@
PatchSet.Id ps1 = c.currentPatchSetId();
ChangeNotes notes = newNotes(c);
- ListMultimap<PatchSet.Id, ChangeMessage> changeMessages =
- notes.getChangeMessagesByPatchSet();
+ ListMultimap<PatchSet.Id, ChangeMessage> changeMessages = notes.getChangeMessagesByPatchSet();
assertThat(changeMessages.keySet()).containsExactly(ps1);
ChangeMessage cm = Iterables.getOnlyElement(changeMessages.get(ps1));
@@ -1328,14 +1376,12 @@
public void changeMessageWithTrailingDoubleNewline() throws Exception {
Change c = newChange();
ChangeUpdate update = newUpdate(c, changeOwner);
- update.setChangeMessage("Testing trailing double newline\n"
- + "\n");
+ update.setChangeMessage("Testing trailing double newline\n" + "\n");
update.commit();
PatchSet.Id ps1 = c.currentPatchSetId();
ChangeNotes notes = newNotes(c);
- ListMultimap<PatchSet.Id, ChangeMessage> changeMessages =
- notes.getChangeMessagesByPatchSet();
+ ListMultimap<PatchSet.Id, ChangeMessage> changeMessages = notes.getChangeMessagesByPatchSet();
assertThat(changeMessages).hasSize(1);
ChangeMessage cm1 = Iterables.getOnlyElement(changeMessages.get(ps1));
@@ -1347,25 +1393,23 @@
public void changeMessageWithMultipleParagraphs() throws Exception {
Change c = newChange();
ChangeUpdate update = newUpdate(c, changeOwner);
- update.setChangeMessage("Testing paragraph 1\n"
- + "\n"
- + "Testing paragraph 2\n"
- + "\n"
- + "Testing paragraph 3");
+ update.setChangeMessage(
+ "Testing paragraph 1\n" + "\n" + "Testing paragraph 2\n" + "\n" + "Testing paragraph 3");
update.commit();
PatchSet.Id ps1 = c.currentPatchSetId();
ChangeNotes notes = newNotes(c);
- ListMultimap<PatchSet.Id, ChangeMessage> changeMessages =
- notes.getChangeMessagesByPatchSet();
+ ListMultimap<PatchSet.Id, ChangeMessage> changeMessages = notes.getChangeMessagesByPatchSet();
assertThat(changeMessages).hasSize(1);
ChangeMessage cm1 = Iterables.getOnlyElement(changeMessages.get(ps1));
- assertThat(cm1.getMessage()).isEqualTo("Testing paragraph 1\n"
- + "\n"
- + "Testing paragraph 2\n"
- + "\n"
- + "Testing paragraph 3");
+ assertThat(cm1.getMessage())
+ .isEqualTo(
+ "Testing paragraph 1\n"
+ + "\n"
+ + "Testing paragraph 2\n"
+ + "\n"
+ + "Testing paragraph 3");
assertThat(cm1.getAuthor()).isEqualTo(changeOwner.getAccount().getId());
}
@@ -1386,19 +1430,16 @@
PatchSet.Id ps2 = c.currentPatchSetId();
ChangeNotes notes = newNotes(c);
- ListMultimap<PatchSet.Id, ChangeMessage> changeMessages =
- notes.getChangeMessagesByPatchSet();
+ ListMultimap<PatchSet.Id, ChangeMessage> changeMessages = notes.getChangeMessagesByPatchSet();
assertThat(changeMessages).hasSize(2);
ChangeMessage cm1 = Iterables.getOnlyElement(changeMessages.get(ps1));
- assertThat(cm1.getMessage())
- .isEqualTo("This is the change message for the first PS.");
+ assertThat(cm1.getMessage()).isEqualTo("This is the change message for the first PS.");
assertThat(cm1.getAuthor()).isEqualTo(changeOwner.getAccount().getId());
ChangeMessage cm2 = Iterables.getOnlyElement(changeMessages.get(ps2));
assertThat(cm1.getPatchSetId()).isEqualTo(ps1);
- assertThat(cm2.getMessage())
- .isEqualTo("This is the change message for the second PS.");
+ assertThat(cm2.getMessage()).isEqualTo("This is the change message for the second PS.");
assertThat(cm2.getAuthor()).isEqualTo(changeOwner.getAccount().getId());
assertThat(cm2.getPatchSetId()).isEqualTo(ps2);
}
@@ -1419,19 +1460,16 @@
update.commit();
ChangeNotes notes = newNotes(c);
- ListMultimap<PatchSet.Id, ChangeMessage> changeMessages =
- notes.getChangeMessagesByPatchSet();
+ ListMultimap<PatchSet.Id, ChangeMessage> changeMessages = notes.getChangeMessagesByPatchSet();
assertThat(changeMessages.keySet()).hasSize(1);
List<ChangeMessage> cm = changeMessages.get(ps1);
assertThat(cm).hasSize(2);
assertThat(cm.get(0).getMessage()).isEqualTo("First change message.\n");
- assertThat(cm.get(0).getAuthor())
- .isEqualTo(changeOwner.getAccount().getId());
+ assertThat(cm.get(0).getAuthor()).isEqualTo(changeOwner.getAccount().getId());
assertThat(cm.get(0).getPatchSetId()).isEqualTo(ps1);
assertThat(cm.get(1).getMessage()).isEqualTo("Second change message.\n");
- assertThat(cm.get(1).getAuthor())
- .isEqualTo(changeOwner.getAccount().getId());
+ assertThat(cm.get(1).getAuthor()).isEqualTo(changeOwner.getAccount().getId());
assertThat(cm.get(1).getPatchSetId()).isEqualTo(ps1);
}
@@ -1442,16 +1480,26 @@
PatchSet.Id psId = c.currentPatchSetId();
RevId revId = new RevId("abcd1234abcd1234abcd1234abcd1234abcd1234");
- Comment comment = newComment(psId, "file1",
- "uuid", null, 0, otherUser, null,
- TimeUtil.nowTs(), "message", (short) 1, revId.get(), false);
+ Comment comment =
+ newComment(
+ psId,
+ "file1",
+ "uuid",
+ null,
+ 0,
+ otherUser,
+ null,
+ TimeUtil.nowTs(),
+ "message",
+ (short) 1,
+ revId.get(),
+ false);
update.setPatchSetId(psId);
update.putComment(Status.PUBLISHED, comment);
update.commit();
ChangeNotes notes = newNotes(c);
- assertThat(notes.getComments())
- .isEqualTo(ImmutableListMultimap.of(revId, comment));
+ assertThat(notes.getComments()).isEqualTo(ImmutableListMultimap.of(revId, comment));
}
@Test
@@ -1462,16 +1510,26 @@
RevId revId = new RevId("abcd1234abcd1234abcd1234abcd1234abcd1234");
CommentRange range = new CommentRange(1, 0, 2, 0);
- Comment comment = newComment(psId, "file1",
- "uuid", range, range.getEndLine(), otherUser, null,
- TimeUtil.nowTs(), "message", (short) 1, revId.get(), false);
+ Comment comment =
+ newComment(
+ psId,
+ "file1",
+ "uuid",
+ range,
+ range.getEndLine(),
+ otherUser,
+ null,
+ TimeUtil.nowTs(),
+ "message",
+ (short) 1,
+ revId.get(),
+ false);
update.setPatchSetId(psId);
update.putComment(Status.PUBLISHED, comment);
update.commit();
ChangeNotes notes = newNotes(c);
- assertThat(notes.getComments())
- .isEqualTo(ImmutableListMultimap.of(revId, comment));
+ assertThat(notes.getComments()).isEqualTo(ImmutableListMultimap.of(revId, comment));
}
@Test
@@ -1482,16 +1540,26 @@
RevId revId = new RevId("abcd1234abcd1234abcd1234abcd1234abcd1234");
CommentRange range = new CommentRange(0, 0, 0, 0);
- Comment comment = newComment(psId, "file",
- "uuid", range, range.getEndLine(), otherUser, null,
- TimeUtil.nowTs(), "message", (short) 1, revId.get(), false);
+ Comment comment =
+ newComment(
+ psId,
+ "file",
+ "uuid",
+ range,
+ range.getEndLine(),
+ otherUser,
+ null,
+ TimeUtil.nowTs(),
+ "message",
+ (short) 1,
+ revId.get(),
+ false);
update.setPatchSetId(psId);
update.putComment(Status.PUBLISHED, comment);
update.commit();
ChangeNotes notes = newNotes(c);
- assertThat(notes.getComments())
- .isEqualTo(ImmutableListMultimap.of(revId, comment));
+ assertThat(notes.getComments()).isEqualTo(ImmutableListMultimap.of(revId, comment));
}
@Test
@@ -1502,16 +1570,26 @@
RevId revId = new RevId("abcd1234abcd1234abcd1234abcd1234abcd1234");
CommentRange range = new CommentRange(1, 2, 3, 4);
- Comment comment = newComment(psId, "", "uuid", range, range.getEndLine(),
- otherUser, null, TimeUtil.nowTs(), "message", (short) 1, revId.get(),
- false);
+ Comment comment =
+ newComment(
+ psId,
+ "",
+ "uuid",
+ range,
+ range.getEndLine(),
+ otherUser,
+ null,
+ TimeUtil.nowTs(),
+ "message",
+ (short) 1,
+ revId.get(),
+ false);
update.setPatchSetId(psId);
update.putComment(Status.PUBLISHED, comment);
update.commit();
ChangeNotes notes = newNotes(c);
- assertThat(notes.getComments())
- .isEqualTo(ImmutableListMultimap.of(revId, comment));
+ assertThat(notes.getComments()).isEqualTo(ImmutableListMultimap.of(revId, comment));
}
@Test
@@ -1530,27 +1608,60 @@
Timestamp time3 = TimeUtil.nowTs();
PatchSet.Id psId = c.currentPatchSetId();
- Comment comment1 = newComment(psId, "file1", uuid1, range1,
- range1.getEndLine(), otherUser, null, time1, message1, (short) 1,
- "abcd1234abcd1234abcd1234abcd1234abcd1234", false);
+ Comment comment1 =
+ newComment(
+ psId,
+ "file1",
+ uuid1,
+ range1,
+ range1.getEndLine(),
+ otherUser,
+ null,
+ time1,
+ message1,
+ (short) 1,
+ "abcd1234abcd1234abcd1234abcd1234abcd1234",
+ false);
update.setPatchSetId(psId);
update.putComment(Status.PUBLISHED, comment1);
update.commit();
update = newUpdate(c, otherUser);
CommentRange range2 = new CommentRange(2, 1, 3, 1);
- Comment comment2 = newComment(psId, "file1", uuid2, range2,
- range2.getEndLine(), otherUser, null, time2, message2, (short) 1,
- "abcd1234abcd1234abcd1234abcd1234abcd1234", false);
+ Comment comment2 =
+ newComment(
+ psId,
+ "file1",
+ uuid2,
+ range2,
+ range2.getEndLine(),
+ otherUser,
+ null,
+ time2,
+ message2,
+ (short) 1,
+ "abcd1234abcd1234abcd1234abcd1234abcd1234",
+ false);
update.setPatchSetId(psId);
update.putComment(Status.PUBLISHED, comment2);
update.commit();
update = newUpdate(c, otherUser);
CommentRange range3 = new CommentRange(3, 0, 4, 1);
- Comment comment3 = newComment(psId, "file2", uuid3, range3,
- range3.getEndLine(), otherUser, null, time3, message3, (short) 1,
- "abcd1234abcd1234abcd1234abcd1234abcd1234", false);
+ Comment comment3 =
+ newComment(
+ psId,
+ "file2",
+ uuid3,
+ range3,
+ range3.getEndLine(),
+ otherUser,
+ null,
+ time3,
+ message3,
+ (short) 1,
+ "abcd1234abcd1234abcd1234abcd1234abcd1234",
+ false);
update.setPatchSetId(psId);
update.putComment(Status.PUBLISHED, comment3);
update.commit();
@@ -1558,47 +1669,48 @@
ChangeNotes notes = newNotes(c);
try (RevWalk walk = new RevWalk(repo)) {
- ArrayList<Note> notesInTree =
- Lists.newArrayList(notes.revisionNoteMap.noteMap.iterator());
+ ArrayList<Note> notesInTree = Lists.newArrayList(notes.revisionNoteMap.noteMap.iterator());
Note note = Iterables.getOnlyElement(notesInTree);
- byte[] bytes =
- walk.getObjectReader().open(
- note.getData(), Constants.OBJ_BLOB).getBytes();
+ byte[] bytes = walk.getObjectReader().open(note.getData(), Constants.OBJ_BLOB).getBytes();
String noteString = new String(bytes, UTF_8);
if (!testJson()) {
- assertThat(noteString).isEqualTo(
- "Revision: abcd1234abcd1234abcd1234abcd1234abcd1234\n"
- + "Patch-set: 1\n"
- + "File: file1\n"
- + "\n"
- + "1:1-2:1\n"
- + ChangeNoteUtil.formatTime(serverIdent, time1) + "\n"
- + "Author: Other Account <2@gerrit>\n"
- + "Unresolved: false\n"
- + "UUID: uuid1\n"
- + "Bytes: 9\n"
- + "comment 1\n"
- + "\n"
- + "2:1-3:1\n"
- + ChangeNoteUtil.formatTime(serverIdent, time2) + "\n"
- + "Author: Other Account <2@gerrit>\n"
- + "Unresolved: false\n"
- + "UUID: uuid2\n"
- + "Bytes: 9\n"
- + "comment 2\n"
- + "\n"
- + "File: file2\n"
- + "\n"
- + "3:0-4:1\n"
- + ChangeNoteUtil.formatTime(serverIdent, time3) + "\n"
- + "Author: Other Account <2@gerrit>\n"
- + "Unresolved: false\n"
- + "UUID: uuid3\n"
- + "Bytes: 9\n"
- + "comment 3\n"
- + "\n");
+ assertThat(noteString)
+ .isEqualTo(
+ "Revision: abcd1234abcd1234abcd1234abcd1234abcd1234\n"
+ + "Patch-set: 1\n"
+ + "File: file1\n"
+ + "\n"
+ + "1:1-2:1\n"
+ + ChangeNoteUtil.formatTime(serverIdent, time1)
+ + "\n"
+ + "Author: Other Account <2@gerrit>\n"
+ + "Unresolved: false\n"
+ + "UUID: uuid1\n"
+ + "Bytes: 9\n"
+ + "comment 1\n"
+ + "\n"
+ + "2:1-3:1\n"
+ + ChangeNoteUtil.formatTime(serverIdent, time2)
+ + "\n"
+ + "Author: Other Account <2@gerrit>\n"
+ + "Unresolved: false\n"
+ + "UUID: uuid2\n"
+ + "Bytes: 9\n"
+ + "comment 2\n"
+ + "\n"
+ + "File: file2\n"
+ + "\n"
+ + "3:0-4:1\n"
+ + ChangeNoteUtil.formatTime(serverIdent, time3)
+ + "\n"
+ + "Author: Other Account <2@gerrit>\n"
+ + "Unresolved: false\n"
+ + "UUID: uuid3\n"
+ + "Bytes: 9\n"
+ + "comment 3\n"
+ + "\n");
}
}
}
@@ -1616,18 +1728,40 @@
Timestamp time2 = TimeUtil.nowTs();
PatchSet.Id psId = c.currentPatchSetId();
- Comment comment1 = newComment(psId, "file1",
- uuid1, range1, range1.getEndLine(), otherUser, null, time1, message1,
- (short) 0, "abcd1234abcd1234abcd1234abcd1234abcd1234", false);
+ Comment comment1 =
+ newComment(
+ psId,
+ "file1",
+ uuid1,
+ range1,
+ range1.getEndLine(),
+ otherUser,
+ null,
+ time1,
+ message1,
+ (short) 0,
+ "abcd1234abcd1234abcd1234abcd1234abcd1234",
+ false);
update.setPatchSetId(psId);
update.putComment(Status.PUBLISHED, comment1);
update.commit();
update = newUpdate(c, otherUser);
CommentRange range2 = new CommentRange(2, 1, 3, 1);
- Comment comment2 = newComment(psId, "file1",
- uuid2, range2, range2.getEndLine(), otherUser, null, time2, message2,
- (short) 0, "abcd1234abcd1234abcd1234abcd1234abcd1234", false);
+ Comment comment2 =
+ newComment(
+ psId,
+ "file1",
+ uuid2,
+ range2,
+ range2.getEndLine(),
+ otherUser,
+ null,
+ time2,
+ message2,
+ (short) 0,
+ "abcd1234abcd1234abcd1234abcd1234abcd1234",
+ false);
update.setPatchSetId(psId);
update.putComment(Status.PUBLISHED, comment2);
update.commit();
@@ -1635,37 +1769,37 @@
ChangeNotes notes = newNotes(c);
try (RevWalk walk = new RevWalk(repo)) {
- ArrayList<Note> notesInTree =
- Lists.newArrayList(notes.revisionNoteMap.noteMap.iterator());
+ ArrayList<Note> notesInTree = Lists.newArrayList(notes.revisionNoteMap.noteMap.iterator());
Note note = Iterables.getOnlyElement(notesInTree);
- byte[] bytes =
- walk.getObjectReader().open(
- note.getData(), Constants.OBJ_BLOB).getBytes();
+ byte[] bytes = walk.getObjectReader().open(note.getData(), Constants.OBJ_BLOB).getBytes();
String noteString = new String(bytes, UTF_8);
if (!testJson()) {
- assertThat(noteString).isEqualTo(
- "Revision: abcd1234abcd1234abcd1234abcd1234abcd1234\n"
- + "Base-for-patch-set: 1\n"
- + "File: file1\n"
- + "\n"
- + "1:1-2:1\n"
- + ChangeNoteUtil.formatTime(serverIdent, time1) + "\n"
- + "Author: Other Account <2@gerrit>\n"
- + "Unresolved: false\n"
- + "UUID: uuid1\n"
- + "Bytes: 9\n"
- + "comment 1\n"
- + "\n"
- + "2:1-3:1\n"
- + ChangeNoteUtil.formatTime(serverIdent, time2) + "\n"
- + "Author: Other Account <2@gerrit>\n"
- + "Unresolved: false\n"
- + "UUID: uuid2\n"
- + "Bytes: 9\n"
- + "comment 2\n"
- + "\n");
+ assertThat(noteString)
+ .isEqualTo(
+ "Revision: abcd1234abcd1234abcd1234abcd1234abcd1234\n"
+ + "Base-for-patch-set: 1\n"
+ + "File: file1\n"
+ + "\n"
+ + "1:1-2:1\n"
+ + ChangeNoteUtil.formatTime(serverIdent, time1)
+ + "\n"
+ + "Author: Other Account <2@gerrit>\n"
+ + "Unresolved: false\n"
+ + "UUID: uuid1\n"
+ + "Bytes: 9\n"
+ + "comment 1\n"
+ + "\n"
+ + "2:1-3:1\n"
+ + ChangeNoteUtil.formatTime(serverIdent, time2)
+ + "\n"
+ + "Author: Other Account <2@gerrit>\n"
+ + "Unresolved: false\n"
+ + "UUID: uuid2\n"
+ + "Bytes: 9\n"
+ + "comment 2\n"
+ + "\n");
}
}
}
@@ -1683,17 +1817,39 @@
Timestamp time2 = TimeUtil.nowTs();
PatchSet.Id psId = c.currentPatchSetId();
- Comment comment1 = newComment(psId, "file1",
- uuid1, range1, range1.getEndLine(), otherUser, null, time1, message1,
- (short) 0, "abcd1234abcd1234abcd1234abcd1234abcd1234", false);
+ Comment comment1 =
+ newComment(
+ psId,
+ "file1",
+ uuid1,
+ range1,
+ range1.getEndLine(),
+ otherUser,
+ null,
+ time1,
+ message1,
+ (short) 0,
+ "abcd1234abcd1234abcd1234abcd1234abcd1234",
+ false);
update.setPatchSetId(psId);
update.putComment(Status.PUBLISHED, comment1);
update.commit();
update = newUpdate(c, otherUser);
- Comment comment2 = newComment(psId, "file1",
- uuid2, range1, range1.getEndLine(), otherUser, uuid1, time2, message2,
- (short) 0, "abcd1234abcd1234abcd1234abcd1234abcd1234", true);
+ Comment comment2 =
+ newComment(
+ psId,
+ "file1",
+ uuid2,
+ range1,
+ range1.getEndLine(),
+ otherUser,
+ uuid1,
+ time2,
+ message2,
+ (short) 0,
+ "abcd1234abcd1234abcd1234abcd1234abcd1234",
+ true);
update.setPatchSetId(psId);
update.putComment(Status.PUBLISHED, comment2);
update.commit();
@@ -1701,45 +1857,44 @@
ChangeNotes notes = newNotes(c);
try (RevWalk walk = new RevWalk(repo)) {
- ArrayList<Note> notesInTree =
- Lists.newArrayList(notes.revisionNoteMap.noteMap.iterator());
+ ArrayList<Note> notesInTree = Lists.newArrayList(notes.revisionNoteMap.noteMap.iterator());
Note note = Iterables.getOnlyElement(notesInTree);
- byte[] bytes =
- walk.getObjectReader().open(
- note.getData(), Constants.OBJ_BLOB).getBytes();
+ byte[] bytes = walk.getObjectReader().open(note.getData(), Constants.OBJ_BLOB).getBytes();
String noteString = new String(bytes, UTF_8);
if (!testJson()) {
- assertThat(noteString).isEqualTo(
- "Revision: abcd1234abcd1234abcd1234abcd1234abcd1234\n"
- + "Base-for-patch-set: 1\n"
- + "File: file1\n"
- + "\n"
- + "1:1-2:1\n"
- + ChangeNoteUtil.formatTime(serverIdent, time1) + "\n"
- + "Author: Other Account <2@gerrit>\n"
- + "Unresolved: false\n"
- + "UUID: uuid1\n"
- + "Bytes: 9\n"
- + "comment 1\n"
- + "\n"
- + "1:1-2:1\n"
- + ChangeNoteUtil.formatTime(serverIdent, time2) + "\n"
- + "Author: Other Account <2@gerrit>\n"
- + "Parent: uuid1\n"
- + "Unresolved: true\n"
- + "UUID: uuid2\n"
- + "Bytes: 9\n"
- + "comment 2\n"
- + "\n");
+ assertThat(noteString)
+ .isEqualTo(
+ "Revision: abcd1234abcd1234abcd1234abcd1234abcd1234\n"
+ + "Base-for-patch-set: 1\n"
+ + "File: file1\n"
+ + "\n"
+ + "1:1-2:1\n"
+ + ChangeNoteUtil.formatTime(serverIdent, time1)
+ + "\n"
+ + "Author: Other Account <2@gerrit>\n"
+ + "Unresolved: false\n"
+ + "UUID: uuid1\n"
+ + "Bytes: 9\n"
+ + "comment 1\n"
+ + "\n"
+ + "1:1-2:1\n"
+ + ChangeNoteUtil.formatTime(serverIdent, time2)
+ + "\n"
+ + "Author: Other Account <2@gerrit>\n"
+ + "Parent: uuid1\n"
+ + "Unresolved: true\n"
+ + "UUID: uuid2\n"
+ + "Bytes: 9\n"
+ + "comment 2\n"
+ + "\n");
}
}
}
@Test
- public void patchLineCommentNotesFormatMultiplePatchSetsSameRevId()
- throws Exception {
+ public void patchLineCommentNotesFormatMultiplePatchSetsSameRevId() throws Exception {
Change c = newChange();
PatchSet.Id psId1 = c.currentPatchSetId();
incrementPatchSet(c);
@@ -1756,14 +1911,47 @@
RevId revId = new RevId("abcd1234abcd1234abcd1234abcd1234abcd1234");
Comment comment1 =
- newComment(psId1, "file1", uuid1, range1, range1.getEndLine(),
- otherUser, null, time, message1, (short) 0, revId.get(), false);
+ newComment(
+ psId1,
+ "file1",
+ uuid1,
+ range1,
+ range1.getEndLine(),
+ otherUser,
+ null,
+ time,
+ message1,
+ (short) 0,
+ revId.get(),
+ false);
Comment comment2 =
- newComment(psId1, "file1", uuid2, range2, range2.getEndLine(),
- otherUser, null, time, message2, (short) 0, revId.get(), false);
+ newComment(
+ psId1,
+ "file1",
+ uuid2,
+ range2,
+ range2.getEndLine(),
+ otherUser,
+ null,
+ time,
+ message2,
+ (short) 0,
+ revId.get(),
+ false);
Comment comment3 =
- newComment(psId2, "file1", uuid3, range1, range1.getEndLine(),
- otherUser, null, time, message3, (short) 0, revId.get(), false);
+ newComment(
+ psId2,
+ "file1",
+ uuid3,
+ range1,
+ range1.getEndLine(),
+ otherUser,
+ null,
+ time,
+ message3,
+ (short) 0,
+ revId.get(),
+ false);
ChangeUpdate update = newUpdate(c, otherUser);
update.setPatchSetId(psId2);
@@ -1775,63 +1963,64 @@
ChangeNotes notes = newNotes(c);
try (RevWalk walk = new RevWalk(repo)) {
- ArrayList<Note> notesInTree =
- Lists.newArrayList(notes.revisionNoteMap.noteMap.iterator());
+ ArrayList<Note> notesInTree = Lists.newArrayList(notes.revisionNoteMap.noteMap.iterator());
Note note = Iterables.getOnlyElement(notesInTree);
- byte[] bytes =
- walk.getObjectReader().open(
- note.getData(), Constants.OBJ_BLOB).getBytes();
+ byte[] bytes = walk.getObjectReader().open(note.getData(), Constants.OBJ_BLOB).getBytes();
String noteString = new String(bytes, UTF_8);
String timeStr = ChangeNoteUtil.formatTime(serverIdent, time);
if (!testJson()) {
- assertThat(noteString).isEqualTo(
- "Revision: abcd1234abcd1234abcd1234abcd1234abcd1234\n"
- + "Base-for-patch-set: 1\n"
- + "File: file1\n"
- + "\n"
- + "1:1-2:1\n"
- + timeStr + "\n"
- + "Author: Other Account <2@gerrit>\n"
- + "Unresolved: false\n"
- + "UUID: uuid1\n"
- + "Bytes: 9\n"
- + "comment 1\n"
- + "\n"
- + "2:1-3:1\n"
- + timeStr + "\n"
- + "Author: Other Account <2@gerrit>\n"
- + "Unresolved: false\n"
- + "UUID: uuid2\n"
- + "Bytes: 9\n"
- + "comment 2\n"
- + "\n"
- + "Base-for-patch-set: 2\n"
- + "File: file1\n"
- + "\n"
- + "1:1-2:1\n"
- + timeStr + "\n"
- + "Author: Other Account <2@gerrit>\n"
- + "Unresolved: false\n"
- + "UUID: uuid3\n"
- + "Bytes: 9\n"
- + "comment 3\n"
- + "\n");
+ assertThat(noteString)
+ .isEqualTo(
+ "Revision: abcd1234abcd1234abcd1234abcd1234abcd1234\n"
+ + "Base-for-patch-set: 1\n"
+ + "File: file1\n"
+ + "\n"
+ + "1:1-2:1\n"
+ + timeStr
+ + "\n"
+ + "Author: Other Account <2@gerrit>\n"
+ + "Unresolved: false\n"
+ + "UUID: uuid1\n"
+ + "Bytes: 9\n"
+ + "comment 1\n"
+ + "\n"
+ + "2:1-3:1\n"
+ + timeStr
+ + "\n"
+ + "Author: Other Account <2@gerrit>\n"
+ + "Unresolved: false\n"
+ + "UUID: uuid2\n"
+ + "Bytes: 9\n"
+ + "comment 2\n"
+ + "\n"
+ + "Base-for-patch-set: 2\n"
+ + "File: file1\n"
+ + "\n"
+ + "1:1-2:1\n"
+ + timeStr
+ + "\n"
+ + "Author: Other Account <2@gerrit>\n"
+ + "Unresolved: false\n"
+ + "UUID: uuid3\n"
+ + "Bytes: 9\n"
+ + "comment 3\n"
+ + "\n");
}
}
- assertThat(notes.getComments()).isEqualTo(
- ImmutableListMultimap.of(
- revId, comment1,
- revId, comment2,
- revId, comment3));
+ assertThat(notes.getComments())
+ .isEqualTo(
+ ImmutableListMultimap.of(
+ revId, comment1,
+ revId, comment2,
+ revId, comment3));
}
@Test
public void patchLineCommentNotesFormatRealAuthor() throws Exception {
Change c = newChange();
- CurrentUser ownerAsOtherUser =
- userFactory.runAs(null, otherUserId, changeOwner);
+ CurrentUser ownerAsOtherUser = userFactory.runAs(null, otherUserId, changeOwner);
ChangeUpdate update = newUpdate(c, ownerAsOtherUser);
String uuid = "uuid";
String message = "comment";
@@ -1840,9 +2029,20 @@
PatchSet.Id psId = c.currentPatchSetId();
RevId revId = new RevId("abcd1234abcd1234abcd1234abcd1234abcd1234");
- Comment comment = newComment(psId, "file", uuid, range,
- range.getEndLine(), otherUser, null, time, message, (short) 1,
- revId.get(), false);
+ Comment comment =
+ newComment(
+ psId,
+ "file",
+ uuid,
+ range,
+ range.getEndLine(),
+ otherUser,
+ null,
+ time,
+ message,
+ (short) 1,
+ revId.get(),
+ false);
comment.setRealAuthor(changeOwner.getAccountId());
update.setPatchSetId(psId);
update.putComment(Status.PUBLISHED, comment);
@@ -1851,34 +2051,32 @@
ChangeNotes notes = newNotes(c);
try (RevWalk walk = new RevWalk(repo)) {
- ArrayList<Note> notesInTree =
- Lists.newArrayList(notes.revisionNoteMap.noteMap.iterator());
+ ArrayList<Note> notesInTree = Lists.newArrayList(notes.revisionNoteMap.noteMap.iterator());
Note note = Iterables.getOnlyElement(notesInTree);
- byte[] bytes =
- walk.getObjectReader().open(
- note.getData(), Constants.OBJ_BLOB).getBytes();
+ byte[] bytes = walk.getObjectReader().open(note.getData(), Constants.OBJ_BLOB).getBytes();
String noteString = new String(bytes, UTF_8);
if (!testJson()) {
- assertThat(noteString).isEqualTo(
- "Revision: abcd1234abcd1234abcd1234abcd1234abcd1234\n"
- + "Patch-set: 1\n"
- + "File: file\n"
- + "\n"
- + "1:1-2:1\n"
- + ChangeNoteUtil.formatTime(serverIdent, time) + "\n"
- + "Author: Other Account <2@gerrit>\n"
- + "Real-author: Change Owner <1@gerrit>\n"
- + "Unresolved: false\n"
- + "UUID: uuid\n"
- + "Bytes: 7\n"
- + "comment\n"
- + "\n");
+ assertThat(noteString)
+ .isEqualTo(
+ "Revision: abcd1234abcd1234abcd1234abcd1234abcd1234\n"
+ + "Patch-set: 1\n"
+ + "File: file\n"
+ + "\n"
+ + "1:1-2:1\n"
+ + ChangeNoteUtil.formatTime(serverIdent, time)
+ + "\n"
+ + "Author: Other Account <2@gerrit>\n"
+ + "Real-author: Change Owner <1@gerrit>\n"
+ + "Unresolved: false\n"
+ + "UUID: uuid\n"
+ + "Bytes: 7\n"
+ + "comment\n"
+ + "\n");
}
}
- assertThat(notes.getComments())
- .isEqualTo(ImmutableListMultimap.of(revId, comment));
+ assertThat(notes.getComments()).isEqualTo(ImmutableListMultimap.of(revId, comment));
}
@Test
@@ -1896,9 +2094,20 @@
Timestamp time = TimeUtil.nowTs();
PatchSet.Id psId = c.currentPatchSetId();
- Comment comment = newComment(psId, "file1", uuid, range, range.getEndLine(),
- user, null, time, "comment", (short) 1,
- "abcd1234abcd1234abcd1234abcd1234abcd1234", false);
+ Comment comment =
+ newComment(
+ psId,
+ "file1",
+ uuid,
+ range,
+ range.getEndLine(),
+ user,
+ null,
+ time,
+ "comment",
+ (short) 1,
+ "abcd1234abcd1234abcd1234abcd1234abcd1234",
+ false);
update.setPatchSetId(psId);
update.putComment(Status.PUBLISHED, comment);
update.commit();
@@ -1906,30 +2115,29 @@
ChangeNotes notes = newNotes(c);
try (RevWalk walk = new RevWalk(repo)) {
- ArrayList<Note> notesInTree =
- Lists.newArrayList(notes.revisionNoteMap.noteMap.iterator());
+ ArrayList<Note> notesInTree = Lists.newArrayList(notes.revisionNoteMap.noteMap.iterator());
Note note = Iterables.getOnlyElement(notesInTree);
- byte[] bytes =
- walk.getObjectReader().open(
- note.getData(), Constants.OBJ_BLOB).getBytes();
+ byte[] bytes = walk.getObjectReader().open(note.getData(), Constants.OBJ_BLOB).getBytes();
String noteString = new String(bytes, UTF_8);
String timeStr = ChangeNoteUtil.formatTime(serverIdent, time);
if (!testJson()) {
- assertThat(noteString).isEqualTo(
- "Revision: abcd1234abcd1234abcd1234abcd1234abcd1234\n"
- + "Patch-set: 1\n"
- + "File: file1\n"
- + "\n"
- + "1:1-2:1\n"
- + timeStr + "\n"
- + "Author: Weird\u0002User <3@gerrit>\n"
- + "Unresolved: false\n"
- + "UUID: uuid\n"
- + "Bytes: 7\n"
- + "comment\n"
- + "\n");
+ assertThat(noteString)
+ .isEqualTo(
+ "Revision: abcd1234abcd1234abcd1234abcd1234abcd1234\n"
+ + "Patch-set: 1\n"
+ + "File: file1\n"
+ + "\n"
+ + "1:1-2:1\n"
+ + timeStr
+ + "\n"
+ + "Author: Weird\u0002User <3@gerrit>\n"
+ + "Unresolved: false\n"
+ + "UUID: uuid\n"
+ + "Bytes: 7\n"
+ + "comment\n"
+ + "\n");
}
}
assertThat(notes.getComments())
@@ -1937,8 +2145,7 @@
}
@Test
- public void patchLineCommentMultipleOnePatchsetOneFileBothSides()
- throws Exception {
+ public void patchLineCommentMultipleOnePatchsetOneFileBothSides() throws Exception {
Change c = newChange();
ChangeUpdate update = newUpdate(c, otherUser);
String uuid1 = "uuid1";
@@ -1952,25 +2159,47 @@
PatchSet.Id psId = c.currentPatchSetId();
Comment commentForBase =
- newComment(psId, "filename", uuid1, range, range.getEndLine(),
- otherUser, null, now, messageForBase, (short) 0, rev1, false);
+ newComment(
+ psId,
+ "filename",
+ uuid1,
+ range,
+ range.getEndLine(),
+ otherUser,
+ null,
+ now,
+ messageForBase,
+ (short) 0,
+ rev1,
+ false);
update.setPatchSetId(psId);
update.putComment(Status.PUBLISHED, commentForBase);
update.commit();
update = newUpdate(c, otherUser);
Comment commentForPS =
- newComment(psId, "filename", uuid2, range, range.getEndLine(),
- otherUser, null, now, messageForPS,
- (short) 1, rev2, false);
+ newComment(
+ psId,
+ "filename",
+ uuid2,
+ range,
+ range.getEndLine(),
+ otherUser,
+ null,
+ now,
+ messageForPS,
+ (short) 1,
+ rev2,
+ false);
update.setPatchSetId(psId);
update.putComment(Status.PUBLISHED, commentForPS);
update.commit();
- assertThat(newNotes(c).getComments()).containsExactlyEntriesIn(
- ImmutableListMultimap.of(
- new RevId(rev1), commentForBase,
- new RevId(rev2), commentForPS));
+ assertThat(newNotes(c).getComments())
+ .containsExactlyEntriesIn(
+ ImmutableListMultimap.of(
+ new RevId(rev1), commentForBase,
+ new RevId(rev2), commentForPS));
}
@Test
@@ -1988,29 +2217,52 @@
Timestamp timeForComment1 = TimeUtil.nowTs();
Timestamp timeForComment2 = TimeUtil.nowTs();
Comment comment1 =
- newComment(psId, filename, uuid1, range, range.getEndLine(), otherUser,
- null, timeForComment1, "comment 1", side, rev, false);
+ newComment(
+ psId,
+ filename,
+ uuid1,
+ range,
+ range.getEndLine(),
+ otherUser,
+ null,
+ timeForComment1,
+ "comment 1",
+ side,
+ rev,
+ false);
update.setPatchSetId(psId);
update.putComment(Status.PUBLISHED, comment1);
update.commit();
update = newUpdate(c, otherUser);
Comment comment2 =
- newComment(psId, filename, uuid2, range, range.getEndLine(), otherUser,
- null, timeForComment2, "comment 2", side, rev, false);
+ newComment(
+ psId,
+ filename,
+ uuid2,
+ range,
+ range.getEndLine(),
+ otherUser,
+ null,
+ timeForComment2,
+ "comment 2",
+ side,
+ rev,
+ false);
update.setPatchSetId(psId);
update.putComment(Status.PUBLISHED, comment2);
update.commit();
- assertThat(newNotes(c).getComments()).containsExactlyEntriesIn(
- ImmutableListMultimap.of(
- new RevId(rev), comment1,
- new RevId(rev), comment2)).inOrder();
+ assertThat(newNotes(c).getComments())
+ .containsExactlyEntriesIn(
+ ImmutableListMultimap.of(
+ new RevId(rev), comment1,
+ new RevId(rev), comment2))
+ .inOrder();
}
@Test
- public void patchLineCommentMultipleOnePatchsetMultipleFiles()
- throws Exception {
+ public void patchLineCommentMultipleOnePatchsetMultipleFiles() throws Exception {
Change c = newChange();
String uuid = "uuid";
String rev = "abcd1234abcd1234abcd1234abcd1234abcd1234";
@@ -2022,25 +2274,49 @@
ChangeUpdate update = newUpdate(c, otherUser);
Timestamp now = TimeUtil.nowTs();
- Comment comment1 = newComment(psId, filename1,
- uuid, range, range.getEndLine(), otherUser, null, now, "comment 1",
- side, rev, false);
+ Comment comment1 =
+ newComment(
+ psId,
+ filename1,
+ uuid,
+ range,
+ range.getEndLine(),
+ otherUser,
+ null,
+ now,
+ "comment 1",
+ side,
+ rev,
+ false);
update.setPatchSetId(psId);
update.putComment(Status.PUBLISHED, comment1);
update.commit();
update = newUpdate(c, otherUser);
- Comment comment2 = newComment(psId, filename2,
- uuid, range, range.getEndLine(), otherUser, null, now, "comment 2",
- side, rev, false);
+ Comment comment2 =
+ newComment(
+ psId,
+ filename2,
+ uuid,
+ range,
+ range.getEndLine(),
+ otherUser,
+ null,
+ now,
+ "comment 2",
+ side,
+ rev,
+ false);
update.setPatchSetId(psId);
update.putComment(Status.PUBLISHED, comment2);
update.commit();
- assertThat(newNotes(c).getComments()).containsExactlyEntriesIn(
- ImmutableListMultimap.of(
- new RevId(rev), comment1,
- new RevId(rev), comment2)).inOrder();
+ assertThat(newNotes(c).getComments())
+ .containsExactlyEntriesIn(
+ ImmutableListMultimap.of(
+ new RevId(rev), comment1,
+ new RevId(rev), comment2))
+ .inOrder();
}
@Test
@@ -2056,9 +2332,20 @@
ChangeUpdate update = newUpdate(c, otherUser);
Timestamp now = TimeUtil.nowTs();
- Comment comment1 = newComment(ps1, filename, uuid, range,
- range.getEndLine(), otherUser, null, now, "comment on ps1",
- side, rev1, false);
+ Comment comment1 =
+ newComment(
+ ps1,
+ filename,
+ uuid,
+ range,
+ range.getEndLine(),
+ otherUser,
+ null,
+ now,
+ "comment on ps1",
+ side,
+ rev1,
+ false);
update.setPatchSetId(ps1);
update.putComment(Status.PUBLISHED, comment1);
update.commit();
@@ -2068,17 +2355,29 @@
update = newUpdate(c, otherUser);
now = TimeUtil.nowTs();
- Comment comment2 = newComment(ps2, filename, uuid, range,
- range.getEndLine(), otherUser, null, now, "comment on ps2",
- side, rev2, false);
+ Comment comment2 =
+ newComment(
+ ps2,
+ filename,
+ uuid,
+ range,
+ range.getEndLine(),
+ otherUser,
+ null,
+ now,
+ "comment on ps2",
+ side,
+ rev2,
+ false);
update.setPatchSetId(ps2);
update.putComment(Status.PUBLISHED, comment2);
update.commit();
- assertThat(newNotes(c).getComments()).containsExactlyEntriesIn(
- ImmutableListMultimap.of(
- new RevId(rev1), comment1,
- new RevId(rev2), comment2));
+ assertThat(newNotes(c).getComments())
+ .containsExactlyEntriesIn(
+ ImmutableListMultimap.of(
+ new RevId(rev1), comment1,
+ new RevId(rev2), comment2));
}
@Test
@@ -2093,16 +2392,27 @@
ChangeUpdate update = newUpdate(c, otherUser);
Timestamp now = TimeUtil.nowTs();
- Comment comment1 = newComment(ps1, filename, uuid, range,
- range.getEndLine(), otherUser, null, now, "comment on ps1",
- side, rev, false);
+ Comment comment1 =
+ newComment(
+ ps1,
+ filename,
+ uuid,
+ range,
+ range.getEndLine(),
+ otherUser,
+ null,
+ now,
+ "comment on ps1",
+ side,
+ rev,
+ false);
update.setPatchSetId(ps1);
update.putComment(Status.DRAFT, comment1);
update.commit();
ChangeNotes notes = newNotes(c);
- assertThat(notes.getDraftComments(otherUserId)).containsExactlyEntriesIn(
- ImmutableListMultimap.of(new RevId(rev), comment1));
+ assertThat(notes.getDraftComments(otherUserId))
+ .containsExactlyEntriesIn(ImmutableListMultimap.of(new RevId(rev), comment1));
assertThat(notes.getComments()).isEmpty();
update = newUpdate(c, otherUser);
@@ -2112,13 +2422,12 @@
notes = newNotes(c);
assertThat(notes.getDraftComments(otherUserId)).isEmpty();
- assertThat(notes.getComments()).containsExactlyEntriesIn(
- ImmutableListMultimap.of(new RevId(rev), comment1));
+ assertThat(notes.getComments())
+ .containsExactlyEntriesIn(ImmutableListMultimap.of(new RevId(rev), comment1));
}
@Test
- public void patchLineCommentMultipleDraftsSameSidePublishOne()
- throws Exception {
+ public void patchLineCommentMultipleDraftsSameSidePublishOne() throws Exception {
Change c = newChange();
String uuid1 = "uuid1";
String uuid2 = "uuid2";
@@ -2133,21 +2442,45 @@
// Write two drafts on the same side of one patch set.
ChangeUpdate update = newUpdate(c, otherUser);
update.setPatchSetId(psId);
- Comment comment1 = newComment(psId, filename, uuid1, range1,
- range1.getEndLine(), otherUser, null, now, "comment on ps1",
- side, rev, false);
- Comment comment2 = newComment(psId, filename, uuid2, range2,
- range2.getEndLine(), otherUser, null, now, "other on ps1",
- side, rev, false);
+ Comment comment1 =
+ newComment(
+ psId,
+ filename,
+ uuid1,
+ range1,
+ range1.getEndLine(),
+ otherUser,
+ null,
+ now,
+ "comment on ps1",
+ side,
+ rev,
+ false);
+ Comment comment2 =
+ newComment(
+ psId,
+ filename,
+ uuid2,
+ range2,
+ range2.getEndLine(),
+ otherUser,
+ null,
+ now,
+ "other on ps1",
+ side,
+ rev,
+ false);
update.putComment(Status.DRAFT, comment1);
update.putComment(Status.DRAFT, comment2);
update.commit();
ChangeNotes notes = newNotes(c);
- assertThat(notes.getDraftComments(otherUserId)).containsExactlyEntriesIn(
- ImmutableListMultimap.of(
- new RevId(rev), comment1,
- new RevId(rev), comment2)).inOrder();
+ assertThat(notes.getDraftComments(otherUserId))
+ .containsExactlyEntriesIn(
+ ImmutableListMultimap.of(
+ new RevId(rev), comment1,
+ new RevId(rev), comment2))
+ .inOrder();
assertThat(notes.getComments()).isEmpty();
// Publish first draft.
@@ -2157,15 +2490,14 @@
update.commit();
notes = newNotes(c);
- assertThat(notes.getDraftComments(otherUserId)).containsExactlyEntriesIn(
- ImmutableListMultimap.of(new RevId(rev), comment2));
- assertThat(notes.getComments()).containsExactlyEntriesIn(
- ImmutableListMultimap.of(new RevId(rev), comment1));
+ assertThat(notes.getDraftComments(otherUserId))
+ .containsExactlyEntriesIn(ImmutableListMultimap.of(new RevId(rev), comment2));
+ assertThat(notes.getComments())
+ .containsExactlyEntriesIn(ImmutableListMultimap.of(new RevId(rev), comment1));
}
@Test
- public void patchLineCommentsMultipleDraftsBothSidesPublishAll()
- throws Exception {
+ public void patchLineCommentsMultipleDraftsBothSidesPublishAll() throws Exception {
Change c = newChange();
String uuid1 = "uuid1";
String uuid2 = "uuid2";
@@ -2181,21 +2513,44 @@
ChangeUpdate update = newUpdate(c, otherUser);
update.setPatchSetId(psId);
Comment baseComment =
- newComment(psId, filename, uuid1, range1, range1.getEndLine(),
- otherUser, null, now, "comment on base", (short) 0, rev1, false);
+ newComment(
+ psId,
+ filename,
+ uuid1,
+ range1,
+ range1.getEndLine(),
+ otherUser,
+ null,
+ now,
+ "comment on base",
+ (short) 0,
+ rev1,
+ false);
Comment psComment =
- newComment(psId, filename, uuid2, range2, range2.getEndLine(),
- otherUser, null, now, "comment on ps", (short) 1, rev2, false);
+ newComment(
+ psId,
+ filename,
+ uuid2,
+ range2,
+ range2.getEndLine(),
+ otherUser,
+ null,
+ now,
+ "comment on ps",
+ (short) 1,
+ rev2,
+ false);
update.putComment(Status.DRAFT, baseComment);
update.putComment(Status.DRAFT, psComment);
update.commit();
ChangeNotes notes = newNotes(c);
- assertThat(notes.getDraftComments(otherUserId)).containsExactlyEntriesIn(
- ImmutableListMultimap.of(
- new RevId(rev1), baseComment,
- new RevId(rev2), psComment));
+ assertThat(notes.getDraftComments(otherUserId))
+ .containsExactlyEntriesIn(
+ ImmutableListMultimap.of(
+ new RevId(rev1), baseComment,
+ new RevId(rev2), psComment));
assertThat(notes.getComments()).isEmpty();
// Publish both comments.
@@ -2208,10 +2563,11 @@
notes = newNotes(c);
assertThat(notes.getDraftComments(otherUserId)).isEmpty();
- assertThat(notes.getComments()).containsExactlyEntriesIn(
- ImmutableListMultimap.of(
- new RevId(rev1), baseComment,
- new RevId(rev2), psComment));
+ assertThat(notes.getComments())
+ .containsExactlyEntriesIn(
+ ImmutableListMultimap.of(
+ new RevId(rev1), baseComment,
+ new RevId(rev2), psComment));
}
@Test
@@ -2227,17 +2583,27 @@
ChangeUpdate update = newUpdate(c, otherUser);
Timestamp now = TimeUtil.nowTs();
- Comment comment = newComment(psId, filename, uuid, range,
- range.getEndLine(), otherUser, null, now, "comment on ps1",
- side, rev, false);
+ Comment comment =
+ newComment(
+ psId,
+ filename,
+ uuid,
+ range,
+ range.getEndLine(),
+ otherUser,
+ null,
+ now,
+ "comment on ps1",
+ side,
+ rev,
+ false);
update.setPatchSetId(psId);
update.putComment(Status.DRAFT, comment);
update.commit();
ChangeNotes notes = newNotes(c);
assertThat(notes.getDraftComments(otherUserId)).hasSize(1);
- assertThat(notes.getDraftCommentNotes().getNoteMap().contains(objId))
- .isTrue();
+ assertThat(notes.getDraftCommentNotes().getNoteMap().contains(objId)).isTrue();
update = newUpdate(c, otherUser);
now = TimeUtil.nowTs();
@@ -2251,8 +2617,7 @@
}
@Test
- public void patchLineCommentsDeleteAllDraftsForOneRevision()
- throws Exception {
+ public void patchLineCommentsDeleteAllDraftsForOneRevision() throws Exception {
Change c = newChange();
String uuid = "uuid";
String rev1 = "abcd1234abcd1234abcd1234abcd1234abcd1234";
@@ -2266,9 +2631,20 @@
ChangeUpdate update = newUpdate(c, otherUser);
Timestamp now = TimeUtil.nowTs();
- Comment comment1 = newComment(ps1, filename, uuid, range,
- range.getEndLine(), otherUser, null, now, "comment on ps1",
- side, rev1, false);
+ Comment comment1 =
+ newComment(
+ ps1,
+ filename,
+ uuid,
+ range,
+ range.getEndLine(),
+ otherUser,
+ null,
+ now,
+ "comment on ps1",
+ side,
+ rev1,
+ false);
update.setPatchSetId(ps1);
update.putComment(Status.DRAFT, comment1);
update.commit();
@@ -2278,9 +2654,20 @@
update = newUpdate(c, otherUser);
now = TimeUtil.nowTs();
- Comment comment2 = newComment(ps2, filename, uuid, range,
- range.getEndLine(), otherUser, null, now, "comment on ps2",
- side, rev2, false);
+ Comment comment2 =
+ newComment(
+ ps2,
+ filename,
+ uuid,
+ range,
+ range.getEndLine(),
+ otherUser,
+ null,
+ now,
+ "comment on ps2",
+ side,
+ rev2,
+ false);
update.setPatchSetId(ps2);
update.putComment(Status.DRAFT, comment2);
update.commit();
@@ -2302,8 +2689,7 @@
}
@Test
- public void addingPublishedCommentDoesNotCreateNoOpCommitOnEmptyDraftRef()
- throws Exception {
+ public void addingPublishedCommentDoesNotCreateNoOpCommitOnEmptyDraftRef() throws Exception {
Change c = newChange();
String uuid = "uuid";
String rev = "abcd4567abcd4567abcd4567abcd4567abcd4567";
@@ -2314,8 +2700,20 @@
ChangeUpdate update = newUpdate(c, otherUser);
Timestamp now = TimeUtil.nowTs();
- Comment comment = newComment(ps1, filename, uuid, range, range.getEndLine(),
- otherUser, null, now, "comment on ps1", side, rev, false);
+ Comment comment =
+ newComment(
+ ps1,
+ filename,
+ uuid,
+ range,
+ range.getEndLine(),
+ otherUser,
+ null,
+ now,
+ "comment on ps1",
+ side,
+ rev,
+ false);
update.putComment(Status.PUBLISHED, comment);
update.commit();
@@ -2325,8 +2723,7 @@
}
@Test
- public void addingPublishedCommentDoesNotCreateNoOpCommitOnNonEmptyDraftRef()
- throws Exception {
+ public void addingPublishedCommentDoesNotCreateNoOpCommitOnNonEmptyDraftRef() throws Exception {
Change c = newChange();
String rev = "abcd4567abcd4567abcd4567abcd4567abcd4567";
CommentRange range = new CommentRange(1, 1, 2, 1);
@@ -2337,8 +2734,19 @@
ChangeUpdate update = newUpdate(c, otherUser);
Timestamp now = TimeUtil.nowTs();
Comment draft =
- newComment(ps1, filename, "uuid1", range, range.getEndLine(), otherUser,
- null, now, "draft comment on ps1", side, rev, false);
+ newComment(
+ ps1,
+ filename,
+ "uuid1",
+ range,
+ range.getEndLine(),
+ otherUser,
+ null,
+ now,
+ "draft comment on ps1",
+ side,
+ rev,
+ false);
update.putComment(Status.DRAFT, draft);
update.commit();
@@ -2347,8 +2755,20 @@
assertThat(old).isNotNull();
update = newUpdate(c, otherUser);
- Comment pub = newComment(ps1, filename, "uuid2", range, range.getEndLine(),
- otherUser, null, now, "comment on ps1", side, rev, false);
+ Comment pub =
+ newComment(
+ ps1,
+ filename,
+ "uuid2",
+ range,
+ range.getEndLine(),
+ otherUser,
+ null,
+ now,
+ "comment on ps1",
+ side,
+ rev,
+ false);
update.putComment(Status.PUBLISHED, pub);
update.commit();
@@ -2365,14 +2785,26 @@
Timestamp now = TimeUtil.nowTs();
PatchSet.Id psId = c.currentPatchSetId();
- Comment comment = newComment(psId, "filename", uuid, null, 0, otherUser,
- null, now, messageForBase, (short) 0, rev, false);
+ Comment comment =
+ newComment(
+ psId,
+ "filename",
+ uuid,
+ null,
+ 0,
+ otherUser,
+ null,
+ now,
+ messageForBase,
+ (short) 0,
+ rev,
+ false);
update.setPatchSetId(psId);
update.putComment(Status.PUBLISHED, comment);
update.commit();
- assertThat(newNotes(c).getComments()).containsExactlyEntriesIn(
- ImmutableListMultimap.of(new RevId(rev), comment));
+ assertThat(newNotes(c).getComments())
+ .containsExactlyEntriesIn(ImmutableListMultimap.of(new RevId(rev), comment));
}
@Test
@@ -2385,14 +2817,26 @@
Timestamp now = TimeUtil.nowTs();
PatchSet.Id psId = c.currentPatchSetId();
- Comment comment = newComment(psId, "filename", uuid, null, 1, otherUser,
- null, now, messageForBase, (short) 0, rev, false);
+ Comment comment =
+ newComment(
+ psId,
+ "filename",
+ uuid,
+ null,
+ 1,
+ otherUser,
+ null,
+ now,
+ messageForBase,
+ (short) 0,
+ rev,
+ false);
update.setPatchSetId(psId);
update.putComment(Status.PUBLISHED, comment);
update.commit();
- assertThat(newNotes(c).getComments()).containsExactlyEntriesIn(
- ImmutableListMultimap.of(new RevId(rev), comment));
+ assertThat(newNotes(c).getComments())
+ .containsExactlyEntriesIn(ImmutableListMultimap.of(new RevId(rev), comment));
}
@Test
@@ -2412,12 +2856,34 @@
ChangeUpdate update = newUpdate(c, otherUser);
update.setPatchSetId(ps2);
Timestamp now = TimeUtil.nowTs();
- Comment comment1 = newComment(ps1, filename, uuid, range,
- range.getEndLine(), otherUser, null, now, "comment on ps1",
- side, rev1, false);
- Comment comment2 = newComment(ps2, filename, uuid, range,
- range.getEndLine(), otherUser, null, now, "comment on ps2",
- side, rev2, false);
+ Comment comment1 =
+ newComment(
+ ps1,
+ filename,
+ uuid,
+ range,
+ range.getEndLine(),
+ otherUser,
+ null,
+ now,
+ "comment on ps1",
+ side,
+ rev1,
+ false);
+ Comment comment2 =
+ newComment(
+ ps2,
+ filename,
+ uuid,
+ range,
+ range.getEndLine(),
+ otherUser,
+ null,
+ now,
+ "comment on ps2",
+ side,
+ rev2,
+ false);
update.putComment(Status.DRAFT, comment1);
update.putComment(Status.DRAFT, comment2);
update.commit();
@@ -2448,19 +2914,40 @@
ChangeUpdate update = newUpdate(c, otherUser);
update.setPatchSetId(ps1);
Timestamp now = TimeUtil.nowTs();
- Comment comment1 = newComment(ps1, "file1", "uuid1", range,
- range.getEndLine(), otherUser, null, now, "comment1",
- side, rev1.get(), false);
- Comment comment2 = newComment(ps1, "file2", "uuid2", range,
- range.getEndLine(), otherUser, null, now, "comment2",
- side, rev1.get(), false);
+ Comment comment1 =
+ newComment(
+ ps1,
+ "file1",
+ "uuid1",
+ range,
+ range.getEndLine(),
+ otherUser,
+ null,
+ now,
+ "comment1",
+ side,
+ rev1.get(),
+ false);
+ Comment comment2 =
+ newComment(
+ ps1,
+ "file2",
+ "uuid2",
+ range,
+ range.getEndLine(),
+ otherUser,
+ null,
+ now,
+ "comment2",
+ side,
+ rev1.get(),
+ false);
update.putComment(Status.DRAFT, comment1);
update.putComment(Status.DRAFT, comment2);
update.commit();
ChangeNotes notes = newNotes(c);
- assertThat(notes.getDraftComments(otherUserId).get(rev1))
- .containsExactly(comment1, comment2);
+ assertThat(notes.getDraftComments(otherUserId).get(rev1)).containsExactly(comment1, comment2);
assertThat(notes.getComments()).isEmpty();
update = newUpdate(c, otherUser);
@@ -2469,8 +2956,7 @@
update.commit();
notes = newNotes(c);
- assertThat(notes.getDraftComments(otherUserId).get(rev1))
- .containsExactly(comment1);
+ assertThat(notes.getDraftComments(otherUserId).get(rev1)).containsExactly(comment1);
assertThat(notes.getComments().get(rev1)).containsExactly(comment2);
}
@@ -2501,11 +2987,33 @@
ChangeUpdate update = newUpdate(c, otherUser);
Timestamp now = TimeUtil.nowTs();
Comment comment1 =
- newComment(ps1, "file1", "uuid1", range, range.getEndLine(), otherUser,
- null, now, "comment on ps1", side, rev1.get(), false);
+ newComment(
+ ps1,
+ "file1",
+ "uuid1",
+ range,
+ range.getEndLine(),
+ otherUser,
+ null,
+ now,
+ "comment on ps1",
+ side,
+ rev1.get(),
+ false);
Comment comment2 =
- newComment(ps1, "file2", "uuid2", range, range.getEndLine(), otherUser,
- null, now, "another comment", side, rev1.get(), false);
+ newComment(
+ ps1,
+ "file2",
+ "uuid2",
+ range,
+ range.getEndLine(),
+ otherUser,
+ null,
+ now,
+ "another comment",
+ side,
+ rev1.get(),
+ false);
update.putComment(Status.DRAFT, comment1);
update.putComment(Status.DRAFT, comment2);
update.commit();
@@ -2523,26 +3031,21 @@
// Re-add draft version of comment2 back to draft ref without updating
// change ref. Simulates the case where deleting the draft failed
// non-atomically after adding the published comment succeeded.
- ChangeDraftUpdate draftUpdate =
- newUpdate(c, otherUser).createDraftUpdateIfNull();
+ ChangeDraftUpdate draftUpdate = newUpdate(c, otherUser).createDraftUpdateIfNull();
draftUpdate.putComment(comment2);
- try (NoteDbUpdateManager manager =
- updateManagerFactory.create(c.getProject())) {
+ try (NoteDbUpdateManager manager = updateManagerFactory.create(c.getProject())) {
manager.add(draftUpdate);
manager.execute();
}
// Looking at drafts directly shows the zombie comment.
DraftCommentNotes draftNotes = draftNotesFactory.create(c, otherUserId);
- assertThat(draftNotes.load().getComments().get(rev1))
- .containsExactly(comment1, comment2);
+ assertThat(draftNotes.load().getComments().get(rev1)).containsExactly(comment1, comment2);
// Zombie comment is filtered out of drafts via ChangeNotes.
ChangeNotes notes = newNotes(c);
- assertThat(notes.getDraftComments(otherUserId).get(rev1))
- .containsExactly(comment1);
- assertThat(notes.getComments().get(rev1))
- .containsExactly(comment2);
+ assertThat(notes.getDraftComments(otherUserId).get(rev1)).containsExactly(comment1);
+ assertThat(notes.getComments().get(rev1)).containsExactly(comment2);
update = newUpdate(c, otherUser);
update.setPatchSetId(ps1);
@@ -2560,17 +3063,37 @@
String rev = "abcd1234abcd1234abcd1234abcd1234abcd1234";
ChangeUpdate update1 = newUpdate(c, otherUser);
- Comment comment1 = newComment(c.currentPatchSetId(), "filename",
- "uuid1", range, range.getEndLine(), otherUser, null,
- new Timestamp(update1.getWhen().getTime()), "comment 1",
- (short) 1, rev, false);
+ Comment comment1 =
+ newComment(
+ c.currentPatchSetId(),
+ "filename",
+ "uuid1",
+ range,
+ range.getEndLine(),
+ otherUser,
+ null,
+ new Timestamp(update1.getWhen().getTime()),
+ "comment 1",
+ (short) 1,
+ rev,
+ false);
update1.putComment(Status.PUBLISHED, comment1);
ChangeUpdate update2 = newUpdate(c, otherUser);
- Comment comment2 = newComment(c.currentPatchSetId(), "filename",
- "uuid2", range, range.getEndLine(), otherUser, null,
- new Timestamp(update2.getWhen().getTime()), "comment 2",
- (short) 1, rev, false);
+ Comment comment2 =
+ newComment(
+ c.currentPatchSetId(),
+ "filename",
+ "uuid2",
+ range,
+ range.getEndLine(),
+ otherUser,
+ null,
+ new Timestamp(update2.getWhen().getTime()),
+ "comment 2",
+ (short) 1,
+ rev,
+ false);
update2.putComment(Status.PUBLISHED, comment2);
try (NoteDbUpdateManager manager = updateManagerFactory.create(project)) {
@@ -2589,8 +3112,7 @@
@Test
public void realUser() throws Exception {
Change c = newChange();
- CurrentUser ownerAsOtherUser =
- userFactory.runAs(null, otherUserId, changeOwner);
+ CurrentUser ownerAsOtherUser = userFactory.runAs(null, otherUserId, changeOwner);
ChangeUpdate update = newUpdate(c, ownerAsOtherUser);
update.setChangeMessage("Message on behalf of other user");
update.commit();
@@ -2611,15 +3133,24 @@
int numComments = notes.getComments().size();
ChangeUpdate update = newUpdate(c, changeOwner);
- update.setPatchSetId(
- new PatchSet.Id(c.getId(), c.currentPatchSetId().get() + 1));
+ update.setPatchSetId(new PatchSet.Id(c.getId(), c.currentPatchSetId().get() + 1));
update.setChangeMessage("Should be ignored");
update.putApproval("Code-Review", (short) 2);
CommentRange range = new CommentRange(1, 1, 2, 1);
- Comment comment = newComment(update.getPatchSetId(), "filename",
- "uuid", range, range.getEndLine(), changeOwner, null,
- new Timestamp(update.getWhen().getTime()), "comment", (short) 1,
- "abcd1234abcd1234abcd1234abcd1234abcd1234", false);
+ Comment comment =
+ newComment(
+ update.getPatchSetId(),
+ "filename",
+ "uuid",
+ range,
+ range.getEndLine(),
+ changeOwner,
+ null,
+ new Timestamp(update.getWhen().getTime()),
+ "comment",
+ (short) 1,
+ "abcd1234abcd1234abcd1234abcd1234abcd1234",
+ false);
update.putComment(Status.PUBLISHED, comment);
update.commit();
@@ -2668,8 +3199,7 @@
private String readNote(ChangeNotes notes, ObjectId noteId) throws Exception {
ObjectId dataId = notes.revisionNoteMap.noteMap.getNote(noteId).getData();
- return new String(
- rw.getObjectReader().open(dataId, OBJ_BLOB).getCachedBytes(), UTF_8);
+ return new String(rw.getObjectReader().open(dataId, OBJ_BLOB).getCachedBytes(), UTF_8);
}
private ObjectId exactRefAllUsers(String refName) throws Exception {
@@ -2679,8 +3209,8 @@
}
}
- private void assertCause(Throwable e,
- Class<? extends Throwable> expectedClass, String expectedMsg) {
+ private void assertCause(
+ Throwable e, Class<? extends Throwable> expectedClass, String expectedMsg) {
Throwable cause = null;
for (Throwable t : Throwables.getCausalChain(e)) {
if (expectedClass.isAssignableFrom(t.getClass())) {
@@ -2689,8 +3219,10 @@
}
}
assertThat(cause)
- .named(expectedClass.getSimpleName() + " in causal chain of:\n"
- + Throwables.getStackTraceAsString(e))
+ .named(
+ expectedClass.getSimpleName()
+ + " in causal chain of:\n"
+ + Throwables.getStackTraceAsString(e))
.isNotNull();
assertThat(cause.getMessage()).isEqualTo(expectedMsg);
}
@@ -2703,12 +3235,9 @@
return incrementPatchSet(c, userFactory.create(c.getOwner()));
}
- private RevCommit incrementPatchSet(Change c, IdentifiedUser user)
- throws Exception {
+ private RevCommit incrementPatchSet(Change c, IdentifiedUser user) throws Exception {
incrementCurrentPatchSetFieldOnly(c);
- RevCommit commit = tr.commit()
- .message("PS" + c.currentPatchSetId().get())
- .create();
+ RevCommit commit = tr.commit().message("PS" + c.currentPatchSetId().get()).create();
ChangeUpdate update = newUpdate(c, user);
update.setCommit(rw, commit);
update.commit();
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/notedb/CommitMessageOutputTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/notedb/CommitMessageOutputTest.java
index 1c1f653..2e58382 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/notedb/CommitMessageOutputTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/notedb/CommitMessageOutputTest.java
@@ -26,7 +26,8 @@
import com.google.gerrit.server.util.RequestId;
import com.google.gerrit.testutil.ConfigSuite;
import com.google.gerrit.testutil.TestChanges;
-
+import java.util.Date;
+import java.util.TimeZone;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.PersonIdent;
import org.eclipse.jgit.revwalk.RevCommit;
@@ -34,9 +35,6 @@
import org.junit.Test;
import org.junit.runner.RunWith;
-import java.util.Date;
-import java.util.TimeZone;
-
@RunWith(ConfigSuite.class)
public class CommitMessageOutputTest extends AbstractChangeNotesTest {
@Test
@@ -51,26 +49,29 @@
assertThat(update.getRefName()).isEqualTo("refs/changes/01/1/meta");
RevCommit commit = parseCommit(update.getResult());
- assertBodyEquals("Update patch set 1\n"
- + "\n"
- + "Patch-set: 1\n"
- + "Change-id: " + c.getKey().get() + "\n"
- + "Subject: Change subject\n"
- + "Branch: refs/heads/master\n"
- + "Commit: " + update.getCommit().name() + "\n"
- + "Reviewer: Change Owner <1@gerrit>\n"
- + "CC: Other Account <2@gerrit>\n"
- + "Label: Code-Review=-1\n"
- + "Label: Verified=+1\n",
+ assertBodyEquals(
+ "Update patch set 1\n"
+ + "\n"
+ + "Patch-set: 1\n"
+ + "Change-id: "
+ + c.getKey().get()
+ + "\n"
+ + "Subject: Change subject\n"
+ + "Branch: refs/heads/master\n"
+ + "Commit: "
+ + update.getCommit().name()
+ + "\n"
+ + "Reviewer: Change Owner <1@gerrit>\n"
+ + "CC: Other Account <2@gerrit>\n"
+ + "Label: Code-Review=-1\n"
+ + "Label: Verified=+1\n",
commit);
PersonIdent author = commit.getAuthorIdent();
assertThat(author.getName()).isEqualTo("Change Owner");
assertThat(author.getEmailAddress()).isEqualTo("1@gerrit");
- assertThat(author.getWhen())
- .isEqualTo(new Date(c.getCreatedOn().getTime() + 1000));
- assertThat(author.getTimeZone())
- .isEqualTo(TimeZone.getTimeZone("GMT-7:00"));
+ assertThat(author.getWhen()).isEqualTo(new Date(c.getCreatedOn().getTime() + 1000));
+ assertThat(author.getTimeZone()).isEqualTo(TimeZone.getTimeZone("GMT-7:00"));
PersonIdent committer = commit.getCommitterIdent();
assertThat(committer.getName()).isEqualTo("Gerrit Server");
@@ -83,21 +84,25 @@
public void changeMessageCommitFormatSimple() throws Exception {
Change c = TestChanges.newChange(project, changeOwner.getAccountId(), 1);
ChangeUpdate update = newUpdate(c, changeOwner);
- update.setChangeMessage("Just a little code change.\n"
- + "How about a new line");
+ update.setChangeMessage("Just a little code change.\n" + "How about a new line");
update.commit();
assertThat(update.getRefName()).isEqualTo("refs/changes/01/1/meta");
- assertBodyEquals("Update patch set 1\n"
- + "\n"
- + "Just a little code change.\n"
- + "How about a new line\n"
- + "\n"
- + "Patch-set: 1\n"
- + "Change-id: " + c.getKey().get() + "\n"
- + "Subject: Change subject\n"
- + "Branch: refs/heads/master\n"
- + "Commit: " + update.getCommit().name() + "\n",
+ assertBodyEquals(
+ "Update patch set 1\n"
+ + "\n"
+ + "Just a little code change.\n"
+ + "How about a new line\n"
+ + "\n"
+ + "Patch-set: 1\n"
+ + "Change-id: "
+ + c.getKey().get()
+ + "\n"
+ + "Subject: Change subject\n"
+ + "Branch: refs/heads/master\n"
+ + "Commit: "
+ + update.getCommit().name()
+ + "\n",
update.getResult());
}
@@ -111,15 +116,20 @@
update.commit();
assertThat(update.getRefName()).isEqualTo("refs/changes/01/1/meta");
- assertBodyEquals("Update patch set 1\n"
- + "\n"
- + "Foo\n"
- + "\n"
- + "Patch-set: 1\n"
- + "Change-id: " + c.getKey().get() + "\n"
- + "Subject: Subject\n"
- + "Branch: refs/heads/master\n"
- + "Commit: " + commit.name() + "\n",
+ assertBodyEquals(
+ "Update patch set 1\n"
+ + "\n"
+ + "Foo\n"
+ + "\n"
+ + "Patch-set: 1\n"
+ + "Change-id: "
+ + c.getKey().get()
+ + "\n"
+ + "Subject: Subject\n"
+ + "Branch: refs/heads/master\n"
+ + "Commit: "
+ + commit.name()
+ + "\n",
update.getResult());
}
@@ -130,10 +140,8 @@
update.removeApproval("Code-Review");
update.commit();
- assertBodyEquals("Update patch set 1\n"
- + "\n"
- + "Patch-set: 1\n"
- + "Label: -Code-Review\n",
+ assertBodyEquals(
+ "Update patch set 1\n" + "\n" + "Patch-set: 1\n" + "Label: -Code-Review\n",
update.getResult());
}
@@ -144,36 +152,43 @@
update.setSubjectForCommit("Submit patch set 1");
RequestId submissionId = RequestId.forChange(c);
- update.merge(submissionId, ImmutableList.of(
- submitRecord("NOT_READY", null,
- submitLabel("Verified", "OK", changeOwner.getAccountId()),
- submitLabel("Code-Review", "NEED", null)),
- submitRecord("NOT_READY", null,
- submitLabel("Verified", "OK", changeOwner.getAccountId()),
- submitLabel("Alternative-Code-Review", "NEED", null))));
+ update.merge(
+ submissionId,
+ ImmutableList.of(
+ submitRecord(
+ "NOT_READY",
+ null,
+ submitLabel("Verified", "OK", changeOwner.getAccountId()),
+ submitLabel("Code-Review", "NEED", null)),
+ submitRecord(
+ "NOT_READY",
+ null,
+ submitLabel("Verified", "OK", changeOwner.getAccountId()),
+ submitLabel("Alternative-Code-Review", "NEED", null))));
update.commit();
RevCommit commit = parseCommit(update.getResult());
- assertBodyEquals("Submit patch set 1\n"
- + "\n"
- + "Patch-set: 1\n"
- + "Status: merged\n"
- + "Submission-id: " + submissionId.toStringForStorage() + "\n"
- + "Submitted-with: NOT_READY\n"
- + "Submitted-with: OK: Verified: Change Owner <1@gerrit>\n"
- + "Submitted-with: NEED: Code-Review\n"
- + "Submitted-with: NOT_READY\n"
- + "Submitted-with: OK: Verified: Change Owner <1@gerrit>\n"
- + "Submitted-with: NEED: Alternative-Code-Review\n",
+ assertBodyEquals(
+ "Submit patch set 1\n"
+ + "\n"
+ + "Patch-set: 1\n"
+ + "Status: merged\n"
+ + "Submission-id: "
+ + submissionId.toStringForStorage()
+ + "\n"
+ + "Submitted-with: NOT_READY\n"
+ + "Submitted-with: OK: Verified: Change Owner <1@gerrit>\n"
+ + "Submitted-with: NEED: Code-Review\n"
+ + "Submitted-with: NOT_READY\n"
+ + "Submitted-with: OK: Verified: Change Owner <1@gerrit>\n"
+ + "Submitted-with: NEED: Alternative-Code-Review\n",
commit);
PersonIdent author = commit.getAuthorIdent();
assertThat(author.getName()).isEqualTo("Change Owner");
assertThat(author.getEmailAddress()).isEqualTo("1@gerrit");
- assertThat(author.getWhen())
- .isEqualTo(new Date(c.getCreatedOn().getTime() + 2000));
- assertThat(author.getTimeZone())
- .isEqualTo(TimeZone.getTimeZone("GMT-7:00"));
+ assertThat(author.getWhen()).isEqualTo(new Date(c.getCreatedOn().getTime() + 2000));
+ assertThat(author.getTimeZone()).isEqualTo(TimeZone.getTimeZone("GMT-7:00"));
PersonIdent committer = commit.getCommitterIdent();
assertThat(committer.getName()).isEqualTo("Gerrit Server");
@@ -192,11 +207,8 @@
update.commit();
RevCommit commit = parseCommit(update.getResult());
- assertBodyEquals("Update patch set 1\n"
- + "\n"
- + "Comment on the change.\n"
- + "\n"
- + "Patch-set: 1\n",
+ assertBodyEquals(
+ "Update patch set 1\n" + "\n" + "Comment on the change.\n" + "\n" + "Patch-set: 1\n",
commit);
PersonIdent author = commit.getAuthorIdent();
@@ -211,16 +223,19 @@
update.setSubjectForCommit("Submit patch set 1");
RequestId submissionId = RequestId.forChange(c);
- update.merge(submissionId, ImmutableList.of(
- submitRecord("RULE_ERROR", "Problem with patch set:\n1")));
+ update.merge(
+ submissionId, ImmutableList.of(submitRecord("RULE_ERROR", "Problem with patch set:\n1")));
update.commit();
- assertBodyEquals("Submit patch set 1\n"
- + "\n"
- + "Patch-set: 1\n"
- + "Status: merged\n"
- + "Submission-id: " + submissionId.toStringForStorage() + "\n"
- + "Submitted-with: RULE_ERROR Problem with patch set: 1\n",
+ assertBodyEquals(
+ "Submit patch set 1\n"
+ + "\n"
+ + "Patch-set: 1\n"
+ + "Status: merged\n"
+ + "Submission-id: "
+ + submissionId.toStringForStorage()
+ + "\n"
+ + "Submitted-with: RULE_ERROR Problem with patch set: 1\n",
update.getResult());
}
@@ -231,10 +246,8 @@
update.putReviewer(changeOwner.getAccount().getId(), REVIEWER);
update.commit();
- assertBodyEquals("Update patch set 1\n"
- + "\n"
- + "Patch-set: 1\n"
- + "Reviewer: Change Owner <1@gerrit>\n",
+ assertBodyEquals(
+ "Update patch set 1\n" + "\n" + "Patch-set: 1\n" + "Reviewer: Change Owner <1@gerrit>\n",
update.getResult());
}
@@ -242,17 +255,17 @@
public void changeMessageWithTrailingDoubleNewline() throws Exception {
Change c = newChange();
ChangeUpdate update = newUpdate(c, changeOwner);
- update.setChangeMessage("Testing trailing double newline\n"
- + "\n");
+ update.setChangeMessage("Testing trailing double newline\n" + "\n");
update.commit();
- assertBodyEquals("Update patch set 1\n"
- + "\n"
- + "Testing trailing double newline\n"
- + "\n"
- + "\n"
- + "\n"
- + "Patch-set: 1\n",
+ assertBodyEquals(
+ "Update patch set 1\n"
+ + "\n"
+ + "Testing trailing double newline\n"
+ + "\n"
+ + "\n"
+ + "\n"
+ + "Patch-set: 1\n",
update.getResult());
}
@@ -260,22 +273,20 @@
public void changeMessageWithMultipleParagraphs() throws Exception {
Change c = newChange();
ChangeUpdate update = newUpdate(c, changeOwner);
- update.setChangeMessage("Testing paragraph 1\n"
- + "\n"
- + "Testing paragraph 2\n"
- + "\n"
- + "Testing paragraph 3");
+ update.setChangeMessage(
+ "Testing paragraph 1\n" + "\n" + "Testing paragraph 2\n" + "\n" + "Testing paragraph 3");
update.commit();
- assertBodyEquals("Update patch set 1\n"
- + "\n"
- + "Testing paragraph 1\n"
- + "\n"
- + "Testing paragraph 2\n"
- + "\n"
- + "Testing paragraph 3\n"
- + "\n"
- + "Patch-set: 1\n",
+ assertBodyEquals(
+ "Update patch set 1\n"
+ + "\n"
+ + "Testing paragraph 1\n"
+ + "\n"
+ + "Testing paragraph 2\n"
+ + "\n"
+ + "Testing paragraph 3\n"
+ + "\n"
+ + "Patch-set: 1\n",
update.getResult());
}
@@ -287,57 +298,65 @@
update.setTag("jenkins");
update.commit();
- assertBodyEquals("Update patch set 1\n"
- + "\n"
- + "Change message with tag\n"
- + "\n"
- + "Patch-set: 1\n"
- + "Tag: jenkins\n",
+ assertBodyEquals(
+ "Update patch set 1\n"
+ + "\n"
+ + "Change message with tag\n"
+ + "\n"
+ + "Patch-set: 1\n"
+ + "Tag: jenkins\n",
update.getResult());
}
@Test
public void leadingWhitespace() throws Exception {
Change c = TestChanges.newChange(project, changeOwner.getAccountId());
- c.setCurrentPatchSet(c.currentPatchSetId(), " " + c.getSubject(),
- c.getOriginalSubject());
+ c.setCurrentPatchSet(c.currentPatchSetId(), " " + c.getSubject(), c.getOriginalSubject());
ChangeUpdate update = newUpdate(c, changeOwner);
update.setChangeId(c.getKey().get());
update.setBranch(c.getDest().get());
update.commit();
- assertBodyEquals("Update patch set 1\n"
- + "\n"
- + "Patch-set: 1\n"
- + "Change-id: " + c.getKey().get() + "\n"
- + "Subject: Change subject\n"
- + "Branch: refs/heads/master\n"
- + "Commit: " + update.getCommit().name() + "\n",
+ assertBodyEquals(
+ "Update patch set 1\n"
+ + "\n"
+ + "Patch-set: 1\n"
+ + "Change-id: "
+ + c.getKey().get()
+ + "\n"
+ + "Subject: Change subject\n"
+ + "Branch: refs/heads/master\n"
+ + "Commit: "
+ + update.getCommit().name()
+ + "\n",
update.getResult());
c = TestChanges.newChange(project, changeOwner.getAccountId());
- c.setCurrentPatchSet(c.currentPatchSetId(), "\t\t" + c.getSubject(),
- c.getOriginalSubject());
+ c.setCurrentPatchSet(c.currentPatchSetId(), "\t\t" + c.getSubject(), c.getOriginalSubject());
update = newUpdate(c, changeOwner);
update.setChangeId(c.getKey().get());
update.setBranch(c.getDest().get());
update.commit();
- assertBodyEquals("Update patch set 1\n"
- + "\n"
- + "Patch-set: 1\n"
- + "Change-id: " + c.getKey().get() + "\n"
- + "Subject: \t\tChange subject\n"
- + "Branch: refs/heads/master\n"
- + "Commit: " + update.getCommit().name() + "\n",
+ assertBodyEquals(
+ "Update patch set 1\n"
+ + "\n"
+ + "Patch-set: 1\n"
+ + "Change-id: "
+ + c.getKey().get()
+ + "\n"
+ + "Subject: \t\tChange subject\n"
+ + "Branch: refs/heads/master\n"
+ + "Commit: "
+ + update.getCommit().name()
+ + "\n",
update.getResult());
}
@Test
public void realUser() throws Exception {
Change c = newChange();
- CurrentUser ownerAsOtherUser =
- userFactory.runAs(null, otherUserId, changeOwner);
+ CurrentUser ownerAsOtherUser = userFactory.runAs(null, otherUserId, changeOwner);
ChangeUpdate update = newUpdate(c, ownerAsOtherUser);
update.setChangeMessage("Message on behalf of other user");
update.commit();
@@ -347,12 +366,13 @@
assertThat(author.getName()).isEqualTo("Other Account");
assertThat(author.getEmailAddress()).isEqualTo("2@gerrit");
- assertBodyEquals("Update patch set 1\n"
- + "\n"
- + "Message on behalf of other user\n"
- + "\n"
- + "Patch-set: 1\n"
- + "Real-user: Change Owner <1@gerrit>\n",
+ assertBodyEquals(
+ "Update patch set 1\n"
+ + "\n"
+ + "Message on behalf of other user\n"
+ + "\n"
+ + "Patch-set: 1\n"
+ + "Real-user: Change Owner <1@gerrit>\n",
commit);
}
@@ -363,11 +383,8 @@
update.setCurrentPatchSet();
update.commit();
- assertBodyEquals("Update patch set 1\n"
- + "\n"
- + "Patch-set: 1\n"
- + "Current: true\n",
- update.getResult());
+ assertBodyEquals(
+ "Update patch set 1\n" + "\n" + "Patch-set: 1\n" + "Current: true\n", update.getResult());
}
private RevCommit parseCommit(ObjectId id) throws Exception {
@@ -381,8 +398,7 @@
}
}
- private void assertBodyEquals(String expected, ObjectId commitId)
- throws Exception {
+ private void assertBodyEquals(String expected, ObjectId commitId) throws Exception {
RevCommit commit = parseCommit(commitId);
assertThat(commit.getFullMessage()).isEqualTo(expected);
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/notedb/NoteDbChangeStateTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/notedb/NoteDbChangeStateTest.java
index a7ccfc8..0553dc5 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/notedb/NoteDbChangeStateTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/notedb/NoteDbChangeStateTest.java
@@ -17,10 +17,10 @@
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.truth.Truth.assertThat;
import static com.google.gerrit.common.TimeUtil.nowTs;
-import static com.google.gerrit.server.notedb.NoteDbChangeState.applyDelta;
-import static com.google.gerrit.server.notedb.NoteDbChangeState.parse;
import static com.google.gerrit.server.notedb.NoteDbChangeState.PrimaryStorage.NOTE_DB;
import static com.google.gerrit.server.notedb.NoteDbChangeState.PrimaryStorage.REVIEW_DB;
+import static com.google.gerrit.server.notedb.NoteDbChangeState.applyDelta;
+import static com.google.gerrit.server.notedb.NoteDbChangeState.parse;
import static org.eclipse.jgit.lib.ObjectId.zeroId;
import com.google.common.collect.ImmutableMap;
@@ -32,24 +32,19 @@
import com.google.gerrit.testutil.GerritBaseTests;
import com.google.gerrit.testutil.TestChanges;
import com.google.gerrit.testutil.TestTimeUtil;
-
+import java.sql.Timestamp;
+import java.util.Optional;
+import java.util.concurrent.TimeUnit;
import org.eclipse.jgit.lib.ObjectId;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
-import java.sql.Timestamp;
-import java.util.Optional;
-import java.util.concurrent.TimeUnit;
-
/** Unit tests for {@link NoteDbChangeState}. */
public class NoteDbChangeStateTest extends GerritBaseTests {
- ObjectId SHA1 =
- ObjectId.fromString("deadbeefdeadbeefdeadbeefdeadbeefdeadbeef");
- ObjectId SHA2 =
- ObjectId.fromString("abcd1234abcd1234abcd1234abcd1234abcd1234");
- ObjectId SHA3 =
- ObjectId.fromString("badc0feebadc0feebadc0feebadc0feebadc0fee");
+ ObjectId SHA1 = ObjectId.fromString("deadbeefdeadbeefdeadbeefdeadbeefdeadbeef");
+ ObjectId SHA2 = ObjectId.fromString("abcd1234abcd1234abcd1234abcd1234abcd1234");
+ ObjectId SHA3 = ObjectId.fromString("badc0feebadc0feebadc0feebadc0feebadc0fee");
@Before
public void setUp() {
@@ -83,15 +78,15 @@
@Test
public void parseReviewDbWithDrafts() {
String str = SHA1.name() + ",2003=" + SHA2.name() + ",1001=" + SHA3.name();
- String expected =
- SHA1.name() + ",1001=" + SHA3.name() + ",2003=" + SHA2.name();
+ String expected = SHA1.name() + ",1001=" + SHA3.name() + ",2003=" + SHA2.name();
NoteDbChangeState state = parse(new Change.Id(1), str);
assertThat(state.getPrimaryStorage()).isEqualTo(REVIEW_DB);
assertThat(state.getChangeId()).isEqualTo(new Change.Id(1));
assertThat(state.getChangeMetaId()).isEqualTo(SHA1);
- assertThat(state.getDraftIds()).containsExactly(
- new Account.Id(1001), SHA3,
- new Account.Id(2003), SHA2);
+ assertThat(state.getDraftIds())
+ .containsExactly(
+ new Account.Id(1001), SHA3,
+ new Account.Id(2003), SHA2);
assertThat(state.getReadOnlyUntil().isPresent()).isFalse();
assertThat(state.toString()).isEqualTo(expected);
@@ -99,9 +94,10 @@
assertThat(state.getPrimaryStorage()).isEqualTo(REVIEW_DB);
assertThat(state.getChangeId()).isEqualTo(new Change.Id(1));
assertThat(state.getChangeMetaId()).isEqualTo(SHA1);
- assertThat(state.getDraftIds()).containsExactly(
- new Account.Id(1001), SHA3,
- new Account.Id(2003), SHA2);
+ assertThat(state.getDraftIds())
+ .containsExactly(
+ new Account.Id(1001), SHA3,
+ new Account.Id(2003), SHA2);
assertThat(state.getReadOnlyUntil().isPresent()).isFalse();
assertThat(state.toString()).isEqualTo(expected);
}
@@ -133,11 +129,7 @@
applyDelta(c, Delta.create(c.getId(), noMetaId(), noDrafts()));
assertThat(c.getNoteDbState()).isNull();
- applyDelta(
- c,
- Delta.create(
- c.getId(), noMetaId(),
- drafts(new Account.Id(1001), zeroId())));
+ applyDelta(c, Delta.create(c.getId(), noMetaId(), drafts(new Account.Id(1001), zeroId())));
assertThat(c.getNoteDbState()).isNull();
}
@@ -162,53 +154,40 @@
@Test
public void applyDeltaToDrafts() throws Exception {
Change c = newChange();
- applyDelta(
- c,
- Delta.create(
- c.getId(), metaId(SHA1),
- drafts(new Account.Id(1001), SHA2)));
- assertThat(c.getNoteDbState()).isEqualTo(
- SHA1.name() + ",1001=" + SHA2.name());
+ applyDelta(c, Delta.create(c.getId(), metaId(SHA1), drafts(new Account.Id(1001), SHA2)));
+ assertThat(c.getNoteDbState()).isEqualTo(SHA1.name() + ",1001=" + SHA2.name());
- applyDelta(
- c,
- Delta.create(
- c.getId(), noMetaId(),
- drafts(new Account.Id(2003), SHA3)));
- assertThat(c.getNoteDbState()).isEqualTo(
- SHA1.name() + ",1001=" + SHA2.name() + ",2003=" + SHA3.name());
+ applyDelta(c, Delta.create(c.getId(), noMetaId(), drafts(new Account.Id(2003), SHA3)));
+ assertThat(c.getNoteDbState())
+ .isEqualTo(SHA1.name() + ",1001=" + SHA2.name() + ",2003=" + SHA3.name());
- applyDelta(
- c,
- Delta.create(
- c.getId(), noMetaId(),
- drafts(new Account.Id(2003), zeroId())));
- assertThat(c.getNoteDbState()).isEqualTo(
- SHA1.name() + ",1001=" + SHA2.name());
+ applyDelta(c, Delta.create(c.getId(), noMetaId(), drafts(new Account.Id(2003), zeroId())));
+ assertThat(c.getNoteDbState()).isEqualTo(SHA1.name() + ",1001=" + SHA2.name());
- applyDelta(
- c, Delta.create(c.getId(), metaId(SHA3), noDrafts()));
- assertThat(c.getNoteDbState()).isEqualTo(
- SHA3.name() + ",1001=" + SHA2.name());
+ applyDelta(c, Delta.create(c.getId(), metaId(SHA3), noDrafts()));
+ assertThat(c.getNoteDbState()).isEqualTo(SHA3.name() + ",1001=" + SHA2.name());
}
@Test
public void applyDeltaToReadOnly() throws Exception {
Timestamp ts = nowTs();
Change c = newChange();
- NoteDbChangeState state = new NoteDbChangeState(c.getId(),
- REVIEW_DB,
- Optional.of(RefState.create(SHA1, ImmutableMap.of())),
- Optional.of(new Timestamp(ts.getTime() + 10000)));
+ NoteDbChangeState state =
+ new NoteDbChangeState(
+ c.getId(),
+ REVIEW_DB,
+ Optional.of(RefState.create(SHA1, ImmutableMap.of())),
+ Optional.of(new Timestamp(ts.getTime() + 10000)));
c.setNoteDbState(state.toString());
Delta delta = Delta.create(c.getId(), metaId(SHA2), noDrafts());
applyDelta(c, delta);
- assertThat(NoteDbChangeState.parse(c)).isEqualTo(
- new NoteDbChangeState(
- state.getChangeId(),
- state.getPrimaryStorage(),
- Optional.of(RefState.create(SHA2, ImmutableMap.of())),
- state.getReadOnlyUntil()));
+ assertThat(NoteDbChangeState.parse(c))
+ .isEqualTo(
+ new NoteDbChangeState(
+ state.getChangeId(),
+ state.getPrimaryStorage(),
+ Optional.of(RefState.create(SHA2, ImmutableMap.of())),
+ state.getReadOnlyUntil()));
}
@Test
@@ -228,14 +207,12 @@
public void applyDeltaToNoteDbPrimaryIsNoOp() throws Exception {
Change c = newChange();
c.setNoteDbState("N");
- applyDelta(c, Delta.create(c.getId(), metaId(SHA1),
- drafts(new Account.Id(1001), SHA2)));
+ applyDelta(c, Delta.create(c.getId(), metaId(SHA1), drafts(new Account.Id(1001), SHA2)));
assertThat(c.getNoteDbState()).isEqualTo("N");
}
private static Change newChange() {
- return TestChanges.newChange(
- new Project.NameKey("project"), new Account.Id(12345));
+ return TestChanges.newChange(new Project.NameKey("project"), new Account.Id(12345));
}
// Static factory methods to avoid type arguments when using as method args.
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/notedb/RepoSequenceTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/notedb/RepoSequenceTest.java
index cab6549..df3e405 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/notedb/RepoSequenceTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/notedb/RepoSequenceTest.java
@@ -19,17 +19,19 @@
import static org.eclipse.jgit.lib.Constants.OBJ_BLOB;
import static org.junit.Assert.fail;
+import com.github.rholder.retry.BlockStrategy;
+import com.github.rholder.retry.Retryer;
+import com.github.rholder.retry.RetryerBuilder;
+import com.github.rholder.retry.StopStrategies;
import com.google.common.util.concurrent.Runnables;
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.reviewdb.client.RefNames;
import com.google.gerrit.testutil.InMemoryRepositoryManager;
import com.google.gwtorm.server.OrmException;
-
-import com.github.rholder.retry.BlockStrategy;
-import com.github.rholder.retry.Retryer;
-import com.github.rholder.retry.RetryerBuilder;
-import com.github.rholder.retry.StopStrategies;
-
+import java.io.IOException;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
import org.eclipse.jgit.errors.IncorrectObjectTypeException;
import org.eclipse.jgit.junit.TestRepository;
import org.eclipse.jgit.lib.ObjectId;
@@ -42,22 +44,19 @@
import org.junit.Test;
import org.junit.rules.ExpectedException;
-import java.io.IOException;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicInteger;
-
public class RepoSequenceTest {
private static final Retryer<RefUpdate.Result> RETRYER =
- RepoSequence.retryerBuilder().withBlockStrategy(new BlockStrategy() {
- @Override
- public void block(long sleepTime) {
- // Don't sleep in tests.
- }
- }).build();
+ RepoSequence.retryerBuilder()
+ .withBlockStrategy(
+ new BlockStrategy() {
+ @Override
+ public void block(long sleepTime) {
+ // Don't sleep in tests.
+ }
+ })
+ .build();
- @Rule
- public ExpectedException exception = ExpectedException.none();
+ @Rule public ExpectedException exception = ExpectedException.none();
private InMemoryRepositoryManager repoManager;
private Project.NameKey project;
@@ -79,8 +78,7 @@
try {
assertThat(s.next()).named("i=" + i + " for " + name).isEqualTo(i);
} catch (OrmException e) {
- throw new AssertionError(
- "failed batchSize=" + batchSize + ", i=" + i, e);
+ throw new AssertionError("failed batchSize=" + batchSize + ", i=" + i, e);
}
}
assertThat(s.acquireCount)
@@ -162,14 +160,15 @@
writeBlob("id", "1");
final AtomicBoolean doneBgUpdate = new AtomicBoolean(false);
- Runnable bgUpdate = new Runnable() {
- @Override
- public void run() {
- if (!doneBgUpdate.getAndSet(true)) {
- writeBlob("id", "1234");
- }
- }
- };
+ Runnable bgUpdate =
+ new Runnable() {
+ @Override
+ public void run() {
+ if (!doneBgUpdate.getAndSet(true)) {
+ writeBlob("id", "1234");
+ }
+ }
+ };
RepoSequence s = newSequence("id", 1, 10, bgUpdate, RETRYER);
assertThat(doneBgUpdate.get()).isFalse();
@@ -183,8 +182,7 @@
public void failOnInvalidValue() throws Exception {
ObjectId id = writeBlob("id", "not a number");
exception.expect(OrmException.class);
- exception.expectMessage(
- "invalid value in refs/sequences/id blob at " + id.name());
+ exception.expectMessage("invalid value in refs/sequences/id blob at " + id.name());
newSequence("id", 1, 3).next();
}
@@ -198,8 +196,7 @@
fail();
} catch (OrmException e) {
assertThat(e.getCause()).isInstanceOf(ExecutionException.class);
- assertThat(e.getCause().getCause())
- .isInstanceOf(IncorrectObjectTypeException.class);
+ assertThat(e.getCause().getCause()).isInstanceOf(IncorrectObjectTypeException.class);
}
}
}
@@ -207,17 +204,22 @@
@Test
public void failAfterRetryerGivesUp() throws Exception {
final AtomicInteger bgCounter = new AtomicInteger(1234);
- Runnable bgUpdate = new Runnable() {
- @Override
- public void run() {
- writeBlob("id", Integer.toString(bgCounter.getAndAdd(1000)));
- }
- };
- RepoSequence s = newSequence(
- "id", 1, 10, bgUpdate,
- RetryerBuilder.<RefUpdate.Result> newBuilder()
- .withStopStrategy(StopStrategies.stopAfterAttempt(3))
- .build());
+ Runnable bgUpdate =
+ new Runnable() {
+ @Override
+ public void run() {
+ writeBlob("id", Integer.toString(bgCounter.getAndAdd(1000)));
+ }
+ };
+ RepoSequence s =
+ newSequence(
+ "id",
+ 1,
+ 10,
+ bgUpdate,
+ RetryerBuilder.<RefUpdate.Result>newBuilder()
+ .withStopStrategy(StopStrategies.stopAfterAttempt(3))
+ .build());
exception.expect(OrmException.class);
exception.expectMessage("failed to update refs/sequences/id: LOCK_FAILURE");
s.next();
@@ -270,12 +272,15 @@
}
private RepoSequence newSequence(String name, int start, int batchSize) {
- return newSequence(
- name, start, batchSize, Runnables.doNothing(), RETRYER);
+ return newSequence(name, start, batchSize, Runnables.doNothing(), RETRYER);
}
- private RepoSequence newSequence(String name, final int start, int batchSize,
- Runnable afterReadRef, Retryer<RefUpdate.Result> retryer) {
+ private RepoSequence newSequence(
+ String name,
+ final int start,
+ int batchSize,
+ Runnable afterReadRef,
+ Retryer<RefUpdate.Result> retryer) {
return new RepoSequence(
repoManager,
project,
@@ -299,8 +304,7 @@
ins.flush();
RefUpdate ru = repo.updateRef(refName);
ru.setNewObjectId(newId);
- assertThat(ru.forceUpdate())
- .isAnyOf(RefUpdate.Result.NEW, RefUpdate.Result.FORCED);
+ assertThat(ru.forceUpdate()).isAnyOf(RefUpdate.Result.NEW, RefUpdate.Result.FORCED);
return newId;
} catch (IOException e) {
throw new RuntimeException(e);
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/notedb/rebuild/EventSorterTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/notedb/rebuild/EventSorterTest.java
index 1db59c5..1de82b1 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/notedb/rebuild/EventSorterTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/notedb/rebuild/EventSorterTest.java
@@ -26,23 +26,24 @@
import com.google.gerrit.reviewdb.client.PatchSet;
import com.google.gerrit.server.notedb.ChangeUpdate;
import com.google.gerrit.testutil.TestTimeUtil;
-
-import org.junit.Before;
-import org.junit.Test;
-
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
+import org.junit.Before;
+import org.junit.Test;
public class EventSorterTest {
private class TestEvent extends Event {
protected TestEvent(Timestamp when) {
super(
new PatchSet.Id(new Change.Id(1), 1),
- new Account.Id(1000), new Account.Id(1000),
- when, changeCreatedOn, null);
+ new Account.Id(1000),
+ new Account.Id(1000),
+ when,
+ changeCreatedOn,
+ null);
}
@Override
@@ -113,10 +114,11 @@
}
private List<Event> threeEventsOneDep(int depFromIdx, int depOnIdx) {
- List<Event> events = Lists.newArrayList(
- new TestEvent(TimeUtil.nowTs()),
- new TestEvent(TimeUtil.nowTs()),
- new TestEvent(TimeUtil.nowTs()));
+ List<Event> events =
+ Lists.newArrayList(
+ new TestEvent(TimeUtil.nowTs()),
+ new TestEvent(TimeUtil.nowTs()),
+ new TestEvent(TimeUtil.nowTs()));
events.get(depFromIdx).addDep(events.get(depOnIdx));
return events;
}
@@ -155,9 +157,7 @@
e2.addDep(e3);
e3.addDep(e4);
- assertSorted(
- events(e1, e2, e3, e4),
- events(e4, e3, e2, e1));
+ assertSorted(events(e1, e2, e3, e4), events(e4, e3, e2, e1));
}
@Test
@@ -171,9 +171,7 @@
e2.addDep(e3);
// Processing 3 pops 2, processing 4 pops 1.
- assertSorted(
- events(e2, e3, e1, e4),
- events(e3, e2, e4, e1));
+ assertSorted(events(e2, e3, e1, e4), events(e3, e2, e4, e1));
}
@Test
@@ -187,9 +185,7 @@
e3.addDep(e4);
// Processing 4 pops 1, 2, 3 in natural order.
- assertSorted(
- events(e4, e3, e2, e1),
- events(e4, e1, e2, e3));
+ assertSorted(events(e4, e3, e2, e1), events(e4, e1, e2, e3));
}
@Test
@@ -200,9 +196,7 @@
// Implementation is not really defined, but infinite looping would be bad.
// According to current implementation details, 2 pops 1, 1 pops 2 which was
// already seen.
- assertSorted(
- events(e2, e1),
- events(e1, e2));
+ assertSorted(events(e2, e1), events(e1, e2));
}
@Test
@@ -232,8 +226,6 @@
private static void assertSorted(List<Event> unsorted, List<Event> expected) {
List<Event> actual = new ArrayList<>(unsorted);
new EventSorter(actual).sort();
- assertThat(actual)
- .named("sorted" + unsorted)
- .isEqualTo(expected);
+ assertThat(actual).named("sorted" + unsorted).isEqualTo(expected);
}
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/patch/IntraLineLoaderTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/patch/IntraLineLoaderTest.java
index eda2b82..0859bf7 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/patch/IntraLineLoaderTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/patch/IntraLineLoaderTest.java
@@ -17,67 +17,56 @@
import static com.google.common.truth.Truth.assertThat;
import static java.nio.charset.StandardCharsets.UTF_8;
+import java.util.List;
import org.eclipse.jgit.diff.Edit;
import org.eclipse.jgit.diff.EditList;
import org.eclipse.jgit.diff.ReplaceEdit;
import org.junit.Test;
-import java.util.List;
-
public class IntraLineLoaderTest {
@Test
public void rewriteAtStartOfLineIsRecognized() throws Exception {
String a = "abc1\n";
String b = "def1\n";
- assertThat(intraline(a, b)).isEqualTo(ref()
- .replace("abc", "def").common("1\n").edits
- );
+ assertThat(intraline(a, b)).isEqualTo(ref().replace("abc", "def").common("1\n").edits);
}
@Test
public void rewriteAtEndOfLineIsRecognized() throws Exception {
String a = "abc1\n";
String b = "abc2\n";
- assertThat(intraline(a, b)).isEqualTo(ref()
- .common("abc").replace("1", "2").common("\n").edits
- );
+ assertThat(intraline(a, b)).isEqualTo(ref().common("abc").replace("1", "2").common("\n").edits);
}
@Test
public void completeRewriteIncludesNewline() throws Exception {
String a = "abc1\n";
String b = "def2\n";
- assertThat(intraline(a, b)).isEqualTo(ref()
- .replace("abc1\n", "def2\n").edits
- );
+ assertThat(intraline(a, b)).isEqualTo(ref().replace("abc1\n", "def2\n").edits);
}
@Test
public void closeEditsAreCombined() throws Exception {
String a = "ab1cdef2gh\n";
String b = "ab2cdef3gh\n";
- assertThat(intraline(a, b)).isEqualTo(ref()
- .common("ab").replace("1cdef2", "2cdef3").common("gh\n").edits
- );
+ assertThat(intraline(a, b))
+ .isEqualTo(ref().common("ab").replace("1cdef2", "2cdef3").common("gh\n").edits);
}
@Test
public void preferInsertAfterCommonPart1() throws Exception {
String a = "start middle end\n";
String b = "start middlemiddle end\n";
- assertThat(intraline(a, b)).isEqualTo(ref()
- .common("start middle").insert("middle").common(" end\n").edits
- );
+ assertThat(intraline(a, b))
+ .isEqualTo(ref().common("start middle").insert("middle").common(" end\n").edits);
}
@Test
public void preferInsertAfterCommonPart2() throws Exception {
String a = "abc def\n";
String b = "abc def\n";
- assertThat(intraline(a, b)).isEqualTo(ref()
- .common("abc ").insert(" ").common("def\n").edits
- );
+ assertThat(intraline(a, b)).isEqualTo(ref().common("abc ").insert(" ").common("def\n").edits);
}
@Test
@@ -100,10 +89,8 @@
public void preferInsertAtLineBreak2() throws Exception {
String a = " abc\n def\n";
String b = " abc\n def\n";
- assertThat(intraline(a, b)).isEqualTo(ref()
- .insert(" ").common(" abc\n")
- .insert(" ").common(" def\n").edits
- );
+ assertThat(intraline(a, b))
+ .isEqualTo(ref().insert(" ").common(" abc\n").insert(" ").common(" def\n").edits);
}
//TODO: expected failure
@@ -112,19 +99,16 @@
public void preferDeleteAtLineBreak() throws Exception {
String a = " abc\n def\n";
String b = " abc\n def\n";
- assertThat(intraline(a, b)).isEqualTo(ref()
- .remove(" ").common(" abc\n")
- .remove(" ").common(" def\n").edits
- );
+ assertThat(intraline(a, b))
+ .isEqualTo(ref().remove(" ").common(" abc\n").remove(" ").common(" def\n").edits);
}
@Test
public void insertedWhitespaceIsRecognized() throws Exception {
String a = " int *foobar\n";
String b = " int * foobar\n";
- assertThat(intraline(a, b)).isEqualTo(ref()
- .common(" int *").insert(" ").common("foobar\n").edits
- );
+ assertThat(intraline(a, b))
+ .isEqualTo(ref().common(" int *").insert(" ").common("foobar\n").edits);
}
@Test
@@ -132,10 +116,16 @@
// |0 5 10 | 5 20 5 30
String a = " int *foobar\n int *foobar\n";
String b = " int * foobar\n int * foobar\n";
- assertThat(intraline(a, b)).isEqualTo(ref()
- .common(" int *").insert(" ").common("foobar\n")
- .common(" int *").insert(" ").common("foobar\n").edits
- );
+ assertThat(intraline(a, b))
+ .isEqualTo(
+ ref()
+ .common(" int *")
+ .insert(" ")
+ .common("foobar\n")
+ .common(" int *")
+ .insert(" ")
+ .common("foobar\n")
+ .edits);
}
// helper functions to call IntraLineLoader.compute
@@ -154,8 +144,7 @@
return intraline(a, b, new Edit(0, countLines(a), 0, countLines(b)));
}
- private static List<Edit> intraline(String a, String b, Edit lines)
- throws Exception {
+ private static List<Edit> intraline(String a, String b, Edit lines) throws Exception {
Text aText = new Text(a.getBytes(UTF_8));
Text bText = new Text(b.getBytes(UTF_8));
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/patch/PatchListEntryTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/patch/PatchListEntryTest.java
index 2721b30..81f03af 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/patch/PatchListEntryTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/patch/PatchListEntryTest.java
@@ -20,7 +20,6 @@
import static org.junit.Assert.assertTrue;
import com.google.gerrit.reviewdb.client.Patch;
-
import org.junit.Test;
public class PatchListEntryTest {
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/project/ProjectControlTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/project/ProjectControlTest.java
index 79983f9..92d7a52 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/project/ProjectControlTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/project/ProjectControlTest.java
@@ -45,7 +45,6 @@
import com.google.inject.Injector;
import com.google.inject.Provider;
import com.google.inject.util.Providers;
-
import org.eclipse.jgit.internal.storage.dfs.InMemoryRepository;
import org.eclipse.jgit.junit.TestRepository;
import org.eclipse.jgit.lib.ObjectId;
@@ -94,8 +93,7 @@
admins = groupCache.get(new AccountGroup.NameKey("Administrators")).getGroupUUID();
setUpPermissions();
- Account.Id userId = accountManager.authenticate(AuthRequest.forUser("user"))
- .getAccountId();
+ Account.Id userId = accountManager.authenticate(AuthRequest.forUser("user")).getAccountId();
user = userFactory.create(userId);
Project.NameKey name = new Project.NameKey("project");
@@ -104,17 +102,18 @@
project.load(inMemoryRepo);
repo = new TestRepository<>(inMemoryRepo);
- requestContext.setContext(new RequestContext() {
- @Override
- public CurrentUser getUser() {
- return user;
- }
+ requestContext.setContext(
+ new RequestContext() {
+ @Override
+ public CurrentUser getUser() {
+ return user;
+ }
- @Override
- public Provider<ReviewDb> getReviewDbProvider() {
- return Providers.of(db);
- }
- });
+ @Override
+ public Provider<ReviewDb> getReviewDbProvider() {
+ return Providers.of(db);
+ }
+ });
}
@After
@@ -235,15 +234,13 @@
return projectControlFactory.controlFor(project.getName(), user);
}
- protected void allow(ProjectConfig project, String permission,
- AccountGroup.UUID id, String ref)
+ protected void allow(ProjectConfig project, String permission, AccountGroup.UUID id, String ref)
throws Exception {
Util.allow(project, permission, id, ref);
saveProjectConfig(project);
}
- protected void deny(ProjectConfig project, String permission,
- AccountGroup.UUID id, String ref)
+ protected void deny(ProjectConfig project, String permission, AccountGroup.UUID id, String ref)
throws Exception {
Util.deny(project, permission, id, ref);
saveProjectConfig(project);
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/project/RefControlTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/project/RefControlTest.java
index e2efc4a..21297e1 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/project/RefControlTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/project/RefControlTest.java
@@ -70,14 +70,6 @@
import com.google.inject.Injector;
import com.google.inject.Provider;
import com.google.inject.util.Providers;
-
-import org.eclipse.jgit.errors.ConfigInvalidException;
-import org.eclipse.jgit.internal.storage.dfs.InMemoryRepository;
-import org.eclipse.jgit.lib.Repository;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
@@ -85,6 +77,12 @@
import java.util.List;
import java.util.Map;
import java.util.Set;
+import org.eclipse.jgit.errors.ConfigInvalidException;
+import org.eclipse.jgit.internal.storage.dfs.InMemoryRepository;
+import org.eclipse.jgit.lib.Repository;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
public class RefControlTest {
private void assertAdminsAreOwnersAndDevsAreNot() {
@@ -96,10 +94,9 @@
}
private void assertOwner(String ref, ProjectControl u) {
- assertThat(u.controlForRef(ref).isOwner())
- .named("OWN " + ref)
- .isTrue();
+ assertThat(u.controlForRef(ref).isOwner()).named("OWN " + ref).isTrue();
}
+
private void assertNotOwner(ProjectControl u) {
assertThat(u.isOwner()).named("not owner").isFalse();
}
@@ -109,123 +106,84 @@
}
private void assertNotOwner(String ref, ProjectControl u) {
- assertThat(u.controlForRef(ref).isOwner())
- .named("NOT OWN " + ref)
- .isFalse();
+ assertThat(u.controlForRef(ref).isOwner()).named("NOT OWN " + ref).isFalse();
}
private void assertCanRead(ProjectControl u) {
- assertThat(u.isVisible())
- .named("can read")
- .isTrue();
+ assertThat(u.isVisible()).named("can read").isTrue();
}
private void assertCannotRead(ProjectControl u) {
- assertThat(u.isVisible())
- .named("cannot read")
- .isFalse();
+ assertThat(u.isVisible()).named("cannot read").isFalse();
}
private void assertCanRead(String ref, ProjectControl u) {
- assertThat(u.controlForRef(ref).isVisible())
- .named("can read " + ref)
- .isTrue();
+ assertThat(u.controlForRef(ref).isVisible()).named("can read " + ref).isTrue();
}
private void assertCannotRead(String ref, ProjectControl u) {
- assertThat(u.controlForRef(ref).isVisible())
- .named("cannot read " + ref)
- .isFalse();
+ assertThat(u.controlForRef(ref).isVisible()).named("cannot read " + ref).isFalse();
}
private void assertCanSubmit(String ref, ProjectControl u) {
- assertThat(u.controlForRef(ref).canSubmit(false))
- .named("can submit " + ref)
- .isTrue();
+ assertThat(u.controlForRef(ref).canSubmit(false)).named("can submit " + ref).isTrue();
}
private void assertCannotSubmit(String ref, ProjectControl u) {
- assertThat(u.controlForRef(ref).canSubmit(false))
- .named("can submit " + ref)
- .isFalse();
+ assertThat(u.controlForRef(ref).canSubmit(false)).named("can submit " + ref).isFalse();
}
private void assertCanUpload(ProjectControl u) {
- assertThat(u.canPushToAtLeastOneRef())
- .named("can upload")
- .isEqualTo(Capable.OK);
+ assertThat(u.canPushToAtLeastOneRef()).named("can upload").isEqualTo(Capable.OK);
}
private void assertCanUpload(String ref, ProjectControl u) {
- assertThat(u.controlForRef(ref).canUpload())
- .named("can upload " + ref)
- .isTrue();
+ assertThat(u.controlForRef(ref).canUpload()).named("can upload " + ref).isTrue();
}
private void assertCannotUpload(ProjectControl u) {
- assertThat(u.canPushToAtLeastOneRef())
- .named("cannot upload")
- .isNotEqualTo(Capable.OK);
+ assertThat(u.canPushToAtLeastOneRef()).named("cannot upload").isNotEqualTo(Capable.OK);
}
private void assertCannotUpload(String ref, ProjectControl u) {
- assertThat(u.controlForRef(ref).canUpload())
- .named("cannot upload " + ref)
- .isFalse();
+ assertThat(u.controlForRef(ref).canUpload()).named("cannot upload " + ref).isFalse();
}
private void assertBlocked(String p, String ref, ProjectControl u) {
- assertThat(u.controlForRef(ref).isBlocked(p))
- .named(p + " is blocked for " + ref)
- .isTrue();
+ assertThat(u.controlForRef(ref).isBlocked(p)).named(p + " is blocked for " + ref).isTrue();
}
private void assertNotBlocked(String p, String ref, ProjectControl u) {
- assertThat(u.controlForRef(ref).isBlocked(p))
- .named(p + " is blocked for " + ref)
- .isFalse();
+ assertThat(u.controlForRef(ref).isBlocked(p)).named(p + " is blocked for " + ref).isFalse();
}
private void assertCanUpdate(String ref, ProjectControl u) {
- assertThat(u.controlForRef(ref).canUpdate())
- .named("can update " + ref)
- .isTrue();
+ assertThat(u.controlForRef(ref).canUpdate()).named("can update " + ref).isTrue();
}
private void assertCannotUpdate(String ref, ProjectControl u) {
- assertThat(u.controlForRef(ref).canUpdate())
- .named("cannot update " + ref)
- .isFalse();
+ assertThat(u.controlForRef(ref).canUpdate()).named("cannot update " + ref).isFalse();
}
private void assertCanForceUpdate(String ref, ProjectControl u) {
- assertThat(u.controlForRef(ref).canForceUpdate())
- .named("can force push " + ref)
- .isTrue();
+ assertThat(u.controlForRef(ref).canForceUpdate()).named("can force push " + ref).isTrue();
}
private void assertCannotForceUpdate(String ref, ProjectControl u) {
- assertThat(u.controlForRef(ref).canForceUpdate())
- .named("cannot force push " + ref)
- .isFalse();
+ assertThat(u.controlForRef(ref).canForceUpdate()).named("cannot force push " + ref).isFalse();
}
private void assertCanVote(int score, PermissionRange range) {
- assertThat(range.contains(score))
- .named("can vote " + score)
- .isTrue();
+ assertThat(range.contains(score)).named("can vote " + score).isTrue();
}
private void assertCannotVote(int score, PermissionRange range) {
- assertThat(range.contains(score))
- .named("cannot vote " + score)
- .isFalse();
+ assertThat(range.contains(score)).named("cannot vote " + score).isFalse();
}
private final AllProjectsName allProjectsName =
new AllProjectsName(AllProjectsNameProvider.DEFAULT);
- private final AllUsersName allUsersName =
- new AllUsersName(AllUsersNameProvider.DEFAULT);
+ private final AllUsersName allUsersName = new AllUsersName(AllUsersNameProvider.DEFAULT);
private final AccountGroup.UUID fixers = new AccountGroup.UUID("test.fixers");
private final Map<Project.NameKey, ProjectState> all = new HashMap<>();
private Project.NameKey localKey = new Project.NameKey("local");
@@ -249,67 +207,62 @@
@Before
public void setUp() throws Exception {
repoManager = new InMemoryRepositoryManager();
- projectCache = new ProjectCache() {
- @Override
- public ProjectState getAllProjects() {
- return get(allProjectsName);
- }
+ projectCache =
+ new ProjectCache() {
+ @Override
+ public ProjectState getAllProjects() {
+ return get(allProjectsName);
+ }
- @Override
- public ProjectState getAllUsers() {
- return null;
- }
+ @Override
+ public ProjectState getAllUsers() {
+ return null;
+ }
- @Override
- public ProjectState get(Project.NameKey projectName) {
- return all.get(projectName);
- }
+ @Override
+ public ProjectState get(Project.NameKey projectName) {
+ return all.get(projectName);
+ }
- @Override
- public void evict(Project p) {
- }
+ @Override
+ public void evict(Project p) {}
- @Override
- public void remove(Project p) {
- }
+ @Override
+ public void remove(Project p) {}
- @Override
- public Iterable<Project.NameKey> all() {
- return Collections.emptySet();
- }
+ @Override
+ public Iterable<Project.NameKey> all() {
+ return Collections.emptySet();
+ }
- @Override
- public Iterable<Project.NameKey> byName(String prefix) {
- return Collections.emptySet();
- }
+ @Override
+ public Iterable<Project.NameKey> byName(String prefix) {
+ return Collections.emptySet();
+ }
- @Override
- public void onCreateProject(Project.NameKey newProjectName) {
- }
+ @Override
+ public void onCreateProject(Project.NameKey newProjectName) {}
- @Override
- public Set<AccountGroup.UUID> guessRelevantGroupUUIDs() {
- return Collections.emptySet();
- }
+ @Override
+ public Set<AccountGroup.UUID> guessRelevantGroupUUIDs() {
+ return Collections.emptySet();
+ }
- @Override
- public ProjectState checkedGet(Project.NameKey projectName)
- throws IOException {
- return all.get(projectName);
- }
+ @Override
+ public ProjectState checkedGet(Project.NameKey projectName) throws IOException {
+ return all.get(projectName);
+ }
- @Override
- public void evict(Project.NameKey p) {
- }
- };
+ @Override
+ public void evict(Project.NameKey p) {}
+ };
Injector injector = Guice.createInjector(new InMemoryModule());
injector.injectMembers(this);
try {
Repository repo = repoManager.createRepository(allProjectsName);
- ProjectConfig allProjects =
- new ProjectConfig(new Project.NameKey(allProjectsName.get()));
+ ProjectConfig allProjects = new ProjectConfig(new Project.NameKey(allProjectsName.get()));
allProjects.load(repo);
LabelType cr = Util.codeReview();
allProjects.getLabelSections().put(cr.getName(), cr);
@@ -339,17 +292,18 @@
add(local);
local.getProject().setParentName(parentKey);
- requestContext.setContext(new RequestContext() {
- @Override
- public CurrentUser getUser() {
- return null;
- }
+ requestContext.setContext(
+ new RequestContext() {
+ @Override
+ public CurrentUser getUser() {
+ return null;
+ }
- @Override
- public Provider<ReviewDb> getReviewDbProvider() {
- return Providers.of(db);
- }
- });
+ @Override
+ public Provider<ReviewDb> getReviewDbProvider() {
+ return Providers.of(db);
+ }
+ });
changeControlFactory = injector.getInstance(ChangeControl.Factory.class);
}
@@ -632,13 +586,11 @@
public void blockLabelRange_ParentBlocksChildEvenIfAlreadyBlockedInChild() {
allow(local, LABEL + "Code-Review", -2, +2, DEVS, "refs/heads/*");
block(local, LABEL + "Code-Review", -2, +2, DEVS, "refs/heads/*");
- block(parent, LABEL + "Code-Review", -2, +2, DEVS,
- "refs/heads/*");
+ block(parent, LABEL + "Code-Review", -2, +2, DEVS, "refs/heads/*");
ProjectControl u = user(local, DEVS);
- PermissionRange range =
- u.controlForRef("refs/heads/master").getRange(LABEL + "Code-Review");
+ PermissionRange range = u.controlForRef("refs/heads/master").getRange(LABEL + "Code-Review");
assertCanVote(-1, range);
assertCanVote(1, range);
assertCannotVote(-2, range);
@@ -765,8 +717,8 @@
ProjectControl u = user(local, REGISTERED_USERS);
assertThat(u.controlForRef("refs/heads/master").isVisibleByRegisteredUsers())
- .named("u can read")
- .isTrue();
+ .named("u can read")
+ .isTrue();
}
@Test
@@ -776,8 +728,8 @@
ProjectControl u = user(local, REGISTERED_USERS);
assertThat(u.controlForRef("refs/heads/master").isVisibleByRegisteredUsers())
- .named("u can't read")
- .isFalse();
+ .named("u can't read")
+ .isFalse();
}
@Test
@@ -787,8 +739,8 @@
ProjectControl u = user(local, DEVS);
assertThat(u.controlForRef("refs/heads/master").canForceEditTopicName())
- .named("u can edit topic name")
- .isTrue();
+ .named("u can edit topic name")
+ .isTrue();
}
@Test
@@ -798,8 +750,8 @@
ProjectControl u = user(local, REGISTERED_USERS);
assertThat(u.controlForRef("refs/heads/master").canForceEditTopicName())
- .named("u can't edit topic name")
- .isFalse();
+ .named("u can't edit topic name")
+ .isFalse();
}
@Test
@@ -837,13 +789,11 @@
@Test
public void unblockInLocalRange_Fails() {
- block(parent, LABEL + "Code-Review", -1, 1, ANONYMOUS_USERS,
- "refs/heads/*");
+ block(parent, LABEL + "Code-Review", -1, 1, ANONYMOUS_USERS, "refs/heads/*");
allow(local, LABEL + "Code-Review", -2, +2, DEVS, "refs/heads/*");
ProjectControl u = user(local, DEVS);
- PermissionRange range =
- u.controlForRef("refs/heads/master").getRange(LABEL + "Code-Review");
+ PermissionRange range = u.controlForRef("refs/heads/master").getRange(LABEL + "Code-Review");
assertCannotVote(-2, range);
assertCannotVote(2, range);
}
@@ -853,8 +803,8 @@
allow(local, LABEL + "Code-Review", -2, +2, CHANGE_OWNER, "refs/heads/*");
ProjectControl u = user(local, DEVS);
- PermissionRange range = u.controlForRef("refs/heads/master")
- .getRange(LABEL + "Code-Review", true);
+ PermissionRange range =
+ u.controlForRef("refs/heads/master").getRange(LABEL + "Code-Review", true);
assertCanVote(-2, range);
assertCanVote(2, range);
}
@@ -864,8 +814,7 @@
allow(local, LABEL + "Code-Review", -2, +2, CHANGE_OWNER, "refs/heads/*");
ProjectControl u = user(local, DEVS);
- PermissionRange range = u.controlForRef("refs/heads/master")
- .getRange(LABEL + "Code-Review");
+ PermissionRange range = u.controlForRef("refs/heads/master").getRange(LABEL + "Code-Review");
assertCannotVote(-2, range);
assertCannotVote(2, range);
}
@@ -893,8 +842,7 @@
@Test(expected = InvalidNameException.class)
public void testValidateBadRefPatternDanglingCharacter() throws Exception {
- RefPattern
- .validate("^refs/heads/tmp/sdk/[0-9]{3,3}_R[1-9][A-Z][0-9]{3,3}*");
+ RefPattern.validate("^refs/heads/tmp/sdk/[0-9]{3,3}_R[1-9][A-Z][0-9]{3,3}*");
}
@Test
@@ -918,26 +866,43 @@
} catch (IOException | ConfigInvalidException e) {
throw new RuntimeException(e);
}
- all.put(pc.getName(),
- new ProjectState(sitePaths, projectCache, allProjectsName, allUsersName,
- projectControlFactory, envFactory, repoManager, rulesCache,
- commentLinks, capabilityCollectionFactory, pc));
+ all.put(
+ pc.getName(),
+ new ProjectState(
+ sitePaths,
+ projectCache,
+ allProjectsName,
+ allUsersName,
+ projectControlFactory,
+ envFactory,
+ repoManager,
+ rulesCache,
+ commentLinks,
+ capabilityCollectionFactory,
+ pc));
return repo;
}
- private ProjectControl user(ProjectConfig local,
- AccountGroup.UUID... memberOf) {
+ private ProjectControl user(ProjectConfig local, AccountGroup.UUID... memberOf) {
return user(local, null, memberOf);
}
- private ProjectControl user(ProjectConfig local, String name,
- AccountGroup.UUID... memberOf) {
+ private ProjectControl user(ProjectConfig local, String name, AccountGroup.UUID... memberOf) {
String canonicalWebUrl = "http://localhost";
- return new ProjectControl(Collections.<AccountGroup.UUID> emptySet(),
- Collections.<AccountGroup.UUID> emptySet(), projectCache,
- sectionSorter, null, changeControlFactory, null, queryProvider, null,
- canonicalWebUrl, new MockUser(name, memberOf), newProjectState(local));
+ return new ProjectControl(
+ Collections.<AccountGroup.UUID>emptySet(),
+ Collections.<AccountGroup.UUID>emptySet(),
+ projectCache,
+ sectionSorter,
+ null,
+ changeControlFactory,
+ null,
+ queryProvider,
+ null,
+ canonicalWebUrl,
+ new MockUser(name, memberOf),
+ newProjectState(local));
}
private ProjectState newProjectState(ProjectConfig local) {
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/project/Util.java b/gerrit-server/src/test/java/com/google/gerrit/server/project/Util.java
index d3f0bcb..3ad0116 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/project/Util.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/project/Util.java
@@ -24,7 +24,6 @@
import com.google.gerrit.common.data.PermissionRule;
import com.google.gerrit.reviewdb.client.AccountGroup;
import com.google.gerrit.server.git.ProjectConfig;
-
import java.util.Arrays;
public class Util {
@@ -32,7 +31,8 @@
public static final AccountGroup.UUID DEVS = new AccountGroup.UUID("test.devs");
public static final LabelType codeReview() {
- return category("Code-Review",
+ return category(
+ "Code-Review",
value(2, "Looks good to me, approved"),
value(1, "Looks good to me, but someone else must approve"),
value(0, "No score"),
@@ -41,16 +41,12 @@
}
public static final LabelType verified() {
- return category("Verified",
- value(1, "Verified"),
- value(0, "No score"),
- value(-1, "Fails"));
+ return category("Verified", value(1, "Verified"), value(0, "No score"), value(-1, "Fails"));
}
public static final LabelType patchSetLock() {
- LabelType label = category("Patch-Set-Lock",
- value(1, "Patch Set Locked"),
- value(0, "Patch Set Unlocked"));
+ LabelType label =
+ category("Patch-Set-Lock", value(1, "Patch Set Locked"), value(0, "Patch Set Unlocked"));
label.setFunctionName("PatchSetLock");
return label;
}
@@ -63,16 +59,19 @@
return new LabelType(name, Arrays.asList(values));
}
- public static PermissionRule newRule(ProjectConfig project,
- AccountGroup.UUID groupUUID) {
+ public static PermissionRule newRule(ProjectConfig project, AccountGroup.UUID groupUUID) {
GroupReference group = new GroupReference(groupUUID, groupUUID.get());
group = project.resolve(group);
return new PermissionRule(group);
}
- public static PermissionRule allow(ProjectConfig project,
- String permissionName, int min, int max, AccountGroup.UUID group,
+ public static PermissionRule allow(
+ ProjectConfig project,
+ String permissionName,
+ int min,
+ int max,
+ AccountGroup.UUID group,
String ref) {
PermissionRule rule = newRule(project, group);
rule.setMin(min);
@@ -80,8 +79,12 @@
return grant(project, permissionName, rule, ref);
}
- public static PermissionRule block(ProjectConfig project,
- String permissionName, int min, int max, AccountGroup.UUID group,
+ public static PermissionRule block(
+ ProjectConfig project,
+ String permissionName,
+ int min,
+ int max,
+ AccountGroup.UUID group,
String ref) {
PermissionRule rule = newRule(project, group);
rule.setMin(min);
@@ -91,102 +94,104 @@
return r;
}
- public static PermissionRule allow(ProjectConfig project,
- String permissionName, AccountGroup.UUID group, String ref) {
+ public static PermissionRule allow(
+ ProjectConfig project, String permissionName, AccountGroup.UUID group, String ref) {
return grant(project, permissionName, newRule(project, group), ref);
}
- public static PermissionRule allow(ProjectConfig project,
- String permissionName, AccountGroup.UUID group, String ref,
+ public static PermissionRule allow(
+ ProjectConfig project,
+ String permissionName,
+ AccountGroup.UUID group,
+ String ref,
boolean exclusive) {
- return grant(project, permissionName, newRule(project, group), ref,
- exclusive);
+ return grant(project, permissionName, newRule(project, group), ref, exclusive);
}
- public static PermissionRule allow(ProjectConfig project,
- String capabilityName, AccountGroup.UUID group) {
+ public static PermissionRule allow(
+ ProjectConfig project, String capabilityName, AccountGroup.UUID group) {
PermissionRule rule = newRule(project, group);
- project.getAccessSection(AccessSection.GLOBAL_CAPABILITIES, true)
+ project
+ .getAccessSection(AccessSection.GLOBAL_CAPABILITIES, true)
.getPermission(capabilityName, true)
.add(rule);
- if (GlobalCapability.hasRange(capabilityName)) {
- PermissionRange.WithDefaults range =
- GlobalCapability.getRange(capabilityName);
- if (range != null) {
- rule.setRange(range.getDefaultMin(), range.getDefaultMax());
- }
+ if (GlobalCapability.hasRange(capabilityName)) {
+ PermissionRange.WithDefaults range = GlobalCapability.getRange(capabilityName);
+ if (range != null) {
+ rule.setRange(range.getDefaultMin(), range.getDefaultMax());
}
+ }
return rule;
}
- public static PermissionRule remove(ProjectConfig project,
- String capabilityName, AccountGroup.UUID group) {
+ public static PermissionRule remove(
+ ProjectConfig project, String capabilityName, AccountGroup.UUID group) {
PermissionRule rule = newRule(project, group);
- project.getAccessSection(AccessSection.GLOBAL_CAPABILITIES, true)
+ project
+ .getAccessSection(AccessSection.GLOBAL_CAPABILITIES, true)
.getPermission(capabilityName, true)
.remove(rule);
return rule;
}
- public static PermissionRule remove(ProjectConfig project,
- String permissionName, AccountGroup.UUID group, String ref) {
+ public static PermissionRule remove(
+ ProjectConfig project, String permissionName, AccountGroup.UUID group, String ref) {
PermissionRule rule = newRule(project, group);
- project.getAccessSection(ref, true)
- .getPermission(permissionName, true)
- .remove(rule);
+ project.getAccessSection(ref, true).getPermission(permissionName, true).remove(rule);
return rule;
}
- public static PermissionRule block(ProjectConfig project,
- String capabilityName, AccountGroup.UUID group) {
+ public static PermissionRule block(
+ ProjectConfig project, String capabilityName, AccountGroup.UUID group) {
PermissionRule rule = newRule(project, group);
- project.getAccessSection(AccessSection.GLOBAL_CAPABILITIES, true)
+ project
+ .getAccessSection(AccessSection.GLOBAL_CAPABILITIES, true)
.getPermission(capabilityName, true)
.add(rule);
return rule;
}
- public static PermissionRule block(ProjectConfig project,
- String permissionName, AccountGroup.UUID group, String ref) {
+ public static PermissionRule block(
+ ProjectConfig project, String permissionName, AccountGroup.UUID group, String ref) {
PermissionRule r = grant(project, permissionName, newRule(project, group), ref);
r.setBlock();
return r;
}
- public static PermissionRule blockLabel(ProjectConfig project,
- String labelName, AccountGroup.UUID group, String ref) {
- PermissionRule r =
- grant(project, Permission.LABEL + labelName, newRule(project, group),
- ref);
+ public static PermissionRule blockLabel(
+ ProjectConfig project, String labelName, AccountGroup.UUID group, String ref) {
+ PermissionRule r = grant(project, Permission.LABEL + labelName, newRule(project, group), ref);
r.setBlock();
r.setRange(-1, 1);
return r;
}
- public static PermissionRule deny(ProjectConfig project,
- String permissionName, AccountGroup.UUID group, String ref) {
+ public static PermissionRule deny(
+ ProjectConfig project, String permissionName, AccountGroup.UUID group, String ref) {
PermissionRule r = grant(project, permissionName, newRule(project, group), ref);
r.setDeny();
return r;
}
- public static void doNotInherit(ProjectConfig project, String permissionName,
- String ref) {
- project.getAccessSection(ref, true) //
+ public static void doNotInherit(ProjectConfig project, String permissionName, String ref) {
+ project
+ .getAccessSection(ref, true) //
.getPermission(permissionName, true) //
.setExclusiveGroup(true);
}
- private static PermissionRule grant(ProjectConfig project,
- String permissionName, PermissionRule rule, String ref) {
+ private static PermissionRule grant(
+ ProjectConfig project, String permissionName, PermissionRule rule, String ref) {
return grant(project, permissionName, rule, ref, false);
}
- private static PermissionRule grant(ProjectConfig project,
- String permissionName, PermissionRule rule, String ref,
+ private static PermissionRule grant(
+ ProjectConfig project,
+ String permissionName,
+ PermissionRule rule,
+ String ref,
boolean exclusive) {
- Permission permission = project.getAccessSection(ref, true)
- .getPermission(permissionName, true);
+ Permission permission = project.getAccessSection(ref, true).getPermission(permissionName, true);
if (exclusive) {
permission.setExclusiveGroup(exclusive);
}
@@ -194,6 +199,5 @@
return rule;
}
- private Util() {
- }
+ private Util() {}
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/query/AndPredicateTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/query/AndPredicateTest.java
index 01efa1d..cc59081 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/query/AndPredicateTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/query/AndPredicateTest.java
@@ -23,9 +23,8 @@
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
-import org.junit.Test;
-
import java.util.List;
+import org.junit.Test;
public class AndPredicateTest extends PredicateTest {
@Test
@@ -69,8 +68,8 @@
assertChildren("iterator().remove()", n, of(a, b));
}
- private static void assertChildren(String o, Predicate<String> p,
- List<? extends Predicate<String>> l) {
+ private static void assertChildren(
+ String o, Predicate<String> p, List<? extends Predicate<String>> l) {
assertEquals(o + " did not affect child", l, p.getChildren());
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/query/FieldPredicateTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/query/FieldPredicateTest.java
index 550bee5..ea22c00 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/query/FieldPredicateTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/query/FieldPredicateTest.java
@@ -19,9 +19,8 @@
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
-import org.junit.Test;
-
import java.util.Collections;
+import org.junit.Test;
public class FieldPredicateTest extends PredicateTest {
@Test
@@ -58,7 +57,7 @@
@Test
public void testCopy() {
final OperatorPredicate<String> f = f("author", "alice");
- assertSame(f, f.copy(Collections.<Predicate<String>> emptyList()));
+ assertSame(f, f.copy(Collections.<Predicate<String>>emptyList()));
assertSame(f, f.copy(f.getChildren()));
exception.expect(IllegalArgumentException.class);
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/query/NotPredicateTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/query/NotPredicateTest.java
index 93c1bf4..05df241 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/query/NotPredicateTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/query/NotPredicateTest.java
@@ -23,10 +23,9 @@
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
-import org.junit.Test;
-
import java.util.Collections;
import java.util.List;
+import org.junit.Test;
public class NotPredicateTest extends PredicateTest {
@Test
@@ -64,8 +63,7 @@
assertOnlyChild("remove(0)", p, n);
}
- private static void assertOnlyChild(String o, Predicate<String> c,
- Predicate<String> p) {
+ private static void assertOnlyChild(String o, Predicate<String> c, Predicate<String> p) {
assertEquals(o + " did not affect child", 1, p.getChildCount());
assertSame(o + " did not affect child", c, p.getChild(0));
}
@@ -105,7 +103,7 @@
assertEquals(sb, n.copy(sb).getChildren());
try {
- n.copy(Collections.<Predicate> emptyList());
+ n.copy(Collections.<Predicate>emptyList());
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
assertEquals("Expected exactly one child", e.getMessage());
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/query/OrPredicateTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/query/OrPredicateTest.java
index 27be48d..7d97a0d 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/query/OrPredicateTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/query/OrPredicateTest.java
@@ -23,9 +23,8 @@
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
-import org.junit.Test;
-
import java.util.List;
+import org.junit.Test;
public class OrPredicateTest extends PredicateTest {
@Test
@@ -69,8 +68,8 @@
assertChildren("iterator().remove()", n, of(a, b));
}
- private static void assertChildren(String o, Predicate<String> p,
- List<? extends Predicate<String>> l) {
+ private static void assertChildren(
+ String o, Predicate<String> p, List<? extends Predicate<String>> l) {
assertEquals(o + " did not affect child", l, p.getChildren());
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/query/PredicateTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/query/PredicateTest.java
index 7762e50..2d13876 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/query/PredicateTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/query/PredicateTest.java
@@ -15,7 +15,6 @@
package com.google.gerrit.server.query;
import com.google.gerrit.testutil.GerritBaseTests;
-
import org.junit.Ignore;
@Ignore
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/query/QueryParserTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/query/QueryParserTest.java
index efa1039..4c0bcc0 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/query/QueryParserTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/query/QueryParserTest.java
@@ -13,6 +13,7 @@
// limitations under the License.
package com.google.gerrit.server.query;
+
import static org.junit.Assert.assertEquals;
import org.antlr.runtime.tree.Tree;
@@ -30,8 +31,7 @@
assertSingleWord("project", "tools/*", r);
}
- private static void assertSingleWord(final String name, final String value,
- final Tree r) {
+ private static void assertSingleWord(final String name, final String value, final Tree r) {
assertEquals(QueryParser.FIELD_NAME, r.getType());
assertEquals(name, r.getText());
assertEquals(1, r.getChildCount());
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/query/account/AbstractQueryAccountsTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/query/account/AbstractQueryAccountsTest.java
index 037d1da..3d13536 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/query/account/AbstractQueryAccountsTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/query/account/AbstractQueryAccountsTest.java
@@ -51,7 +51,11 @@
import com.google.inject.Injector;
import com.google.inject.Provider;
import com.google.inject.util.Providers;
-
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
import org.eclipse.jgit.lib.Config;
import org.junit.After;
import org.junit.Before;
@@ -60,12 +64,6 @@
import org.junit.Test;
import org.junit.rules.TestName;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.List;
-
@Ignore
public abstract class AbstractQueryAccountsTest extends GerritServerTests {
@ConfigSuite.Default
@@ -75,41 +73,29 @@
return cfg;
}
- @Rule
- public final TestName testName = new TestName();
+ @Rule public final TestName testName = new TestName();
- @Inject
- protected AccountCache accountCache;
+ @Inject protected AccountCache accountCache;
- @Inject
- protected AccountManager accountManager;
+ @Inject protected AccountManager accountManager;
- @Inject
- protected GerritApi gApi;
+ @Inject protected GerritApi gApi;
- @Inject
- protected IdentifiedUser.GenericFactory userFactory;
+ @Inject protected IdentifiedUser.GenericFactory userFactory;
- @Inject
- private Provider<AnonymousUser> anonymousUser;
+ @Inject private Provider<AnonymousUser> anonymousUser;
- @Inject
- protected InMemoryDatabase schemaFactory;
+ @Inject protected InMemoryDatabase schemaFactory;
- @Inject
- protected SchemaCreator schemaCreator;
+ @Inject protected SchemaCreator schemaCreator;
- @Inject
- protected ThreadLocalRequestContext requestContext;
+ @Inject protected ThreadLocalRequestContext requestContext;
- @Inject
- protected OneOffRequestContext oneOffRequestContext;
+ @Inject protected OneOffRequestContext oneOffRequestContext;
- @Inject
- protected InternalAccountQuery internalAccountQuery;
+ @Inject protected InternalAccountQuery internalAccountQuery;
- @Inject
- protected AllProjectsName allProjects;
+ @Inject protected AllProjectsName allProjects;
protected LifecycleManager lifecycle;
protected ReviewDb db;
@@ -136,8 +122,7 @@
}
protected RequestContext newRequestContext(Account.Id requestUserId) {
- final CurrentUser requestUser =
- userFactory.create(requestUserId);
+ final CurrentUser requestUser = userFactory.create(requestUserId);
return new RequestContext() {
@Override
public CurrentUser getUser() {
@@ -152,17 +137,18 @@
}
protected void setAnonymous() {
- requestContext.setContext(new RequestContext() {
- @Override
- public CurrentUser getUser() {
- return anonymousUser.get();
- }
+ requestContext.setContext(
+ new RequestContext() {
+ @Override
+ public CurrentUser getUser() {
+ return anonymousUser.get();
+ }
- @Override
- public Provider<ReviewDb> getReviewDbProvider() {
- return Providers.of(db);
- }
- });
+ @Override
+ public Provider<ReviewDb> getReviewDbProvider() {
+ return Providers.of(db);
+ }
+ });
}
@After
@@ -200,11 +186,9 @@
AccountInfo user3 = newAccountWithEmail("user3", "user3@" + domain);
String prefix = name("prefix");
- AccountInfo user4 =
- newAccountWithEmail("user4", prefix + "user4@example.com");
+ AccountInfo user4 = newAccountWithEmail("user4", prefix + "user4@example.com");
- AccountInfo user5 =
- newAccountWithEmail("user5", name("user5MixedCase@example.com"));
+ AccountInfo user5 = newAccountWithEmail("user5", name("user5MixedCase@example.com"));
assertQuery("notexisting@test.com");
@@ -332,8 +316,7 @@
@Test
public void withDetails() throws Exception {
- AccountInfo user1 =
- newAccount("myuser", "My User", "my.user@example.com", true);
+ AccountInfo user1 = newAccount("myuser", "My User", "my.user@example.com", true);
List<AccountInfo> result = assertQuery(user1.username, user1);
AccountInfo ai = result.get(0);
@@ -343,8 +326,7 @@
assertThat(ai.email).isNull();
assertThat(ai.avatars).isNull();
- result = assertQuery(
- newQuery(user1.username).withOption(ListAccountsOption.DETAILS), user1);
+ result = assertQuery(newQuery(user1.username).withOption(ListAccountsOption.DETAILS), user1);
ai = result.get(0);
assertThat(ai._accountId).isEqualTo(user1._accountId);
assertThat(ai.name).isEqualTo(user1.name);
@@ -355,30 +337,29 @@
@Test
public void withSecondaryEmails() throws Exception {
- AccountInfo user1 =
- newAccount("myuser", "My User", "my.user@example.com", true);
- String[] secondaryEmails =
- new String[] {"bar@example.com", "foo@example.com"};
+ AccountInfo user1 = newAccount("myuser", "My User", "my.user@example.com", true);
+ String[] secondaryEmails = new String[] {"bar@example.com", "foo@example.com"};
addEmails(user1, secondaryEmails);
-
List<AccountInfo> result = assertQuery(user1.username, user1);
assertThat(result.get(0).secondaryEmails).isNull();
- result = assertQuery(
- newQuery(user1.username).withOption(ListAccountsOption.DETAILS), user1);
+ result = assertQuery(newQuery(user1.username).withOption(ListAccountsOption.DETAILS), user1);
assertThat(result.get(0).secondaryEmails).isNull();
- result = assertQuery(
- newQuery(user1.username).withOption(ListAccountsOption.ALL_EMAILS),
- user1);
+ result = assertQuery(newQuery(user1.username).withOption(ListAccountsOption.ALL_EMAILS), user1);
assertThat(result.get(0).secondaryEmails)
- .containsExactlyElementsIn(Arrays.asList(secondaryEmails)).inOrder();
+ .containsExactlyElementsIn(Arrays.asList(secondaryEmails))
+ .inOrder();
- result = assertQuery(newQuery(user1.username).withOptions(
- ListAccountsOption.DETAILS, ListAccountsOption.ALL_EMAILS), user1);
+ result =
+ assertQuery(
+ newQuery(user1.username)
+ .withOptions(ListAccountsOption.DETAILS, ListAccountsOption.ALL_EMAILS),
+ user1);
assertThat(result.get(0).secondaryEmails)
- .containsExactlyElementsIn(Arrays.asList(secondaryEmails)).inOrder();
+ .containsExactlyElementsIn(Arrays.asList(secondaryEmails))
+ .inOrder();
}
@Test
@@ -414,23 +395,20 @@
return newAccountWithEmail(username, null);
}
- protected AccountInfo newAccountWithEmail(String username, String email)
- throws Exception {
+ protected AccountInfo newAccountWithEmail(String username, String email) throws Exception {
return newAccount(username, email, true);
}
- protected AccountInfo newAccountWithFullName(String username, String fullName)
- throws Exception {
+ protected AccountInfo newAccountWithFullName(String username, String fullName) throws Exception {
return newAccount(username, fullName, null, true);
}
- protected AccountInfo newAccount(String username, String email,
- boolean active) throws Exception {
+ protected AccountInfo newAccount(String username, String email, boolean active) throws Exception {
return newAccount(username, null, email, active);
}
- protected AccountInfo newAccount(String username, String fullName,
- String email, boolean active) throws Exception {
+ protected AccountInfo newAccount(String username, String fullName, String email, boolean active)
+ throws Exception {
String uniqueName = name(username);
try {
@@ -449,8 +427,8 @@
return new Project.NameKey(name);
}
- protected void watch(AccountInfo account, Project.NameKey project,
- String filter) throws RestApiException {
+ protected void watch(AccountInfo account, Project.NameKey project, String filter)
+ throws RestApiException {
List<ProjectWatchInfo> projectsToWatch = new ArrayList<>();
ProjectWatchInfo pwi = new ProjectWatchInfo();
pwi.project = project.get();
@@ -477,11 +455,10 @@
return name + "_" + suffix;
}
- private Account.Id createAccount(String username, String fullName,
- String email, boolean active) throws Exception {
+ private Account.Id createAccount(String username, String fullName, String email, boolean active)
+ throws Exception {
try (ManualRequestContext ctx = oneOffRequestContext.open()) {
- Account.Id id =
- accountManager.authenticate(AuthRequest.forUser(username)).getAccountId();
+ Account.Id id = accountManager.authenticate(AuthRequest.forUser(username)).getAccountId();
if (email != null) {
accountManager.link(id, AuthRequest.forEmail(email));
}
@@ -495,8 +472,7 @@
}
}
- private void addEmails(AccountInfo account, String... emails)
- throws Exception {
+ private void addEmails(AccountInfo account, String... emails) throws Exception {
Account.Id id = new Account.Id(account._accountId);
for (String email : emails) {
accountManager.link(id, AuthRequest.forEmail(email));
@@ -508,39 +484,36 @@
return gApi.accounts().query(query.toString());
}
- protected List<AccountInfo> assertQuery(Object query, AccountInfo... accounts)
- throws Exception {
+ protected List<AccountInfo> assertQuery(Object query, AccountInfo... accounts) throws Exception {
return assertQuery(newQuery(query), accounts);
}
- protected List<AccountInfo> assertQuery(QueryRequest query,
- AccountInfo... accounts) throws Exception {
+ protected List<AccountInfo> assertQuery(QueryRequest query, AccountInfo... accounts)
+ throws Exception {
return assertQuery(query, Arrays.asList(accounts));
}
-
- protected List<AccountInfo> assertQuery(QueryRequest query,
- List<AccountInfo> accounts) throws Exception {
+ protected List<AccountInfo> assertQuery(QueryRequest query, List<AccountInfo> accounts)
+ throws Exception {
List<AccountInfo> result = query.get();
Iterable<Integer> ids = ids(result);
- assertThat(ids).named(format(query, result, accounts))
- .containsExactlyElementsIn(ids(accounts)).inOrder();
+ assertThat(ids)
+ .named(format(query, result, accounts))
+ .containsExactlyElementsIn(ids(accounts))
+ .inOrder();
return result;
}
- protected void assertAccounts(List<AccountState> accounts,
- AccountInfo... expectedAccounts) {
- assertThat(accounts.stream().map(a -> a.getAccount().getId().get())
- .collect(toList()))
- .containsExactlyElementsIn(Arrays.asList(expectedAccounts).stream()
- .map(a -> a._accountId).collect(toList()));
+ protected void assertAccounts(List<AccountState> accounts, AccountInfo... expectedAccounts) {
+ assertThat(accounts.stream().map(a -> a.getAccount().getId().get()).collect(toList()))
+ .containsExactlyElementsIn(
+ Arrays.asList(expectedAccounts).stream().map(a -> a._accountId).collect(toList()));
}
- private String format(QueryRequest query, List<AccountInfo> actualIds,
- List<AccountInfo> expectedAccounts) {
+ private String format(
+ QueryRequest query, List<AccountInfo> actualIds, List<AccountInfo> expectedAccounts) {
StringBuilder b = new StringBuilder();
- b.append("query '").append(query.getQuery())
- .append("' with expected accounts ");
+ b.append("query '").append(query.getQuery()).append("' with expected accounts ");
b.append(format(expectedAccounts));
b.append(" and result ");
b.append(format(actualIds));
@@ -553,9 +526,18 @@
Iterator<AccountInfo> it = accounts.iterator();
while (it.hasNext()) {
AccountInfo a = it.next();
- b.append("{").append(a._accountId).append(", ").append("name=")
- .append(a.name).append(", ").append("email=").append(a.email)
- .append(", ").append("username=").append(a.username).append("}");
+ b.append("{")
+ .append(a._accountId)
+ .append(", ")
+ .append("name=")
+ .append(a.name)
+ .append(", ")
+ .append("email=")
+ .append(a.email)
+ .append(", ")
+ .append("username=")
+ .append(a.username)
+ .append("}");
if (it.hasNext()) {
b.append(", ");
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/query/account/LuceneQueryAccountsTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/query/account/LuceneQueryAccountsTest.java
index 857b661..978283a 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/query/account/LuceneQueryAccountsTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/query/account/LuceneQueryAccountsTest.java
@@ -17,7 +17,6 @@
import com.google.gerrit.testutil.InMemoryModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
-
import org.eclipse.jgit.lib.Config;
public class LuceneQueryAccountsTest extends AbstractQueryAccountsTest {
@@ -25,7 +24,6 @@
protected Injector createInjector() {
Config luceneConfig = new Config(config);
InMemoryModule.setDefaults(luceneConfig);
- return Guice.createInjector(
- new InMemoryModule(luceneConfig, notesMigration));
+ return Guice.createInjector(new InMemoryModule(luceneConfig, notesMigration));
}
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/query/change/AbstractQueryChangesTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/query/change/AbstractQueryChangesTest.java
index 64a71db..bf3e618 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/query/change/AbstractQueryChangesTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/query/change/AbstractQueryChangesTest.java
@@ -96,19 +96,6 @@
import com.google.inject.Injector;
import com.google.inject.Provider;
import com.google.inject.util.Providers;
-
-import org.eclipse.jgit.junit.TestRepository;
-import org.eclipse.jgit.lib.Config;
-import org.eclipse.jgit.lib.ObjectInserter;
-import org.eclipse.jgit.lib.Ref;
-import org.eclipse.jgit.lib.RefUpdate;
-import org.eclipse.jgit.revwalk.RevCommit;
-import org.eclipse.jgit.util.SystemReader;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Test;
-
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
@@ -120,6 +107,17 @@
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
+import org.eclipse.jgit.junit.TestRepository;
+import org.eclipse.jgit.lib.Config;
+import org.eclipse.jgit.lib.ObjectInserter;
+import org.eclipse.jgit.lib.Ref;
+import org.eclipse.jgit.lib.RefUpdate;
+import org.eclipse.jgit.revwalk.RevCommit;
+import org.eclipse.jgit.util.SystemReader;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Ignore;
+import org.junit.Test;
@Ignore
public abstract class AbstractQueryChangesTest extends GerritServerTests {
@@ -176,8 +174,7 @@
db = schemaFactory.open();
schemaCreator.create(db);
- userId = accountManager.authenticate(AuthRequest.forUser("user"))
- .getAccountId();
+ userId = accountManager.authenticate(AuthRequest.forUser("user")).getAccountId();
Account userAccount = db.accounts().get(userId);
userAccount.setPreferredEmail("user@example.com");
db.accounts().update(ImmutableList.of(userAccount));
@@ -186,8 +183,7 @@
}
protected RequestContext newRequestContext(Account.Id requestUserId) {
- final CurrentUser requestUser =
- userFactory.create(requestUserId);
+ final CurrentUser requestUser = userFactory.create(requestUserId);
return new RequestContext() {
@Override
public CurrentUser getUser() {
@@ -270,8 +266,7 @@
assertQuery("change:repo~branch~" + k.substring(0, 10), change);
assertQuery("foo~bar");
- assertThatQueryException("change:foo~bar")
- .hasMessage("Invalid change format");
+ assertThatQueryException("change:foo~bar").hasMessage("Invalid change format");
assertQuery("otherrepo~branch~" + k);
assertQuery("change:otherrepo~branch~" + k);
assertQuery("repo~otherbranch~" + k);
@@ -369,10 +364,8 @@
assertQuery("status:N", change1);
assertQuery("status:nE", change1);
assertQuery("status:neW", change1);
- assertThatQueryException("status:nx")
- .hasMessage("invalid change status: nx");
- assertThatQueryException("status:newx")
- .hasMessage("invalid change status: newx");
+ assertThatQueryException("status:nx").hasMessage("invalid change status: nx");
+ assertThatQueryException("status:newx").hasMessage("invalid change status: newx");
}
@Test
@@ -393,8 +386,8 @@
public void byOwner() throws Exception {
TestRepository<Repo> repo = createProject("repo");
Change change1 = insert(repo, newChange(repo), userId);
- Account.Id user2 = accountManager.authenticate(
- AuthRequest.forUser("anotheruser")).getAccountId();
+ Account.Id user2 =
+ accountManager.authenticate(AuthRequest.forUser("anotheruser")).getAccountId();
Change change2 = insert(repo, newChange(repo), user2);
assertQuery("owner:" + userId.get(), change1);
@@ -462,8 +455,8 @@
public void byOwnerIn() throws Exception {
TestRepository<Repo> repo = createProject("repo");
Change change1 = insert(repo, newChange(repo), userId);
- Account.Id user2 = accountManager.authenticate(
- AuthRequest.forUser("anotheruser")).getAccountId();
+ Account.Id user2 =
+ accountManager.authenticate(AuthRequest.forUser("anotheruser")).getAccountId();
Change change2 = insert(repo, newChange(repo), user2);
assertQuery("ownerin:Administrators", change1);
@@ -557,11 +550,9 @@
@Test
public void fullTextWithNumbers() throws Exception {
TestRepository<Repo> repo = createProject("repo");
- RevCommit commit1 =
- repo.parseBody(repo.commit().message("12345 67890").create());
+ RevCommit commit1 = repo.parseBody(repo.commit().message("12345 67890").create());
Change change1 = insert(repo, newChangeForCommit(repo, commit1));
- RevCommit commit2 =
- repo.parseBody(repo.commit().message("12346 67891").create());
+ RevCommit commit2 = repo.parseBody(repo.commit().message("12346 67891").create());
Change change2 = insert(repo, newChangeForCommit(repo, commit2));
assertQuery("message:1234");
@@ -580,27 +571,24 @@
ChangeInserter ins5 = newChange(repo, null, null, null, null);
Change reviewMinus2Change = insert(repo, ins);
- gApi.changes().id(reviewMinus2Change.getId().get()).current()
- .review(ReviewInput.reject());
+ gApi.changes().id(reviewMinus2Change.getId().get()).current().review(ReviewInput.reject());
Change reviewMinus1Change = insert(repo, ins2);
- gApi.changes().id(reviewMinus1Change.getId().get()).current()
- .review(ReviewInput.dislike());
+ gApi.changes().id(reviewMinus1Change.getId().get()).current().review(ReviewInput.dislike());
Change noLabelChange = insert(repo, ins3);
Change reviewPlus1Change = insert(repo, ins4);
- gApi.changes().id(reviewPlus1Change.getId().get()).current()
- .review(ReviewInput.recommend());
+ gApi.changes().id(reviewPlus1Change.getId().get()).current().review(ReviewInput.recommend());
Change reviewPlus2Change = insert(repo, ins5);
- gApi.changes().id(reviewPlus2Change.getId().get()).current()
- .review(ReviewInput.approve());
+ gApi.changes().id(reviewPlus2Change.getId().get()).current().review(ReviewInput.approve());
- Map<String, Short> m = gApi.changes()
- .id(reviewPlus1Change.getId().get())
- .reviewer(user.getAccountId().toString())
- .votes();
+ Map<String, Short> m =
+ gApi.changes()
+ .id(reviewPlus1Change.getId().get())
+ .reviewer(user.getAccountId().toString())
+ .votes();
assertThat(m).hasSize(1);
assertThat(m).containsEntry("Code-Review", Short.valueOf((short) 1));
@@ -667,15 +655,13 @@
// post a review with user1
requestContext.setContext(newRequestContext(user1));
- gApi.changes().id(reviewPlus1Change.getId().get()).current()
- .review(ReviewInput.recommend());
+ gApi.changes().id(reviewPlus1Change.getId().get()).current().review(ReviewInput.recommend());
assertQuery("label:Code-Review=+1,user=user1", reviewPlus1Change);
assertQuery("label:Code-Review=+1,owner");
}
- private Change[] codeReviewInRange(Map<Integer, Change> changes, int start,
- int end) {
+ private Change[] codeReviewInRange(Map<Integer, Change> changes, int start, int end) {
int size = 0;
Change[] range = new Change[end - start + 1];
for (int i : changes.keySet()) {
@@ -696,8 +682,7 @@
}
private Account.Id createAccount(String name) throws Exception {
- return accountManager.authenticate(
- AuthRequest.forUser(name)).getAccountId();
+ return accountManager.authenticate(AuthRequest.forUser(name)).getAccountId();
}
@Test
@@ -717,8 +702,10 @@
// post a review with user1
requestContext.setContext(newRequestContext(user1));
- gApi.changes().id(change1.getId().get()).current()
- .review(new ReviewInput().label("Code-Review", 1));
+ gApi.changes()
+ .id(change1.getId().get())
+ .current()
+ .review(new ReviewInput().label("Code-Review", 1));
// verify that query with user1 will return results.
requestContext.setContext(newRequestContext(userId));
@@ -751,7 +738,8 @@
String q = "status:new limit:" + i;
List<ChangeInfo> results = newQuery(q).get();
assertThat(results).named(q).hasSize(expectedSize);
- assertThat(results.get(results.size() - 1)._moreChanges).named(q)
+ assertThat(results.get(results.size() - 1)._moreChanges)
+ .named(q)
.isEqualTo(expectedMoreChanges);
assertThat(results.get(0)._number).isEqualTo(last.getId().get());
}
@@ -780,9 +768,7 @@
}
assertQuery("status:new limit:2", changes.get(2), changes.get(1));
- assertQuery(
- newQuery("status:new limit:2").withStart(1),
- changes.get(1), changes.get(0));
+ assertQuery(newQuery("status:new limit:2").withStart(1), changes.get(1), changes.get(0));
assertQuery(newQuery("status:new limit:2").withStart(2), changes.get(0));
assertQuery(newQuery("status:new limit:2").withStart(3));
}
@@ -813,7 +799,9 @@
}
for (int i : ImmutableList.of(2, 0, 1, 4, 3)) {
- gApi.changes().id(changes.get(i).getId().get()).current()
+ gApi.changes()
+ .id(changes.get(i).getId().get())
+ .current()
.review(new ReviewInput().message("modifying " + i));
}
@@ -838,8 +826,7 @@
assertQuery("status:new", change2, change1);
gApi.changes().id(change1.getId().get()).topic("new-topic");
- change1 = notesFactory.create(db, change1.getProject(), change1.getId())
- .getChange();
+ change1 = notesFactory.create(db, change1.getProject(), change1.getId()).getChange();
assertThat(lastUpdatedMs(change1)).isGreaterThan(lastUpdatedMs(change2));
assertThat(lastUpdatedMs(change1) - lastUpdatedMs(change2))
@@ -863,8 +850,7 @@
assertQuery("status:new", change2, change1);
gApi.changes().id(change1.getId().get()).topic("new-topic");
- change1 = notesFactory.create(db, change1.getProject(), change1.getId())
- .getChange();
+ change1 = notesFactory.create(db, change1.getProject(), change1.getId()).getChange();
assertThat(lastUpdatedMs(change1)).isGreaterThan(lastUpdatedMs(change2));
assertThat(lastUpdatedMs(change1) - lastUpdatedMs(change2))
@@ -878,8 +864,8 @@
public void filterOutMoreThanOnePageOfResults() throws Exception {
TestRepository<Repo> repo = createProject("repo");
Change change = insert(repo, newChange(repo), userId);
- Account.Id user2 = accountManager.authenticate(
- AuthRequest.forUser("anotheruser")).getAccountId();
+ Account.Id user2 =
+ accountManager.authenticate(AuthRequest.forUser("anotheruser")).getAccountId();
for (int i = 0; i < 5; i++) {
insert(repo, newChange(repo), user2);
}
@@ -891,8 +877,8 @@
@Test
public void filterOutAllResults() throws Exception {
TestRepository<Repo> repo = createProject("repo");
- Account.Id user2 = accountManager.authenticate(
- AuthRequest.forUser("anotheruser")).getAccountId();
+ Account.Id user2 =
+ accountManager.authenticate(AuthRequest.forUser("anotheruser")).getAccountId();
for (int i = 0; i < 5; i++) {
insert(repo, newChange(repo), user2);
}
@@ -904,10 +890,13 @@
@Test
public void byFileExact() throws Exception {
TestRepository<Repo> repo = createProject("repo");
- RevCommit commit = repo.parseBody(
- repo.commit().message("one")
- .add("dir/file1", "contents1").add("dir/file2", "contents2")
- .create());
+ RevCommit commit =
+ repo.parseBody(
+ repo.commit()
+ .message("one")
+ .add("dir/file1", "contents1")
+ .add("dir/file2", "contents2")
+ .create());
Change change = insert(repo, newChangeForCommit(repo, commit));
assertQuery("file:file");
@@ -921,10 +910,13 @@
@Test
public void byFileRegex() throws Exception {
TestRepository<Repo> repo = createProject("repo");
- RevCommit commit = repo.parseBody(
- repo.commit().message("one")
- .add("dir/file1", "contents1").add("dir/file2", "contents2")
- .create());
+ RevCommit commit =
+ repo.parseBody(
+ repo.commit()
+ .message("one")
+ .add("dir/file1", "contents1")
+ .add("dir/file2", "contents2")
+ .create());
Change change = insert(repo, newChangeForCommit(repo, commit));
assertQuery("file:.*file.*");
@@ -935,10 +927,13 @@
@Test
public void byPathExact() throws Exception {
TestRepository<Repo> repo = createProject("repo");
- RevCommit commit = repo.parseBody(
- repo.commit().message("one")
- .add("dir/file1", "contents1").add("dir/file2", "contents2")
- .create());
+ RevCommit commit =
+ repo.parseBody(
+ repo.commit()
+ .message("one")
+ .add("dir/file1", "contents1")
+ .add("dir/file2", "contents2")
+ .create());
Change change = insert(repo, newChangeForCommit(repo, commit));
assertQuery("path:file");
@@ -952,10 +947,13 @@
@Test
public void byPathRegex() throws Exception {
TestRepository<Repo> repo = createProject("repo");
- RevCommit commit = repo.parseBody(
- repo.commit().message("one")
- .add("dir/file1", "contents1").add("dir/file2", "contents2")
- .create());
+ RevCommit commit =
+ repo.parseBody(
+ repo.commit()
+ .message("one")
+ .add("dir/file1", "contents1")
+ .add("dir/file2", "contents2")
+ .create());
Change change = insert(repo, newChangeForCommit(repo, commit));
assertQuery("path:.*file.*");
@@ -973,21 +971,19 @@
ReviewInput.CommentInput commentInput = new ReviewInput.CommentInput();
commentInput.line = 1;
commentInput.message = "inline";
- input.comments = ImmutableMap.<String, List<ReviewInput.CommentInput>> of(
- Patch.COMMIT_MSG,
- ImmutableList.<ReviewInput.CommentInput> of(commentInput));
+ input.comments =
+ ImmutableMap.<String, List<ReviewInput.CommentInput>>of(
+ Patch.COMMIT_MSG, ImmutableList.<ReviewInput.CommentInput>of(commentInput));
gApi.changes().id(change.getId().get()).current().review(input);
Map<String, List<CommentInfo>> comments =
gApi.changes().id(change.getId().get()).current().comments();
assertThat(comments).hasSize(1);
- CommentInfo comment =
- Iterables.getOnlyElement(comments.get(Patch.COMMIT_MSG));
+ CommentInfo comment = Iterables.getOnlyElement(comments.get(Patch.COMMIT_MSG));
assertThat(comment.message).isEqualTo(commentInput.message);
- ChangeMessageInfo lastMsg = Iterables.getLast(
- gApi.changes().id(change.getId().get()).get().messages, null);
- assertThat(lastMsg.message)
- .isEqualTo("Patch Set 1:\n\n(1 comment)\n\n" + input.message);
+ ChangeMessageInfo lastMsg =
+ Iterables.getLast(gApi.changes().id(change.getId().get()).get().messages, null);
+ assertThat(lastMsg.message).isEqualTo("Patch Set 1:\n\n(1 comment)\n\n" + input.message);
assertQuery("comment:foo");
assertQuery("comment:toplevel", change);
@@ -1000,19 +996,15 @@
resetTimeWithClockStep(thirtyHoursInMs, MILLISECONDS);
TestRepository<Repo> repo = createProject("repo");
long startMs = TestTimeUtil.START.getMillis();
- Change change1 =
- insert(repo, newChange(repo), null, new Timestamp(startMs));
- Change change2 = insert(
- repo, newChange(repo), null,
- new Timestamp(startMs + thirtyHoursInMs));
+ Change change1 = insert(repo, newChange(repo), null, new Timestamp(startMs));
+ Change change2 = insert(repo, newChange(repo), null, new Timestamp(startMs + thirtyHoursInMs));
// Stop time so age queries use the same endpoint.
TestTimeUtil.setClockStep(0, MILLISECONDS);
TestTimeUtil.setClock(new Timestamp(startMs + 2 * thirtyHoursInMs));
long nowMs = TimeUtil.nowMs();
- assertThat(lastUpdatedMs(change2) - lastUpdatedMs(change1))
- .isEqualTo(thirtyHoursInMs);
+ assertThat(lastUpdatedMs(change2) - lastUpdatedMs(change1)).isEqualTo(thirtyHoursInMs);
assertThat(nowMs - lastUpdatedMs(change2)).isEqualTo(thirtyHoursInMs);
assertThat(TimeUtil.nowMs()).isEqualTo(nowMs);
@@ -1031,10 +1023,8 @@
resetTimeWithClockStep(thirtyHoursInMs, MILLISECONDS);
TestRepository<Repo> repo = createProject("repo");
long startMs = TestTimeUtil.START.getMillis();
- Change change1 =
- insert(repo, newChange(repo), null, new Timestamp(startMs));
- Change change2 = insert(
- repo, newChange(repo), null, new Timestamp(startMs + thirtyHoursInMs));
+ Change change1 = insert(repo, newChange(repo), null, new Timestamp(startMs));
+ Change change2 = insert(repo, newChange(repo), null, new Timestamp(startMs + thirtyHoursInMs));
TestTimeUtil.setClockStep(0, MILLISECONDS);
assertQuery("before:2009-09-29");
@@ -1055,10 +1045,8 @@
resetTimeWithClockStep(thirtyHoursInMs, MILLISECONDS);
TestRepository<Repo> repo = createProject("repo");
long startMs = TestTimeUtil.START.getMillis();
- Change change1 =
- insert(repo, newChange(repo), null, new Timestamp(startMs));
- Change change2 = insert(
- repo, newChange(repo), null, new Timestamp(startMs + thirtyHoursInMs));
+ Change change1 = insert(repo, newChange(repo), null, new Timestamp(startMs));
+ Change change2 = insert(repo, newChange(repo), null, new Timestamp(startMs + thirtyHoursInMs));
TestTimeUtil.setClockStep(0, MILLISECONDS);
assertQuery("after:2009-10-03");
@@ -1073,11 +1061,9 @@
TestRepository<Repo> repo = createProject("repo");
// added = 3, deleted = 0, delta = 3
- RevCommit commit1 = repo.parseBody(
- repo.commit().add("file1", "foo\n\foo\nfoo").create());
+ RevCommit commit1 = repo.parseBody(repo.commit().add("file1", "foo\n\foo\nfoo").create());
// added = 0, deleted = 2, delta = 2
- RevCommit commit2 = repo.parseBody(
- repo.commit().parent(commit1).add("file1", "foo").create());
+ RevCommit commit2 = repo.parseBody(repo.commit().parent(commit1).add("file1", "foo").create());
Change change1 = insert(repo, newChangeForCommit(repo, commit1));
Change change2 = insert(repo, newChangeForCommit(repo, commit2));
@@ -1190,21 +1176,17 @@
Change change1 = insert(repo, newChange(repo));
- RevCommit commit2 = repo.parseBody(
- repo.commit().message("foosubject").create());
+ RevCommit commit2 = repo.parseBody(repo.commit().message("foosubject").create());
Change change2 = insert(repo, newChangeForCommit(repo, commit2));
- RevCommit commit3 = repo.parseBody(
- repo.commit()
- .add("Foo.java", "foo contents")
- .create());
+ RevCommit commit3 = repo.parseBody(repo.commit().add("Foo.java", "foo contents").create());
Change change3 = insert(repo, newChangeForCommit(repo, commit3));
ChangeInserter ins4 = newChange(repo);
Change change4 = insert(repo, ins4);
ReviewInput ri4 = new ReviewInput();
ri4.message = "toplevel";
- ri4.labels = ImmutableMap.<String, Short> of("Code-Review", (short) 1);
+ ri4.labels = ImmutableMap.<String, Short>of("Code-Review", (short) 1);
gApi.changes().id(change4.getId().get()).current().review(ri4);
ChangeInserter ins5 = newChangeWithTopic(repo, "feature5");
@@ -1222,8 +1204,7 @@
assertQuery("branch6", change6);
assertQuery("refs/heads/branch6", change6);
- Change[] expected =
- new Change[] {change6, change5, change4, change3, change2, change1};
+ Change[] expected = new Change[] {change6, change5, change4, change3, change2, change1};
assertQuery("user@example.com", expected);
assertQuery("repo", expected);
}
@@ -1232,15 +1213,15 @@
public void implicitVisibleTo() throws Exception {
TestRepository<Repo> repo = createProject("repo");
Change change1 = insert(repo, newChange(repo), userId);
- Change change2 =
- insert(repo, newChangeWithStatus(repo, Change.Status.DRAFT), userId);
+ Change change2 = insert(repo, newChangeWithStatus(repo, Change.Status.DRAFT), userId);
String q = "project:repo";
assertQuery(q, change2, change1);
// Second user cannot see first user's drafts.
- requestContext.setContext(newRequestContext(accountManager
- .authenticate(AuthRequest.forUser("anotheruser")).getAccountId()));
+ requestContext.setContext(
+ newRequestContext(
+ accountManager.authenticate(AuthRequest.forUser("anotheruser")).getAccountId()));
assertQuery(q, change1);
}
@@ -1248,16 +1229,14 @@
public void explicitVisibleTo() throws Exception {
TestRepository<Repo> repo = createProject("repo");
Change change1 = insert(repo, newChange(repo), userId);
- Change change2 =
- insert(repo, newChangeWithStatus(repo, Change.Status.DRAFT), userId);
+ Change change2 = insert(repo, newChangeWithStatus(repo, Change.Status.DRAFT), userId);
String q = "project:repo";
assertQuery(q, change2, change1);
// Second user cannot see first user's drafts.
- Account.Id user2 = accountManager
- .authenticate(AuthRequest.forUser("anotheruser"))
- .getAccountId();
+ Account.Id user2 =
+ accountManager.authenticate(AuthRequest.forUser("anotheruser")).getAccountId();
assertQuery(q + " visibleto:" + user2.get(), change1);
}
@@ -1267,16 +1246,17 @@
Change change1 = insert(repo, newChange(repo));
Change change2 = insert(repo, newChange(repo));
- int user2 = accountManager.authenticate(AuthRequest.forUser("anotheruser"))
- .getAccountId().get();
+ int user2 =
+ accountManager.authenticate(AuthRequest.forUser("anotheruser")).getAccountId().get();
ReviewInput input = new ReviewInput();
input.message = "toplevel";
ReviewInput.CommentInput comment = new ReviewInput.CommentInput();
comment.line = 1;
comment.message = "inline";
- input.comments = ImmutableMap.<String, List<ReviewInput.CommentInput>> of(
- Patch.COMMIT_MSG, ImmutableList.<ReviewInput.CommentInput> of(comment));
+ input.comments =
+ ImmutableMap.<String, List<ReviewInput.CommentInput>>of(
+ Patch.COMMIT_MSG, ImmutableList.<ReviewInput.CommentInput>of(comment));
gApi.changes().id(change1.getId().get()).current().review(input);
input = new ReviewInput();
@@ -1305,8 +1285,8 @@
in.path = Patch.COMMIT_MSG;
gApi.changes().id(change2.getId().get()).current().createDraft(in);
- int user2 = accountManager.authenticate(AuthRequest.forUser("anotheruser"))
- .getAccountId().get();
+ int user2 =
+ accountManager.authenticate(AuthRequest.forUser("anotheruser")).getAccountId().get();
assertQuery("draftby:" + userId.get(), change2, change1);
assertQuery("draftby:" + user2);
@@ -1330,11 +1310,9 @@
assertQuery("draftby:" + userId, change);
assertQuery("commentby:" + userId);
- TestRepository<Repo> allUsers =
- new TestRepository<>(repoManager.openRepository(allUsersName));
+ TestRepository<Repo> allUsers = new TestRepository<>(repoManager.openRepository(allUsersName));
- Ref draftsRef = allUsers.getRepository().exactRef(
- RefNames.refsDraftComments(id, userId));
+ Ref draftsRef = allUsers.getRepository().exactRef(RefNames.refsDraftComments(id, userId));
assertThat(draftsRef).isNotNull();
ReviewInput rin = ReviewInput.dislike();
@@ -1347,17 +1325,16 @@
// Re-add drafts ref and ensure it gets filtered out during indexing.
allUsers.update(draftsRef.getName(), draftsRef.getObjectId());
- assertThat(allUsers.getRepository().exactRef(draftsRef.getName()))
- .isNotNull();
+ assertThat(allUsers.getRepository().exactRef(draftsRef.getName())).isNotNull();
if (PrimaryStorage.of(change) == PrimaryStorage.REVIEW_DB) {
// Record draft ref in noteDbState as well.
ReviewDb db = ReviewDbUtil.unwrapDb(this.db);
change = db.changes().get(id);
- NoteDbChangeState.applyDelta(change,
+ NoteDbChangeState.applyDelta(
+ change,
NoteDbChangeState.Delta.create(
- id, Optional.empty(),
- ImmutableMap.of(userId, draftsRef.getObjectId())));
+ id, Optional.empty(), ImmutableMap.of(userId, draftsRef.getObjectId())));
db.changes().update(Collections.singleton(change));
}
@@ -1375,8 +1352,8 @@
gApi.accounts().self().starChange(change1.getId().toString());
gApi.accounts().self().starChange(change2.getId().toString());
- int user2 = accountManager.authenticate(AuthRequest.forUser("anotheruser"))
- .getAccountId().get();
+ int user2 =
+ accountManager.authenticate(AuthRequest.forUser("anotheruser")).getAccountId().get();
assertQuery("starredby:self", change2, change1);
assertQuery("starredby:" + user2);
@@ -1391,13 +1368,15 @@
gApi.accounts()
.self()
- .setStars(change1.getId().toString(),
+ .setStars(
+ change1.getId().toString(),
new StarsInput(new HashSet<>(Arrays.asList("red", "blue"))));
gApi.accounts()
.self()
- .setStars(change2.getId().toString(),
- new StarsInput(new HashSet<>(Arrays.asList(
- StarredChangesUtil.DEFAULT_LABEL, "green", "blue"))));
+ .setStars(
+ change2.getId().toString(),
+ new StarsInput(
+ new HashSet<>(Arrays.asList(StarredChangesUtil.DEFAULT_LABEL, "green", "blue"))));
// check labeled stars
assertQuery("star:red", change1);
@@ -1416,8 +1395,8 @@
TestRepository<Repo> repo = createProject("repo");
Change change1 = insert(repo, newChange(repo));
- Account.Id user2 = accountManager.authenticate(
- AuthRequest.forUser("anotheruser")).getAccountId();
+ Account.Id user2 =
+ accountManager.authenticate(AuthRequest.forUser("anotheruser")).getAccountId();
Change change2 = insert(repo, newChange(repo), user2);
ReviewInput input = new ReviewInput();
@@ -1425,8 +1404,9 @@
ReviewInput.CommentInput comment = new ReviewInput.CommentInput();
comment.line = 1;
comment.message = "inline";
- input.comments = ImmutableMap.<String, List<ReviewInput.CommentInput>> of(
- Patch.COMMIT_MSG, ImmutableList.<ReviewInput.CommentInput> of(comment));
+ input.comments =
+ ImmutableMap.<String, List<ReviewInput.CommentInput>>of(
+ Patch.COMMIT_MSG, ImmutableList.<ReviewInput.CommentInput>of(comment));
gApi.changes().id(change2.getId().get()).current().review(input);
assertQuery("from:" + userId.get(), change2, change1);
@@ -1436,24 +1416,17 @@
@Test
public void conflicts() throws Exception {
TestRepository<Repo> repo = createProject("repo");
- RevCommit commit1 = repo.parseBody(
- repo.commit()
- .add("file1", "contents1")
- .add("dir/file2", "contents2")
- .add("dir/file3", "contents3")
- .create());
- RevCommit commit2 = repo.parseBody(
- repo.commit()
- .add("file1", "contents1")
- .create());
- RevCommit commit3 = repo.parseBody(
- repo.commit()
- .add("dir/file2", "contents2 different")
- .create());
- RevCommit commit4 = repo.parseBody(
- repo.commit()
- .add("file4", "contents4")
- .create());
+ RevCommit commit1 =
+ repo.parseBody(
+ repo.commit()
+ .add("file1", "contents1")
+ .add("dir/file2", "contents2")
+ .add("dir/file3", "contents3")
+ .create());
+ RevCommit commit2 = repo.parseBody(repo.commit().add("file1", "contents1").create());
+ RevCommit commit3 =
+ repo.parseBody(repo.commit().add("dir/file2", "contents2 different").create());
+ RevCommit commit4 = repo.parseBody(repo.commit().add("file4", "contents4").create());
Change change1 = insert(repo, newChangeForCommit(repo, commit1));
Change change2 = insert(repo, newChangeForCommit(repo, commit2));
Change change3 = insert(repo, newChangeForCommit(repo, commit3));
@@ -1473,20 +1446,13 @@
Change change2 = insert(repo, newChange(repo));
Change change3 = insert(repo, newChange(repo));
- gApi.changes()
- .id(change1.getId().get())
- .current()
- .review(new ReviewInput().message("comment"));
+ gApi.changes().id(change1.getId().get()).current().review(new ReviewInput().message("comment"));
- Account.Id user2 = accountManager
- .authenticate(AuthRequest.forUser("anotheruser"))
- .getAccountId();
+ Account.Id user2 =
+ accountManager.authenticate(AuthRequest.forUser("anotheruser")).getAccountId();
requestContext.setContext(newRequestContext(user2));
- gApi.changes()
- .id(change2.getId().get())
- .current()
- .review(new ReviewInput().message("comment"));
+ gApi.changes().id(change2.getId().get()).current().review(new ReviewInput().message("comment"));
PatchSet.Id ps3_1 = change3.currentPatchSetId();
change3 = newPatchSet(repo, change3);
@@ -1498,22 +1464,17 @@
.review(new ReviewInput().message("comment"));
List<ChangeInfo> actual;
- actual = assertQuery(
- newQuery("is:reviewed").withOption(REVIEWED),
- change3, change2);
+ actual = assertQuery(newQuery("is:reviewed").withOption(REVIEWED), change3, change2);
assertThat(actual.get(0).reviewed).isTrue();
assertThat(actual.get(1).reviewed).isTrue();
- actual = assertQuery(
- newQuery("-is:reviewed").withOption(REVIEWED),
- change1);
+ actual = assertQuery(newQuery("-is:reviewed").withOption(REVIEWED), change1);
assertThat(actual.get(0).reviewed).isNull();
actual = assertQuery("reviewedby:" + userId.get());
- actual = assertQuery(
- newQuery("reviewedby:" + user2.get()).withOption(REVIEWED),
- change3, change2);
+ actual =
+ assertQuery(newQuery("reviewedby:" + user2.get()).withOption(REVIEWED), change3, change2);
assertThat(actual.get(0).reviewed).isTrue();
assertThat(actual.get(1).reviewed).isTrue();
}
@@ -1525,14 +1486,8 @@
Change change2 = insert(repo, newChange(repo));
insert(repo, newChange(repo));
- gApi.changes()
- .id(change1.getId().get())
- .current()
- .review(ReviewInput.approve());
- gApi.changes()
- .id(change2.getId().get())
- .current()
- .review(ReviewInput.approve());
+ gApi.changes().id(change1.getId().get()).current().review(ReviewInput.approve());
+ gApi.changes().id(change2.getId().get()).current().review(ReviewInput.approve());
Account.Id id = user.getAccountId();
assertQuery("reviewer:" + id, change2, change1);
@@ -1545,15 +1500,9 @@
Change change1 = insert(repo, newChange(repo));
Change change2 = insert(repo, newChange(repo));
- gApi.changes()
- .id(change1.getId().get())
- .current()
- .review(ReviewInput.approve());
+ gApi.changes().id(change1.getId().get()).current().review(ReviewInput.approve());
requestContext.setContext(newRequestContext(user1));
- gApi.changes()
- .id(change2.getId().get())
- .current()
- .review(ReviewInput.recommend());
+ gApi.changes().id(change2.getId().get()).current().review(ReviewInput.recommend());
requestContext.setContext(newRequestContext(user.getAccountId()));
assertQuery("is:submittable", change1);
@@ -1585,21 +1534,12 @@
requestContext.setContext(newRequestContext(user1));
assertQuery("has:edit");
- gApi.changes()
- .id(changeId1)
- .edit()
- .create();
- gApi.changes()
- .id(changeId2)
- .edit()
- .create();
+ gApi.changes().id(changeId1).edit().create();
+ gApi.changes().id(changeId2).edit().create();
requestContext.setContext(newRequestContext(user2));
assertQuery("has:edit");
- gApi.changes()
- .id(changeId2)
- .edit()
- .create();
+ gApi.changes().id(changeId2).edit().create();
requestContext.setContext(newRequestContext(user1));
assertQuery("has:edit", change2, change1);
@@ -1626,14 +1566,12 @@
}
for (int i = 1; i <= 11; i++) {
- Iterable<ChangeData> cds = internalChangeQuery.byCommitsOnBranchNotMerged(
- repo.getRepository(), db, dest, shas, i);
- Iterable<Integer> ids = FluentIterable.from(cds)
- .transform(in -> in.getId().get());
+ Iterable<ChangeData> cds =
+ internalChangeQuery.byCommitsOnBranchNotMerged(repo.getRepository(), db, dest, shas, i);
+ Iterable<Integer> ids = FluentIterable.from(cds).transform(in -> in.getId().get());
String name = "limit " + i;
assertThat(ids).named(name).hasSize(n);
- assertThat(ids).named(name)
- .containsExactlyElementsIn(expectedIds);
+ assertThat(ids).named(name).containsExactlyElementsIn(expectedIds);
}
}
@@ -1646,9 +1584,8 @@
db = new DisabledReviewDb();
requestContext.setContext(newRequestContext(userId));
// Use QueryProcessor directly instead of API so we get ChangeDatas back.
- List<ChangeData> cds = queryProcessor
- .query(queryBuilder.parse(change.getId().toString()))
- .entities();
+ List<ChangeData> cds =
+ queryProcessor.query(queryBuilder.parse(change.getId().toString())).entities();
assertThat(cds).hasSize(1);
ChangeData cd = cds.get(0);
@@ -1676,12 +1613,12 @@
db = new DisabledReviewDb();
requestContext.setContext(newRequestContext(userId));
// Use QueryProcessor directly instead of API so we get ChangeDatas back.
- List<ChangeData> cds = queryProcessor
- .setRequestedFields(ImmutableSet.of(
- ChangeField.PATCH_SET.getName(),
- ChangeField.CHANGE.getName()))
- .query(queryBuilder.parse(change.getId().toString()))
- .entities();
+ List<ChangeData> cds =
+ queryProcessor
+ .setRequestedFields(
+ ImmutableSet.of(ChangeField.PATCH_SET.getName(), ChangeField.CHANGE.getName()))
+ .query(queryBuilder.parse(change.getId().toString()))
+ .entities();
assertThat(cds).hasSize(1);
ChangeData cd = cds.get(0);
@@ -1699,21 +1636,17 @@
TestRepository<Repo> repo = createProject(project.get());
Change change = insert(repo, newChange(repo));
String changeId = change.getKey().get();
- ChangeNotes notes =
- notesFactory.create(db, change.getProject(), change.getId());
+ ChangeNotes notes = notesFactory.create(db, change.getProject(), change.getId());
PatchSet ps = psUtil.get(db, notes, change.currentPatchSetId());
requestContext.setContext(newRequestContext(user));
- gApi.changes()
- .id(changeId)
- .edit()
- .create();
+ gApi.changes().id(changeId).edit().create();
assertQuery("has:edit", change);
assertThat(indexer.reindexIfStale(project, change.getId()).get()).isFalse();
// Delete edit ref behind index's back.
- RefUpdate ru = repo.getRepository().updateRef(
- RefNames.refsEdit(user, change.getId(), ps.getId()));
+ RefUpdate ru =
+ repo.getRepository().updateRef(RefNames.refsEdit(user, change.getId(), ps.getId()));
ru.setForceUpdate(true);
assertThat(ru.delete()).isEqualTo(RefUpdate.Result.FORCED);
@@ -1726,14 +1659,12 @@
@Test
public void refStateFields() throws Exception {
// This test method manages primary storage manually.
- assume().that(notesMigration.changePrimaryStorage())
- .isEqualTo(PrimaryStorage.REVIEW_DB);
+ assume().that(notesMigration.changePrimaryStorage()).isEqualTo(PrimaryStorage.REVIEW_DB);
Account.Id user = createAccount("user");
Project.NameKey project = new Project.NameKey("repo");
TestRepository<Repo> repo = createProject(project.get());
String path = "file";
- RevCommit commit = repo.parseBody(
- repo.commit().message("one").add(path, "contents").create());
+ RevCommit commit = repo.parseBody(repo.commit().message("one").add(path, "contents").create());
Change change = insert(repo, newChangeForCommit(repo, commit));
Change.Id id = change.getId();
int c = id.get();
@@ -1744,15 +1675,10 @@
// any more refs are added, update this test to reflect them.
// Edit
- gApi.changes()
- .id(changeId)
- .edit()
- .create();
+ gApi.changes().id(changeId).edit().create();
// Star
- gApi.accounts()
- .self()
- .starChange(change.getId().toString());
+ gApi.accounts().self().starChange(change.getId().toString());
if (notesMigration.readChanges()) {
// Robot comment.
@@ -1782,71 +1708,72 @@
indexer.index(db, change);
}
- QueryOptions opts = IndexedChangeQuery.createOptions(
- indexConfig, 0, 1, StalenessChecker.FIELDS);
+ QueryOptions opts =
+ IndexedChangeQuery.createOptions(indexConfig, 0, 1, StalenessChecker.FIELDS);
ChangeData cd = indexes.getSearchIndex().get(id, opts).get();
String cs = RefNames.shard(c);
int u = user.get();
String us = RefNames.shard(u);
- List<String> expectedStates = Lists.newArrayList(
- "repo:refs/users/" + us + "/edit-" + c + "/1",
- "All-Users:refs/starred-changes/" + cs + "/" + u);
+ List<String> expectedStates =
+ Lists.newArrayList(
+ "repo:refs/users/" + us + "/edit-" + c + "/1",
+ "All-Users:refs/starred-changes/" + cs + "/" + u);
if (notesMigration.readChanges()) {
expectedStates.add("repo:refs/changes/" + cs + "/meta");
expectedStates.add("repo:refs/changes/" + cs + "/robot-comments");
expectedStates.add("All-Users:refs/draft-comments/" + cs + "/" + u);
}
assertThat(
- cd.getRefStates().stream()
+ cd.getRefStates()
+ .stream()
.map(String::new)
// Omit SHA-1, we're just concerned with the project/ref names.
.map(s -> s.substring(0, s.lastIndexOf(':')))
.collect(toList()))
.containsExactlyElementsIn(expectedStates);
- List<String> expectedPatterns = Lists.newArrayList(
- "repo:refs/users/*/edit-" + c + "/*");
+ List<String> expectedPatterns = Lists.newArrayList("repo:refs/users/*/edit-" + c + "/*");
expectedPatterns.add("All-Users:refs/starred-changes/" + cs + "/*");
if (notesMigration.readChanges()) {
expectedPatterns.add("All-Users:refs/draft-comments/" + cs + "/*");
}
- assertThat(
- cd.getRefStatePatterns().stream()
- .map(String::new)
- .collect(toList()))
+ assertThat(cd.getRefStatePatterns().stream().map(String::new).collect(toList()))
.containsExactlyElementsIn(expectedPatterns);
}
- protected ChangeInserter newChange(TestRepository<Repo> repo)
- throws Exception {
+ protected ChangeInserter newChange(TestRepository<Repo> repo) throws Exception {
return newChange(repo, null, null, null, null);
}
- protected ChangeInserter newChangeForCommit(TestRepository<Repo> repo,
- RevCommit commit) throws Exception {
+ protected ChangeInserter newChangeForCommit(TestRepository<Repo> repo, RevCommit commit)
+ throws Exception {
return newChange(repo, commit, null, null, null);
}
- protected ChangeInserter newChangeForBranch(TestRepository<Repo> repo,
- String branch) throws Exception {
+ protected ChangeInserter newChangeForBranch(TestRepository<Repo> repo, String branch)
+ throws Exception {
return newChange(repo, null, branch, null, null);
}
- protected ChangeInserter newChangeWithStatus(TestRepository<Repo> repo,
- Change.Status status) throws Exception {
+ protected ChangeInserter newChangeWithStatus(TestRepository<Repo> repo, Change.Status status)
+ throws Exception {
return newChange(repo, null, null, status, null);
}
- protected ChangeInserter newChangeWithTopic(TestRepository<Repo> repo,
- String topic) throws Exception {
+ protected ChangeInserter newChangeWithTopic(TestRepository<Repo> repo, String topic)
+ throws Exception {
return newChange(repo, null, null, null, topic);
}
- protected ChangeInserter newChange(TestRepository<Repo> repo,
- @Nullable RevCommit commit, @Nullable String branch,
- @Nullable Change.Status status, @Nullable String topic) throws Exception {
+ protected ChangeInserter newChange(
+ TestRepository<Repo> repo,
+ @Nullable RevCommit commit,
+ @Nullable String branch,
+ @Nullable Change.Status status,
+ @Nullable String topic)
+ throws Exception {
if (commit == null) {
commit = repo.parseBody(repo.commit().message("message").create());
}
@@ -1857,11 +1784,12 @@
}
Change.Id id = new Change.Id(seq.nextChangeId());
- ChangeInserter ins = changeFactory.create(
- id, commit, branch)
- .setValidatePolicy(CommitValidators.Policy.NONE)
- .setStatus(status)
- .setTopic(topic);
+ ChangeInserter ins =
+ changeFactory
+ .create(id, commit, branch)
+ .setValidatePolicy(CommitValidators.Policy.NONE)
+ .setStatus(status)
+ .setTopic(topic);
return ins;
}
@@ -1869,15 +1797,19 @@
return insert(repo, ins, null, TimeUtil.nowTs());
}
- protected Change insert(TestRepository<Repo> repo, ChangeInserter ins,
- @Nullable Account.Id owner) throws Exception {
+ protected Change insert(TestRepository<Repo> repo, ChangeInserter ins, @Nullable Account.Id owner)
+ throws Exception {
return insert(repo, ins, owner, TimeUtil.nowTs());
}
- protected Change insert(TestRepository<Repo> repo, ChangeInserter ins,
- @Nullable Account.Id owner, Timestamp createdOn) throws Exception {
- Project.NameKey project = new Project.NameKey(
- repo.getRepository().getDescription().getRepositoryName());
+ protected Change insert(
+ TestRepository<Repo> repo,
+ ChangeInserter ins,
+ @Nullable Account.Id owner,
+ Timestamp createdOn)
+ throws Exception {
+ Project.NameKey project =
+ new Project.NameKey(repo.getRepository().getDescription().getRepositoryName());
Account.Id ownerId = owner != null ? owner : userId;
IdentifiedUser user = userFactory.create(ownerId);
try (BatchUpdate bu = updateFactory.create(db, project, user, createdOn)) {
@@ -1887,25 +1819,21 @@
}
}
- protected Change newPatchSet(TestRepository<Repo> repo, Change c)
- throws Exception {
+ protected Change newPatchSet(TestRepository<Repo> repo, Change c) throws Exception {
// Add a new file so the patch set is not a trivial rebase, to avoid default
// Code-Review label copying.
int n = c.currentPatchSetId().get() + 1;
- RevCommit commit = repo.parseBody(
- repo.commit()
- .message("message")
- .add("file" + n, "contents " + n)
- .create());
+ RevCommit commit =
+ repo.parseBody(repo.commit().message("message").add("file" + n, "contents " + n).create());
ChangeControl ctl = changeControlFactory.controlFor(db, c, user);
- PatchSetInserter inserter = patchSetFactory.create(
- ctl, new PatchSet.Id(c.getId(), n), commit)
- .setNotify(NotifyHandling.NONE)
- .setFireRevisionCreated(false)
- .setValidatePolicy(CommitValidators.Policy.NONE);
- try (BatchUpdate bu = updateFactory.create(
- db, c.getProject(), user, TimeUtil.nowTs());
+ PatchSetInserter inserter =
+ patchSetFactory
+ .create(ctl, new PatchSet.Id(c.getId(), n), commit)
+ .setNotify(NotifyHandling.NONE)
+ .setFireRevisionCreated(false)
+ .setValidatePolicy(CommitValidators.Policy.NONE);
+ try (BatchUpdate bu = updateFactory.create(db, c.getProject(), user, TimeUtil.nowTs());
ObjectInserter oi = repo.getRepository().newObjectInserter()) {
bu.setRepository(repo.getRepository(), repo.getRevWalk(), oi);
bu.addOp(c.getId(), inserter);
@@ -1915,17 +1843,14 @@
return inserter.getChange();
}
- protected ThrowableSubject assertThatQueryException(Object query)
- throws Exception {
+ protected ThrowableSubject assertThatQueryException(Object query) throws Exception {
return assertThatQueryException(newQuery(query));
}
- protected ThrowableSubject assertThatQueryException(QueryRequest query)
- throws Exception {
+ protected ThrowableSubject assertThatQueryException(QueryRequest query) throws Exception {
try {
query.get();
- throw new AssertionError(
- "expected BadRequestException for query: " + query);
+ throw new AssertionError("expected BadRequestException for query: " + query);
} catch (BadRequestException e) {
return assertThat(e);
}
@@ -1933,35 +1858,32 @@
protected TestRepository<Repo> createProject(String name) throws Exception {
gApi.projects().create(name).get();
- return new TestRepository<>(
- repoManager.openRepository(new Project.NameKey(name)));
+ return new TestRepository<>(repoManager.openRepository(new Project.NameKey(name)));
}
protected QueryRequest newQuery(Object query) {
return gApi.changes().query(query.toString());
}
- protected List<ChangeInfo> assertQuery(Object query, Change... changes)
- throws Exception {
+ protected List<ChangeInfo> assertQuery(Object query, Change... changes) throws Exception {
return assertQuery(newQuery(query), changes);
}
- protected List<ChangeInfo> assertQuery(QueryRequest query, Change... changes)
- throws Exception {
+ protected List<ChangeInfo> assertQuery(QueryRequest query, Change... changes) throws Exception {
List<ChangeInfo> result = query.get();
Iterable<Integer> ids = ids(result);
- assertThat(ids).named(format(query, ids, changes))
- .containsExactlyElementsIn(ids(changes)).inOrder();
+ assertThat(ids)
+ .named(format(query, ids, changes))
+ .containsExactlyElementsIn(ids(changes))
+ .inOrder();
return result;
}
- private String format(QueryRequest query, Iterable<Integer> actualIds,
- Change... expectedChanges) throws RestApiException {
+ private String format(QueryRequest query, Iterable<Integer> actualIds, Change... expectedChanges)
+ throws RestApiException {
StringBuilder b = new StringBuilder();
- b.append("query '").append(query.getQuery())
- .append("' with expected changes ");
- b.append(format(
- Arrays.stream(expectedChanges).map(Change::getChangeId).iterator()));
+ b.append("query '").append(query.getQuery()).append("' with expected changes ");
+ b.append(format(Arrays.stream(expectedChanges).map(Change::getChangeId).iterator()));
b.append(" and result ");
b.append(format(actualIds));
return b.toString();
@@ -1977,12 +1899,19 @@
while (changeIds.hasNext()) {
int id = changeIds.next();
ChangeInfo c = gApi.changes().id(id).get();
- b.append("{").append(id).append(" (").append(c.changeId)
- .append("), ").append("dest=").append(
- new Branch.NameKey(
- new Project.NameKey(c.project), c.branch)).append(", ")
- .append("status=").append(c.status).append(", ")
- .append("lastUpdated=").append(c.updated.getTime())
+ b.append("{")
+ .append(id)
+ .append(" (")
+ .append(c.changeId)
+ .append("), ")
+ .append("dest=")
+ .append(new Branch.NameKey(new Project.NameKey(c.project), c.branch))
+ .append(", ")
+ .append("status=")
+ .append(c.status)
+ .append(", ")
+ .append("lastUpdated=")
+ .append(c.updated.getTime())
.append("}");
if (changeIds.hasNext()) {
b.append(", ");
@@ -1993,13 +1922,11 @@
}
protected static Iterable<Integer> ids(Change... changes) {
- return FluentIterable.from(Arrays.asList(changes))
- .transform(in -> in.getId().get());
+ return FluentIterable.from(Arrays.asList(changes)).transform(in -> in.getId().get());
}
protected static Iterable<Integer> ids(Iterable<ChangeInfo> changes) {
- return FluentIterable.from(changes)
- .transform(in -> in._number);
+ return FluentIterable.from(changes).transform(in -> in._number);
}
protected static long lastUpdatedMs(Change c) {
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/query/change/ChangeDataTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/query/change/ChangeDataTest.java
index eb19ebe..def0b08 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/query/change/ChangeDataTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/query/change/ChangeDataTest.java
@@ -22,7 +22,6 @@
import com.google.gerrit.reviewdb.client.PatchSet;
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.testutil.TestChanges;
-
import org.junit.Test;
public class ChangeDataTest {
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/query/change/LuceneQueryChangesTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/query/change/LuceneQueryChangesTest.java
index 70493e8..d3ecc29 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/query/change/LuceneQueryChangesTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/query/change/LuceneQueryChangesTest.java
@@ -20,7 +20,6 @@
import com.google.gerrit.testutil.InMemoryRepositoryManager.Repo;
import com.google.inject.Guice;
import com.google.inject.Injector;
-
import org.eclipse.jgit.junit.TestRepository;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.revwalk.RevCommit;
@@ -31,18 +30,15 @@
protected Injector createInjector() {
Config luceneConfig = new Config(config);
InMemoryModule.setDefaults(luceneConfig);
- return Guice.createInjector(
- new InMemoryModule(luceneConfig, notesMigration));
+ return Guice.createInjector(new InMemoryModule(luceneConfig, notesMigration));
}
@Test
public void fullTextWithSpecialChars() throws Exception {
TestRepository<Repo> repo = createProject("repo");
- RevCommit commit1 =
- repo.parseBody(repo.commit().message("foo_bar_foo").create());
+ RevCommit commit1 = repo.parseBody(repo.commit().message("foo_bar_foo").create());
Change change1 = insert(repo, newChangeForCommit(repo, commit1));
- RevCommit commit2 =
- repo.parseBody(repo.commit().message("one.two.three").create());
+ RevCommit commit2 = repo.parseBody(repo.commit().message("one.two.three").create());
Change change2 = insert(repo, newChangeForCommit(repo, commit2));
assertQuery("message:foo_ba");
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/query/change/RegexPathPredicateTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/query/change/RegexPathPredicateTest.java
index 0480c5e..a13a8f7 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/query/change/RegexPathPredicateTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/query/change/RegexPathPredicateTest.java
@@ -20,10 +20,8 @@
import com.google.gerrit.reviewdb.client.Change;
import com.google.gerrit.reviewdb.client.Project;
import com.google.gwtorm.server.OrmException;
-
-import org.junit.Test;
-
import java.util.Arrays;
+import org.junit.Test;
public class RegexPathPredicateTest {
@Test
@@ -85,8 +83,7 @@
private static ChangeData change(String... files) throws OrmException {
Arrays.sort(files);
- ChangeData cd = ChangeData.createForTest(new Project.NameKey("project"),
- new Change.Id(1), 1);
+ ChangeData cd = ChangeData.createForTest(new Project.NameKey("project"), new Change.Id(1), 1);
cd.setCurrentFilePaths(Arrays.asList(files));
return cd;
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/query/group/AbstractQueryGroupsTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/query/group/AbstractQueryGroupsTest.java
index 0ecc125..2813c03 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/query/group/AbstractQueryGroupsTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/query/group/AbstractQueryGroupsTest.java
@@ -49,7 +49,11 @@
import com.google.inject.Injector;
import com.google.inject.Provider;
import com.google.inject.util.Providers;
-
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Locale;
import org.eclipse.jgit.lib.Config;
import org.junit.After;
import org.junit.Before;
@@ -58,12 +62,6 @@
import org.junit.Test;
import org.junit.rules.TestName;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Locale;
-
@Ignore
public abstract class AbstractQueryGroupsTest extends GerritServerTests {
@ConfigSuite.Default
@@ -73,44 +71,31 @@
return cfg;
}
- @Rule
- public final TestName testName = new TestName();
+ @Rule public final TestName testName = new TestName();
- @Inject
- protected AccountCache accountCache;
+ @Inject protected AccountCache accountCache;
- @Inject
- protected AccountManager accountManager;
+ @Inject protected AccountManager accountManager;
- @Inject
- protected GerritApi gApi;
+ @Inject protected GerritApi gApi;
- @Inject
- protected IdentifiedUser.GenericFactory userFactory;
+ @Inject protected IdentifiedUser.GenericFactory userFactory;
- @Inject
- private Provider<AnonymousUser> anonymousUser;
+ @Inject private Provider<AnonymousUser> anonymousUser;
- @Inject
- protected InMemoryDatabase schemaFactory;
+ @Inject protected InMemoryDatabase schemaFactory;
- @Inject
- protected SchemaCreator schemaCreator;
+ @Inject protected SchemaCreator schemaCreator;
- @Inject
- protected ThreadLocalRequestContext requestContext;
+ @Inject protected ThreadLocalRequestContext requestContext;
- @Inject
- protected OneOffRequestContext oneOffRequestContext;
+ @Inject protected OneOffRequestContext oneOffRequestContext;
- @Inject
- protected InternalAccountQuery internalAccountQuery;
+ @Inject protected InternalAccountQuery internalAccountQuery;
- @Inject
- protected AllProjectsName allProjects;
+ @Inject protected AllProjectsName allProjects;
- @Inject
- protected GroupCache groupCache;
+ @Inject protected GroupCache groupCache;
protected LifecycleManager lifecycle;
protected ReviewDb db;
@@ -137,8 +122,7 @@
}
protected RequestContext newRequestContext(Account.Id requestUserId) {
- final CurrentUser requestUser =
- userFactory.create(requestUserId);
+ final CurrentUser requestUser = userFactory.create(requestUserId);
return new RequestContext() {
@Override
public CurrentUser getUser() {
@@ -153,17 +137,18 @@
}
protected void setAnonymous() {
- requestContext.setContext(new RequestContext() {
- @Override
- public CurrentUser getUser() {
- return anonymousUser.get();
- }
+ requestContext.setContext(
+ new RequestContext() {
+ @Override
+ public CurrentUser getUser() {
+ return anonymousUser.get();
+ }
- @Override
- public Provider<ReviewDb> getReviewDbProvider() {
- return Providers.of(db);
- }
- });
+ @Override
+ public Provider<ReviewDb> getReviewDbProvider() {
+ return Providers.of(db);
+ }
+ });
}
@After
@@ -211,18 +196,14 @@
GroupInfo group2 = createGroup("group-" + namePart + "-2");
GroupInfo group3 = createGroup("group-" + namePart + "3");
assertQuery("inname:" + namePart, group1, group2, group3);
- assertQuery("inname:" + namePart.toUpperCase(Locale.US), group1, group2,
- group3);
- assertQuery("inname:" + namePart.toLowerCase(Locale.US), group1, group2,
- group3);
+ assertQuery("inname:" + namePart.toUpperCase(Locale.US), group1, group2, group3);
+ assertQuery("inname:" + namePart.toLowerCase(Locale.US), group1, group2, group3);
}
@Test
public void byDescription() throws Exception {
- GroupInfo group1 =
- createGroupWithDescription(name("group1"), "This is a test group.");
- GroupInfo group2 =
- createGroupWithDescription(name("group2"), "ANOTHER TEST GROUP.");
+ GroupInfo group1 = createGroupWithDescription(name("group1"), "This is a test group.");
+ GroupInfo group2 = createGroupWithDescription(name("group2"), "ANOTHER TEST GROUP.");
createGroupWithDescription(name("group3"), "Maintainers of project foo.");
assertQuery("description:test", group1, group2);
@@ -260,8 +241,9 @@
public void byDefaultField() throws Exception {
GroupInfo group1 = createGroup(name("foo-group"));
GroupInfo group2 = createGroup(name("group2"));
- GroupInfo group3 = createGroupWithDescription(name("group3"),
- "decription that contains foo and the UUID of group2: " + group2.id);
+ GroupInfo group3 =
+ createGroupWithDescription(
+ name("group3"), "decription that contains foo and the UUID of group2: " + group2.id);
assertQuery("non-existing");
assertQuery("foo", group1, group3);
@@ -274,8 +256,7 @@
GroupInfo group2 = createGroup(name("group2"));
GroupInfo group3 = createGroup(name("group3"));
- String query =
- "uuid:" + group1.id + " OR uuid:" + group2.id + " OR uuid:" + group3.id;
+ String query = "uuid:" + group1.id + " OR uuid:" + group2.id + " OR uuid:" + group3.id;
List<GroupInfo> result = assertQuery(query, group1, group2, group3);
assertThat(result.get(result.size() - 1)._moreGroups).isNull();
@@ -289,8 +270,7 @@
GroupInfo group2 = createGroup(name("group2"));
GroupInfo group3 = createGroup(name("group3"));
- String query =
- "uuid:" + group1.id + " OR uuid:" + group2.id + " OR uuid:" + group3.id;
+ String query = "uuid:" + group1.id + " OR uuid:" + group2.id + " OR uuid:" + group3.id;
List<GroupInfo> result = assertQuery(query, group1, group2, group3);
assertQuery(newQuery(query).withStart(1), result.subList(1, 3));
@@ -311,8 +291,7 @@
// update group in the database so that group index is stale
String newDescription = "barY";
- AccountGroup group =
- db.accountGroups().get(new AccountGroup.Id(group1.groupId));
+ AccountGroup group = db.accountGroups().get(new AccountGroup.Id(group1.groupId));
group.setDescription(newDescription);
db.accountGroups().update(Collections.singleton(group));
@@ -324,11 +303,10 @@
assertQuery("description:" + newDescription, group1);
}
- private Account.Id createAccount(String username, String fullName,
- String email, boolean active) throws Exception {
+ private Account.Id createAccount(String username, String fullName, String email, boolean active)
+ throws Exception {
try (ManualRequestContext ctx = oneOffRequestContext.open()) {
- Account.Id id =
- accountManager.authenticate(AuthRequest.forUser(username)).getAccountId();
+ Account.Id id = accountManager.authenticate(AuthRequest.forUser(username)).getAccountId();
if (email != null) {
accountManager.link(id, AuthRequest.forEmail(email));
}
@@ -342,31 +320,28 @@
}
}
- protected GroupInfo createGroup(String name, AccountInfo... members)
- throws Exception {
+ protected GroupInfo createGroup(String name, AccountInfo... members) throws Exception {
return createGroupWithDescription(name, null, members);
}
- protected GroupInfo createGroupWithDescription(String name,
- String description, AccountInfo... members) throws Exception {
+ protected GroupInfo createGroupWithDescription(
+ String name, String description, AccountInfo... members) throws Exception {
GroupInput in = new GroupInput();
in.name = name;
in.description = description;
- in.members = Arrays.asList(members).stream()
- .map(a -> String.valueOf(a._accountId)).collect(toList());
+ in.members =
+ Arrays.asList(members).stream().map(a -> String.valueOf(a._accountId)).collect(toList());
return gApi.groups().create(in).get();
}
- protected GroupInfo createGroupWithOwner(String name, GroupInfo ownerGroup)
- throws Exception {
+ protected GroupInfo createGroupWithOwner(String name, GroupInfo ownerGroup) throws Exception {
GroupInput in = new GroupInput();
in.name = name;
in.ownerId = ownerGroup.id;
return gApi.groups().create(in).get();
}
- protected GroupInfo createGroupThatIsVisibleToAll(String name)
- throws Exception {
+ protected GroupInfo createGroupThatIsVisibleToAll(String name) throws Exception {
GroupInput in = new GroupInput();
in.name = name;
in.visibleToAll = true;
@@ -377,22 +352,19 @@
return gApi.groups().id(uuid.get()).get();
}
- protected List<GroupInfo> assertQuery(Object query, GroupInfo... groups)
- throws Exception {
+ protected List<GroupInfo> assertQuery(Object query, GroupInfo... groups) throws Exception {
return assertQuery(newQuery(query), groups);
}
- protected List<GroupInfo> assertQuery(QueryRequest query,
- GroupInfo... groups) throws Exception {
+ protected List<GroupInfo> assertQuery(QueryRequest query, GroupInfo... groups) throws Exception {
return assertQuery(query, Arrays.asList(groups));
}
- protected List<GroupInfo> assertQuery(QueryRequest query,
- List<GroupInfo> groups) throws Exception {
+ protected List<GroupInfo> assertQuery(QueryRequest query, List<GroupInfo> groups)
+ throws Exception {
List<GroupInfo> result = query.get();
Iterable<String> uuids = uuids(result);
- assertThat(uuids).named(format(query, result, groups))
- .containsExactlyElementsIn(uuids(groups));
+ assertThat(uuids).named(format(query, result, groups)).containsExactlyElementsIn(uuids(groups));
return result;
}
@@ -400,11 +372,10 @@
return gApi.groups().query(query.toString());
}
- protected String format(QueryRequest query, List<GroupInfo> actualGroups,
- List<GroupInfo> expectedGroups) {
+ protected String format(
+ QueryRequest query, List<GroupInfo> actualGroups, List<GroupInfo> expectedGroups) {
StringBuilder b = new StringBuilder();
- b.append("query '").append(query.getQuery())
- .append("' with expected groups ");
+ b.append("query '").append(query.getQuery()).append("' with expected groups ");
b.append(format(expectedGroups));
b.append(" and result ");
b.append(format(actualGroups));
@@ -417,13 +388,30 @@
Iterator<GroupInfo> it = groups.iterator();
while (it.hasNext()) {
GroupInfo g = it.next();
- b.append("{").append(g.id).append(", ").append("name=").append(g.name)
- .append(", ").append("groupId=").append(g.groupId).append(", ")
- .append("url=").append(g.url).append(", ").append("ownerId=")
- .append(g.ownerId).append(", ").append("owner=").append(g.owner)
- .append(", ").append("description=").append(g.description)
- .append(", ").append("visibleToAll=")
- .append(toBoolean(g.options.visibleToAll)).append("}");
+ b.append("{")
+ .append(g.id)
+ .append(", ")
+ .append("name=")
+ .append(g.name)
+ .append(", ")
+ .append("groupId=")
+ .append(g.groupId)
+ .append(", ")
+ .append("url=")
+ .append(g.url)
+ .append(", ")
+ .append("ownerId=")
+ .append(g.ownerId)
+ .append(", ")
+ .append("owner=")
+ .append(g.owner)
+ .append(", ")
+ .append("description=")
+ .append(g.description)
+ .append(", ")
+ .append("visibleToAll=")
+ .append(toBoolean(g.options.visibleToAll))
+ .append("}");
if (it.hasNext()) {
b.append(", ");
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/query/group/LuceneQueryGroupsTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/query/group/LuceneQueryGroupsTest.java
index d8deca6..0551e92 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/query/group/LuceneQueryGroupsTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/query/group/LuceneQueryGroupsTest.java
@@ -17,7 +17,6 @@
import com.google.gerrit.testutil.InMemoryModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
-
import org.eclipse.jgit.lib.Config;
public class LuceneQueryGroupsTest extends AbstractQueryGroupsTest {
@@ -25,7 +24,6 @@
protected Injector createInjector() {
Config luceneConfig = new Config(config);
InMemoryModule.setDefaults(luceneConfig);
- return Guice.createInjector(
- new InMemoryModule(luceneConfig, notesMigration));
+ return Guice.createInjector(new InMemoryModule(luceneConfig, notesMigration));
}
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/schema/SchemaCreatorTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/schema/SchemaCreatorTest.java
index ccd399f..cc3519d 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/schema/SchemaCreatorTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/schema/SchemaCreatorTest.java
@@ -30,12 +30,6 @@
import com.google.gwtorm.jdbc.JdbcSchema;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
-
-import org.eclipse.jgit.lib.Repository;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
import java.io.File;
import java.io.IOException;
import java.sql.ResultSet;
@@ -43,16 +37,17 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
+import org.eclipse.jgit.lib.Repository;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
public class SchemaCreatorTest {
- @Inject
- private AllProjectsName allProjects;
+ @Inject private AllProjectsName allProjects;
- @Inject
- private GitRepositoryManager repoManager;
+ @Inject private GitRepositoryManager repoManager;
- @Inject
- private InMemoryDatabase db;
+ @Inject private InMemoryDatabase db;
private LifecycleManager lifecycle;
@@ -72,13 +67,11 @@
}
@Test
- public void getCauses_CreateSchema() throws OrmException, SQLException,
- IOException {
+ public void getCauses_CreateSchema() throws OrmException, SQLException, IOException {
// Initially the schema should be empty.
String[] types = {"TABLE", "VIEW"};
try (JdbcSchema d = (JdbcSchema) db.open();
- ResultSet rs = d.getConnection().getMetaData()
- .getTables(null, null, null, types)) {
+ ResultSet rs = d.getConnection().getMetaData().getTables(null, null, null, types)) {
assertThat(rs.next()).isFalse();
}
@@ -93,8 +86,7 @@
if (sitePath.getName().equals(".")) {
sitePath = sitePath.getParentFile();
}
- assertThat(db.getSystemConfig().sitePath)
- .isEqualTo(sitePath.getCanonicalPath());
+ assertThat(db.getSystemConfig().sitePath).isEqualTo(sitePath.getCanonicalPath());
}
private LabelTypes getLabelTypes() throws Exception {
@@ -102,8 +94,7 @@
ProjectConfig c = new ProjectConfig(allProjects);
try (Repository repo = repoManager.openRepository(allProjects)) {
c.load(repo);
- return new LabelTypes(
- ImmutableList.copyOf(c.getLabelSections().values()));
+ return new LabelTypes(ImmutableList.copyOf(c.getLabelSections().values()));
}
}
@@ -128,8 +119,7 @@
}
private void assertValueRange(LabelType label, Integer... range) {
- assertThat(label.getValuesAsList())
- .containsExactlyElementsIn(Arrays.asList(range)).inOrder();
+ assertThat(label.getValuesAsList()).containsExactlyElementsIn(Arrays.asList(range)).inOrder();
assertThat(label.getMax().getValue()).isEqualTo(range[0]);
assertThat(label.getMin().getValue()).isEqualTo(range[range.length - 1]);
for (LabelValue v : label.getValues()) {
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/schema/SchemaUpdaterTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/schema/SchemaUpdaterTest.java
index dbb7db6..112fdd6 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/schema/SchemaUpdaterTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/schema/SchemaUpdaterTest.java
@@ -39,19 +39,17 @@
import com.google.inject.Guice;
import com.google.inject.ProvisionException;
import com.google.inject.TypeLiteral;
-
-import org.eclipse.jgit.lib.Config;
-import org.eclipse.jgit.lib.PersonIdent;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.UUID;
+import org.eclipse.jgit.lib.Config;
+import org.eclipse.jgit.lib.PersonIdent;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
public class SchemaUpdaterTest {
private LifecycleManager lifecycle;
@@ -73,53 +71,52 @@
}
@Test
- public void update() throws OrmException, FileNotFoundException,
- IOException {
+ public void update() throws OrmException, FileNotFoundException, IOException {
db.create();
final Path site = Paths.get(UUID.randomUUID().toString());
final SitePaths paths = new SitePaths(site);
- SchemaUpdater u = Guice.createInjector(new FactoryModule() {
- @Override
- protected void configure() {
- bind(new TypeLiteral<SchemaFactory<ReviewDb>>() {}).toInstance(db);
- bind(SitePaths.class).toInstance(paths);
+ SchemaUpdater u =
+ Guice.createInjector(
+ new FactoryModule() {
+ @Override
+ protected void configure() {
+ bind(new TypeLiteral<SchemaFactory<ReviewDb>>() {}).toInstance(db);
+ bind(SitePaths.class).toInstance(paths);
- Config cfg = new Config();
- cfg.setString("user", null, "name", "Gerrit Code Review");
- cfg.setString("user", null, "email", "gerrit@localhost");
+ Config cfg = new Config();
+ cfg.setString("user", null, "name", "Gerrit Code Review");
+ cfg.setString("user", null, "email", "gerrit@localhost");
- bind(Config.class) //
- .annotatedWith(GerritServerConfig.class) //
- .toInstance(cfg);
+ bind(Config.class) //
+ .annotatedWith(GerritServerConfig.class) //
+ .toInstance(cfg);
- bind(PersonIdent.class) //
- .annotatedWith(GerritPersonIdent.class) //
- .toProvider(GerritPersonIdentProvider.class);
+ bind(PersonIdent.class) //
+ .annotatedWith(GerritPersonIdent.class) //
+ .toProvider(GerritPersonIdentProvider.class);
- bind(AllProjectsName.class)
- .toInstance(new AllProjectsName("All-Projects"));
- bind(AllUsersName.class)
- .toInstance(new AllUsersName("All-Users"));
+ bind(AllProjectsName.class).toInstance(new AllProjectsName("All-Projects"));
+ bind(AllUsersName.class).toInstance(new AllUsersName("All-Users"));
- bind(GitRepositoryManager.class)
- .toInstance(new InMemoryRepositoryManager());
+ bind(GitRepositoryManager.class).toInstance(new InMemoryRepositoryManager());
- bind(String.class) //
- .annotatedWith(AnonymousCowardName.class) //
- .toProvider(AnonymousCowardNameProvider.class);
+ bind(String.class) //
+ .annotatedWith(AnonymousCowardName.class) //
+ .toProvider(AnonymousCowardNameProvider.class);
- bind(DataSourceType.class).to(InMemoryH2Type.class);
+ bind(DataSourceType.class).to(InMemoryH2Type.class);
- bind(SystemGroupBackend.class);
- }
- }).getInstance(SchemaUpdater.class);
+ bind(SystemGroupBackend.class);
+ }
+ })
+ .getInstance(SchemaUpdater.class);
- for (SchemaVersion s = u.getLatestSchemaVersion();
- s.getVersionNbr() > 1; s = s.getPrior()) {
+ for (SchemaVersion s = u.getLatestSchemaVersion(); s.getVersionNbr() > 1; s = s.getPrior()) {
try {
assertThat(s.getPrior().getVersionNbr())
- .named("schema %s has prior version %s. Not true that",
+ .named(
+ "schema %s has prior version %s. Not true that",
s.getVersionNbr(), s.getPrior().getVersionNbr())
.isEqualTo(s.getVersionNbr() - 1);
} catch (ProvisionException e) {
@@ -130,33 +127,31 @@
}
}
- u.update(new UpdateUI() {
- @Override
- public void message(String msg) {
- }
+ u.update(
+ new UpdateUI() {
+ @Override
+ public void message(String msg) {}
- @Override
- public boolean yesno(boolean def, String msg) {
- return def;
- }
+ @Override
+ public boolean yesno(boolean def, String msg) {
+ return def;
+ }
- @Override
- public boolean isBatch() {
- return true;
- }
+ @Override
+ public boolean isBatch() {
+ return true;
+ }
- @Override
- public void pruneSchema(StatementExecutor e, List<String> pruneList)
- throws OrmException {
- for (String sql : pruneList) {
- e.execute(sql);
- }
- }
- });
+ @Override
+ public void pruneSchema(StatementExecutor e, List<String> pruneList) throws OrmException {
+ for (String sql : pruneList) {
+ e.execute(sql);
+ }
+ }
+ });
db.assertSchemaVersion();
final SystemConfig sc = db.getSystemConfig();
- assertThat(sc.sitePath)
- .isEqualTo(paths.site_path.toAbsolutePath().toString());
+ assertThat(sc.sitePath).isEqualTo(paths.site_path.toAbsolutePath().toString());
}
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/tools/hooks/CommitMsgHookTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/tools/hooks/CommitMsgHookTest.java
index 0d3dfb8..ec0dad5 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/tools/hooks/CommitMsgHookTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/tools/hooks/CommitMsgHookTest.java
@@ -20,7 +20,10 @@
import static org.junit.Assert.assertTrue;
import com.google.gerrit.server.util.HostPlatform;
-
+import java.io.File;
+import java.io.IOException;
+import java.util.Date;
+import java.util.TimeZone;
import org.eclipse.jgit.dircache.DirCacheBuilder;
import org.eclipse.jgit.dircache.DirCacheEntry;
import org.eclipse.jgit.lib.CommitBuilder;
@@ -35,11 +38,6 @@
import org.junit.BeforeClass;
import org.junit.Test;
-import java.io.File;
-import java.io.IOException;
-import java.util.Date;
-import java.util.TimeZone;
-
public class CommitMsgHookTest extends HookTestCase {
private final String SOB1 = "Signed-off-by: J Author <ja@example.com>\n";
private final String SOB2 = "Signed-off-by: J Committer <jc@example.com>\n";
@@ -80,8 +78,9 @@
hookDoesNotModify("\n# on branch master\n# Untracked files:\n");
hookDoesNotModify("\n\n# on branch master\n# Untracked files:\n");
- hookDoesNotModify("\n# on branch master\ndiff --git a/src b/src\n"
- + "new file mode 100644\nindex 0000000..c78b7f0\n");
+ hookDoesNotModify(
+ "\n# on branch master\ndiff --git a/src b/src\n"
+ + "new file mode 100644\nindex 0000000..c78b7f0\n");
}
@Test
@@ -89,316 +88,537 @@
// If a Change-Id is already present in the footer, the hook must
// not modify the message but instead must leave the identity alone.
//
- hookDoesNotModify("a\n" + //
- "\n" + //
- "Change-Id: Iaeac9b4149291060228ef0154db2985a31111335\n");
- hookDoesNotModify("fix: this thing\n" + //
- "\n" + //
- "Change-Id: I388bdaf52ed05b55e62a22d0a20d2c1ae0d33e7e\n");
- hookDoesNotModify("fix-a-widget: this thing\n" + //
- "\n" + //
- "Change-Id: Id3bc5359d768a6400450283e12bdfb6cd135ea4b\n");
- hookDoesNotModify("FIX: this thing\n" + //
- "\n" + //
- "Change-Id: I1b55098b5a2cce0b3f3da783dda50d5f79f873fa\n");
- hookDoesNotModify("Fix-A-Widget: this thing\n" + //
- "\n" + //
- "Change-Id: I4f4e2e1e8568ddc1509baecb8c1270a1fb4b6da7\n");
+ hookDoesNotModify(
+ "a\n"
+ + //
+ "\n"
+ + //
+ "Change-Id: Iaeac9b4149291060228ef0154db2985a31111335\n");
+ hookDoesNotModify(
+ "fix: this thing\n"
+ + //
+ "\n"
+ + //
+ "Change-Id: I388bdaf52ed05b55e62a22d0a20d2c1ae0d33e7e\n");
+ hookDoesNotModify(
+ "fix-a-widget: this thing\n"
+ + //
+ "\n"
+ + //
+ "Change-Id: Id3bc5359d768a6400450283e12bdfb6cd135ea4b\n");
+ hookDoesNotModify(
+ "FIX: this thing\n"
+ + //
+ "\n"
+ + //
+ "Change-Id: I1b55098b5a2cce0b3f3da783dda50d5f79f873fa\n");
+ hookDoesNotModify(
+ "Fix-A-Widget: this thing\n"
+ + //
+ "\n"
+ + //
+ "Change-Id: I4f4e2e1e8568ddc1509baecb8c1270a1fb4b6da7\n");
}
@Test
public void timeAltersId() throws Exception {
- assertEquals("a\n" + //
- "\n" + //
- "Change-Id: I7fc3876fee63c766a2063df97fbe04a2dddd8d7c\n",//
+ assertEquals(
+ "a\n"
+ + //
+ "\n"
+ + //
+ "Change-Id: I7fc3876fee63c766a2063df97fbe04a2dddd8d7c\n", //
call("a\n"));
tick();
- assertEquals("a\n" + //
- "\n" + //
- "Change-Id: I3251906b99dda598a58a6346d8126237ee1ea800\n",//
+ assertEquals(
+ "a\n"
+ + //
+ "\n"
+ + //
+ "Change-Id: I3251906b99dda598a58a6346d8126237ee1ea800\n", //
call("a\n"));
tick();
- assertEquals("a\n" + //
- "\n" + //
- "Change-Id: I69adf9208d828f41a3d7e41afbca63aff37c0c5c\n",//
+ assertEquals(
+ "a\n"
+ + //
+ "\n"
+ + //
+ "Change-Id: I69adf9208d828f41a3d7e41afbca63aff37c0c5c\n", //
call("a\n"));
}
@Test
public void firstParentAltersId() throws Exception {
- assertEquals("a\n" + //
- "\n" + //
- "Change-Id: I7fc3876fee63c766a2063df97fbe04a2dddd8d7c\n",//
+ assertEquals(
+ "a\n"
+ + //
+ "\n"
+ + //
+ "Change-Id: I7fc3876fee63c766a2063df97fbe04a2dddd8d7c\n", //
call("a\n"));
setHEAD();
- assertEquals("a\n" + //
- "\n" + //
- "Change-Id: I51e86482bde7f92028541aaf724d3a3f996e7ea2\n",//
+ assertEquals(
+ "a\n"
+ + //
+ "\n"
+ + //
+ "Change-Id: I51e86482bde7f92028541aaf724d3a3f996e7ea2\n", //
call("a\n"));
}
@Test
public void dirCacheAltersId() throws Exception {
- assertEquals("a\n" + //
- "\n" + //
- "Change-Id: I7fc3876fee63c766a2063df97fbe04a2dddd8d7c\n",//
+ assertEquals(
+ "a\n"
+ + //
+ "\n"
+ + //
+ "Change-Id: I7fc3876fee63c766a2063df97fbe04a2dddd8d7c\n", //
call("a\n"));
final DirCacheBuilder builder = repository.lockDirCache().builder();
builder.add(file("A"));
assertTrue(builder.commit());
- assertEquals("a\n" + //
- "\n" + //
- "Change-Id: If56597ea9759f23b070677ea6f064c60c38da631\n",//
+ assertEquals(
+ "a\n"
+ + //
+ "\n"
+ + //
+ "Change-Id: If56597ea9759f23b070677ea6f064c60c38da631\n", //
call("a\n"));
}
@Test
public void singleLineMessages() throws Exception {
- assertEquals("a\n" + //
- "\n" + //
- "Change-Id: I7fc3876fee63c766a2063df97fbe04a2dddd8d7c\n",//
+ assertEquals(
+ "a\n"
+ + //
+ "\n"
+ + //
+ "Change-Id: I7fc3876fee63c766a2063df97fbe04a2dddd8d7c\n", //
call("a\n"));
- assertEquals("fix: this thing\n" + //
- "\n" + //
- "Change-Id: I0f13d0e6c739ca3ae399a05a93792e80feb97f37\n",//
+ assertEquals(
+ "fix: this thing\n"
+ + //
+ "\n"
+ + //
+ "Change-Id: I0f13d0e6c739ca3ae399a05a93792e80feb97f37\n", //
call("fix: this thing\n"));
- assertEquals("fix-a-widget: this thing\n" + //
- "\n" + //
- "Change-Id: I1a1a0c751e4273d532e4046a501a612b9b8a775e\n",//
+ assertEquals(
+ "fix-a-widget: this thing\n"
+ + //
+ "\n"
+ + //
+ "Change-Id: I1a1a0c751e4273d532e4046a501a612b9b8a775e\n", //
call("fix-a-widget: this thing\n"));
- assertEquals("FIX: this thing\n" + //
- "\n" + //
- "Change-Id: If816d944c57d3893b60cf10c65931fead1290d97\n",//
+ assertEquals(
+ "FIX: this thing\n"
+ + //
+ "\n"
+ + //
+ "Change-Id: If816d944c57d3893b60cf10c65931fead1290d97\n", //
call("FIX: this thing\n"));
- assertEquals("Fix-A-Widget: this thing\n" + //
- "\n" + //
- "Change-Id: I3e18d00cbda2ba1f73aeb63ed8c7d57d7fd16c76\n",//
+ assertEquals(
+ "Fix-A-Widget: this thing\n"
+ + //
+ "\n"
+ + //
+ "Change-Id: I3e18d00cbda2ba1f73aeb63ed8c7d57d7fd16c76\n", //
call("Fix-A-Widget: this thing\n"));
}
@Test
public void multiLineMessagesWithoutFooter() throws Exception {
- assertEquals("a\n" + //
- "\n" + //
- "b\n" + //
- "\n" + //
- "Change-Id: Id0b4f42d3d6fc1569595c9b97cb665e738486f5d\n",//
+ assertEquals(
+ "a\n"
+ + //
+ "\n"
+ + //
+ "b\n"
+ + //
+ "\n"
+ + //
+ "Change-Id: Id0b4f42d3d6fc1569595c9b97cb665e738486f5d\n", //
call("a\n" + "\n" + "b\n"));
- assertEquals("a\n" + //
- "\n" + //
- "b\nc\nd\ne\n" + //
- "\n" + //
- "Change-Id: I7d237b20058a0f46cc3f5fabc4a0476877289d75\n",//
+ assertEquals(
+ "a\n"
+ + //
+ "\n"
+ + //
+ "b\nc\nd\ne\n"
+ + //
+ "\n"
+ + //
+ "Change-Id: I7d237b20058a0f46cc3f5fabc4a0476877289d75\n", //
call("a\n" + "\n" + "b\nc\nd\ne\n"));
- assertEquals("a\n" + //
- "\n" + //
- "b\nc\nd\ne\n" + //
- "\n" + //
- "f\ng\nh\n" + //
- "\n" + //
- "Change-Id: I382e662f47bf164d6878b7fe61637873ab7fa4e8\n",//
+ assertEquals(
+ "a\n"
+ + //
+ "\n"
+ + //
+ "b\nc\nd\ne\n"
+ + //
+ "\n"
+ + //
+ "f\ng\nh\n"
+ + //
+ "\n"
+ + //
+ "Change-Id: I382e662f47bf164d6878b7fe61637873ab7fa4e8\n", //
call("a\n" + "\n" + "b\nc\nd\ne\n" + "\n" + "f\ng\nh\n"));
}
@Test
public void singleLineMessagesWithSignedOffBy() throws Exception {
- assertEquals("a\n" + //
- "\n" + //
- "Change-Id: I7fc3876fee63c766a2063df97fbe04a2dddd8d7c\n" + //
- SOB1,//
+ assertEquals(
+ "a\n"
+ + //
+ "\n"
+ + //
+ "Change-Id: I7fc3876fee63c766a2063df97fbe04a2dddd8d7c\n"
+ + //
+ SOB1, //
call("a\n" + "\n" + SOB1));
- assertEquals("a\n" + //
- "\n" + //
- "Change-Id: I7fc3876fee63c766a2063df97fbe04a2dddd8d7c\n" + //
- SOB1 + //
- SOB2,//
+ assertEquals(
+ "a\n"
+ + //
+ "\n"
+ + //
+ "Change-Id: I7fc3876fee63c766a2063df97fbe04a2dddd8d7c\n"
+ + //
+ SOB1
+ + //
+ SOB2, //
call("a\n" + "\n" + SOB1 + SOB2));
}
@Test
public void multiLineMessagesWithSignedOffBy() throws Exception {
- assertEquals("a\n" + //
- "\n" + //
- "b\nc\nd\ne\n" + //
- "\n" + //
- "f\ng\nh\n" + //
- "\n" + //
- "Change-Id: I382e662f47bf164d6878b7fe61637873ab7fa4e8\n" + //
- SOB1,//
+ assertEquals(
+ "a\n"
+ + //
+ "\n"
+ + //
+ "b\nc\nd\ne\n"
+ + //
+ "\n"
+ + //
+ "f\ng\nh\n"
+ + //
+ "\n"
+ + //
+ "Change-Id: I382e662f47bf164d6878b7fe61637873ab7fa4e8\n"
+ + //
+ SOB1, //
call("a\n" + "\n" + "b\nc\nd\ne\n" + "\n" + "f\ng\nh\n" + "\n" + SOB1));
- assertEquals("a\n" + //
- "\n" + //
- "b\nc\nd\ne\n" + //
- "\n" + //
- "f\ng\nh\n" + //
- "\n" + //
- "Change-Id: I382e662f47bf164d6878b7fe61637873ab7fa4e8\n" + //
- SOB1 + //
- SOB2,//
- call("a\n" + //
- "\n" + //
- "b\nc\nd\ne\n" + //
- "\n" + //
- "f\ng\nh\n" + //
- "\n" + //
- SOB1 + //
- SOB2));
+ assertEquals(
+ "a\n"
+ + //
+ "\n"
+ + //
+ "b\nc\nd\ne\n"
+ + //
+ "\n"
+ + //
+ "f\ng\nh\n"
+ + //
+ "\n"
+ + //
+ "Change-Id: I382e662f47bf164d6878b7fe61637873ab7fa4e8\n"
+ + //
+ SOB1
+ + //
+ SOB2, //
+ call(
+ "a\n"
+ + //
+ "\n"
+ + //
+ "b\nc\nd\ne\n"
+ + //
+ "\n"
+ + //
+ "f\ng\nh\n"
+ + //
+ "\n"
+ + //
+ SOB1
+ + //
+ SOB2));
- assertEquals("a\n" + //
- "\n" + //
- "b: not a footer\nc\nd\ne\n" + //
- "\n" + //
- "f\ng\nh\n" + //
- "\n" + //
- "Change-Id: I8869aabd44b3017cd55d2d7e0d546a03e3931ee2\n" + //
- SOB1 + //
- SOB2,//
- call("a\n" + //
- "\n" + //
- "b: not a footer\nc\nd\ne\n" + //
- "\n" + //
- "f\ng\nh\n" + //
- "\n" + //
- SOB1 + //
- SOB2));
+ assertEquals(
+ "a\n"
+ + //
+ "\n"
+ + //
+ "b: not a footer\nc\nd\ne\n"
+ + //
+ "\n"
+ + //
+ "f\ng\nh\n"
+ + //
+ "\n"
+ + //
+ "Change-Id: I8869aabd44b3017cd55d2d7e0d546a03e3931ee2\n"
+ + //
+ SOB1
+ + //
+ SOB2, //
+ call(
+ "a\n"
+ + //
+ "\n"
+ + //
+ "b: not a footer\nc\nd\ne\n"
+ + //
+ "\n"
+ + //
+ "f\ng\nh\n"
+ + //
+ "\n"
+ + //
+ SOB1
+ + //
+ SOB2));
}
@Test
public void noteInMiddle() throws Exception {
- assertEquals("a\n" + //
- "\n" + //
- "NOTE: This\n" + //
- "does not fix it.\n" + //
- "\n" + //
- "Change-Id: I988a127969a6ee5e58db546aab74fc46e66847f8\n", //
- call("a\n" + //
- "\n" + //
- "NOTE: This\n" + //
- "does not fix it.\n"));
+ assertEquals(
+ "a\n"
+ + //
+ "\n"
+ + //
+ "NOTE: This\n"
+ + //
+ "does not fix it.\n"
+ + //
+ "\n"
+ + //
+ "Change-Id: I988a127969a6ee5e58db546aab74fc46e66847f8\n", //
+ call(
+ "a\n"
+ + //
+ "\n"
+ + //
+ "NOTE: This\n"
+ + //
+ "does not fix it.\n"));
}
@Test
public void kernelStyleFooter() throws Exception {
- assertEquals("a\n" + //
- "\n" + //
- "Change-Id: I1bd787f9e7590a2ac82b02c404c955ffb21877c4\n" + //
- SOB1 + //
- "[ja: Fixed\n" + //
- " the indentation]\n" + //
- SOB2, //
- call("a\n" + //
- "\n" + //
- SOB1 + //
- "[ja: Fixed\n" + //
- " the indentation]\n" + //
- SOB2));
+ assertEquals(
+ "a\n"
+ + //
+ "\n"
+ + //
+ "Change-Id: I1bd787f9e7590a2ac82b02c404c955ffb21877c4\n"
+ + //
+ SOB1
+ + //
+ "[ja: Fixed\n"
+ + //
+ " the indentation]\n"
+ + //
+ SOB2, //
+ call(
+ "a\n"
+ + //
+ "\n"
+ + //
+ SOB1
+ + //
+ "[ja: Fixed\n"
+ + //
+ " the indentation]\n"
+ + //
+ SOB2));
}
@Test
public void changeIdAfterBugOrIssue() throws Exception {
- assertEquals("a\n" + //
- "\n" + //
- "Bug: 42\n" + //
- "Change-Id: I8c0321227c4324e670b9ae8cf40eccc87af21b1b\n" + //
- SOB1,//
- call("a\n" + //
- "\n" + //
- "Bug: 42\n" + //
- SOB1));
+ assertEquals(
+ "a\n"
+ + //
+ "\n"
+ + //
+ "Bug: 42\n"
+ + //
+ "Change-Id: I8c0321227c4324e670b9ae8cf40eccc87af21b1b\n"
+ + //
+ SOB1, //
+ call(
+ "a\n"
+ + //
+ "\n"
+ + //
+ "Bug: 42\n"
+ + //
+ SOB1));
- assertEquals("a\n" + //
- "\n" + //
- "Issue: 42\n" + //
- "Change-Id: Ie66e07d89ae5b114c0975b49cf326e90331dd822\n" + //
- SOB1,//
- call("a\n" + //
- "\n" + //
- "Issue: 42\n" + //
- SOB1));
+ assertEquals(
+ "a\n"
+ + //
+ "\n"
+ + //
+ "Issue: 42\n"
+ + //
+ "Change-Id: Ie66e07d89ae5b114c0975b49cf326e90331dd822\n"
+ + //
+ SOB1, //
+ call(
+ "a\n"
+ + //
+ "\n"
+ + //
+ "Issue: 42\n"
+ + //
+ SOB1));
}
@Test
public void commitDashV() throws Exception {
- assertEquals("a\n" + //
- "\n" + //
- "Change-Id: I7fc3876fee63c766a2063df97fbe04a2dddd8d7c\n" + //
- SOB1 + //
- SOB2, //
- call("a\n" + //
- "\n" + //
- SOB1 + //
- SOB2 + //
- "\n" + //
- "# on branch master\n" + //
- "diff --git a/src b/src\n" + //
- "new file mode 100644\n" + //
- "index 0000000..c78b7f0\n"));
+ assertEquals(
+ "a\n"
+ + //
+ "\n"
+ + //
+ "Change-Id: I7fc3876fee63c766a2063df97fbe04a2dddd8d7c\n"
+ + //
+ SOB1
+ + //
+ SOB2, //
+ call(
+ "a\n"
+ + //
+ "\n"
+ + //
+ SOB1
+ + //
+ SOB2
+ + //
+ "\n"
+ + //
+ "# on branch master\n"
+ + //
+ "diff --git a/src b/src\n"
+ + //
+ "new file mode 100644\n"
+ + //
+ "index 0000000..c78b7f0\n"));
}
@Test
public void withEndingURL() throws Exception {
- assertEquals("a\n" + //
- "\n" + //
- "http://example.com/ fixes this\n" + //
- "\n" + //
- "Change-Id: I3b7e4e16b503ce00f07ba6ad01d97a356dad7701\n", //
- call("a\n" + //
- "\n" + //
- "http://example.com/ fixes this\n"));
- assertEquals("a\n" + //
- "\n" + //
- "https://example.com/ fixes this\n" + //
- "\n" + //
- "Change-Id: I62b9039e2fc0dce274af55e8f99312a8a80a805d\n", //
- call("a\n" + //
- "\n" + //
- "https://example.com/ fixes this\n"));
- assertEquals("a\n" + //
- "\n" + //
- "ftp://example.com/ fixes this\n" + //
- "\n" + //
- "Change-Id: I71b05dc1f6b9a5540a53a693e64d58b65a8910e8\n", //
- call("a\n" + //
- "\n" + //
- "ftp://example.com/ fixes this\n"));
- assertEquals("a\n" + //
- "\n" + //
- "git://example.com/ fixes this\n" + //
- "\n" + //
- "Change-Id: Id34e942baa68d790633737d815ddf11bac9183e5\n", //
- call("a\n" + //
- "\n" + //
- "git://example.com/ fixes this\n"));
+ assertEquals(
+ "a\n"
+ + //
+ "\n"
+ + //
+ "http://example.com/ fixes this\n"
+ + //
+ "\n"
+ + //
+ "Change-Id: I3b7e4e16b503ce00f07ba6ad01d97a356dad7701\n", //
+ call(
+ "a\n"
+ + //
+ "\n"
+ + //
+ "http://example.com/ fixes this\n"));
+ assertEquals(
+ "a\n"
+ + //
+ "\n"
+ + //
+ "https://example.com/ fixes this\n"
+ + //
+ "\n"
+ + //
+ "Change-Id: I62b9039e2fc0dce274af55e8f99312a8a80a805d\n", //
+ call(
+ "a\n"
+ + //
+ "\n"
+ + //
+ "https://example.com/ fixes this\n"));
+ assertEquals(
+ "a\n"
+ + //
+ "\n"
+ + //
+ "ftp://example.com/ fixes this\n"
+ + //
+ "\n"
+ + //
+ "Change-Id: I71b05dc1f6b9a5540a53a693e64d58b65a8910e8\n", //
+ call(
+ "a\n"
+ + //
+ "\n"
+ + //
+ "ftp://example.com/ fixes this\n"));
+ assertEquals(
+ "a\n"
+ + //
+ "\n"
+ + //
+ "git://example.com/ fixes this\n"
+ + //
+ "\n"
+ + //
+ "Change-Id: Id34e942baa68d790633737d815ddf11bac9183e5\n", //
+ call(
+ "a\n"
+ + //
+ "\n"
+ + //
+ "git://example.com/ fixes this\n"));
}
@Test
public void withFalseTags() throws Exception {
- assertEquals("foo\n" + //
- "\n" + //
- "FakeLine:\n" + //
- " foo\n" + //
- " bar\n" + //
- "\n" + //
- "Change-Id: I67632a37fd2e08a35f766f52fc9a47f4ea868c55\n" + //
- "RealTag: abc\n", //
- call("foo\n" + //
- "\n" + //
- "FakeLine:\n" + //
- " foo\n" + //
- " bar\n" + //
- "\n" + //
- "RealTag: abc\n"));
+ assertEquals(
+ "foo\n"
+ + //
+ "\n"
+ + //
+ "FakeLine:\n"
+ + //
+ " foo\n"
+ + //
+ " bar\n"
+ + //
+ "\n"
+ + //
+ "Change-Id: I67632a37fd2e08a35f766f52fc9a47f4ea868c55\n"
+ + //
+ "RealTag: abc\n", //
+ call(
+ "foo\n"
+ + //
+ "\n"
+ + //
+ "FakeLine:\n"
+ + //
+ " foo\n"
+ + //
+ " bar\n"
+ + //
+ "\n"
+ + //
+ "RealTag: abc\n"));
}
private void hookDoesNotModify(final String in) throws Exception {
@@ -439,9 +659,9 @@
ref.setNewObjectId(commitId);
Result result = ref.forceUpdate();
assert_()
- .withFailureMessage(Constants.HEAD + " did not change: " + ref.getResult())
- .that(result)
- .isAnyOf(Result.FAST_FORWARD, Result.FORCED, Result.NEW, Result.NO_CHANGE);
+ .withFailureMessage(Constants.HEAD + " did not change: " + ref.getResult())
+ .that(result)
+ .isAnyOf(Result.FAST_FORWARD, Result.FORCED, Result.NEW, Result.NO_CHANGE);
}
}
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/tools/hooks/HookTestCase.java b/gerrit-server/src/test/java/com/google/gerrit/server/tools/hooks/HookTestCase.java
index 69a8487..21c8764 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/tools/hooks/HookTestCase.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/tools/hooks/HookTestCase.java
@@ -53,13 +53,6 @@
import static com.google.common.truth.Truth.assert_;
import com.google.common.io.ByteStreams;
-
-import org.eclipse.jgit.junit.LocalDiskRepositoryTestCase;
-import org.eclipse.jgit.lib.Repository;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Ignore;
-
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
@@ -69,6 +62,11 @@
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
+import org.eclipse.jgit.junit.LocalDiskRepositoryTestCase;
+import org.eclipse.jgit.lib.Repository;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Ignore;
@Ignore
public abstract class HookTestCase extends LocalDiskRepositoryTestCase {
@@ -105,20 +103,14 @@
String path = scproot + "/hooks/" + name;
String errorMessage = "Cannot locate " + path + " in CLASSPATH";
URL url = cl().getResource(path);
- assert_()
- .withFailureMessage(errorMessage)
- .that(url).isNotNull();
+ assert_().withFailureMessage(errorMessage).that(url).isNotNull();
String protocol = url.getProtocol();
- assert_()
- .withFailureMessage("Cannot invoke " + url)
- .that(protocol).isAnyOf("file", "jar");
+ assert_().withFailureMessage("Cannot invoke " + url).that(protocol).isAnyOf("file", "jar");
if ("file".equals(protocol)) {
hook = new File(url.getPath());
- assert_()
- .withFailureMessage(errorMessage)
- .that(hook.isFile()).isTrue();
+ assert_().withFailureMessage(errorMessage).that(hook.isFile()).isTrue();
long time = hook.lastModified();
hook.setExecutable(true);
hook.setLastModified(time);
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/util/IdGeneratorTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/util/IdGeneratorTest.java
index 2a61165..39afcac 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/util/IdGeneratorTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/util/IdGeneratorTest.java
@@ -17,9 +17,8 @@
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
-import org.junit.Test;
-
import java.util.HashSet;
+import org.junit.Test;
public class IdGeneratorTest {
@Test
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/util/LabelVoteTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/util/LabelVoteTest.java
index 4fdbdb2..0592041 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/util/LabelVoteTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/util/LabelVoteTest.java
@@ -79,15 +79,10 @@
@Test
public void formatWithEquals() {
- assertEquals("Code-Review=-2",
- LabelVote.parseWithEquals("Code-Review=-2").formatWithEquals());
- assertEquals("Code-Review=-1",
- LabelVote.parseWithEquals("Code-Review=-1").formatWithEquals());
- assertEquals("Code-Review=0",
- LabelVote.parseWithEquals("Code-Review=0").formatWithEquals());
- assertEquals("Code-Review=+1",
- LabelVote.parseWithEquals("Code-Review=+1").formatWithEquals());
- assertEquals("Code-Review=+2",
- LabelVote.parseWithEquals("Code-Review=+2").formatWithEquals());
+ assertEquals("Code-Review=-2", LabelVote.parseWithEquals("Code-Review=-2").formatWithEquals());
+ assertEquals("Code-Review=-1", LabelVote.parseWithEquals("Code-Review=-1").formatWithEquals());
+ assertEquals("Code-Review=0", LabelVote.parseWithEquals("Code-Review=0").formatWithEquals());
+ assertEquals("Code-Review=+1", LabelVote.parseWithEquals("Code-Review=+1").formatWithEquals());
+ assertEquals("Code-Review=+2", LabelVote.parseWithEquals("Code-Review=+2").formatWithEquals());
}
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/util/MostSpecificComparatorTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/util/MostSpecificComparatorTest.java
index e974f1f..025bf84 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/util/MostSpecificComparatorTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/util/MostSpecificComparatorTest.java
@@ -33,9 +33,8 @@
}
/**
- * Assuming two patterns have the same Levenshtein distance,
- * the pattern which represents a finite language wins over a pattern
- * which represents an infinite language.
+ * Assuming two patterns have the same Levenshtein distance, the pattern which represents a finite
+ * language wins over a pattern which represents an infinite language.
*/
@Test
public void finiteWinsOverInfinite() {
@@ -45,9 +44,8 @@
}
/**
- * Assuming two patterns have the same Levenshtein distance
- * and are both either finite or infinite the one with the higher
- * number of state transitions (in an equivalent automaton) wins
+ * Assuming two patterns have the same Levenshtein distance and are both either finite or infinite
+ * the one with the higher number of state transitions (in an equivalent automaton) wins
*/
@Test
public void higherNumberOfTransitionsWins() {
@@ -65,8 +63,8 @@
}
/**
- * Assuming the same Levenshtein distance, (in)finity and the number
- * of transitions, the longer pattern wins
+ * Assuming the same Levenshtein distance, (in)finity and the number of transitions, the longer
+ * pattern wins
*/
@Test
public void longerPatternWins() {
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/util/ParboiledTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/util/ParboiledTest.java
index 6efc881..3bcfb56 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/util/ParboiledTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/util/ParboiledTest.java
@@ -29,14 +29,14 @@
public class ParboiledTest {
private static final String EXPECTED =
- "[Expression] '42'\n" +
- " [Term] '42'\n" +
- " [Factor] '42'\n" +
- " [Number] '42'\n" +
- " [0..9] '4'\n" +
- " [0..9] '2'\n" +
- " [zeroOrMore]\n" +
- " [zeroOrMore]\n";
+ "[Expression] '42'\n"
+ + " [Term] '42'\n"
+ + " [Factor] '42'\n"
+ + " [Number] '42'\n"
+ + " [0..9] '4'\n"
+ + " [0..9] '2'\n"
+ + " [zeroOrMore]\n"
+ + " [zeroOrMore]\n";
private CalculatorParser parser;
@@ -47,8 +47,7 @@
@Test
public void test() {
- ParsingResult<String> result =
- new ReportingParseRunner<String>(parser.Expression()).run("42");
+ ParsingResult<String> result = new ReportingParseRunner<String>(parser.Expression()).run("42");
assertThat(result.isSuccess()).isTrue();
// next test is optional; we could stop here.
assertThat(ParseTreeUtils.printNodeTree(result)).isEqualTo(EXPECTED);
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/util/RegexListSearcherTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/util/RegexListSearcherTest.java
index 8f73005..322484a 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/util/RegexListSearcherTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/util/RegexListSearcherTest.java
@@ -20,10 +20,8 @@
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Ordering;
-
-import org.junit.Test;
-
import java.util.List;
+import org.junit.Test;
public class RegexListSearcherTest {
private static final List<String> EMPTY = ImmutableList.of();
@@ -55,30 +53,20 @@
List<String> list = ImmutableList.of("bar", "foo", "quux");
assertSearchReturns(ImmutableList.of("foo"), "f.*", list);
assertSearchReturns(ImmutableList.of("foo"), ".*o.*", list);
- assertSearchReturns(ImmutableList.of("bar", "foo", "quux"), ".*[aou].*",
- list);
+ assertSearchReturns(ImmutableList.of("bar", "foo", "quux"), ".*[aou].*", list);
}
@Test
public void commonPrefix() {
- List<String> list = ImmutableList.of(
- "bar",
- "baz",
- "foo1",
- "foo2",
- "foo3",
- "quux");
+ List<String> list = ImmutableList.of("bar", "baz", "foo1", "foo2", "foo3", "quux");
assertSearchReturns(ImmutableList.of("bar", "baz"), "b.*", list);
assertSearchReturns(ImmutableList.of("foo1", "foo2"), "foo[12]", list);
- assertSearchReturns(ImmutableList.of("foo1", "foo2", "foo3"), "foo.*",
- list);
+ assertSearchReturns(ImmutableList.of("foo1", "foo2", "foo3"), "foo.*", list);
assertSearchReturns(ImmutableList.of("quux"), "q.*", list);
}
- private void assertSearchReturns(List<?> expected, String re,
- List<String> inputs) {
+ private void assertSearchReturns(List<?> expected, String re, List<String> inputs) {
assertTrue(Ordering.natural().isOrdered(inputs));
- assertEquals(expected,
- ImmutableList.copyOf(RegexListSearcher.ofStrings(re).search(inputs)));
+ assertEquals(expected, ImmutableList.copyOf(RegexListSearcher.ofStrings(re).search(inputs)));
}
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/util/SocketUtilTest.java b/gerrit-server/src/test/java/com/google/gerrit/server/util/SocketUtilTest.java
index 3e3c13e..473c44d 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/util/SocketUtilTest.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/util/SocketUtilTest.java
@@ -25,14 +25,12 @@
import static org.junit.Assert.assertTrue;
import com.google.gerrit.testutil.GerritBaseTests;
-
-import org.junit.Test;
-
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
+import org.junit.Test;
public class SocketUtilTest extends GerritBaseTests {
@Test
@@ -61,15 +59,19 @@
assertEquals("foo:1234", SocketUtil.format(createUnresolved("foo", 1234), 80));
assertEquals("foo", SocketUtil.format(createUnresolved("foo", 80), 80));
- assertEquals("[1:2:3:4:5:6:7:8]:1234",//
+ assertEquals(
+ "[1:2:3:4:5:6:7:8]:1234", //
SocketUtil.format(new InetSocketAddress(getByName("1:2:3:4:5:6:7:8"), 1234), 80));
- assertEquals("[1:2:3:4:5:6:7:8]",//
+ assertEquals(
+ "[1:2:3:4:5:6:7:8]", //
SocketUtil.format(new InetSocketAddress(getByName("1:2:3:4:5:6:7:8"), 80), 80));
- assertEquals("localhost:1234",//
+ assertEquals(
+ "localhost:1234", //
SocketUtil.format(new InetSocketAddress("localhost", 1234), 80));
- assertEquals("localhost",//
- SocketUtil. format(new InetSocketAddress("localhost", 80), 80));
+ assertEquals(
+ "localhost", //
+ SocketUtil.format(new InetSocketAddress("localhost", 80), 80));
}
@Test
@@ -79,19 +81,25 @@
assertEquals(new InetSocketAddress(1234), parse(":1234", 80));
assertEquals(new InetSocketAddress(80), parse("", 80));
- assertEquals(createUnresolved("1:2:3:4:5:6:7:8", 1234), //
+ assertEquals(
+ createUnresolved("1:2:3:4:5:6:7:8", 1234), //
parse("[1:2:3:4:5:6:7:8]:1234", 80));
- assertEquals(createUnresolved("1:2:3:4:5:6:7:8", 80), //
+ assertEquals(
+ createUnresolved("1:2:3:4:5:6:7:8", 80), //
parse("[1:2:3:4:5:6:7:8]", 80));
- assertEquals(createUnresolved("localhost", 1234), //
+ assertEquals(
+ createUnresolved("localhost", 1234), //
parse("[localhost]:1234", 80));
- assertEquals(createUnresolved("localhost", 80), //
+ assertEquals(
+ createUnresolved("localhost", 80), //
parse("[localhost]", 80));
- assertEquals(createUnresolved("foo.bar.example.com", 1234), //
+ assertEquals(
+ createUnresolved("foo.bar.example.com", 1234), //
parse("[foo.bar.example.com]:1234", 80));
- assertEquals(createUnresolved("foo.bar.example.com", 80), //
+ assertEquals(
+ createUnresolved("foo.bar.example.com", 80), //
parse("[foo.bar.example.com]", 80));
}
@@ -116,14 +124,18 @@
assertEquals(new InetSocketAddress(1234), resolve(":1234", 80));
assertEquals(new InetSocketAddress(80), resolve("", 80));
- assertEquals(new InetSocketAddress(getByName("1:2:3:4:5:6:7:8"), 1234), //
+ assertEquals(
+ new InetSocketAddress(getByName("1:2:3:4:5:6:7:8"), 1234), //
resolve("[1:2:3:4:5:6:7:8]:1234", 80));
- assertEquals(new InetSocketAddress(getByName("1:2:3:4:5:6:7:8"), 80), //
+ assertEquals(
+ new InetSocketAddress(getByName("1:2:3:4:5:6:7:8"), 80), //
resolve("[1:2:3:4:5:6:7:8]", 80));
- assertEquals(new InetSocketAddress(getByName("localhost"), 1234), //
+ assertEquals(
+ new InetSocketAddress(getByName("localhost"), 1234), //
resolve("[localhost]:1234", 80));
- assertEquals(new InetSocketAddress(getByName("localhost"), 80), //
+ assertEquals(
+ new InetSocketAddress(getByName("localhost"), 80), //
resolve("[localhost]", 80));
}
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/testutil/ConfigSuite.java b/gerrit-server/src/test/java/com/google/gerrit/testutil/ConfigSuite.java
index d769bcc..eaa9bc4 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/testutil/ConfigSuite.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/testutil/ConfigSuite.java
@@ -22,13 +22,6 @@
import com.google.common.base.MoreObjects;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
-
-import org.junit.runner.Runner;
-import org.junit.runners.BlockJUnit4ClassRunner;
-import org.junit.runners.Suite;
-import org.junit.runners.model.FrameworkMethod;
-import org.junit.runners.model.InitializationError;
-
import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
@@ -37,12 +30,17 @@
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.List;
+import org.junit.runner.Runner;
+import org.junit.runners.BlockJUnit4ClassRunner;
+import org.junit.runners.Suite;
+import org.junit.runners.model.FrameworkMethod;
+import org.junit.runners.model.InitializationError;
/**
* Suite to run tests with different {@code gerrit.config} values.
- * <p>
- * For each {@link Config} method in the class and base classes, a new group of
- * tests is created with the {@link Parameter} field set to the config.
+ *
+ * <p>For each {@link Config} method in the class and base classes, a new group of tests is created
+ * with the {@link Parameter} field set to the config.
*
* <pre>
* {@literal @}RunWith(ConfigSuite.class)
@@ -72,40 +70,37 @@
* </pre>
*
* This creates a suite of tests with three groups:
+ *
* <ul>
- * <li><strong>default</strong>: {@code MyTest.myTest}</li>
- * <li><strong>firstConfig</strong>: {@code MyTest.myTest[firstConfig]}</li>
- * <li><strong>secondConfig</strong>: {@code MyTest.myTest[secondConfig]}</li>
+ * <li><strong>default</strong>: {@code MyTest.myTest}
+ * <li><strong>firstConfig</strong>: {@code MyTest.myTest[firstConfig]}
+ * <li><strong>secondConfig</strong>: {@code MyTest.myTest[secondConfig]}
* </ul>
*
- * Additionally, config values used by <strong>default</strong> can be set
- * in a method annotated with {@code @ConfigSuite.Default}.
- * <p>
- * The name of the config method corresponding to the currently-running test can
- * be stored in a field annotated with {@code @ConfigSuite.Name}.
+ * Additionally, config values used by <strong>default</strong> can be set in a method annotated
+ * with {@code @ConfigSuite.Default}.
+ *
+ * <p>The name of the config method corresponding to the currently-running test can be stored in a
+ * field annotated with {@code @ConfigSuite.Name}.
*/
public class ConfigSuite extends Suite {
private static final String DEFAULT = "default";
@Target({METHOD})
@Retention(RUNTIME)
- public static @interface Default {
- }
+ public static @interface Default {}
@Target({METHOD})
@Retention(RUNTIME)
- public static @interface Config {
- }
+ public static @interface Config {}
@Target({FIELD})
@Retention(RUNTIME)
- public static @interface Parameter {
- }
+ public static @interface Parameter {}
@Target({FIELD})
@Retention(RUNTIME)
- public static @interface Name {
- }
+ public static @interface Name {}
private static class ConfigRunner extends BlockJUnit4ClassRunner {
private final Method configMethod;
@@ -113,8 +108,9 @@
private final Field nameField;
private final String name;
- private ConfigRunner(Class<?> clazz, Field parameterField, Field nameField,
- String name, Method configMethod) throws InitializationError {
+ private ConfigRunner(
+ Class<?> clazz, Field parameterField, Field nameField, String name, Method configMethod)
+ throws InitializationError {
super(clazz);
this.parameterField = parameterField;
this.nameField = nameField;
@@ -152,11 +148,9 @@
Field nameField = getOnlyField(clazz, Name.class);
List<Runner> result = Lists.newArrayListWithCapacity(configs.size() + 1);
try {
- result.add(new ConfigRunner(
- clazz, parameterField, nameField, null, defaultConfig));
+ result.add(new ConfigRunner(clazz, parameterField, nameField, null, defaultConfig));
for (Method m : configs) {
- result.add(new ConfigRunner(
- clazz, parameterField, nameField, m.getName(), m));
+ result.add(new ConfigRunner(clazz, parameterField, nameField, m.getName(), m));
}
return result;
} catch (InitializationError e) {
@@ -173,9 +167,11 @@
for (Method m : clazz.getMethods()) {
Default ann = m.getAnnotation(Default.class);
if (ann != null) {
- checkArgument(result == null,
+ checkArgument(
+ result == null,
"Multiple methods annotated with @ConfigSuite.Method: %s, %s",
- result, m);
+ result,
+ m);
result = m;
}
}
@@ -187,8 +183,8 @@
for (Method m : clazz.getMethods()) {
Config ann = m.getAnnotation(Config.class);
if (ann != null) {
- checkArgument(!m.getName().equals(DEFAULT),
- "@ConfigSuite.Config cannot be named %s", DEFAULT);
+ checkArgument(
+ !m.getName().equals(DEFAULT), "@ConfigSuite.Config cannot be named %s", DEFAULT);
result.add(m);
}
}
@@ -201,30 +197,29 @@
}
checkArgument(
org.eclipse.jgit.lib.Config.class.isAssignableFrom(m.getReturnType()),
- "%s must return Config", m);
- checkArgument((m.getModifiers() & Modifier.STATIC) != 0,
- "%s must be static", m);
- checkArgument(m.getParameterTypes().length == 0,
- "%s must take no parameters", m);
+ "%s must return Config",
+ m);
+ checkArgument((m.getModifiers() & Modifier.STATIC) != 0, "%s must be static", m);
+ checkArgument(m.getParameterTypes().length == 0, "%s must take no parameters", m);
try {
return (org.eclipse.jgit.lib.Config) m.invoke(null);
- } catch (IllegalAccessException | IllegalArgumentException
- | InvocationTargetException e) {
+ } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
throw new IllegalArgumentException(e);
}
}
- private static Field getOnlyField(Class<?> clazz,
- Class<? extends Annotation> ann) {
+ private static Field getOnlyField(Class<?> clazz, Class<? extends Annotation> ann) {
List<Field> fields = Lists.newArrayListWithExpectedSize(1);
for (Field f : clazz.getFields()) {
if (f.getAnnotation(ann) != null) {
fields.add(f);
}
}
- checkArgument(fields.size() <= 1,
+ checkArgument(
+ fields.size() <= 1,
"expected 1 @ConfigSuite.%s field, found: %s",
- ann.getSimpleName(), fields);
+ ann.getSimpleName(),
+ fields);
return Iterables.getFirst(fields, null);
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/testutil/FakeAccountCache.java b/gerrit-server/src/test/java/com/google/gerrit/testutil/FakeAccountCache.java
index 76f24df..d495c77 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/testutil/FakeAccountCache.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/testutil/FakeAccountCache.java
@@ -23,7 +23,6 @@
import com.google.gerrit.server.account.AccountState;
import com.google.gerrit.server.account.WatchConfig.NotifyType;
import com.google.gerrit.server.account.WatchConfig.ProjectWatchKey;
-
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
@@ -82,8 +81,10 @@
}
private static AccountState newState(Account account) {
- return new AccountState(account, ImmutableSet.<AccountGroup.UUID> of(),
- ImmutableSet.<AccountExternalId> of(),
+ return new AccountState(
+ account,
+ ImmutableSet.<AccountGroup.UUID>of(),
+ ImmutableSet.<AccountExternalId>of(),
new HashMap<ProjectWatchKey, Set<NotifyType>>());
}
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/testutil/FakeEmailSender.java b/gerrit-server/src/test/java/com/google/gerrit/testutil/FakeEmailSender.java
index 875d43f..5d40187 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/testutil/FakeEmailSender.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/testutil/FakeEmailSender.java
@@ -27,29 +27,26 @@
import com.google.inject.AbstractModule;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* Email sender implementation that records messages in memory.
- * <p>
- * This class is mostly threadsafe. The only exception is that not all {@link
- * EmailHeader} subclasses are immutable. In particular, if a caller holds a
- * reference to an {@code AddressList} and mutates it after sending, the message
- * returned by {@link #getMessages()} may or may not reflect mutations.
+ *
+ * <p>This class is mostly threadsafe. The only exception is that not all {@link EmailHeader}
+ * subclasses are immutable. In particular, if a caller holds a reference to an {@code AddressList}
+ * and mutates it after sending, the message returned by {@link #getMessages()} may or may not
+ * reflect mutations.
*/
@Singleton
public class FakeEmailSender implements EmailSender {
- private static final Logger log =
- LoggerFactory.getLogger(FakeEmailSender.class);
+ private static final Logger log = LoggerFactory.getLogger(FakeEmailSender.class);
public static class Module extends AbstractModule {
@Override
@@ -60,15 +57,18 @@
@AutoValue
public abstract static class Message {
- private static Message create(Address from, Collection<Address> rcpt,
- Map<String, EmailHeader> headers, String body) {
- return new AutoValue_FakeEmailSender_Message(from,
- ImmutableList.copyOf(rcpt), ImmutableMap.copyOf(headers), body);
+ private static Message create(
+ Address from, Collection<Address> rcpt, Map<String, EmailHeader> headers, String body) {
+ return new AutoValue_FakeEmailSender_Message(
+ from, ImmutableList.copyOf(rcpt), ImmutableMap.copyOf(headers), body);
}
public abstract Address from();
+
public abstract ImmutableList<Address> rcpt();
+
public abstract ImmutableMap<String, EmailHeader> headers();
+
public abstract String body();
}
@@ -92,8 +92,9 @@
}
@Override
- public void send(Address from, Collection<Address> rcpt,
- Map<String, EmailHeader> headers, String body) throws EmailException {
+ public void send(
+ Address from, Collection<Address> rcpt, Map<String, EmailHeader> headers, String body)
+ throws EmailException {
messages.add(Message.create(from, rcpt, headers, body));
}
@@ -116,8 +117,7 @@
final String typeFooter = "\nGerrit-MessageType: " + type + "\n";
return getMessages()
.stream()
- .filter(in -> in.body().contains(idFooter)
- && in.body().contains(typeFooter))
+ .filter(in -> in.body().contains(idFooter) && in.body().contains(typeFooter))
.collect(toList());
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/testutil/GerritBaseTests.java b/gerrit-server/src/test/java/com/google/gerrit/testutil/GerritBaseTests.java
index 3edc9f4..4f08c9e 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/testutil/GerritBaseTests.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/testutil/GerritBaseTests.java
@@ -16,7 +16,6 @@
import com.google.gwtorm.client.KeyUtil;
import com.google.gwtorm.server.StandardKeyEncoder;
-
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.rules.ExpectedException;
@@ -27,6 +26,5 @@
KeyUtil.setEncoderImpl(new StandardKeyEncoder());
}
- @Rule
- public ExpectedException exception = ExpectedException.none();
+ @Rule public ExpectedException exception = ExpectedException.none();
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/testutil/GerritServerTests.java b/gerrit-server/src/test/java/com/google/gerrit/testutil/GerritServerTests.java
index 797f1cb..038baac 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/testutil/GerritServerTests.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/testutil/GerritServerTests.java
@@ -23,36 +23,34 @@
@RunWith(ConfigSuite.class)
public class GerritServerTests extends GerritBaseTests {
- @ConfigSuite.Parameter
- public Config config;
+ @ConfigSuite.Parameter public Config config;
- @ConfigSuite.Name
- private String configName;
+ @ConfigSuite.Name private String configName;
protected TestNotesMigration notesMigration;
@Rule
- public TestRule testRunner = new TestRule() {
- @Override
- public Statement apply(final Statement base, final Description description) {
- return new Statement() {
+ public TestRule testRunner =
+ new TestRule() {
@Override
- public void evaluate() throws Throwable {
- beforeTest();
- try {
- base.evaluate();
- } finally {
- afterTest();
- }
+ public Statement apply(final Statement base, final Description description) {
+ return new Statement() {
+ @Override
+ public void evaluate() throws Throwable {
+ beforeTest();
+ try {
+ base.evaluate();
+ } finally {
+ afterTest();
+ }
+ }
+ };
}
};
- }
- };
public void beforeTest() throws Exception {
notesMigration = new TestNotesMigration().setFromEnv();
}
- public void afterTest() {
- }
+ public void afterTest() {}
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/testutil/InMemoryDatabase.java b/gerrit-server/src/test/java/com/google/gerrit/testutil/InMemoryDatabase.java
index ae0a23a..9a41a9c 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/testutil/InMemoryDatabase.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/testutil/InMemoryDatabase.java
@@ -34,23 +34,20 @@
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
-
-import org.eclipse.jgit.errors.ConfigInvalidException;
-
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
-
import javax.sql.DataSource;
+import org.eclipse.jgit.errors.ConfigInvalidException;
/**
* An in-memory test instance of {@link ReviewDb} database.
- * <p>
- * Test classes should create one instance of this class for each unique test
- * database they want to use. When the tests needing this instance are complete,
- * ensure that {@link #drop(InMemoryDatabase)} is called to free the resources so
- * the JVM running the unit tests doesn't run out of heap space.
+ *
+ * <p>Test classes should create one instance of this class for each unique test database they want
+ * to use. When the tests needing this instance are complete, ensure that {@link
+ * #drop(InMemoryDatabase)} is called to free the resources so the JVM running the unit tests
+ * doesn't run out of heap space.
*/
public class InMemoryDatabase implements SchemaFactory<ReviewDb> {
public static InMemoryDatabase newDatabase(LifecycleManager lifecycle) {
@@ -78,36 +75,36 @@
private final SchemaCreator schemaCreator;
private final SingleVersionListener singleVersionListener;
-
private Connection openHandle;
private Database<ReviewDb> database;
private boolean created;
@Inject
InMemoryDatabase(Injector injector) throws OrmException {
- Injector childInjector = injector.createChildInjector(new AbstractModule() {
- @Override
- protected void configure() {
- switch (IndexModule.getIndexType(injector)) {
- case LUCENE:
- install(new LuceneIndexModuleOnInit());
- break;
- case ELASTICSEARCH:
- install(new ElasticIndexModuleOnInit());
- break;
- default:
- throw new IllegalStateException("unsupported index.type");
- }
- }
- });
+ Injector childInjector =
+ injector.createChildInjector(
+ new AbstractModule() {
+ @Override
+ protected void configure() {
+ switch (IndexModule.getIndexType(injector)) {
+ case LUCENE:
+ install(new LuceneIndexModuleOnInit());
+ break;
+ case ELASTICSEARCH:
+ install(new ElasticIndexModuleOnInit());
+ break;
+ default:
+ throw new IllegalStateException("unsupported index.type");
+ }
+ }
+ });
this.schemaCreator = childInjector.getInstance(SchemaCreator.class);
- this.singleVersionListener =
- childInjector.getInstance(SingleVersionListener.class);
+ this.singleVersionListener = childInjector.getInstance(SingleVersionListener.class);
initDatabase();
}
- InMemoryDatabase(SchemaCreator schemaCreator,
- SingleVersionListener singleVersionListener) throws OrmException {
+ InMemoryDatabase(SchemaCreator schemaCreator, SingleVersionListener singleVersionListener)
+ throws OrmException {
this.schemaCreator = schemaCreator;
this.singleVersionListener = singleVersionListener;
initDatabase();
@@ -184,7 +181,6 @@
}
public void assertSchemaVersion() throws OrmException {
- assertThat(getSchemaVersion().versionNbr)
- .isEqualTo(SchemaVersion.getBinaryVersion());
+ assertThat(getSchemaVersion().versionNbr).isEqualTo(SchemaVersion.getBinaryVersion());
}
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/testutil/InMemoryModule.java b/gerrit-server/src/test/java/com/google/gerrit/testutil/InMemoryModule.java
index 254c7e7..9350252 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/testutil/InMemoryModule.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/testutil/InMemoryModule.java
@@ -78,10 +78,6 @@
import com.google.inject.TypeLiteral;
import com.google.inject.servlet.RequestScoped;
import com.google.inject.util.Providers;
-
-import org.eclipse.jgit.lib.Config;
-import org.eclipse.jgit.lib.PersonIdent;
-
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.file.Path;
@@ -89,6 +85,8 @@
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
+import org.eclipse.jgit.lib.Config;
+import org.eclipse.jgit.lib.PersonIdent;
public class InMemoryModule extends FactoryModule {
public static Config newDefaultConfig() {
@@ -139,13 +137,14 @@
// For simplicity, don't create child injectors, just use this one to get a
// few required modules.
- Injector cfgInjector = Guice.createInjector(new AbstractModule() {
- @Override
- protected void configure() {
- bind(Config.class).annotatedWith(GerritServerConfig.class)
- .toInstance(cfg);
- }
- });
+ Injector cfgInjector =
+ Guice.createInjector(
+ new AbstractModule() {
+ @Override
+ protected void configure() {
+ bind(Config.class).annotatedWith(GerritServerConfig.class).toInstance(cfg);
+ }
+ });
bind(MetricMaker.class).to(DisabledMetricMaker.class);
install(cfgInjector.getInstance(GerritGlobalModule.class));
install(new SearchingChangeCacheImpl.Module());
@@ -156,58 +155,51 @@
// TODO(dborowitz): Use jimfs.
bind(Path.class).annotatedWith(SitePath.class).toInstance(Paths.get("."));
bind(Config.class).annotatedWith(GerritServerConfig.class).toInstance(cfg);
- bind(GerritOptions.class)
- .toInstance(new GerritOptions(cfg, false, false, false));
+ bind(GerritOptions.class).toInstance(new GerritOptions(cfg, false, false, false));
bind(PersonIdent.class)
.annotatedWith(GerritPersonIdent.class)
.toProvider(GerritPersonIdentProvider.class);
bind(String.class)
.annotatedWith(AnonymousCowardName.class)
.toProvider(AnonymousCowardNameProvider.class);
- bind(String.class)
- .annotatedWith(GerritServerId.class)
- .toInstance("gerrit");
- bind(AllProjectsName.class)
- .toProvider(AllProjectsNameProvider.class);
- bind(AllUsersName.class)
- .toProvider(AllUsersNameProvider.class);
- bind(GitRepositoryManager.class)
- .to(InMemoryRepositoryManager.class);
+ bind(String.class).annotatedWith(GerritServerId.class).toInstance("gerrit");
+ bind(AllProjectsName.class).toProvider(AllProjectsNameProvider.class);
+ bind(AllUsersName.class).toProvider(AllUsersNameProvider.class);
+ bind(GitRepositoryManager.class).to(InMemoryRepositoryManager.class);
bind(InMemoryRepositoryManager.class).in(SINGLETON);
- bind(TrackingFooters.class).toProvider(TrackingFootersProvider.class)
- .in(SINGLETON);
+ bind(TrackingFooters.class).toProvider(TrackingFootersProvider.class).in(SINGLETON);
bind(NotesMigration.class).toInstance(notesMigration);
bind(ListeningExecutorService.class)
.annotatedWith(ChangeUpdateExecutor.class)
.toInstance(MoreExecutors.newDirectExecutorService());
- bind(DataSourceType.class)
- .to(InMemoryH2Type.class);
- bind(new TypeLiteral<SchemaFactory<ReviewDb>>() {})
- .to(InMemoryDatabase.class);
+ bind(DataSourceType.class).to(InMemoryH2Type.class);
+ bind(new TypeLiteral<SchemaFactory<ReviewDb>>() {}).to(InMemoryDatabase.class);
bind(ChangeBundleReader.class).to(GwtormChangeBundleReader.class);
bind(SecureStore.class).to(DefaultSecureStore.class);
install(NoSshKeyCache.module());
- install(new CanonicalWebUrlModule() {
- @Override
- protected Class<? extends Provider<String>> provider() {
- return CanonicalWebUrlProvider.class;
- }
- });
+ install(
+ new CanonicalWebUrlModule() {
+ @Override
+ protected Class<? extends Provider<String>> provider() {
+ return CanonicalWebUrlProvider.class;
+ }
+ });
//Replacement of DiffExecutorModule to not use thread pool in the tests
- install(new AbstractModule() {
- @Override
- protected void configure() {
- }
- @Provides
- @Singleton
- @DiffExecutor
- public ExecutorService createDiffExecutor() {
- return MoreExecutors.newDirectExecutorService();
- }
- });
+ install(
+ new AbstractModule() {
+ @Override
+ protected void configure() {}
+
+ @Provides
+ @Singleton
+ @DiffExecutor
+ public ExecutorService createDiffExecutor() {
+ return MoreExecutors.newDirectExecutorService();
+ }
+ });
install(new DefaultCacheFactory.Module());
install(new FakeEmailSender.Module());
install(new SignedTokenEmailTokenVerifier.Module());
@@ -233,8 +225,7 @@
install(elasticIndexModule());
break;
default:
- throw new ProvisionException(
- "index type unsupported in tests: " + indexType);
+ throw new ProvisionException("index type unsupported in tests: " + indexType);
}
}
}
@@ -248,8 +239,9 @@
@Provides
@Singleton
- InMemoryDatabase getInMemoryDatabase(SchemaCreator schemaCreator,
- SingleVersionListener singleVersionListener) throws OrmException {
+ InMemoryDatabase getInMemoryDatabase(
+ SchemaCreator schemaCreator, SingleVersionListener singleVersionListener)
+ throws OrmException {
return new InMemoryDatabase(schemaCreator, singleVersionListener);
}
@@ -269,11 +261,13 @@
singleVersions.put(ChangeSchemaDefinitions.INSTANCE.getName(), version);
}
Class<?> clazz = Class.forName(moduleClassName);
- Method m = clazz.getMethod(
- "singleVersionWithExplicitVersions", Map.class, int.class);
+ Method m = clazz.getMethod("singleVersionWithExplicitVersions", Map.class, int.class);
return (Module) m.invoke(null, singleVersions, 0);
- } catch (ClassNotFoundException | SecurityException | NoSuchMethodException
- | IllegalArgumentException | IllegalAccessException
+ } catch (ClassNotFoundException
+ | SecurityException
+ | NoSuchMethodException
+ | IllegalArgumentException
+ | IllegalAccessException
| InvocationTargetException e) {
e.printStackTrace();
ProvisionException pe = new ProvisionException(e.getMessage());
diff --git a/gerrit-server/src/test/java/com/google/gerrit/testutil/InMemoryRepositoryManager.java b/gerrit-server/src/test/java/com/google/gerrit/testutil/InMemoryRepositoryManager.java
index b6e59dd..4826d9e 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/testutil/InMemoryRepositoryManager.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/testutil/InMemoryRepositoryManager.java
@@ -19,16 +19,14 @@
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.server.git.GitRepositoryManager;
import com.google.gerrit.server.git.RepositoryCaseMismatchException;
-
+import java.util.HashMap;
+import java.util.Map;
+import java.util.SortedSet;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
import org.eclipse.jgit.internal.storage.dfs.DfsRepository;
import org.eclipse.jgit.internal.storage.dfs.DfsRepositoryDescription;
import org.eclipse.jgit.internal.storage.dfs.InMemoryRepository;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.SortedSet;
-
/** Repository manager that uses in-memory repositories. */
public class InMemoryRepositoryManager implements GitRepositoryManager {
public static InMemoryRepository newRepository(Project.NameKey name) {
@@ -77,8 +75,7 @@
private Map<String, Repo> repos = new HashMap<>();
@Override
- public synchronized Repo openRepository(Project.NameKey name)
- throws RepositoryNotFoundException {
+ public synchronized Repo openRepository(Project.NameKey name) throws RepositoryNotFoundException {
return get(name);
}
@@ -111,8 +108,7 @@
repos.remove(normalize(name));
}
- private synchronized Repo get(Project.NameKey name)
- throws RepositoryNotFoundException {
+ private synchronized Repo get(Project.NameKey name) throws RepositoryNotFoundException {
Repo repo = repos.get(normalize(name));
if (repo != null) {
repo.incrementOpen();
diff --git a/gerrit-server/src/test/java/com/google/gerrit/testutil/NoteDbChecker.java b/gerrit-server/src/test/java/com/google/gerrit/testutil/NoteDbChecker.java
index ae0e515..aeaaa47 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/testutil/NoteDbChecker.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/testutil/NoteDbChecker.java
@@ -36,18 +36,16 @@
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
-
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.stream.Stream;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
import org.eclipse.jgit.lib.Repository;
import org.junit.runner.Description;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.stream.Stream;
-
@Singleton
public class NoteDbChecker {
static final Logger log = LoggerFactory.getLogger(NoteDbChecker.class);
@@ -61,7 +59,8 @@
private final CommentsUtil commentsUtil;
@Inject
- NoteDbChecker(Provider<ReviewDb> dbProvider,
+ NoteDbChecker(
+ Provider<ReviewDb> dbProvider,
GitRepositoryManager repoManager,
TestNotesMigration notesMigration,
ChangeBundleReader bundleReader,
@@ -78,16 +77,14 @@
}
public void rebuildAndCheckAllChanges() throws Exception {
- rebuildAndCheckChanges(
- getUnwrappedDb().changes().all().toList().stream().map(Change::getId));
+ rebuildAndCheckChanges(getUnwrappedDb().changes().all().toList().stream().map(Change::getId));
}
public void rebuildAndCheckChanges(Change.Id... changeIds) throws Exception {
rebuildAndCheckChanges(Arrays.stream(changeIds));
}
- private void rebuildAndCheckChanges(Stream<Change.Id> changeIds)
- throws Exception {
+ private void rebuildAndCheckChanges(Stream<Change.Id> changeIds) throws Exception {
ReviewDb db = getUnwrappedDb();
List<ChangeBundle> allExpected = readExpected(changeIds);
@@ -118,8 +115,7 @@
checkActual(readExpected(Arrays.stream(changeIds)), new ArrayList<>());
}
- public void assertNoChangeRef(Project.NameKey project, Change.Id changeId)
- throws Exception {
+ public void assertNoChangeRef(Project.NameKey project, Change.Id changeId) throws Exception {
try (Repository repo = repoManager.openRepository(project)) {
assertThat(repo.exactRef(RefNames.changeMetaRef(changeId))).isNull();
}
@@ -127,9 +123,7 @@
public void assertNoReviewDbChanges(Description desc) throws Exception {
ReviewDb db = getUnwrappedDb();
- assertThat(db.changes().all().toList())
- .named("Changes in " + desc.getTestClass())
- .isEmpty();
+ assertThat(db.changes().all().toList()).named("Changes in " + desc.getTestClass()).isEmpty();
assertThat(db.changeMessages().all().toList())
.named("ChangeMessages in " + desc.getTestClass())
.isEmpty();
@@ -144,13 +138,14 @@
.isEmpty();
}
- private List<ChangeBundle> readExpected(Stream<Change.Id> changeIds)
- throws Exception {
+ private List<ChangeBundle> readExpected(Stream<Change.Id> changeIds) throws Exception {
boolean old = notesMigration.readChanges();
try {
notesMigration.setReadChanges(false);
- return changeIds.sorted(comparing(IntKey::get))
- .map(this::readBundleUnchecked).collect(toList());
+ return changeIds
+ .sorted(comparing(IntKey::get))
+ .map(this::readBundleUnchecked)
+ .collect(toList());
} finally {
notesMigration.setReadChanges(old);
}
@@ -164,8 +159,7 @@
}
}
- private void checkActual(List<ChangeBundle> allExpected, List<String> msgs)
- throws Exception {
+ private void checkActual(List<ChangeBundle> allExpected, List<String> msgs) throws Exception {
ReviewDb db = getUnwrappedDb();
boolean oldRead = notesMigration.readChanges();
boolean oldWrite = notesMigration.writeChanges();
@@ -176,8 +170,9 @@
Change c = expected.getChange();
ChangeBundle actual;
try {
- actual = ChangeBundle.fromNotes(
- commentsUtil, notesFactory.create(db, c.getProject(), c.getId()));
+ actual =
+ ChangeBundle.fromNotes(
+ commentsUtil, notesFactory.create(db, c.getProject(), c.getId()));
} catch (Throwable t) {
String msg = "Error converting change: " + c;
msgs.add(msg);
@@ -190,8 +185,7 @@
msgs.addAll(diff);
msgs.add("");
} else {
- System.err.println(
- "NoteDb conversion of change " + c.getId() + " successful");
+ System.err.println("NoteDb conversion of change " + c.getId() + " successful");
}
}
} finally {
@@ -205,6 +199,6 @@
private ReviewDb getUnwrappedDb() {
ReviewDb db = dbProvider.get();
- return ReviewDbUtil.unwrapDb(db);
+ return ReviewDbUtil.unwrapDb(db);
}
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/testutil/NoteDbMode.java b/gerrit-server/src/test/java/com/google/gerrit/testutil/NoteDbMode.java
index 7db76fd..093812f 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/testutil/NoteDbMode.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/testutil/NoteDbMode.java
@@ -33,8 +33,8 @@
PRIMARY,
/**
- * Run tests with NoteDb disabled, then convert ReviewDb to NoteDb and check
- * that the results match.
+ * Run tests with NoteDb disabled, then convert ReviewDb to NoteDb and check that the results
+ * match.
*/
CHECK;
@@ -52,11 +52,14 @@
value = value.toUpperCase().replace("-", "_");
NoteDbMode mode = Enums.getIfPresent(NoteDbMode.class, value).orNull();
if (!Strings.isNullOrEmpty(System.getenv(ENV_VAR))) {
- checkArgument(mode != null, "Invalid value for env variable %s: %s",
- ENV_VAR, System.getenv(ENV_VAR));
+ checkArgument(
+ mode != null, "Invalid value for env variable %s: %s", ENV_VAR, System.getenv(ENV_VAR));
} else {
- checkArgument(mode != null, "Invalid value for system property %s: %s",
- SYS_PROP, System.getProperty(SYS_PROP));
+ checkArgument(
+ mode != null,
+ "Invalid value for system property %s: %s",
+ SYS_PROP,
+ System.getProperty(SYS_PROP));
}
return mode;
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/testutil/SshMode.java b/gerrit-server/src/test/java/com/google/gerrit/testutil/SshMode.java
index bc4e4e9..9320331 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/testutil/SshMode.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/testutil/SshMode.java
@@ -40,11 +40,14 @@
value = value.toUpperCase();
SshMode mode = Enums.getIfPresent(SshMode.class, value).orNull();
if (!Strings.isNullOrEmpty(System.getenv(ENV_VAR))) {
- checkArgument(mode != null, "Invalid value for env variable %s: %s",
- ENV_VAR, System.getenv(ENV_VAR));
+ checkArgument(
+ mode != null, "Invalid value for env variable %s: %s", ENV_VAR, System.getenv(ENV_VAR));
} else {
- checkArgument(mode != null, "Invalid value for system property %s: %s",
- SYS_PROP, System.getProperty(SYS_PROP));
+ checkArgument(
+ mode != null,
+ "Invalid value for system property %s: %s",
+ SYS_PROP,
+ System.getProperty(SYS_PROP));
}
return mode;
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/testutil/TempFileUtil.java b/gerrit-server/src/test/java/com/google/gerrit/testutil/TempFileUtil.java
index 72c2b5a..eb50b47 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/testutil/TempFileUtil.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/testutil/TempFileUtil.java
@@ -62,6 +62,5 @@
}
}
- private TempFileUtil() {
- }
+ private TempFileUtil() {}
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/testutil/TestChanges.java b/gerrit-server/src/test/java/com/google/gerrit/testutil/TestChanges.java
index 594ce82..459bccd 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/testutil/TestChanges.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/testutil/TestChanges.java
@@ -36,7 +36,8 @@
import com.google.gerrit.server.project.ChangeControl;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Injector;
-
+import java.util.TimeZone;
+import java.util.concurrent.atomic.AtomicInteger;
import org.easymock.EasyMock;
import org.eclipse.jgit.junit.TestRepository;
import org.eclipse.jgit.lib.ObjectId;
@@ -44,12 +45,9 @@
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
-import java.util.TimeZone;
-import java.util.concurrent.atomic.AtomicInteger;
-
/**
- * Utility functions to create and manipulate Change, ChangeUpdate, and
- * ChangeControl objects for testing.
+ * Utility functions to create and manipulate Change, ChangeUpdate, and ChangeControl objects for
+ * testing.
*/
public class TestChanges {
private static final AtomicInteger nextChangeId = new AtomicInteger(1);
@@ -58,26 +56,24 @@
return newChange(project, userId, nextChangeId.getAndIncrement());
}
- public static Change newChange(Project.NameKey project, Account.Id userId,
- int id) {
+ public static Change newChange(Project.NameKey project, Account.Id userId, int id) {
Change.Id changeId = new Change.Id(id);
- Change c = new Change(
- new Change.Key("Iabcd1234abcd1234abcd1234abcd1234abcd1234"),
- changeId,
- userId,
- new Branch.NameKey(project, "master"),
- TimeUtil.nowTs());
+ Change c =
+ new Change(
+ new Change.Key("Iabcd1234abcd1234abcd1234abcd1234abcd1234"),
+ changeId,
+ userId,
+ new Branch.NameKey(project, "master"),
+ TimeUtil.nowTs());
incrementPatchSet(c);
return c;
}
- public static PatchSet newPatchSet(PatchSet.Id id, ObjectId revision,
- Account.Id userId) {
+ public static PatchSet newPatchSet(PatchSet.Id id, ObjectId revision, Account.Id userId) {
return newPatchSet(id, revision.name(), userId);
}
- public static PatchSet newPatchSet(PatchSet.Id id, String revision,
- Account.Id userId) {
+ public static PatchSet newPatchSet(PatchSet.Id id, String revision, Account.Id userId) {
PatchSet ps = new PatchSet(id);
ps.setRevision(new RevId(revision));
ps.setUploader(userId);
@@ -85,25 +81,26 @@
return ps;
}
- public static ChangeUpdate newUpdate(Injector injector,
- Change c, final CurrentUser user) throws Exception {
- injector = injector.createChildInjector(new FactoryModule() {
- @Override
- public void configure() {
- bind(CurrentUser.class).toInstance(user);
- }
- });
- ChangeUpdate update = injector.getInstance(ChangeUpdate.Factory.class)
- .create(
- stubChangeControl(
- injector.getInstance(AbstractChangeNotes.Args.class),
- c,
- user),
- TimeUtil.nowTs(), Ordering.<String> natural());
+ public static ChangeUpdate newUpdate(Injector injector, Change c, final CurrentUser user)
+ throws Exception {
+ injector =
+ injector.createChildInjector(
+ new FactoryModule() {
+ @Override
+ public void configure() {
+ bind(CurrentUser.class).toInstance(user);
+ }
+ });
+ ChangeUpdate update =
+ injector
+ .getInstance(ChangeUpdate.Factory.class)
+ .create(
+ stubChangeControl(injector.getInstance(AbstractChangeNotes.Args.class), c, user),
+ TimeUtil.nowTs(),
+ Ordering.<String>natural());
ChangeNotes notes = update.getNotes();
- boolean hasPatchSets = notes.getPatchSets() != null
- && !notes.getPatchSets().isEmpty();
+ boolean hasPatchSets = notes.getPatchSets() != null && !notes.getPatchSets().isEmpty();
NotesMigration migration = injector.getInstance(NotesMigration.class);
if (hasPatchSets || !migration.readChanges()) {
return update;
@@ -111,16 +108,16 @@
// Change doesn't exist yet. NoteDb requires that there be a commit for the
// first patch set, so create one.
- GitRepositoryManager repoManager =
- injector.getInstance(GitRepositoryManager.class);
+ GitRepositoryManager repoManager = injector.getInstance(GitRepositoryManager.class);
try (Repository repo = repoManager.openRepository(c.getProject())) {
TestRepository<Repository> tr = new TestRepository<>(repo);
- PersonIdent ident = user.asIdentifiedUser()
- .newCommitterIdent(update.getWhen(), TimeZone.getDefault());
- TestRepository<Repository>.CommitBuilder cb = tr.commit()
- .author(ident)
- .committer(ident)
- .message(firstNonNull(c.getSubject(), "Test change"));
+ PersonIdent ident =
+ user.asIdentifiedUser().newCommitterIdent(update.getWhen(), TimeZone.getDefault());
+ TestRepository<Repository>.CommitBuilder cb =
+ tr.commit()
+ .author(ident)
+ .committer(ident)
+ .message(firstNonNull(c.getSubject(), "Test change"));
Ref parent = repo.exactRef(c.getDest().get());
if (parent != null) {
cb.parent(tr.getRevWalk().parseCommit(parent.getObjectId()));
@@ -133,8 +130,7 @@
}
private static ChangeControl stubChangeControl(
- AbstractChangeNotes.Args args,
- Change c, CurrentUser user) throws OrmException {
+ AbstractChangeNotes.Args args, Change c, CurrentUser user) throws OrmException {
ChangeControl ctl = EasyMock.createMock(ChangeControl.class);
expect(ctl.getChange()).andStubReturn(c);
expect(ctl.getProject()).andStubReturn(new Project(c.getProject()));
@@ -148,8 +144,8 @@
public static void incrementPatchSet(Change change) {
PatchSet.Id curr = change.currentPatchSetId();
- PatchSetInfo ps = new PatchSetInfo(new PatchSet.Id(
- change.getId(), curr != null ? curr.get() + 1 : 1));
+ PatchSetInfo ps =
+ new PatchSetInfo(new PatchSet.Id(change.getId(), curr != null ? curr.get() + 1 : 1));
ps.setSubject("Change subject");
change.setCurrentPatchSet(ps);
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/testutil/TestNotesMigration.java b/gerrit-server/src/test/java/com/google/gerrit/testutil/TestNotesMigration.java
index b11b2cd..2c373d5 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/testutil/TestNotesMigration.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/testutil/TestNotesMigration.java
@@ -25,8 +25,7 @@
public class TestNotesMigration extends NotesMigration {
private volatile boolean readChanges;
private volatile boolean writeChanges;
- private volatile PrimaryStorage changePrimaryStorage =
- PrimaryStorage.REVIEW_DB;
+ private volatile PrimaryStorage changePrimaryStorage = PrimaryStorage.REVIEW_DB;
private volatile boolean failOnLoad;
@Override
@@ -78,8 +77,7 @@
return this;
}
- public TestNotesMigration setChangePrimaryStorage(
- PrimaryStorage changePrimaryStorage) {
+ public TestNotesMigration setChangePrimaryStorage(PrimaryStorage changePrimaryStorage) {
this.changePrimaryStorage = checkNotNull(changePrimaryStorage);
return this;
}
diff --git a/gerrit-server/src/test/java/com/google/gerrit/testutil/TestTimeUtil.java b/gerrit-server/src/test/java/com/google/gerrit/testutil/TestTimeUtil.java
index 32f0af8..dd44cb9ae 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/testutil/TestTimeUtil.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/testutil/TestTimeUtil.java
@@ -17,15 +17,14 @@
import static com.google.common.base.Preconditions.checkState;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
+import java.sql.Timestamp;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
import org.joda.time.DateTime;
import org.joda.time.DateTimeUtils;
import org.joda.time.DateTimeUtils.MillisProvider;
import org.joda.time.DateTimeZone;
-import java.sql.Timestamp;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicLong;
-
/** Static utility methods for dealing with dates and times in tests. */
public class TestTimeUtil {
public static final DateTime START =
@@ -36,14 +35,13 @@
/**
* Reset the clock to a known start point, then set the clock step.
- * <p>
- * The clock is initially set to 2009/09/30 17:00:00 -0400.
+ *
+ * <p>The clock is initially set to 2009/09/30 17:00:00 -0400.
*
* @param clockStep amount to increment clock by on each lookup.
* @param clockStepUnit time unit for {@code clockStep}.
*/
- public static synchronized void resetWithClockStep(
- long clockStep, TimeUnit clockStepUnit) {
+ public static synchronized void resetWithClockStep(long clockStep, TimeUnit clockStepUnit) {
// Set an arbitrary start point so tests are more repeatable.
clockMs = new AtomicLong(START.getMillis());
setClockStep(clockStep, clockStepUnit);
@@ -55,16 +53,16 @@
* @param clockStep amount to increment clock by on each lookup.
* @param clockStepUnit time unit for {@code clockStep}.
*/
- public static synchronized void setClockStep(
- long clockStep, TimeUnit clockStepUnit) {
+ public static synchronized void setClockStep(long clockStep, TimeUnit clockStepUnit) {
checkState(clockMs != null, "call resetWithClockStep first");
clockStepMs = MILLISECONDS.convert(clockStep, clockStepUnit);
- DateTimeUtils.setCurrentMillisProvider(new MillisProvider() {
- @Override
- public long getMillis() {
- return clockMs.getAndAdd(clockStepMs);
- }
- });
+ DateTimeUtils.setCurrentMillisProvider(
+ new MillisProvider() {
+ @Override
+ public long getMillis() {
+ return clockMs.getAndAdd(clockStepMs);
+ }
+ });
}
/**
@@ -83,8 +81,7 @@
* @param clockStep amount to increment clock by.
* @param clockStepUnit time unit for {@code clockStep}.
*/
- public static synchronized void incrementClock(
- long clockStep, TimeUnit clockStepUnit) {
+ public static synchronized void incrementClock(long clockStep, TimeUnit clockStepUnit) {
checkState(clockMs != null, "call resetWithClockStep first");
clockMs.addAndGet(clockStepUnit.toMillis(clockStep));
}
@@ -95,6 +92,5 @@
DateTimeUtils.setCurrentMillisSystem();
}
- private TestTimeUtil() {
- }
+ private TestTimeUtil() {}
}