Format all Java files with google-java-format Change-Id: Ie55d9209cf58d6c267e66b3cea103f6753acc222
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/AccountUtil.java b/src/main/java/com/googlesource/gerrit/plugins/importer/AccountUtil.java index 07e5d8f..b3f62de 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/AccountUtil.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/AccountUtil.java
@@ -37,14 +37,12 @@ import com.google.gwtorm.server.OrmException; import com.google.inject.Inject; import com.google.inject.Singleton; - -import org.eclipse.jgit.errors.ConfigInvalidException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.io.IOException; import java.util.List; import java.util.Objects; +import org.eclipse.jgit.errors.ConfigInvalidException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; @Singleton class AccountUtil { @@ -76,12 +74,13 @@ } Account.Id resolveUser(GerritApi api, AccountInfo acc) - throws NoSuchAccountException, IOException, OrmException, - RestApiException, ConfigInvalidException { + throws NoSuchAccountException, IOException, OrmException, RestApiException, + ConfigInvalidException { if (acc.username == null) { - throw new NoSuchAccountException(String.format( - "User %s <%s> (%s) doesn't have a username and cannot be looked up.", - acc.name, acc.email, acc._accountId)); + throw new NoSuchAccountException( + String.format( + "User %s <%s> (%s) doesn't have a username and cannot be looked up.", + acc.name, acc.email, acc._accountId)); } AccountState a = accountCache.getByUsername(acc.username); @@ -103,19 +102,19 @@ } } if (!Objects.equals(a.getAccount().getPreferredEmail(), acc.email)) { - log.warn(String.format( - "Email mismatch for user %s: expected %s but found %s", - acc.username, acc.email, a.getAccount().getPreferredEmail())); + log.warn( + String.format( + "Email mismatch for user %s: expected %s but found %s", + acc.username, acc.email, a.getAccount().getPreferredEmail())); } return a.getAccount().getId(); } - private Account.Id createAccountByLdapAndAddSshKeys(GerritApi api, - AccountInfo acc) throws NoSuchAccountException, IOException, OrmException, - RestApiException, ConfigInvalidException { + private Account.Id createAccountByLdapAndAddSshKeys(GerritApi api, AccountInfo acc) + throws NoSuchAccountException, IOException, OrmException, RestApiException, + ConfigInvalidException { if (!acc.username.matches(Account.USER_NAME_PATTERN)) { - throw new NoSuchAccountException(String.format("User %s not found", - acc.username)); + throw new NoSuchAccountException(String.format("User %s not found", acc.username)); } try { @@ -130,8 +129,7 @@ } private void addSshKeys(GerritApi api, AccountInfo acc) - throws BadRequestException, IOException, OrmException, - ConfigInvalidException { + throws BadRequestException, IOException, OrmException, ConfigInvalidException { List<SshKeyInfo> sshKeys = api.getSshKeys(acc.username); AccountState a = accountCache.getByUsername(acc.username); for (SshKeyInfo sshKeyInfo : sshKeys) { @@ -153,8 +151,7 @@ input.name = acc.name; AccountInfo accInfo = - createAccountFactory.create(username) - .apply(TopLevelResource.INSTANCE, input).value(); + createAccountFactory.create(username).apply(TopLevelResource.INSTANCE, input).value(); log.info(String.format("Local user '%s' created", username)); Account.Id userId = new Account.Id(accInfo._accountId);
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/AddApprovalsStep.java b/src/main/java/com/googlesource/gerrit/plugins/importer/AddApprovalsStep.java index b541966..51e5dcc 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/AddApprovalsStep.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/AddApprovalsStep.java
@@ -34,15 +34,13 @@ import com.google.gwtorm.server.OrmException; import com.google.inject.Inject; import com.google.inject.assistedinject.Assisted; - -import org.eclipse.jgit.errors.ConfigInvalidException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map.Entry; +import org.eclipse.jgit.errors.ConfigInvalidException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; class AddApprovalsStep { @@ -50,8 +48,7 @@ AddApprovalsStep create(Change change, ChangeInfo changeInfo, boolean resume); } - private static final Logger log = LoggerFactory - .getLogger(ReplayInlineCommentsStep.class); + private static final Logger log = LoggerFactory.getLogger(ReplayInlineCommentsStep.class); private final AccountUtil accountUtil; private final ChangeUpdate.Factory updateFactory; @@ -63,7 +60,8 @@ private final boolean resume; @Inject - public AddApprovalsStep(AccountUtil accountUtil, + public AddApprovalsStep( + AccountUtil accountUtil, ChangeUpdate.Factory updateFactory, ReviewDb db, IdentifiedUser.GenericFactory genericUserFactory, @@ -81,12 +79,11 @@ this.resume = resume; } - void add(GerritApi api) throws OrmException, NoSuchChangeException, - IOException, NoSuchAccountException, RestApiException, - ConfigInvalidException { + void add(GerritApi api) + throws OrmException, NoSuchChangeException, IOException, NoSuchAccountException, + RestApiException, ConfigInvalidException { if (resume) { - db.patchSetApprovals().delete( - db.patchSetApprovals().byChange(change.getId())); + db.patchSetApprovals().delete(db.patchSetApprovals().byChange(change.getId())); } List<PatchSetApproval> approvals = new ArrayList<>(); @@ -98,20 +95,25 @@ Account.Id user = accountUtil.resolveUser(api, a); ChangeControl ctrl = control(change, a); LabelType labelType = ctrl.getLabelTypes().byLabel(labelName); - if(labelType == null) { - log.warn(String.format("Label '%s' not found in target system." - + " This label was referenced by an approval provided from '%s'" - + " for change '%s'." - + " This approval will be skipped. In order to import this" - + " approval configure the missing label and resume the import" - + " with the force option." - , labelName, a.username, changeInfo.id)); + if (labelType == null) { + log.warn( + String.format( + "Label '%s' not found in target system." + + " This label was referenced by an approval provided from '%s'" + + " for change '%s'." + + " This approval will be skipped. In order to import this" + + " approval configure the missing label and resume the import" + + " with the force option.", + labelName, a.username, changeInfo.id)); continue; } short shortValue = a.value != null ? a.value.shortValue() : 0; - approvals.add(new PatchSetApproval(new PatchSetApproval.Key(change - .currentPatchSetId(), user, labelType.getLabelId()), shortValue, - MoreObjects.firstNonNull(a.date, TimeUtil.nowTs()))); + approvals.add( + new PatchSetApproval( + new PatchSetApproval.Key( + change.currentPatchSetId(), user, labelType.getLabelId()), + shortValue, + MoreObjects.firstNonNull(a.date, TimeUtil.nowTs()))); ChangeUpdate update = updateFactory.create(ctrl); if (shortValue != 0) { update.putApproval(labelName, shortValue); @@ -125,16 +127,13 @@ db.patchSetApprovals().insert(approvals); } - private ChangeControl control(Change change, AccountInfo acc) - throws NoSuchChangeException { + private ChangeControl control(Change change, AccountInfo acc) throws NoSuchChangeException { return control(change, new Account.Id(acc._accountId)); } - private ChangeControl control(Change change, Account.Id id) - throws NoSuchChangeException { + private ChangeControl control(Change change, Account.Id id) throws NoSuchChangeException { try { - return changeControlFactory.controlFor(db, change, - genericUserFactory.create(id)); + return changeControlFactory.controlFor(db, change, genericUserFactory.create(id)); } catch (OrmException e) { throw new NoSuchChangeException(change.getId()); }
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/AddHashtagsStep.java b/src/main/java/com/googlesource/gerrit/plugins/importer/AddHashtagsStep.java index 676c063..f2d241a 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/AddHashtagsStep.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/AddHashtagsStep.java
@@ -24,28 +24,25 @@ import com.google.gerrit.server.CurrentUser; import com.google.gerrit.server.change.ChangeTriplet; import com.google.gerrit.server.change.SetHashtagsOp; -import com.google.gerrit.server.update.BatchUpdate; -import com.google.gerrit.server.update.UpdateException; import com.google.gerrit.server.project.ChangeControl; import com.google.gerrit.server.project.NoSuchChangeException; +import com.google.gerrit.server.update.BatchUpdate; +import com.google.gerrit.server.update.UpdateException; import com.google.gwtorm.server.OrmException; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.assistedinject.Assisted; - +import java.util.HashSet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.HashSet; - class AddHashtagsStep { interface Factory { AddHashtagsStep create(Change change, ChangeInfo changeInfo, boolean resume); } - private static final Logger log = LoggerFactory - .getLogger(AddHashtagsStep.class); + private static final Logger log = LoggerFactory.getLogger(AddHashtagsStep.class); private final CurrentUser currentUser; private final ChangeControl.GenericFactory changeControlFactory; @@ -57,7 +54,8 @@ private final SetHashtagsOp.Factory hashtagsFactory; @Inject - AddHashtagsStep(CurrentUser currentUser, + AddHashtagsStep( + CurrentUser currentUser, ChangeControl.GenericFactory changeControlFactory, Provider<ReviewDb> db, BatchUpdate.Factory batchUpdateFactory, @@ -75,38 +73,40 @@ this.resume = resume; } - void add() throws IllegalArgumentException, OrmException, - NoSuchChangeException, UpdateException, RestApiException { - ChangeControl ctrl = - changeControlFactory.controlFor(db.get(), change, currentUser); + void add() + throws IllegalArgumentException, OrmException, NoSuchChangeException, UpdateException, + RestApiException { + ChangeControl ctrl = changeControlFactory.controlFor(db.get(), change, currentUser); try { if (resume) { HashtagsInput input = new HashtagsInput(); input.remove = ctrl.getNotes().load().getHashtags(); - try (BatchUpdate bu = batchUpdateFactory.create(db.get(), - change.getProject(), currentUser, TimeUtil.nowTs())) { - SetHashtagsOp op = hashtagsFactory.create(input); - bu.addOp(change.getId(), op); - bu.execute(); + try (BatchUpdate bu = + batchUpdateFactory.create( + db.get(), change.getProject(), currentUser, TimeUtil.nowTs())) { + SetHashtagsOp op = hashtagsFactory.create(input); + bu.addOp(change.getId(), op); + bu.execute(); } } HashtagsInput input = new HashtagsInput(); input.add = new HashSet<>(changeInfo.hashtags); - try (BatchUpdate bu = batchUpdateFactory.create(db.get(), - change.getProject(), currentUser, TimeUtil.nowTs())) { - SetHashtagsOp op = hashtagsFactory.create(input); - bu.addOp(change.getId(), op); - bu.execute(); + try (BatchUpdate bu = + batchUpdateFactory.create(db.get(), change.getProject(), currentUser, TimeUtil.nowTs())) { + SetHashtagsOp op = hashtagsFactory.create(input); + bu.addOp(change.getId(), op); + bu.execute(); } } catch (AuthException e) { - log.warn(String.format( - "Hashtags cannot be set on change %s because the importing" - + " user %s doesn't have permissions to edit hashtags" - + " (e.g. assign the 'Edit Hashtags' global capability" - + " and resume the import with the force option).", - ChangeTriplet.format(change), currentUser.getUserName())); + log.warn( + String.format( + "Hashtags cannot be set on change %s because the importing" + + " user %s doesn't have permissions to edit hashtags" + + " (e.g. assign the 'Edit Hashtags' global capability" + + " and resume the import with the force option).", + ChangeTriplet.format(change), currentUser.getUserName())); } } }
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/CompleteProjectImport.java b/src/main/java/com/googlesource/gerrit/plugins/importer/CompleteProjectImport.java index 2df913f..dcb6409 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/CompleteProjectImport.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/CompleteProjectImport.java
@@ -30,39 +30,32 @@ import com.google.gerrit.server.project.ProjectResource; import com.google.inject.Inject; import com.google.inject.Provider; - import com.googlesource.gerrit.plugins.importer.CompleteProjectImport.Input; - +import java.io.File; +import java.io.IOException; +import java.util.Map; import org.eclipse.jgit.errors.RepositoryNotFoundException; import org.eclipse.jgit.internal.storage.file.LockFile; import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.lib.RefUpdate; import org.eclipse.jgit.lib.Repository; -import java.io.File; -import java.io.IOException; -import java.util.Map; - @RequiresCapability(ImportCapability.ID) class CompleteProjectImport implements RestModifyView<ImportProjectResource, Input> { - public static class Input { - } + public static class Input {} private final ProjectsCollection projects; private final GitRepositoryManager repoManager; @Inject - CompleteProjectImport( - ProjectsCollection projects, - GitRepositoryManager repoManager) { + CompleteProjectImport(ProjectsCollection projects, GitRepositoryManager repoManager) { this.projects = projects; this.repoManager = repoManager; } @Override public Response<?> apply(ImportProjectResource rsrc, Input input) - throws ResourceConflictException, RepositoryNotFoundException, - IOException { + throws ResourceConflictException, RepositoryNotFoundException, IOException { LockFile lock = lockForDelete(rsrc.getName()); try { deleteImportRefs(rsrc.getName()); @@ -73,16 +66,14 @@ } } - private LockFile lockForDelete(Project.NameKey project) - throws ResourceConflictException { + private LockFile lockForDelete(Project.NameKey project) throws ResourceConflictException { File importStatus = projects.FS_LAYOUT.getImportStatusFile(project.get()); LockFile lockFile = new LockFile(importStatus); try { if (lockFile.lock()) { return lockFile; } - throw new ResourceConflictException( - "project is being imported from another session"); + throw new ResourceConflictException("project is being imported from another session"); } catch (IOException e) { throw new ResourceConflictException("failed to lock project for delete"); } @@ -91,8 +82,7 @@ private void deleteImportRefs(Project.NameKey project) throws RepositoryNotFoundException, IOException { try (Repository repo = repoManager.openRepository(project)) { - Map<String, Ref> refs = repo.getRefDatabase().getRefs( - ConfigureRepositoryStep.R_IMPORTS); + Map<String, Ref> refs = repo.getRefDatabase().getRefs(ConfigureRepositoryStep.R_IMPORTS); for (Ref ref : refs.values()) { RefUpdate ru = repo.updateRef(ref.getName()); ru.setForceUpdate(true); @@ -110,22 +100,23 @@ case REJECTED_CURRENT_BRANCH: case RENAMED: default: - throw new IOException(String.format( - "Failed to delete %s, RefUpdate.Result = %s", ref, result)); + throw new IOException( + String.format("Failed to delete %s, RefUpdate.Result = %s", ref, result)); } } } } - public static class OnProjects implements - RestModifyView<ProjectResource, Input>, UiAction<ProjectResource> { + public static class OnProjects + implements RestModifyView<ProjectResource, Input>, UiAction<ProjectResource> { private final ProjectsCollection projectsCollection; private final CompleteProjectImport completeProjectImport; private final Provider<CurrentUser> currentUserProvider; private final String pluginName; @Inject - public OnProjects(ProjectsCollection projectsCollection, + public OnProjects( + ProjectsCollection projectsCollection, CompleteProjectImport completeProjectImport, Provider<CurrentUser> currentUserProvider, @PluginName String pluginName) { @@ -137,11 +128,10 @@ @Override public Response<?> apply(ProjectResource rsrc, Input input) - throws ResourceNotFoundException, ResourceConflictException, - RepositoryNotFoundException, IOException { + throws ResourceNotFoundException, ResourceConflictException, RepositoryNotFoundException, + IOException { ImportProjectResource projectResource = - projectsCollection.parse(new ConfigResource(), - IdString.fromDecoded(rsrc.getName())); + projectsCollection.parse(new ConfigResource(), IdString.fromDecoded(rsrc.getName())); return completeProjectImport.apply(projectResource, input); } @@ -150,16 +140,18 @@ UiAction.Description desc = new UiAction.Description(); try { - ImportProjectResource importRsrc = projectsCollection.parse(new ConfigResource(), - IdString.fromDecoded(rsrc.getName())); + ImportProjectResource importRsrc = + projectsCollection.parse(new ConfigResource(), IdString.fromDecoded(rsrc.getName())); if (importRsrc.getInfo().from != null) { desc.setLabel("Complete Import...") - .setTitle("Complete the project import." - + " After completion, resume is not possible anymore."); + .setTitle( + "Complete the project import." + + " After completion, resume is not possible anymore."); } else { desc.setLabel("Complete Copy...") - .setTitle("Complete the project copy." - + " After completion, resume is not possible anymore."); + .setTitle( + "Complete the project copy." + + " After completion, resume is not possible anymore."); } desc.setVisible(canCompleteImport(rsrc)); } catch (IOException | ResourceNotFoundException e) {
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/CompleteProjectImportCommand.java b/src/main/java/com/googlesource/gerrit/plugins/importer/CompleteProjectImportCommand.java index 02ff97f..161c3bc 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/CompleteProjectImportCommand.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/CompleteProjectImportCommand.java
@@ -19,29 +19,27 @@ import com.google.gerrit.sshd.CommandMetaData; import com.google.gerrit.sshd.SshCommand; import com.google.inject.Inject; - +import java.io.IOException; import org.eclipse.jgit.errors.RepositoryNotFoundException; import org.kohsuke.args4j.Argument; -import java.io.IOException; - @RequiresCapability(ImportCapability.ID) @CommandMetaData(name = "complete-project", description = "Completes project import") class CompleteProjectImportCommand extends SshCommand { - @Argument(index = 0, required = true, metaVar = "NAME", + @Argument( + index = 0, + required = true, + metaVar = "NAME", usage = "name of the project in target system") private String project; - @Inject - private CompleteProjectImport completeProjectImport; + @Inject private CompleteProjectImport completeProjectImport; - @Inject - private ProjectsCollection projects; + @Inject private ProjectsCollection projects; @Override - protected void run() throws UnloggedFailure, RepositoryNotFoundException, - IOException { + protected void run() throws UnloggedFailure, RepositoryNotFoundException, IOException { try { ImportProjectResource rsrc = projects.parse(project); completeProjectImport.apply(rsrc, new CompleteProjectImport.Input());
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/ConfigureProjectStep.java b/src/main/java/com/googlesource/gerrit/plugins/importer/ConfigureProjectStep.java index 9497262..0d26d31 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/ConfigureProjectStep.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/ConfigureProjectStep.java
@@ -24,10 +24,8 @@ import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.Singleton; - -import org.eclipse.jgit.lib.ProgressMonitor; - import java.io.IOException; +import org.eclipse.jgit.lib.ProgressMonitor; @Singleton class ConfigureProjectStep {
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/ConfigureRepositoryStep.java b/src/main/java/com/googlesource/gerrit/plugins/importer/ConfigureRepositoryStep.java index aca47c3..8b199ca 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/ConfigureRepositoryStep.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/ConfigureRepositoryStep.java
@@ -21,15 +21,13 @@ 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.eclipse.jgit.lib.Config; import org.eclipse.jgit.lib.ProgressMonitor; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.lib.StoredConfig; -import java.io.IOException; -import java.nio.file.Path; - @Singleton class ConfigureRepositoryStep { @@ -38,9 +36,7 @@ private final Path gitDir; @Inject - ConfigureRepositoryStep( - SitePaths site, - @GerritServerConfig Config cfg) { + ConfigureRepositoryStep(SitePaths site, @GerritServerConfig Config cfg) { this.gitDir = site.resolve(cfg.getString("gerrit", null, "basePath")); } @@ -49,13 +45,10 @@ pm.beginTask("Configure repository", 1); StoredConfig config = repo.getConfig(); if (originUrl != null) { - config.setString("remote", "origin", "url", originUrl - .concat("/a/") - .concat(name.get())); + config.setString("remote", "origin", "url", originUrl.concat("/a/").concat(name.get())); } else { - config.setString("remote", "origin", "url", - this.gitDir.resolve(name.get() + ".git").toString()); - + config.setString( + "remote", "origin", "url", this.gitDir.resolve(name.get() + ".git").toString()); } config.setString("remote", "origin", "fetch", "+refs/*:" + R_IMPORTS + "*"); config.setString("http", null, "sslVerify", Boolean.FALSE.toString());
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/CopyProject.java b/src/main/java/com/googlesource/gerrit/plugins/importer/CopyProject.java index 579d684..670b9ab 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/CopyProject.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/CopyProject.java
@@ -26,28 +26,24 @@ import com.google.gerrit.server.CurrentUser; import com.google.gerrit.server.account.CapabilityControl; import com.google.gerrit.server.config.ConfigResource; -import com.google.gerrit.server.update.UpdateException; import com.google.gerrit.server.project.NoSuchChangeException; import com.google.gerrit.server.project.ProjectResource; +import com.google.gerrit.server.update.UpdateException; import com.google.gerrit.server.validators.ValidationException; import com.google.gwtorm.server.OrmException; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.Singleton; - import com.googlesource.gerrit.plugins.importer.CopyProject.Input; - -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.errors.ConfigInvalidException; - import java.io.IOException; import java.io.PrintWriter; import java.io.Writer; +import org.eclipse.jgit.api.errors.GitAPIException; +import org.eclipse.jgit.errors.ConfigInvalidException; @Singleton @RequiresCapability(CopyProjectCapability.ID) -class CopyProject implements RestModifyView<ProjectResource, Input>, - UiAction<ProjectResource> { +class CopyProject implements RestModifyView<ProjectResource, Input>, UiAction<ProjectResource> { public static class Input { public String name; } @@ -70,9 +66,8 @@ @Override public ImportStatistic apply(ProjectResource rsrc, Input input) - throws RestApiException, OrmException, IOException, ValidationException, - GitAPIException, NoSuchChangeException, NoSuchAccountException, - UpdateException, ConfigInvalidException { + throws RestApiException, OrmException, IOException, ValidationException, GitAPIException, + NoSuchChangeException, NoSuchAccountException, UpdateException, ConfigInvalidException { if (Strings.isNullOrEmpty(input.name)) { throw new BadRequestException("name is required"); } @@ -80,7 +75,8 @@ ImportProject.Input in = new ImportProject.Input(); in.name = rsrc.getName(); - return importProjectFactory.create(new Project.NameKey(input.name)) + return importProjectFactory + .create(new Project.NameKey(input.name)) .setCopy(true) .setErr(err) .apply(new ConfigResource(), in);
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/CopyProjectCapability.java b/src/main/java/com/googlesource/gerrit/plugins/importer/CopyProjectCapability.java index fe75fa6..a1b31a9 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/CopyProjectCapability.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/CopyProjectCapability.java
@@ -17,7 +17,7 @@ import com.google.gerrit.extensions.config.CapabilityDefinition; public class CopyProjectCapability extends CapabilityDefinition { - public final static String ID = "copyProject"; + public static final String ID = "copyProject"; @Override public String getDescription() {
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/CopyProjectCommand.java b/src/main/java/com/googlesource/gerrit/plugins/importer/CopyProjectCommand.java index 8737d98..d94f4f1 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/CopyProjectCommand.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/CopyProjectCommand.java
@@ -21,7 +21,6 @@ import com.google.gerrit.sshd.CommandMetaData; import com.google.gerrit.sshd.SshCommand; import com.google.inject.Inject; - import org.kohsuke.args4j.Argument; import org.kohsuke.args4j.Option; @@ -32,19 +31,15 @@ @Option(name = "--quiet", usage = "suppress progress messages") private boolean quiet; - @Argument(index = 0, required = true, metaVar = "NAME", - usage = "name of the source project") + @Argument(index = 0, required = true, metaVar = "NAME", usage = "name of the source project") private String source; - @Argument(index = 1, required = true, metaVar = "COPY", - usage = "name of the project copy") + @Argument(index = 1, required = true, metaVar = "COPY", usage = "name of the project copy") private String target; - @Inject - private ProjectsCollection projects; + @Inject private ProjectsCollection projects; - @Inject - private CopyProject copy; + @Inject private CopyProject copy; @Override protected void run() throws UnloggedFailure, Failure, Exception {
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/GerritApi.java b/src/main/java/com/googlesource/gerrit/plugins/importer/GerritApi.java index ef1c1a6..ffa487c 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/GerritApi.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/GerritApi.java
@@ -23,13 +23,11 @@ import com.google.gerrit.extensions.restapi.BadRequestException; import com.google.gwtorm.server.OrmException; import com.google.inject.Inject; - -import org.eclipse.jgit.errors.ConfigInvalidException; - import java.io.IOException; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; +import org.eclipse.jgit.errors.ConfigInvalidException; interface GerritApi { @@ -49,31 +47,29 @@ } } - public ProjectInfo getProject(String projectName) throws BadRequestException, - IOException; + public ProjectInfo getProject(String projectName) throws BadRequestException, IOException; public List<ChangeInfo> queryChanges(String projectName, int start, int limit) throws BadRequestException, IOException; - public GroupInfo getGroup(String groupName) throws BadRequestException, - IOException, OrmException; + public GroupInfo getGroup(String groupName) throws BadRequestException, IOException, OrmException; /** * Retrieves inline comments of a patch set. * * @param changeId numeric change ID * @param rev the revision - * @return Iterable that provides the inline comments, or {@code null} if the - * revision does not exist + * @return Iterable that provides the inline comments, or {@code null} if the revision does not + * exist * @throws IOException thrown if sending the request fails - * @throws BadRequestException thrown if the response is neither - * {@code 200 OK} nor {@code 404 Not Found} + * @throws BadRequestException thrown if the response is neither {@code 200 OK} nor {@code 404 Not + * Found} */ public Iterable<CommentInfo> getComments(int changeId, String rev) throws BadRequestException, IOException, OrmException; - public List<SshKeyInfo> getSshKeys(String userId) throws BadRequestException, - IOException, OrmException, ConfigInvalidException; + public List<SshKeyInfo> getSshKeys(String userId) + throws BadRequestException, IOException, OrmException, ConfigInvalidException; public Version getVersion() throws BadRequestException, IOException; @@ -88,8 +84,8 @@ Version(String formatted) { this.formatted = formatted; - Matcher m = Pattern.compile("(\\d+)\\.(\\d+)(\\.(\\d+))?(\\.(\\d+))?(-(.+))?") - .matcher(formatted); + Matcher m = + Pattern.compile("(\\d+)\\.(\\d+)(\\.(\\d+))?(\\.(\\d+))?(-(.+))?").matcher(formatted); if (m.matches()) { this.major = Integer.parseInt(m.group(1)); this.minor = Integer.parseInt(m.group(2));
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/GetImportedProject.java b/src/main/java/com/googlesource/gerrit/plugins/importer/GetImportedProject.java index ac72400..de6abd1 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/GetImportedProject.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/GetImportedProject.java
@@ -17,7 +17,6 @@ import com.google.gerrit.extensions.annotations.RequiresCapability; import com.google.gerrit.extensions.restapi.RestReadView; import com.google.inject.Singleton; - import java.io.IOException; @Singleton
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/GitFetchStep.java b/src/main/java/com/googlesource/gerrit/plugins/importer/GitFetchStep.java index 132a36c..e362b96 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/GitFetchStep.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/GitFetchStep.java
@@ -17,7 +17,8 @@ import static com.googlesource.gerrit.plugins.importer.ProgressMonitorUtil.updateAndEnd; import com.google.inject.Singleton; - +import java.io.IOException; +import java.util.Map; import org.eclipse.jgit.api.FetchCommand; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.errors.GitAPIException; @@ -30,20 +31,15 @@ import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider; -import java.io.IOException; -import java.util.Map; - @Singleton class GitFetchStep { void fetch(String user, String password, Repository repo, ProgressMonitor pm) - throws InvalidRemoteException, TransportException, GitAPIException, - IOException { + throws InvalidRemoteException, TransportException, GitAPIException, IOException { pm.beginTask("Fetch project", 1); FetchCommand fetch = Git.wrap(repo).fetch(); if (user != null) { - fetch.setCredentialsProvider( - new UsernamePasswordCredentialsProvider(user, password)); + fetch.setCredentialsProvider(new UsernamePasswordCredentialsProvider(user, password)); } fetch.setRemote("origin").call(); updateNonChangeRefs(repo); @@ -51,8 +47,7 @@ } private void updateNonChangeRefs(Repository repo) throws IOException { - Map<String, Ref> refs = repo.getRefDatabase().getRefs( - ConfigureRepositoryStep.R_IMPORTS); + Map<String, Ref> refs = repo.getRefDatabase().getRefs(ConfigureRepositoryStep.R_IMPORTS); for (Map.Entry<String, Ref> e : refs.entrySet()) { String name = e.getKey(); if (name.startsWith("imports/")) { @@ -84,8 +79,8 @@ case REJECTED_CURRENT_BRANCH: case RENAMED: default: - throw new IOException(String.format( - "Failed to update %s, RefUpdate.Result = %s", targetRef, result)); + throw new IOException( + String.format("Failed to update %s, RefUpdate.Result = %s", targetRef, result)); } } }
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/GroupCommand.java b/src/main/java/com/googlesource/gerrit/plugins/importer/GroupCommand.java index 5b4c758..870ad9b 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/GroupCommand.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/GroupCommand.java
@@ -26,48 +26,65 @@ import com.google.gerrit.sshd.SshCommand; import com.google.gwtorm.server.OrmException; import com.google.inject.Inject; - +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; import org.eclipse.jgit.errors.ConfigInvalidException; import org.kohsuke.args4j.Argument; import org.kohsuke.args4j.Option; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; - @RequiresCapability(ImportCapability.ID) @CommandMetaData(name = "group", description = "Imports a group") public class GroupCommand extends SshCommand { - @Option(name = "--from", aliases = {"-f"}, required = true, metaVar = "URL", + @Option( + name = "--from", + aliases = {"-f"}, + required = true, + metaVar = "URL", usage = "URL of the remote system from where the group is imported from") private String url; - @Option(name = "--user", aliases = {"-u"}, required = true, metaVar = "NAME", + @Option( + name = "--user", + aliases = {"-u"}, + required = true, + metaVar = "NAME", usage = "user on remote system") private String user; - @Option(name = "--pass", aliases = {"-p"}, required = true, metaVar = "-|PASS", + @Option( + name = "--pass", + aliases = {"-p"}, + required = true, + metaVar = "-|PASS", usage = "password of remote user") private String pass; - @Option(name = "--import-owner-group", aliases = {"-o"}, + @Option( + name = "--import-owner-group", + aliases = {"-o"}, usage = "whether missing owner groups should be imported automatically") private boolean importOwnerGroup; - @Option(name = "--import-included-groups", aliases = {"-i"}, + @Option( + name = "--import-included-groups", + aliases = {"-i"}, usage = "whether missing included groups should be imported automatically") private boolean importIncludedGroups; - @Argument(index = 0, required = true, metaVar = "NAME", + @Argument( + index = 0, + required = true, + metaVar = "NAME", usage = "name of the group to be imported") private String group; - @Inject - private ImportGroup.Factory importGroupFactory; + @Inject private ImportGroup.Factory importGroupFactory; @Override - protected void run() throws UnloggedFailure, OrmException, IOException, - NoSuchAccountException, ConfigInvalidException { + protected void run() + throws UnloggedFailure, OrmException, IOException, NoSuchAccountException, + ConfigInvalidException { ImportGroup.Input input = new ImportGroup.Input(); input.from = url; input.user = user; @@ -76,9 +93,8 @@ input.importIncludedGroups = importIncludedGroups; try { - importGroupFactory.create(new AccountGroup.NameKey(group)).apply( - new ConfigResource(), input); - } catch (RestApiException e){ + importGroupFactory.create(new AccountGroup.NameKey(group)).apply(new ConfigResource(), input); + } catch (RestApiException e) { throw die(e.getMessage()); } }
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/GroupsCollection.java b/src/main/java/com/googlesource/gerrit/plugins/importer/GroupsCollection.java index bb692cd..af59bd6 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/GroupsCollection.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/GroupsCollection.java
@@ -28,17 +28,15 @@ import com.google.inject.Singleton; @Singleton -public class GroupsCollection implements - ChildCollection<ConfigResource, ImportGroupResource>, - AcceptsCreate<ConfigResource> { +public class GroupsCollection + implements ChildCollection<ConfigResource, ImportGroupResource>, AcceptsCreate<ConfigResource> { private final DynamicMap<RestView<ImportGroupResource>> views; private final ImportGroup.Factory importGroupFactory; @Inject GroupsCollection( - DynamicMap<RestView<ImportGroupResource>> views, - ImportGroup.Factory importGroupFactory) { + DynamicMap<RestView<ImportGroupResource>> views, ImportGroup.Factory importGroupFactory) { this.views = views; this.importGroupFactory = importGroupFactory; } @@ -61,8 +59,7 @@ @Override @SuppressWarnings("unchecked") - public ImportGroup create(ConfigResource parent, IdString id) - throws RestApiException { + public ImportGroup create(ConfigResource parent, IdString id) throws RestApiException { return importGroupFactory.create(new AccountGroup.NameKey(id.get())); } }
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/HttpModule.java b/src/main/java/com/googlesource/gerrit/plugins/importer/HttpModule.java index 7b6edf0..79fe837 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/HttpModule.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/HttpModule.java
@@ -32,7 +32,6 @@ DynamicSet.bind(binder(), WebUiPlugin.class) .toInstance(new JavaScriptPlugin("complete-project-import.js")); - DynamicSet.bind(binder(), WebUiPlugin.class) - .toInstance(new GwtPlugin("importer")); + DynamicSet.bind(binder(), WebUiPlugin.class).toInstance(new GwtPlugin("importer")); } }
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/HttpResponse.java b/src/main/java/com/googlesource/gerrit/plugins/importer/HttpResponse.java index 4966c3c..7403c58 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/HttpResponse.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/HttpResponse.java
@@ -15,15 +15,13 @@ package com.googlesource.gerrit.plugins.importer; import com.google.common.base.Preconditions; - -import org.apache.http.client.methods.CloseableHttpResponse; -import org.eclipse.jgit.util.IO; -import org.eclipse.jgit.util.RawParseUtils; - import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.nio.ByteBuffer; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.eclipse.jgit.util.IO; +import org.eclipse.jgit.util.RawParseUtils; public class HttpResponse implements AutoCloseable { @@ -61,15 +59,8 @@ public String getEntityContent() throws IOException { Preconditions.checkNotNull(response, "Response is not initialized."); - Preconditions.checkNotNull(response.getEntity(), - "Response.Entity is not initialized."); - ByteBuffer buf = IO.readWholeStream( - response.getEntity().getContent(), - 1024); - return RawParseUtils.decode( - buf.array(), - buf.arrayOffset(), - buf.limit()) - .trim(); + Preconditions.checkNotNull(response.getEntity(), "Response.Entity is not initialized."); + ByteBuffer buf = IO.readWholeStream(response.getEntity().getContent(), 1024); + return RawParseUtils.decode(buf.array(), buf.arrayOffset(), buf.limit()).trim(); } }
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/HttpSession.java b/src/main/java/com/googlesource/gerrit/plugins/importer/HttpSession.java index af7af86..88fa9cd 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/HttpSession.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/HttpSession.java
@@ -15,7 +15,16 @@ package com.googlesource.gerrit.plugins.importer; import com.google.common.base.CharMatcher; - +import java.io.IOException; +import java.net.URI; +import java.security.KeyManagementException; +import java.security.NoSuchAlgorithmException; +import java.security.cert.X509Certificate; +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSession; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.methods.HttpGet; @@ -24,18 +33,6 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; -import java.io.IOException; -import java.net.URI; -import java.security.KeyManagementException; -import java.security.NoSuchAlgorithmException; -import java.security.cert.X509Certificate; - -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSession; -import javax.net.ssl.TrustManager; -import javax.net.ssl.X509TrustManager; - public class HttpSession { protected final String url; @@ -58,13 +55,12 @@ if (client == null) { URI uri = URI.create(url); BasicCredentialsProvider creds = new BasicCredentialsProvider(); - creds.setCredentials(new AuthScope(uri.getHost(), uri.getPort()), - new UsernamePasswordCredentials(user, pass)); + creds.setCredentials( + new AuthScope(uri.getHost(), uri.getPort()), new UsernamePasswordCredentials(user, pass)); SSLContext context; try { - final TrustManager[] trustAllCerts = - new TrustManager[] {new DummyX509TrustManager()}; + final TrustManager[] trustAllCerts = new TrustManager[] {new DummyX509TrustManager()}; context = SSLContext.getInstance("TLS"); context.init(null, trustAllCerts, null); } catch (KeyManagementException | NoSuchAlgorithmException e) { @@ -73,14 +69,13 @@ SSLConnectionSocketFactory sf; sf = new SSLConnectionSocketFactory(context, new DummyHostnameVerifier()); - client = HttpClients - .custom() - .setSSLSocketFactory(sf) - .setDefaultCredentialsProvider(creds) - .setMaxConnPerRoute(10) - .setMaxConnTotal(1024) - .build(); - + client = + HttpClients.custom() + .setSSLSocketFactory(sf) + .setDefaultCredentialsProvider(creds) + .setMaxConnPerRoute(10) + .setMaxConnTotal(1024) + .build(); } return client; } @@ -109,5 +104,4 @@ return true; } } - }
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/ImportCapability.java b/src/main/java/com/googlesource/gerrit/plugins/importer/ImportCapability.java index bb18ef3..d2bd3e5 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/ImportCapability.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/ImportCapability.java
@@ -17,7 +17,7 @@ import com.google.gerrit.extensions.config.CapabilityDefinition; public class ImportCapability extends CapabilityDefinition { - public final static String ID = "import"; + public static final String ID = "import"; @Override public String getDescription() {
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/ImportGroup.java b/src/main/java/com/googlesource/gerrit/plugins/importer/ImportGroup.java index c4bdd7e..230af5d 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/ImportGroup.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/ImportGroup.java
@@ -46,20 +46,17 @@ import com.google.gwtorm.server.OrmException; import com.google.inject.Inject; import com.google.inject.assistedinject.Assisted; - import com.googlesource.gerrit.plugins.importer.ImportGroup.Input; - -import org.eclipse.jgit.errors.ConfigInvalidException; -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.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; +import org.eclipse.jgit.errors.ConfigInvalidException; +import org.eclipse.jgit.lib.Config; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; @RequiresCapability(ImportCapability.ID) class ImportGroup implements RestModifyView<ConfigResource, Input> { @@ -115,8 +112,8 @@ @Override public Response<String> apply(ConfigResource rsrc, Input input) - throws NoSuchAccountException, OrmException, IOException, - RestApiException, ConfigInvalidException { + throws NoSuchAccountException, OrmException, IOException, RestApiException, + ConfigInvalidException { GroupInfo groupInfo; this.api = apiFactory.create(input.from, input.user, input.pass); groupInfo = api.getGroup(group.get()); @@ -127,22 +124,24 @@ } private void validate(Input input, GroupInfo groupInfo) - throws IOException, OrmException, NoSuchAccountException, - RestApiException, ConfigInvalidException { + throws IOException, OrmException, NoSuchAccountException, RestApiException, + ConfigInvalidException { if (!isInternalGroup(new AccountGroup.UUID(groupInfo.id))) { - throw new MethodNotAllowedException(String.format( - "Group with name %s is not an internal group and cannot be imported", - groupInfo.name)); + throw new MethodNotAllowedException( + String.format( + "Group with name %s is not an internal group and cannot be imported", + groupInfo.name)); } if (getGroupByUUID(groupInfo.id) != null) { - throw new ResourceConflictException(String.format( - "Group with UUID %s already exists", groupInfo.id)); + throw new ResourceConflictException( + String.format("Group with UUID %s already exists", groupInfo.id)); } if (!groupInfo.id.equals(groupInfo.ownerId)) if (!input.importOwnerGroup && getGroupByUUID(groupInfo.ownerId) == null) { - throw new PreconditionFailedException(String.format( - "Owner group %s with UUID %s does not exist", - getGroupName(groupInfo.ownerId), groupInfo.ownerId)); + throw new PreconditionFailedException( + String.format( + "Owner group %s with UUID %s does not exist", + getGroupName(groupInfo.ownerId), groupInfo.ownerId)); } if (groupInfo.members != null) { for (AccountInfo member : groupInfo.members) { @@ -157,9 +156,10 @@ if (groupInfo.includes != null) { for (GroupInfo include : groupInfo.includes) { if (getGroupByUUID(include.id) == null) { - throw new PreconditionFailedException(String.format( - "Included group %s with UUID %s does not exist", - getGroupName(include.id), include.id)); + throw new PreconditionFailedException( + String.format( + "Included group %s with UUID %s does not exist", + getGroupName(include.id), include.id)); } } } @@ -183,8 +183,8 @@ } private CreateGroupArgs toCreateGroupArgs(GroupInfo groupInfo) - throws IOException, OrmException, NoSuchAccountException, - RestApiException, ConfigInvalidException { + throws IOException, OrmException, NoSuchAccountException, RestApiException, + ConfigInvalidException { CreateGroupArgs args = new CreateGroupArgs(); args.setGroupName(groupInfo.name); args.groupDescription = groupInfo.description; @@ -201,12 +201,13 @@ } private AccountGroup createGroup(Input input, GroupInfo info) - throws OrmException, NoSuchAccountException, IOException, - RestApiException, ConfigInvalidException { + throws OrmException, NoSuchAccountException, IOException, RestApiException, + ConfigInvalidException { String uniqueName = getUniqueGroupName(info.name); if (!info.name.equals(uniqueName)) { - log.warn(String.format("Group %s with UUID %s is imported with name %s", - info.name, info.id, uniqueName)); + log.warn( + String.format( + "Group %s with UUID %s is imported with name %s", info.name, info.id, uniqueName)); info.name = uniqueName; } AccountGroup group = createAccountGroup(info); @@ -227,12 +228,14 @@ if (isInternalGroup(new AccountGroup.UUID(info.ownerId))) { String ownerGroupName = getGroupName(info.ownerId); if (input.importOwnerGroup) { - importGroupFactory.create(new AccountGroup.NameKey(ownerGroupName)) + importGroupFactory + .create(new AccountGroup.NameKey(ownerGroupName)) .apply(new ConfigResource(), input); } else { - throw new IllegalStateException(String.format( - "Cannot set non-existing group %s as owner of group %s.", - ownerGroupName, info.name)); + throw new IllegalStateException( + String.format( + "Cannot set non-existing group %s as owner of group %s.", + ownerGroupName, info.name)); } } } @@ -266,22 +269,20 @@ } } return getUniqueGroupName(String.format("%s_imported", name), true); - } + private AccountGroup createAccountGroup(GroupInfo info) throws OrmException { AccountGroup.Id groupId = new AccountGroup.Id(db.nextAccountGroupId()); AccountGroup.UUID uuid = new AccountGroup.UUID(info.id); - AccountGroup group = - new AccountGroup(new AccountGroup.NameKey(info.name), groupId, uuid); - group.setVisibleToAll(cfg.getBoolean("groups", "newGroupsVisibleToAll", - false)); + AccountGroup group = new AccountGroup(new AccountGroup.NameKey(info.name), groupId, uuid); + group.setVisibleToAll(cfg.getBoolean("groups", "newGroupsVisibleToAll", false)); group.setDescription(info.description); return group; } private void addMembers(AccountGroup.Id groupId, List<AccountInfo> members) - throws OrmException, NoSuchAccountException, IOException, - RestApiException, ConfigInvalidException { + throws OrmException, NoSuchAccountException, IOException, RestApiException, + ConfigInvalidException { List<AccountGroupMember> memberships = new ArrayList<>(); for (AccountInfo member : members) { Account.Id userId = accountUtil.resolveUser(api, member); @@ -296,23 +297,24 @@ } } - private void addGroups(Input input, AccountGroup.Id groupId, String groupName, - List<GroupInfo> includedGroups) - throws NoSuchAccountException, OrmException, IOException, - RestApiException, ConfigInvalidException { + private void addGroups( + Input input, AccountGroup.Id groupId, String groupName, List<GroupInfo> includedGroups) + throws NoSuchAccountException, OrmException, IOException, RestApiException, + ConfigInvalidException { List<AccountGroupById> includeList = new ArrayList<>(); for (GroupInfo includedGroup : includedGroups) { if (isInternalGroup(new AccountGroup.UUID(includedGroup.id))) { if (getGroupByUUID(includedGroup.id) == null) { String includedGroupName = getGroupName(includedGroup.id); if (input.importIncludedGroups) { - importGroupFactory.create( - new AccountGroup.NameKey(includedGroupName)).apply( - new ConfigResource(), input); + importGroupFactory + .create(new AccountGroup.NameKey(includedGroupName)) + .apply(new ConfigResource(), input); } else { - throw new IllegalStateException(String.format( - "Cannot include non-existing group %s into group %s.", - includedGroupName, groupName)); + throw new IllegalStateException( + String.format( + "Cannot include non-existing group %s into group %s.", + includedGroupName, groupName)); } } } @@ -328,8 +330,7 @@ } } - private String getGroupName(String uuid) throws BadRequestException, - IOException, OrmException { + private String getGroupName(String uuid) throws BadRequestException, IOException, OrmException { return api.getGroup(uuid).name; } }
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/ImportGroupsStep.java b/src/main/java/com/googlesource/gerrit/plugins/importer/ImportGroupsStep.java index e8b0288..308ba83 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/ImportGroupsStep.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/ImportGroupsStep.java
@@ -29,12 +29,10 @@ import com.google.gwtorm.server.OrmException; import com.google.inject.Inject; import com.google.inject.assistedinject.Assisted; - -import org.eclipse.jgit.errors.ConfigInvalidException; -import org.eclipse.jgit.lib.ProgressMonitor; - import java.io.IOException; import java.util.Set; +import org.eclipse.jgit.errors.ConfigInvalidException; +import org.eclipse.jgit.lib.ProgressMonitor; public class ImportGroupsStep { @@ -76,8 +74,9 @@ this.pm = pm; } - void importGroups() throws NoSuchAccountException, OrmException, IOException, - RestApiException, ConfigInvalidException { + void importGroups() + throws NoSuchAccountException, OrmException, IOException, RestApiException, + ConfigInvalidException { ProjectConfig projectConfig = projectCache.get(project).getConfig(); Set<AccountGroup.UUID> groupUUIDs = projectConfig.getAllGroupUUIDs(); pm.beginTask("Import Groups", groupUUIDs.size()); @@ -91,9 +90,9 @@ input.importOwnerGroup = true; input.importIncludedGroups = true; try { - importGroupFactory.create( - new AccountGroup.NameKey(projectConfig.getGroup(groupUUID) - .getName())).apply(new ConfigResource(), input); + importGroupFactory + .create(new AccountGroup.NameKey(projectConfig.getGroup(groupUUID).getName())) + .apply(new ConfigResource(), input); } catch (ResourceConflictException | MethodNotAllowedException e) { // should not happen throw new IllegalStateException(e);
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/ImportInfo.java b/src/main/java/com/googlesource/gerrit/plugins/importer/ImportInfo.java index 16be1c6..97c50f6 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/ImportInfo.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/ImportInfo.java
@@ -15,7 +15,6 @@ package com.googlesource.gerrit.plugins.importer; import com.google.gerrit.extensions.common.AccountInfo; - import java.sql.Timestamp; public class ImportInfo {
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/ImportJson.java b/src/main/java/com/googlesource/gerrit/plugins/importer/ImportJson.java index f5cd59a..d8db8e9 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/ImportJson.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/ImportJson.java
@@ -27,18 +27,15 @@ import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.Singleton; - import com.googlesource.gerrit.plugins.importer.ImportProject.Input; - -import org.eclipse.jgit.internal.storage.file.LockFile; -import org.eclipse.jgit.lib.ProgressMonitor; - import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.OutputStream; import java.sql.Timestamp; import java.util.ArrayList; +import org.eclipse.jgit.internal.storage.file.LockFile; +import org.eclipse.jgit.lib.ProgressMonitor; @Singleton public class ImportJson { @@ -47,15 +44,12 @@ private final AccountLoader.Factory accountLoaderFactory; @Inject - ImportJson( - Provider<CurrentUser> currentUser, - AccountLoader.Factory accountLoaderFactory) { + ImportJson(Provider<CurrentUser> currentUser, AccountLoader.Factory accountLoaderFactory) { this.currentUser = currentUser; this.accountLoaderFactory = accountLoaderFactory; } - public ImportProjectInfo format(Input input, ImportProjectInfo info) - throws OrmException { + public ImportProjectInfo format(Input input, ImportProjectInfo info) throws OrmException { if (info == null) { info = new ImportProjectInfo(); info.from = input.from; @@ -72,15 +66,14 @@ AccountLoader accountLoader = accountLoaderFactory.create(true); ImportInfo importInfo = new ImportInfo(); importInfo.timestamp = new Timestamp(TimeUtil.nowMs()); - importInfo.user = - accountLoader.get(((IdentifiedUser) currentUser.get()).getAccountId()); + importInfo.user = accountLoader.get(((IdentifiedUser) currentUser.get()).getAccountId()); importInfo.remoteUser = remoteUser; accountLoader.fill(); return importInfo; } - public static void persist(LockFile lockFile, ImportProjectInfo info, - ProgressMonitor pm) throws IOException { + public static void persist(LockFile lockFile, ImportProjectInfo info, ProgressMonitor pm) + throws IOException { pm.beginTask("Persist parameters", 1); String s = OutputFormat.JSON_COMPACT.newGson().toJson(info); try (OutputStream out = lockFile.getOutputStream()) { @@ -94,8 +87,9 @@ public static ImportProjectInfo parse(File f) throws IOException { try (FileReader r = new FileReader(f)) { - return OutputFormat.JSON_COMPACT.newGson().fromJson(r, - new TypeToken<ImportProjectInfo>() {}.getType()); + return OutputFormat.JSON_COMPACT + .newGson() + .fromJson(r, new TypeToken<ImportProjectInfo>() {}.getType()); } } }
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/ImportLog.java b/src/main/java/com/googlesource/gerrit/plugins/importer/ImportLog.java index 597c4fc..c61e50d 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/ImportLog.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/ImportLog.java
@@ -28,7 +28,6 @@ import com.google.gerrit.server.util.SystemLog; import com.google.inject.Inject; import com.google.inject.Singleton; - import org.apache.log4j.Level; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; @@ -50,7 +49,8 @@ private final String canonicalWebUrl; @Inject - public ImportLog(SystemLog systemLog, + public ImportLog( + SystemLog systemLog, ServerInformation serverInfo, AuditService auditService, @CanonicalWebUrl String canonicalWebUrl) { @@ -59,30 +59,35 @@ this.canonicalWebUrl = canonicalWebUrl; } - public void onImport(IdentifiedUser user, Project.NameKey srcProject, - Project.NameKey targetProject, String from) { + public void onImport( + IdentifiedUser user, Project.NameKey srcProject, Project.NameKey targetProject, String from) { onImport(user, srcProject, targetProject, from, null); } - public void onImport(IdentifiedUser user, Project.NameKey srcProject, - Project.NameKey targetProject, String from, Exception ex) { + public void onImport( + IdentifiedUser user, + Project.NameKey srcProject, + Project.NameKey targetProject, + String from, + Exception ex) { long ts = TimeUtil.nowMs(); - LoggingEvent event = new LoggingEvent( // - Logger.class.getName(), // fqnOfCategoryClass - log, // logger - ts, // when - ex == null // level - ? Level.INFO - : Level.ERROR, - ex == null // message text - ? "OK" - : "FAIL", - Thread.currentThread().getName(), // thread name - null, // exception information - null, // current NDC string - null, // caller location - null // MDC properties - ); + LoggingEvent event = + new LoggingEvent( // + Logger.class.getName(), // fqnOfCategoryClass + log, // logger + ts, // when + ex == null // level + ? Level.INFO + : Level.ERROR, + ex == null // message text + ? "OK" + : "FAIL", + Thread.currentThread().getName(), // thread name + null, // exception information + null, // current NDC string + null, // caller location + null // MDC properties + ); event.setProperty(ACCOUNT_ID, user.getAccountId().toString()); event.setProperty(USER_NAME, user.getUserName()); @@ -105,10 +110,9 @@ audit(user, ts, srcProject, from, ex); } - private void audit(IdentifiedUser user, long ts, Project.NameKey project, - String from, Exception ex) { - ListMultimap<String, Object> params = - MultimapBuilder.hashKeys().arrayListValues().build(); + private void audit( + IdentifiedUser user, long ts, Project.NameKey project, String from, Exception ex) { + ListMultimap<String, Object> params = MultimapBuilder.hashKeys().arrayListValues().build(); params.put("class", ImportLog.class); params.put("project", project.get()); params.put("from", from); @@ -124,7 +128,6 @@ params, // params ex != null // result ? ex.toString() - : "OK" - )); + : "OK")); } }
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/ImportLogLayout.java b/src/main/java/com/googlesource/gerrit/plugins/importer/ImportLogLayout.java index cc29340..7faceae 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/ImportLogLayout.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/ImportLogLayout.java
@@ -14,14 +14,13 @@ package com.googlesource.gerrit.plugins.importer; -import org.apache.log4j.Layout; -import org.apache.log4j.spi.LoggingEvent; -import org.eclipse.jgit.util.QuotedString; - import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; +import org.apache.log4j.Layout; +import org.apache.log4j.spi.LoggingEvent; +import org.eclipse.jgit.util.QuotedString; final class ImportLogLayout extends Layout { private final Calendar calendar; @@ -29,7 +28,7 @@ private final char[] lastTimeString = new char[20]; private final char[] timeZone; - public ImportLogLayout() { + public ImportLogLayout() { TimeZone tz = TimeZone.getDefault(); calendar = Calendar.getInstance(tz); @@ -41,14 +40,12 @@ /** * Formats the events in the import log. * - * A successful project import will result in a log entry like this: - * [2015-03-05 09:13:28,912 +0100] INFO 1000000 admin OK \ - * https://some-gerrit-server:8080 srcName targetName + * <p>A successful project import will result in a log entry like this: [2015-03-05 09:13:28,912 + * +0100] INFO 1000000 admin OK \ https://some-gerrit-server:8080 srcName targetName * - * The log entry for a failed project import will look like this: - * [2015-03-05 12:14:30,180 +0100] ERROR 1000000 admin FAIL \ - * https://some-gerrit-server:8080 srcName targetName \ - * com.google.gwtorm.server.OrmException: Failed to access the database + * <p>The log entry for a failed project import will look like this: [2015-03-05 12:14:30,180 + * +0100] ERROR 1000000 admin FAIL \ https://some-gerrit-server:8080 srcName targetName \ + * com.google.gwtorm.server.OrmException: Failed to access the database */ @Override public String format(LoggingEvent event) { @@ -139,6 +136,5 @@ } @Override - public void activateOptions() { - } + public void activateOptions() {} }
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/ImportMenu.java b/src/main/java/com/googlesource/gerrit/plugins/importer/ImportMenu.java index f0b0976..1e969af 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/ImportMenu.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/ImportMenu.java
@@ -22,7 +22,6 @@ import com.google.gerrit.server.account.CapabilityControl; import com.google.inject.Inject; import com.google.inject.Provider; - import java.util.List; public class ImportMenu implements TopMenu { @@ -31,9 +30,7 @@ private final List<MenuEntry> menuEntries; @Inject - ImportMenu( - @PluginName String pluginName, - Provider<CurrentUser> userProvider) { + ImportMenu(@PluginName String pluginName, Provider<CurrentUser> userProvider) { this.pluginName = pluginName; this.userProvider = userProvider; menuEntries = Lists.newArrayList(); @@ -55,8 +52,7 @@ private boolean canImport() { CapabilityControl ctl = userProvider.get().getCapabilities(); - return ctl.canAdministrateServer() - || ctl.canPerform(pluginName + "-" + ImportCapability.ID); + return ctl.canAdministrateServer() || ctl.canPerform(pluginName + "-" + ImportCapability.ID); } @Override
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/ImportProject.java b/src/main/java/com/googlesource/gerrit/plugins/importer/ImportProject.java index ea00a2d..4090c99 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/ImportProject.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/ImportProject.java
@@ -28,19 +28,20 @@ import com.google.gerrit.server.CurrentUser; import com.google.gerrit.server.IdentifiedUser; import com.google.gerrit.server.config.ConfigResource; -import com.google.gerrit.server.update.UpdateException; import com.google.gerrit.server.project.NoSuchChangeException; import com.google.gerrit.server.project.ProjectCache; import com.google.gerrit.server.project.ProjectState; +import com.google.gerrit.server.update.UpdateException; import com.google.gerrit.server.validators.ValidationException; import com.google.gwtorm.server.OrmException; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.assistedinject.Assisted; - import com.googlesource.gerrit.plugins.importer.GerritApi.Version; import com.googlesource.gerrit.plugins.importer.ImportProject.Input; - +import java.io.File; +import java.io.IOException; +import java.io.Writer; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.errors.ConfigInvalidException; import org.eclipse.jgit.internal.storage.file.LockFile; @@ -51,10 +52,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.File; -import java.io.IOException; -import java.io.Writer; - @RequiresCapability(ImportCapability.ID) class ImportProject implements RestModifyView<ConfigResource, Input> { public static class Input { @@ -164,9 +161,8 @@ @Override public ImportStatistic apply(ConfigResource rsrc, Input input) - throws RestApiException, OrmException, IOException, ValidationException, - GitAPIException, NoSuchChangeException, NoSuchAccountException, - UpdateException, ConfigInvalidException { + throws RestApiException, OrmException, IOException, ValidationException, GitAPIException, + NoSuchChangeException, NoSuchAccountException, UpdateException, ConfigInvalidException { if (input == null) { input = new Input(); } @@ -179,10 +175,9 @@ } } - public ResumeImportStatistic resume(String user, String pass, boolean force, - File importStatus) throws RestApiException, OrmException, IOException, - GitAPIException, NoSuchChangeException, NoSuchAccountException, - UpdateException, ConfigInvalidException { + public ResumeImportStatistic resume(String user, String pass, boolean force, File importStatus) + throws RestApiException, OrmException, IOException, GitAPIException, NoSuchChangeException, + NoSuchAccountException, UpdateException, ConfigInvalidException { LockFile lockFile = lockForImport(); try { ImportProjectInfo info = ImportJson.parse(importStatus); @@ -202,10 +197,9 @@ } } - private ResumeImportStatistic apply(LockFile lockFile, Input input, - ImportProjectInfo info) throws RestApiException, OrmException, - IOException, GitAPIException, NoSuchChangeException, - NoSuchAccountException, UpdateException, ConfigInvalidException { + private ResumeImportStatistic apply(LockFile lockFile, Input input, ImportProjectInfo info) + throws RestApiException, OrmException, IOException, GitAPIException, NoSuchChangeException, + NoSuchAccountException, UpdateException, ConfigInvalidException { boolean resume = info != null; api = apiFactory.create(input.from, input.user, input.pass); @@ -215,49 +209,49 @@ input.validateImport(); Version v = api.getVersion(); if (v.compareTo(v2_11_2) < 0) { - throw new BadRequestException(String.format( - "The version of the source Gerrit server %s is too old. " - + "Its version is %s, but required is a version >= %s.", - input.from, v.formatted, v2_11_2)); + throw new BadRequestException( + String.format( + "The version of the source Gerrit server %s is too old. " + + "Its version is %s, but required is a version >= %s.", + input.from, v.formatted, v2_11_2)); } } - ProgressMonitor pm = err != null ? new TextProgressMonitor(err) : - NullProgressMonitor.INSTANCE; + ProgressMonitor pm = err != null ? new TextProgressMonitor(err) : NullProgressMonitor.INSTANCE; ResumeImportStatistic statistic = new ResumeImportStatistic(); try { - srcProject = !Strings.isNullOrEmpty(input.name) - ? new Project.NameKey(input.name) : targetProject; + srcProject = + !Strings.isNullOrEmpty(input.name) ? new Project.NameKey(input.name) : targetProject; checkProjectInSource(pm); setParentProjectName(input, pm); checkPreconditions(pm); - try (Repository repo = openRepoStep.open(targetProject, resume, pm, - parent)) { + try (Repository repo = openRepoStep.open(targetProject, resume, pm, parent)) { ImportJson.persist(lockFile, importJson.format(input, info), pm); configRepoStep.configure(repo, srcProject, input.from, pm); gitFetchStep.fetch(input.user, input.pass, repo, pm); configProjectStep.configure(targetProject, parent, pm); - replayChangesFactory.create(input.from, api, repo, - srcProject, targetProject, force, resume, statistic, pm).replay(); + replayChangesFactory + .create(input.from, api, repo, srcProject, targetProject, force, resume, statistic, pm) + .replay(); if (!copy) { - importGroupsStepFactory.create(input.from, input.user, input.pass, - targetProject, pm).importGroups(); + importGroupsStepFactory + .create(input.from, input.user, input.pass, targetProject, pm) + .importGroups(); } } - importLog.onImport((IdentifiedUser) currentUser.get(), srcProject, - targetProject, input.from); + importLog.onImport((IdentifiedUser) currentUser.get(), srcProject, targetProject, input.from); } catch (BadRequestException e) { throw e; } catch (Exception e) { - importLog.onImport((IdentifiedUser) currentUser.get(), srcProject, - targetProject, input.from, e); - String msg = input.from != null - ? format("Unable to transfer project '%s' from" - + " source gerrit host '%s'.", - srcProject.get(), input.from) - : format("Unable to copy project '%s'.", - srcProject.get()); + importLog.onImport( + (IdentifiedUser) currentUser.get(), srcProject, targetProject, input.from, e); + String msg = + input.from != null + ? format( + "Unable to transfer project '%s' from" + " source gerrit host '%s'.", + srcProject.get(), input.from) + : format("Unable to copy project '%s'.", srcProject.get()); log.error(msg, e); throw e; } @@ -265,8 +259,7 @@ return statistic; } - private void checkProjectInSource(ProgressMonitor pm) - throws IOException, BadRequestException { + private void checkProjectInSource(ProgressMonitor pm) throws IOException, BadRequestException { pm.beginTask("Check source project", 1); api.getProject(srcProject.get()); updateAndEnd(pm); @@ -279,8 +272,7 @@ if (!Strings.isNullOrEmpty(input.parent)) { parent = new Project.NameKey(input.parent); } else { - parent = new Project.NameKey( - api.getProject(srcProject.get()).parent); + parent = new Project.NameKey(api.getProject(srcProject.get()).parent); } } updateAndEnd(pm); @@ -295,8 +287,8 @@ } ProjectState p = projectCache.get(parent); if (p == null) { - throw new BadRequestException(format( - "Parent project '%s' does not exist in target.", parent.get())); + throw new BadRequestException( + format("Parent project '%s' does not exist in target.", parent.get())); } updateAndEnd(pm); } @@ -308,8 +300,7 @@ if (lockFile.lock()) { return lockFile; } - throw new ResourceConflictException( - "project is being imported from another session"); + throw new ResourceConflictException("project is being imported from another session"); } catch (IOException e1) { throw new ResourceConflictException("failed to lock project for import"); }
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/ImportProjectResource.java b/src/main/java/com/googlesource/gerrit/plugins/importer/ImportProjectResource.java index 93b6a68..987b448 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/ImportProjectResource.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/ImportProjectResource.java
@@ -18,7 +18,6 @@ import com.google.gerrit.extensions.restapi.RestView; import com.google.gerrit.reviewdb.client.Project; import com.google.inject.TypeLiteral; - import java.io.File; import java.io.IOException;
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/InsertLinkToOriginalChangeStep.java b/src/main/java/com/googlesource/gerrit/plugins/importer/InsertLinkToOriginalChangeStep.java index ba25273..90f4af1 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/InsertLinkToOriginalChangeStep.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/InsertLinkToOriginalChangeStep.java
@@ -33,7 +33,6 @@ import com.google.gwtorm.server.OrmException; import com.google.inject.Inject; import com.google.inject.assistedinject.Assisted; - import java.io.IOException; class InsertLinkToOriginalChangeStep { @@ -52,14 +51,12 @@ interface Factory { InsertLinkToOriginalChangeStep create( - @Nullable String fromGerrit, - Change change, - ChangeInfo changeInfo, - boolean resume); + @Nullable String fromGerrit, Change change, ChangeInfo changeInfo, boolean resume); } @Inject - InsertLinkToOriginalChangeStep(CurrentUser currentUser, + InsertLinkToOriginalChangeStep( + CurrentUser currentUser, ChangeUpdate.Factory updateFactory, IdentifiedUser.GenericFactory genericUserFactory, ChangeControl.GenericFactory changeControlFactory, @@ -84,14 +81,13 @@ } void insert() throws NoSuchChangeException, OrmException, IOException { - insertMessage(change, (resume ? "Resumed import of " : "Imported from ") - + changeUrl(changeInfo)); + insertMessage( + change, (resume ? "Resumed import of " : "Imported from ") + changeUrl(changeInfo)); } private String changeUrl(ChangeInfo c) { StringBuilder url = new StringBuilder(); - url.append(ensureSlash( - MoreObjects.firstNonNull(fromGerrit, canonicalWebUrl))); + url.append(ensureSlash(MoreObjects.firstNonNull(fromGerrit, canonicalWebUrl))); url.append(c._number); return url.toString(); } @@ -101,19 +97,19 @@ Account.Id userId = ((IdentifiedUser) currentUser).getAccountId(); ChangeUpdate update = updateFactory.create(control(change, userId)); ChangeMessage cmsg = - new ChangeMessage(new ChangeMessage.Key(change.getId(), - ChangeUtil.messageUuid()), userId, TimeUtil.nowTs(), + new ChangeMessage( + new ChangeMessage.Key(change.getId(), ChangeUtil.messageUuid()), + userId, + TimeUtil.nowTs(), change.currentPatchSetId()); cmsg.setMessage(message); cmUtil.addChangeMessage(db, update, cmsg); update.commit(); } - private ChangeControl control(Change change, Account.Id id) - throws NoSuchChangeException { + private ChangeControl control(Change change, Account.Id id) throws NoSuchChangeException { try { - return changeControlFactory.controlFor(db, change, - genericUserFactory.create(id)); + return changeControlFactory.controlFor(db, change, genericUserFactory.create(id)); } catch (OrmException e) { throw new NoSuchChangeException(change.getId()); }
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/ListImportedProjects.java b/src/main/java/com/googlesource/gerrit/plugins/importer/ListImportedProjects.java index c63db70..2e6379c 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/ListImportedProjects.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/ListImportedProjects.java
@@ -21,9 +21,6 @@ import com.google.gerrit.server.config.ConfigResource; import com.google.inject.Inject; import com.google.inject.Singleton; - -import org.kohsuke.args4j.Option; - import java.io.File; import java.io.IOException; import java.nio.file.Path; @@ -31,6 +28,7 @@ import java.util.HashSet; import java.util.Locale; import java.util.Map; +import org.kohsuke.args4j.Option; @Singleton @RequiresCapability(ImportCapability.ID) @@ -38,7 +36,9 @@ private final ProjectsCollection projects; - @Option(name = "--match", metaVar = "MATCH", + @Option( + name = "--match", + metaVar = "MATCH", usage = "List only projects containing this substring, case insensitive") public void setMatch(String match) { this.match = match.toLowerCase(Locale.ENGLISH); @@ -52,8 +52,7 @@ } @Override - public Map<String, ImportProjectInfo> apply(ConfigResource rsrc) - throws IOException { + public Map<String, ImportProjectInfo> apply(ConfigResource rsrc) throws IOException { Map<String, ImportProjectInfo> importedProjects = Maps.newTreeMap(); for (File f : listImportFiles()) { importedProjects.put(projects.FS_LAYOUT.resolveProjectName(f), ImportJson.parse(f)); @@ -76,7 +75,6 @@ } private boolean matches(Path p) { - return match == null - || p.toString().toLowerCase(Locale.ENGLISH).contains(match); + return match == null || p.toString().toLowerCase(Locale.ENGLISH).contains(match); } }
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/ListImportsCommand.java b/src/main/java/com/googlesource/gerrit/plugins/importer/ListImportsCommand.java index 701453a..d242cf4 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/ListImportsCommand.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/ListImportsCommand.java
@@ -21,27 +21,30 @@ import com.google.gerrit.sshd.CommandMetaData; import com.google.gerrit.sshd.SshCommand; import com.google.inject.Inject; - -import org.kohsuke.args4j.Argument; -import org.kohsuke.args4j.Option; - import java.io.IOException; import java.util.Map; +import org.kohsuke.args4j.Argument; +import org.kohsuke.args4j.Option; @RequiresCapability(ImportCapability.ID) @CommandMetaData(name = "list-projects", description = "Lists project imports") class ListProjectImportsCommand extends SshCommand { - @Option(name = "--verbose", aliases = {"-v"}, required = false, + @Option( + name = "--verbose", + aliases = {"-v"}, + required = false, usage = "Print detailed info for each project import") private boolean verbose; - @Argument(index = 0, required = false, metaVar = "MATCH", + @Argument( + index = 0, + required = false, + metaVar = "MATCH", usage = "List only projects containing this substring, case insensitive") private String match; - @Inject - private ListImportedProjects list; + @Inject private ListImportedProjects list; @Override protected void run() throws IOException { @@ -58,8 +61,7 @@ stdout.println(" parent: " + info.parent); stdout.println(format(" %-23s %s:%s", "time", "user", "remote-user")); for (ImportInfo i : info.imports) { - stdout.println( - format(" %-23s %s:%s", i.timestamp, i.user.username, i.remoteUser)); + stdout.println(format(" %-23s %s:%s", i.timestamp, i.user.username, i.remoteUser)); } stdout.println(); }
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/LocalApi.java b/src/main/java/com/googlesource/gerrit/plugins/importer/LocalApi.java index a5dd841..420b8d6 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/LocalApi.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/LocalApi.java
@@ -33,12 +33,10 @@ import com.google.gerrit.server.account.GetSshKeys; import com.google.gwtorm.server.OrmException; import com.google.inject.Inject; - -import org.eclipse.jgit.errors.ConfigInvalidException; - import java.io.IOException; import java.util.List; import java.util.Map; +import org.eclipse.jgit.errors.ConfigInvalidException; public class LocalApi implements GerritApi { private final com.google.gerrit.extensions.api.GerritApi gApi; @@ -56,8 +54,7 @@ } @Override - public ProjectInfo getProject(String projectName) throws IOException, - BadRequestException { + public ProjectInfo getProject(String projectName) throws IOException, BadRequestException { try { return gApi.projects().name(projectName).get(); } catch (RestApiException e) { @@ -66,13 +63,11 @@ } @Override - public List<ChangeInfo> queryChanges(String projectName, int start, - int limit) throws IOException, - BadRequestException { + public List<ChangeInfo> queryChanges(String projectName, int start, int limit) + throws IOException, BadRequestException { try { - QueryRequest query = gApi.changes() - .query("project:" + projectName); + QueryRequest query = gApi.changes().query("project:" + projectName); query .withStart(start) .withOptions( @@ -82,7 +77,7 @@ ListChangesOption.CURRENT_REVISION, ListChangesOption.ALL_REVISIONS, ListChangesOption.ALL_COMMITS); - if(limit > 0) { + if (limit > 0) { query.withLimit(limit); } return query.get(); @@ -92,8 +87,8 @@ } @Override - public GroupInfo getGroup(String groupName) throws IOException, - BadRequestException, OrmException { + public GroupInfo getGroup(String groupName) + throws IOException, BadRequestException, OrmException { try { return gApi.groups().id(groupName).get(); } catch (RestApiException e) { @@ -105,8 +100,7 @@ public Iterable<CommentInfo> getComments(int changeId, String rev) throws IOException, OrmException, BadRequestException { try { - Map<String, List<CommentInfo>> result = - gApi.changes().id(changeId).revision(rev).comments(); + Map<String, List<CommentInfo>> result = gApi.changes().id(changeId).revision(rev).comments(); for (Map.Entry<String, List<CommentInfo>> e : result.entrySet()) { for (CommentInfo i : e.getValue()) { @@ -121,12 +115,11 @@ } @Override - public List<SshKeyInfo> getSshKeys(String userId) throws BadRequestException, - IOException, OrmException, ConfigInvalidException { + public List<SshKeyInfo> getSshKeys(String userId) + throws BadRequestException, IOException, OrmException, ConfigInvalidException { try { AccountResource rsrc = - accounts.parse(TopLevelResource.INSTANCE, - IdString.fromDecoded(userId)); + accounts.parse(TopLevelResource.INSTANCE, IdString.fromDecoded(userId)); return getSshKeys.apply(rsrc); } catch (ResourceNotFoundException | AuthException e) { throw new BadRequestException(e.getMessage());
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/Module.java b/src/main/java/com/googlesource/gerrit/plugins/importer/Module.java index 7c2c2d4..e8f7189 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/Module.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/Module.java
@@ -38,28 +38,27 @@ bind(CapabilityDefinition.class) .annotatedWith(Exports.named(CopyProjectCapability.ID)) .to(CopyProjectCapability.class); - install(new RestApiModule() { - @Override - protected void configure() { - DynamicMap.mapOf(binder(), IMPORT_PROJECT_KIND); - DynamicMap.mapOf(binder(), IMPORT_GROUP_KIND); + install( + new RestApiModule() { + @Override + protected void configure() { + DynamicMap.mapOf(binder(), IMPORT_PROJECT_KIND); + DynamicMap.mapOf(binder(), IMPORT_GROUP_KIND); - child(CONFIG_KIND, "projects").to(ProjectsCollection.class); - get(IMPORT_PROJECT_KIND).to(GetImportedProject.class); - put(IMPORT_PROJECT_KIND, "resume").to(ResumeProjectImport.class); - delete(IMPORT_PROJECT_KIND).to(CompleteProjectImport.class); + child(CONFIG_KIND, "projects").to(ProjectsCollection.class); + get(IMPORT_PROJECT_KIND).to(GetImportedProject.class); + put(IMPORT_PROJECT_KIND, "resume").to(ResumeProjectImport.class); + delete(IMPORT_PROJECT_KIND).to(CompleteProjectImport.class); - put(PROJECT_KIND, "copy").to(CopyProject.class); - put(PROJECT_KIND, "copy.resume").to(ResumeCopyProject.class); - put(PROJECT_KIND, "import.resume").to(ResumeProjectImport.OnProjects.class); - post(PROJECT_KIND, "delete").to(CompleteProjectImport.OnProjects.class); + put(PROJECT_KIND, "copy").to(CopyProject.class); + put(PROJECT_KIND, "copy.resume").to(ResumeCopyProject.class); + put(PROJECT_KIND, "import.resume").to(ResumeProjectImport.OnProjects.class); + post(PROJECT_KIND, "delete").to(CompleteProjectImport.OnProjects.class); - child(CONFIG_KIND, "groups").to(GroupsCollection.class); - } - }); - bind(LifecycleListener.class) - .annotatedWith(UniqueAnnotations.create()) - .to(ImportLog.class); + child(CONFIG_KIND, "groups").to(GroupsCollection.class); + } + }); + bind(LifecycleListener.class).annotatedWith(UniqueAnnotations.create()).to(ImportLog.class); bind(OpenRepositoryStep.class); bind(ConfigureRepositoryStep.class); bind(ConfigureProjectStep.class);
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/OpenRepositoryStep.java b/src/main/java/com/googlesource/gerrit/plugins/importer/OpenRepositoryStep.java index 9386c68..75cd315 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/OpenRepositoryStep.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/OpenRepositoryStep.java
@@ -30,23 +30,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.RepositoryNotFoundException; import org.eclipse.jgit.lib.ProgressMonitor; import org.eclipse.jgit.lib.Repository; -import java.io.IOException; - @Singleton class OpenRepositoryStep { private final GitRepositoryManager git; private final ProjectCache projectCache; - private final DynamicSet<ProjectCreationValidationListener> - projectCreationValidationListeners; + private final DynamicSet<ProjectCreationValidationListener> projectCreationValidationListeners; private final Provider<ProjectsCollection> projectsCollection; @Inject - OpenRepositoryStep(GitRepositoryManager git, + OpenRepositoryStep( + GitRepositoryManager git, ProjectCache projectCache, DynamicSet<ProjectCreationValidationListener> projectCreationValidationListeners, Provider<ProjectsCollection> projectsCollection) { @@ -56,8 +54,7 @@ this.projectsCollection = projectsCollection; } - Repository open(Project.NameKey name, boolean resume, ProgressMonitor pm, - Project.NameKey parent) + Repository open(Project.NameKey name, boolean resume, ProgressMonitor pm, Project.NameKey parent) throws ResourceConflictException, IOException, UnprocessableEntityException { pm.beginTask("Open repository", 1); try { @@ -65,13 +62,11 @@ if (resume) { return repo; } - throw new ResourceConflictException(format( - "repository %s already exists", name.get())); + throw new ResourceConflictException(format("repository %s already exists", name.get())); } catch (RepositoryNotFoundException e) { // Project doesn't exist if (resume) { - throw new ResourceConflictException(format( - "repository %s does not exist", name.get())); + throw new ResourceConflictException(format("repository %s does not exist", name.get())); } }
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/PasswordUtil.java b/src/main/java/com/googlesource/gerrit/plugins/importer/PasswordUtil.java index 6409e72..f4705b3 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/PasswordUtil.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/PasswordUtil.java
@@ -18,7 +18,6 @@ import com.google.common.base.Strings; import com.google.gerrit.sshd.BaseCommand.UnloggedFailure; - import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; @@ -30,8 +29,7 @@ static String readPassword(InputStream in, String pass) throws UnsupportedEncodingException, IOException, UnloggedFailure { if ("-".equals(pass)) { - BufferedReader br = new BufferedReader( - new InputStreamReader(in, UTF_8)); + BufferedReader br = new BufferedReader(new InputStreamReader(in, UTF_8)); pass = Strings.nullToEmpty(br.readLine()); if (br.readLine() != null) { throw new UnloggedFailure(1, "multi-line password not allowed");
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/ProjectCommand.java b/src/main/java/com/googlesource/gerrit/plugins/importer/ProjectCommand.java index 5dbbaae..060087b 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/ProjectCommand.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/ProjectCommand.java
@@ -20,60 +20,78 @@ import com.google.gerrit.extensions.restapi.RestApiException; import com.google.gerrit.reviewdb.client.Project; import com.google.gerrit.server.config.ConfigResource; -import com.google.gerrit.server.update.UpdateException; import com.google.gerrit.server.project.NoSuchChangeException; +import com.google.gerrit.server.update.UpdateException; import com.google.gerrit.server.validators.ValidationException; import com.google.gerrit.sshd.CommandMetaData; import com.google.gerrit.sshd.SshCommand; import com.google.gwtorm.server.OrmException; import com.google.inject.Inject; - +import java.io.IOException; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.errors.ConfigInvalidException; import org.kohsuke.args4j.Argument; import org.kohsuke.args4j.Option; -import java.io.IOException; - @RequiresCapability(ImportCapability.ID) @CommandMetaData(name = "project", description = "Imports a project") public class ProjectCommand extends SshCommand { - @Option(name = "--from", aliases = {"-f"}, required = true, metaVar = "URL", + @Option( + name = "--from", + aliases = {"-f"}, + required = true, + metaVar = "URL", usage = "URL of the remote system from where the project should be imported") private String url; - @Option(name = "--name", required = false, metaVar = "NAME", - usage = "name of project in source system (if not specified it is" - + " assumed to be the same name as in the target system)") + @Option( + name = "--name", + required = false, + metaVar = "NAME", + usage = + "name of project in source system (if not specified it is" + + " assumed to be the same name as in the target system)") private String name; - @Option(name = "--user", aliases = {"-u"}, required = true, metaVar = "NAME", + @Option( + name = "--user", + aliases = {"-u"}, + required = true, + metaVar = "NAME", usage = "user on remote system") private String user; - @Option(name = "--pass", aliases = {"-p"}, required = true, metaVar = "-|PASS", + @Option( + name = "--pass", + aliases = {"-p"}, + required = true, + metaVar = "-|PASS", usage = "password of remote user") private String pass; - @Option(name = "--parent", required = false, metaVar = "NAME", + @Option( + name = "--parent", + required = false, + metaVar = "NAME", usage = "name of parent project in target system") private String parent; @Option(name = "--quiet", usage = "suppress progress messages") private boolean quiet; - @Argument(index = 0, required = true, metaVar = "NAME", + @Argument( + index = 0, + required = true, + metaVar = "NAME", usage = "name of the project in target system") private String project; - @Inject - private ImportProject.Factory importProjectFactory; + @Inject private ImportProject.Factory importProjectFactory; @Override protected void run() - throws OrmException, IOException, UnloggedFailure, ValidationException, - GitAPIException, NoSuchChangeException, NoSuchAccountException, - UpdateException, ConfigInvalidException { + throws OrmException, IOException, UnloggedFailure, ValidationException, GitAPIException, + NoSuchChangeException, NoSuchAccountException, UpdateException, ConfigInvalidException { ImportProject.Input input = new ImportProject.Input(); input.from = url; input.name = name;
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/ProjectsCollection.java b/src/main/java/com/googlesource/gerrit/plugins/importer/ProjectsCollection.java index 74d3efb..600ca02 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/ProjectsCollection.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/ProjectsCollection.java
@@ -30,16 +30,15 @@ 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; @Singleton @RequiresCapability(ImportCapability.ID) -public class ProjectsCollection implements - ChildCollection<ConfigResource, ImportProjectResource>, - AcceptsCreate<ConfigResource> { +public class ProjectsCollection + implements ChildCollection<ConfigResource, ImportProjectResource>, + AcceptsCreate<ConfigResource> { class FileSystemLayout { @@ -54,39 +53,40 @@ } String resolveProjectName(File f) throws IOException { - if(! f.isFile()) { - throw new RuntimeException(format("'%s' is not a file. Project names" - + "can only be resolved for existing files, not for directories." - , f)); + if (!f.isFile()) { + throw new RuntimeException( + format( + "'%s' is not a file. Project names" + + "can only be resolved for existing files, not for directories.", + f)); } - if(! f.getName().endsWith(SUFFIX_IMPORT_STATUS_FILE)) { - throw new RuntimeException(format("'%s' is not a valid import status" - + "file. Invalid appendix. Should be '%s'.", f, - SUFFIX_IMPORT_STATUS_FILE)); + if (!f.getName().endsWith(SUFFIX_IMPORT_STATUS_FILE)) { + throw new RuntimeException( + format( + "'%s' is not a valid import status" + "file. Invalid appendix. Should be '%s'.", + f, SUFFIX_IMPORT_STATUS_FILE)); } String diff = diff(lockRoot, f); - return diff.substring(0, diff.length() - - SUFFIX_IMPORT_STATUS_FILE.length()); + return diff.substring(0, diff.length() - SUFFIX_IMPORT_STATUS_FILE.length()); } /** - * Returns the path between two file instances. The child instance - * is expected to be a child of the parent instance. + * Returns the path between two file instances. The child instance is expected to be a child of + * the parent instance. + * * @param parent * @param child * @return The path between parent and child. - * @throws IOException in case <code>child</code> is not a child of - * <code>parent</code>. + * @throws IOException in case <code>child</code> is not a child of <code>parent</code>. */ private String diff(File parent, File child) throws IOException { Path parentPath = parent.getAbsoluteFile().toPath(); - Path childPath= child.getAbsoluteFile().toPath(); + Path childPath = child.getAbsoluteFile().toPath(); if (childPath.startsWith(parentPath)) { return parentPath.relativize(childPath).toString(); } - throw new IOException(String.format("'%s' is not a child of '%s'.", - child, parent)); + throw new IOException(String.format("'%s' is not a child of '%s'.", child, parent)); } } @@ -120,8 +120,7 @@ return parse(id.get()); } - public ImportProjectResource parse(String id) - throws ResourceNotFoundException { + public ImportProjectResource parse(String id) throws ResourceNotFoundException { File f = FS_LAYOUT.getImportStatusFile(id); if (!f.exists()) { throw new ResourceNotFoundException(id); @@ -137,8 +136,7 @@ @Override @SuppressWarnings("unchecked") - public ImportProject create(ConfigResource parent, IdString id) - throws RestApiException { + public ImportProject create(ConfigResource parent, IdString id) throws RestApiException { return importProjectFactory.create(new Project.NameKey(id.get())); } }
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/RemoteApi.java b/src/main/java/com/googlesource/gerrit/plugins/importer/RemoteApi.java index b83a142..061341e 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/RemoteApi.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/RemoteApi.java
@@ -28,14 +28,12 @@ import com.google.gerrit.server.OutputFormat; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; - -import org.apache.http.HttpStatus; - import java.io.IOException; import java.net.UnknownHostException; import java.util.EnumSet; import java.util.List; import java.util.Map; +import org.apache.http.HttpStatus; class RemoteApi implements GerritApi { @@ -46,35 +44,37 @@ } @Override - public ProjectInfo getProject(String projectName) throws IOException, - BadRequestException { + public ProjectInfo getProject(String projectName) throws IOException, BadRequestException { projectName = encode(projectName); String endPoint = "/projects/" + projectName; try (RestResponse r = checkedGet(endPoint)) { - return newGson().fromJson(r.getReader(), - new TypeToken<ProjectInfo>() {}.getType()); + return newGson().fromJson(r.getReader(), new TypeToken<ProjectInfo>() {}.getType()); } } @Override - public List<ChangeInfo> queryChanges(String projectName, - int start, int limit) throws IOException, BadRequestException { + public List<ChangeInfo> queryChanges(String projectName, int start, int limit) + throws IOException, BadRequestException { String endPoint = - "/changes/?S=" + - start + ((limit > 0) ? "&n=" + limit : "") + "&q=project:" + projectName + - "&O=" + Integer.toHexString(ListChangesOption.toBits( - EnumSet.of( - ListChangesOption.DETAILED_LABELS, - ListChangesOption.DETAILED_ACCOUNTS, - ListChangesOption.MESSAGES, - ListChangesOption.CURRENT_REVISION, - ListChangesOption.ALL_REVISIONS, - ListChangesOption.ALL_COMMITS))); + "/changes/?S=" + + start + + ((limit > 0) ? "&n=" + limit : "") + + "&q=project:" + + projectName + + "&O=" + + Integer.toHexString( + ListChangesOption.toBits( + EnumSet.of( + ListChangesOption.DETAILED_LABELS, + ListChangesOption.DETAILED_ACCOUNTS, + ListChangesOption.MESSAGES, + ListChangesOption.CURRENT_REVISION, + ListChangesOption.ALL_REVISIONS, + ListChangesOption.ALL_COMMITS))); List<ChangeInfo> result; try (RestResponse r = checkedGet(endPoint)) { - result = newGson().fromJson(r.getReader(), - new TypeToken<List<ChangeInfo>>() {}.getType()); + result = newGson().fromJson(r.getReader(), new TypeToken<List<ChangeInfo>>() {}.getType()); } for (ChangeInfo c : result) { @@ -87,13 +87,11 @@ } @Override - public GroupInfo getGroup(String groupName) throws IOException, - BadRequestException { + public GroupInfo getGroup(String groupName) throws IOException, BadRequestException { groupName = encode(groupName); String endPoint = "/groups/" + groupName + "/detail"; try (RestResponse r = checkedGet(endPoint)) { - return newGson().fromJson(r.getReader(), - new TypeToken<GroupInfo>() {}.getType()); + return newGson().fromJson(r.getReader(), new TypeToken<GroupInfo>() {}.getType()); } } @@ -107,8 +105,10 @@ return null; } assertOK(HttpMethod.GET, endPoint, r); - result = newGson().fromJson(r.getReader(), - new TypeToken<Map<String, List<CommentInfo>>>() {}.getType()); + result = + newGson() + .fromJson( + r.getReader(), new TypeToken<Map<String, List<CommentInfo>>>() {}.getType()); } for (Map.Entry<String, List<CommentInfo>> e : result.entrySet()) { for (CommentInfo i : e.getValue()) { @@ -122,8 +122,7 @@ public List<SshKeyInfo> getSshKeys(String userId) throws BadRequestException, IOException { String endPoint = "/accounts/" + userId + "/sshkeys/"; try (RestResponse r = checkedGet(endPoint)) { - return newGson().fromJson(r.getReader(), - new TypeToken<List<SshKeyInfo>>() {}.getType()); + return newGson().fromJson(r.getReader(), new TypeToken<List<SshKeyInfo>>() {}.getType()); } } @@ -131,8 +130,8 @@ public Version getVersion() throws BadRequestException, IOException { String endPoint = "/config/server/version"; try (RestResponse r = checkedGet(endPoint)) { - return new Version((String)newGson().fromJson( - r.getReader(), new TypeToken<String>() {}.getType())); + return new Version( + (String) newGson().fromJson(r.getReader(), new TypeToken<String>() {}.getType())); } } @@ -140,8 +139,7 @@ return OutputFormat.JSON_COMPACT.newGson(); } - private RestResponse checkedGet(String endPoint) throws IOException, - BadRequestException { + private RestResponse checkedGet(String endPoint) throws IOException, BadRequestException { try { RestResponse r = restSession.get(endPoint); assertOK(HttpMethod.GET, endPoint, r); @@ -151,22 +149,25 @@ } } - private static void assertOK(HttpMethod method, String endPoint, - RestResponse r) throws IOException, BadRequestException { + private static void assertOK(HttpMethod method, String endPoint, RestResponse r) + throws IOException, BadRequestException { if (r.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { throw new BadRequestException( "invalid credentials: accessing source system failed with 401 Unauthorized"); } if (r.getStatusCode() == HttpStatus.SC_NOT_FOUND) { - throw new BadRequestException(String.format( - "missing permissions or invalid import entity identifier: Accessing " - + "REST endpoint %s on source system failed with 404 Not found", endPoint)); + throw new BadRequestException( + String.format( + "missing permissions or invalid import entity identifier: Accessing " + + "REST endpoint %s on source system failed with 404 Not found", + endPoint)); } if (r.getStatusCode() < 200 || 300 <= r.getStatusCode()) { - throw new IOException(String.format( - "Unexpected response code for %s on %s : %s", method.name(), - endPoint, r.getStatusCode())); + throw new IOException( + String.format( + "Unexpected response code for %s on %s : %s", + method.name(), endPoint, r.getStatusCode())); } }
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/ReplayChangesStep.java b/src/main/java/com/googlesource/gerrit/plugins/importer/ReplayChangesStep.java index 200d7cc..dca177e 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/ReplayChangesStep.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/ReplayChangesStep.java
@@ -28,17 +28,19 @@ import com.google.gerrit.reviewdb.client.RefNames; import com.google.gerrit.reviewdb.server.ReviewDb; import com.google.gerrit.server.Sequences; -import com.google.gerrit.server.update.UpdateException; import com.google.gerrit.server.index.change.ChangeIndexer; import com.google.gerrit.server.notedb.NotesMigration; import com.google.gerrit.server.project.NoSuchChangeException; import com.google.gerrit.server.query.change.ChangeData; import com.google.gerrit.server.query.change.InternalChangeQuery; +import com.google.gerrit.server.update.UpdateException; import com.google.gwtorm.server.OrmException; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.assistedinject.Assisted; - +import java.io.IOException; +import java.util.Collections; +import java.util.List; import org.eclipse.jgit.errors.ConfigInvalidException; import org.eclipse.jgit.lib.ProgressMonitor; import org.eclipse.jgit.lib.Repository; @@ -46,10 +48,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.IOException; -import java.util.Collections; -import java.util.List; - class ReplayChangesStep { interface Factory { @@ -135,16 +133,15 @@ this.isNoteDbEnabled = migration.enabled(); } - void replay() throws IOException, OrmException, - NoSuchAccountException, NoSuchChangeException, RestApiException, - UpdateException, ConfigInvalidException { + void replay() + throws IOException, OrmException, NoSuchAccountException, NoSuchChangeException, + RestApiException, UpdateException, ConfigInvalidException { int start = 0; int limit = GlobalCapability.DEFAULT_MAX_QUERY_LIMIT; pm.beginTask("Replay Changes", ProgressMonitor.UNKNOWN); - for(;;) { - List<ChangeInfo> changes = api.queryChanges(srcProject.get(), - start, limit); - if(changes.isEmpty()) { + for (; ; ) { + List<ChangeInfo> changes = api.queryChanges(srcProject.get(), start, limit); + if (changes.isEmpty()) { break; } start += changes.size(); @@ -154,14 +151,13 @@ try { replayChange(rw, c); } catch (Exception e) { - log.error(String.format("Failed to replay change %s.", - Url.decode(c.id)), e); + log.error(String.format("Failed to replay change %s.", Url.decode(c.id)), e); throw e; } last = c; pm.update(1); } - if(!Boolean.TRUE.equals(last._moreChanges)) { + if (!Boolean.TRUE.equals(last._moreChanges)) { break; } } @@ -170,9 +166,8 @@ } private void replayChange(RevWalk rw, ChangeInfo c) - throws IOException, OrmException, NoSuchAccountException, - NoSuchChangeException, RestApiException, IllegalArgumentException, - UpdateException, ConfigInvalidException { + throws IOException, OrmException, NoSuchAccountException, NoSuchChangeException, + RestApiException, IllegalArgumentException, UpdateException, ConfigInvalidException { if (c.status == ChangeStatus.DRAFT) { // no import of draft changes return; @@ -218,33 +213,38 @@ } private Change findChange(ChangeInfo c) throws OrmException { - List<Change> changes = ChangeData.asChanges( - queryProvider.get().byBranchKey( - new Branch.NameKey(targetProject, RefNames.fullName(c.branch)), - new Change.Key(c.changeId))); + List<Change> changes = + ChangeData.asChanges( + queryProvider + .get() + .byBranchKey( + new Branch.NameKey(targetProject, RefNames.fullName(c.branch)), + new Change.Key(c.changeId))); if (changes.isEmpty()) { return null; } - return db.changes().get( - Iterators.getOnlyElement(changes.iterator()).getId()); + return db.changes().get(Iterators.getOnlyElement(changes.iterator()).getId()); } private Change createChange(ChangeInfo c) - throws OrmException, NoSuchAccountException, IOException, - RestApiException, ConfigInvalidException { + throws OrmException, NoSuchAccountException, IOException, RestApiException, + ConfigInvalidException { Change.Id changeId = new Change.Id(sequences.nextChangeId()); Change change = - new Change(new Change.Key(c.changeId), changeId, accountUtil.resolveUser(api, c.owner), - new Branch.NameKey(targetProject, RefNames.fullName(c.branch)), c.created); + new Change( + new Change.Key(c.changeId), + changeId, + accountUtil.resolveUser(api, c.owner), + new Branch.NameKey(targetProject, RefNames.fullName(c.branch)), + c.created); change.setStatus(Change.Status.forChangeStatus(c.status)); change.setTopic(c.topic); change.setLastUpdatedOn(c.updated); return change; } - private void upsertChange(boolean resumeChange, Change change, ChangeInfo c) - throws OrmException { + private void upsertChange(boolean resumeChange, Change change, ChangeInfo c) throws OrmException { if (resumeChange) { change.setStatus(Change.Status.forChangeStatus(c.status)); change.setTopic(c.topic);
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/ReplayInlineCommentsStep.java b/src/main/java/com/googlesource/gerrit/plugins/importer/ReplayInlineCommentsStep.java index 8fabda0..07c524d 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/ReplayInlineCommentsStep.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/ReplayInlineCommentsStep.java
@@ -48,11 +48,6 @@ import com.google.gwtorm.server.OrmException; import com.google.inject.Inject; import com.google.inject.assistedinject.Assisted; - -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.HashSet; @@ -60,16 +55,18 @@ import java.util.List; import java.util.Map; import java.util.Set; +import org.eclipse.jgit.errors.ConfigInvalidException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; class ReplayInlineCommentsStep { interface Factory { - ReplayInlineCommentsStep create(Change change, ChangeInfo changeInfo, - GerritApi api, boolean resume); + ReplayInlineCommentsStep create( + Change change, ChangeInfo changeInfo, GerritApi api, boolean resume); } - private static final Logger log = LoggerFactory - .getLogger(ReplayInlineCommentsStep.class); + private static final Logger log = LoggerFactory.getLogger(ReplayInlineCommentsStep.class); private final AccountUtil accountUtil; private final ReviewDb db; @@ -86,7 +83,8 @@ private final boolean resume; @Inject - public ReplayInlineCommentsStep(AccountUtil accountUtil, + public ReplayInlineCommentsStep( + AccountUtil accountUtil, ReviewDb db, IdentifiedUser.GenericFactory genericUserFactory, ChangeControl.GenericFactory changeControlFactory, @@ -116,39 +114,38 @@ void replay() throws RestApiException, OrmException, IOException, NoSuchChangeException, - NoSuchAccountException, ConfigInvalidException { - ChangeControl ctrl = control(change, change.getOwner()); - for (PatchSet ps : ChangeUtil.PS_ID_ORDER - .sortedCopy(psUtil.byChange(db, ctrl.getNotes()))) { - Iterable<CommentInfo> comments = api.getComments( - changeInfo._number, ps.getRevision().get()); + NoSuchAccountException, ConfigInvalidException { + ChangeControl ctrl = control(change, change.getOwner()); + for (PatchSet ps : ChangeUtil.PS_ID_ORDER.sortedCopy(psUtil.byChange(db, ctrl.getNotes()))) { + Iterable<CommentInfo> comments = api.getComments(changeInfo._number, ps.getRevision().get()); if (resume) { if (comments == null) { // the revision does not exist in the source system, // it must be a revision that was created in the target system after // the initial import - log.warn(String.format( - "Project %s was modified in target system: " - + "Skip replay inline comments for patch set %s" - + " which doesn't exist in the source system.", - change.getProject().get(), ps.getId().toString())); + log.warn( + String.format( + "Project %s was modified in target system: " + + "Skip replay inline comments for patch set %s" + + " which doesn't exist in the source system.", + change.getProject().get(), ps.getId().toString())); continue; } comments = filterComments(ps, comments); } else if (comments == null) { - log.warn(String.format( - "Cannot retrieve comments for revision %s, " - + "revision not found in source system: " - + "Skip replay inline comments for patch set %s of project %s.", - ps.getRevision().get(), ps.getId().toString(), - change.getProject().get())); + log.warn( + String.format( + "Cannot retrieve comments for revision %s, " + + "revision not found in source system: " + + "Skip replay inline comments for patch set %s of project %s.", + ps.getRevision().get(), ps.getId().toString(), change.getProject().get())); continue; } Multimap<Account.Id, CommentInfo> commentsByAuthor = ArrayListMultimap.create(); for (CommentInfo comment : comments) { - Account.Id id = accountUtil.resolveUser(api, comment.author); + Account.Id id = accountUtil.resolveUser(api, comment.author); commentsByAuthor.put(id, comment); } @@ -158,8 +155,8 @@ } } - private Iterable<CommentInfo> filterComments(PatchSet ps, - Iterable<CommentInfo> comments) throws OrmException { + private Iterable<CommentInfo> filterComments(PatchSet ps, Iterable<CommentInfo> comments) + throws OrmException { Set<String> existingUuids = new HashSet<>(); for (PatchLineComment c : db.patchComments().byPatchSet(ps.getId())) { existingUuids.add(c.getKey().get()); @@ -175,9 +172,8 @@ return comments; } - private void insertComments(PatchSet ps, Account.Id author, - Collection<CommentInfo> comments) throws OrmException, IOException, - NoSuchChangeException { + private void insertComments(PatchSet ps, Account.Id author, Collection<CommentInfo> comments) + throws OrmException, IOException, NoSuchChangeException { ChangeControl ctrl = control(change, author); Map<String, Comment> drafts = scanDraftComments(ctrl, ps); @@ -190,8 +186,9 @@ Comment e = drafts.remove(Url.decode(c.id)); if (e == null) { - e = new Comment( - new Comment.Key(Url.decode(c.id), c.path, ps.getId().get()), + e = + new Comment( + new Comment.Key(Url.decode(c.id), c.path, ps.getId().get()), author, c.updated, c.side == Side.PARENT ? (short) 0 : (short) 1, @@ -203,11 +200,9 @@ } setCommentRevId(e, patchListCache, change, ps); if (c.range != null) { - e.setRange(new CommentRange( - c.range.startLine, - c.range.startCharacter, - c.range.endLine, - c.range.endCharacter)); + e.setRange( + new CommentRange( + c.range.startLine, c.range.startCharacter, c.range.endLine, c.range.endCharacter)); e.lineNbr = c.range.endLine; } else { e.lineNbr = c.line == null ? 0 : c.line; @@ -224,24 +219,22 @@ update.commit(); } - private Map<String, Comment> scanDraftComments(ChangeControl ctrl, - PatchSet ps) throws OrmException { + private Map<String, Comment> scanDraftComments(ChangeControl ctrl, PatchSet ps) + throws OrmException { Map<String, Comment> drafts = Maps.newHashMap(); - for (Comment c : commentsUtil.draftByPatchSetAuthor(db, ps.getId(), - ((IdentifiedUser) ctrl.getUser()).getAccountId(), - ctrl.getNotes())) { + for (Comment c : + commentsUtil.draftByPatchSetAuthor( + db, ps.getId(), ((IdentifiedUser) ctrl.getUser()).getAccountId(), ctrl.getNotes())) { drafts.put(c.key.uuid, c); } return drafts; } - private ChangeControl control(Change change, Account.Id id) - throws NoSuchChangeException { + private ChangeControl control(Change change, Account.Id id) throws NoSuchChangeException { try { - return changeControlFactory.controlFor(db, change, - genericUserFactory.create(id)); + return changeControlFactory.controlFor(db, change, genericUserFactory.create(id)); } catch (OrmException e) { - throw new NoSuchChangeException(change.getId()); - } + throw new NoSuchChangeException(change.getId()); + } } }
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/ReplayMessagesStep.java b/src/main/java/com/googlesource/gerrit/plugins/importer/ReplayMessagesStep.java index dde14ee..d93b9c5 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/ReplayMessagesStep.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/ReplayMessagesStep.java
@@ -31,18 +31,15 @@ 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.sql.Timestamp; import java.util.Collections; +import org.eclipse.jgit.errors.ConfigInvalidException; class ReplayMessagesStep { interface Factory { - ReplayMessagesStep create(Change change, ChangeInfo changeInfo, - boolean resume); + ReplayMessagesStep create(Change change, ChangeInfo changeInfo, boolean resume); } private final AccountUtil accountUtil; @@ -56,7 +53,8 @@ private final boolean resume; @Inject - public ReplayMessagesStep(AccountUtil accountUtil, + public ReplayMessagesStep( + AccountUtil accountUtil, ChangeUpdate.Factory updateFactory, ChangeMessagesUtil cmUtil, IdentifiedUser.GenericFactory genericUserFactory, @@ -76,9 +74,9 @@ this.resume = resume; } - void replay(GerritApi api) throws NoSuchAccountException, - NoSuchChangeException, OrmException, IOException, RestApiException, - ConfigInvalidException { + void replay(GerritApi api) + throws NoSuchAccountException, NoSuchChangeException, OrmException, IOException, + RestApiException, ConfigInvalidException { for (ChangeMessageInfo msg : changeInfo.messages) { ChangeMessage.Key msgKey = new ChangeMessage.Key(change.getId(), msg.id); if (resume && db.changeMessages().get(msgKey) != null) { @@ -87,9 +85,8 @@ } Timestamp ts = msg.date; - PatchSet.Id psId = msg._revisionNumber != null - ? new PatchSet.Id(change.getId(), msg._revisionNumber) - : null; + PatchSet.Id psId = + msg._revisionNumber != null ? new PatchSet.Id(change.getId(), msg._revisionNumber) : null; if (msg.author != null) { Account.Id userId = accountUtil.resolveUser(api, msg.author); ChangeUpdate update = updateFactory.create(control(change, userId), ts); @@ -100,19 +97,16 @@ } else { // Message create by the GerritPersonIdent user ChangeMessage cmsg = - new ChangeMessage(new ChangeMessage.Key(change.getId(), msg.id), - null, ts, psId); + new ChangeMessage(new ChangeMessage.Key(change.getId(), msg.id), null, ts, psId); cmsg.setMessage(msg.message); db.changeMessages().insert(Collections.singleton(cmsg)); } } } - private ChangeControl control(Change change, Account.Id id) - throws NoSuchChangeException { + private ChangeControl control(Change change, Account.Id id) throws NoSuchChangeException { try { - return changeControlFactory.controlFor(db, change, - genericUserFactory.create(id)); + return changeControlFactory.controlFor(db, change, genericUserFactory.create(id)); } catch (OrmException e) { throw new NoSuchChangeException(change.getId()); }
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/ReplayRevisionsStep.java b/src/main/java/com/googlesource/gerrit/plugins/importer/ReplayRevisionsStep.java index 85e1a07..cafb248 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/ReplayRevisionsStep.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/ReplayRevisionsStep.java
@@ -27,7 +27,9 @@ 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.List; import org.eclipse.jgit.errors.ConfigInvalidException; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.ObjectId; @@ -38,19 +40,13 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - class ReplayRevisionsStep { interface Factory { - ReplayRevisionsStep create(Repository repo, RevWalk rw, Change change, - ChangeInfo changeInfo); + ReplayRevisionsStep create(Repository repo, RevWalk rw, Change change, ChangeInfo changeInfo); } - private static final Logger log = LoggerFactory - .getLogger(ReplayRevisionsStep.class); + private static final Logger log = LoggerFactory.getLogger(ReplayRevisionsStep.class); private final AccountUtil accountUtil; private final ReviewDb db; @@ -61,7 +57,8 @@ private final ChangeInfo changeInfo; @Inject - public ReplayRevisionsStep(AccountUtil accountUtil, + public ReplayRevisionsStep( + AccountUtil accountUtil, ReviewDb db, PatchSetInfoFactory patchSetInfoFactory, @Assisted Repository repo, @@ -78,8 +75,8 @@ } void replay(GerritApi api) - throws IOException, OrmException, NoSuchAccountException, - RestApiException, ConfigInvalidException { + throws IOException, OrmException, NoSuchAccountException, RestApiException, + ConfigInvalidException { List<RevisionInfo> revisions = new ArrayList<>(changeInfo.revisions.values()); sortRevisionInfoByNumber(revisions); List<PatchSet> patchSets = new ArrayList<>(); @@ -109,10 +106,11 @@ } // a patch set with the same number was created both in the source // and in the target system - log.warn(String.format( - "Project %s was modified in target system: " - + "Skip replay revision for patch set %s.", - change.getProject().get(), ps.getId().toString())); + log.warn( + String.format( + "Project %s was modified in target system: " + + "Skip replay revision for patch set %s.", + change.getProject().get(), ps.getId().toString())); continue; } @@ -133,15 +131,17 @@ if (change.currentPatchSetId() == null) { if (changeInfo.currentRevision != null) { - log.warn(String.format( - "Current revision %s of change %s not found." - + " Setting lastest revision %s as current patch set.", - changeInfo.currentRevision, changeInfo.id, info.getRevId())); + log.warn( + String.format( + "Current revision %s of change %s not found." + + " Setting lastest revision %s as current patch set.", + changeInfo.currentRevision, changeInfo.id, info.getRevId())); } else { - log.warn(String.format( - "Change %s has no current revision." - + " Setting lastest revision %s as current patch set.", - changeInfo.id, info.getRevId())); + log.warn( + String.format( + "Change %s has no current revision." + + " Setting lastest revision %s as current patch set.", + changeInfo.id, info.getRevId())); } change.setCurrentPatchSet(info); } @@ -154,16 +154,14 @@ } private static String imported(String ref) { - return ConfigureRepositoryStep.R_IMPORTS - + ref.substring(Constants.R_REFS.length()); + return ConfigureRepositoryStep.R_IMPORTS + ref.substring(Constants.R_REFS.length()); } private static void sortRevisionInfoByNumber(List<RevisionInfo> list) { list.sort((a, b) -> a._number - b._number); } - private void updateRef(Repository repo, PatchSet ps) - throws IOException { + private void updateRef(Repository repo, PatchSet ps) throws IOException { String ref = ps.getId().toRefName(); RefUpdate ru = repo.updateRef(ref); ru.setExpectedOldObjectId(ObjectId.zeroId()); @@ -182,8 +180,8 @@ case REJECTED_CURRENT_BRANCH: case RENAMED: default: - throw new IOException(String.format( - "Failed to create ref %s, RefUpdate.Result = %s", ref, result)); + throw new IOException( + String.format("Failed to create ref %s, RefUpdate.Result = %s", ref, result)); } } }
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/RestResponse.java b/src/main/java/com/googlesource/gerrit/plugins/importer/RestResponse.java index 24f6831..27ca570 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/RestResponse.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/RestResponse.java
@@ -16,11 +16,10 @@ import static com.google.gerrit.httpd.restapi.RestApiServlet.JSON_MAGIC; -import org.apache.http.client.methods.CloseableHttpResponse; - import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; +import org.apache.http.client.methods.CloseableHttpResponse; public class RestResponse extends HttpResponse {
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/RestSession.java b/src/main/java/com/googlesource/gerrit/plugins/importer/RestSession.java index d2ca5c7..39e5c38 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/RestSession.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/RestSession.java
@@ -18,7 +18,10 @@ import com.google.common.base.Preconditions; import com.google.gerrit.extensions.restapi.RawInput; import com.google.gerrit.server.OutputFormat; - +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; @@ -28,11 +31,6 @@ import org.apache.http.entity.StringEntity; import org.apache.http.message.BasicHeader; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; - public class RestSession extends HttpSession { public RestSession(String url, String user, String pass) { @@ -53,9 +51,9 @@ HttpPut put = new HttpPut(url + "/a" + endPoint); if (content != null) { put.addHeader(new BasicHeader("Content-Type", "application/json")); - put.setEntity(new StringEntity( - OutputFormat.JSON_COMPACT.newGson().toJson(content), - Charsets.UTF_8.name())); + put.setEntity( + new StringEntity( + OutputFormat.JSON_COMPACT.newGson().toJson(content), Charsets.UTF_8.name())); } return new RestResponse(getClient().execute(put)); } @@ -64,10 +62,9 @@ Preconditions.checkNotNull(stream); HttpPut put = new HttpPut(url + "/a" + endPoint); put.addHeader(new BasicHeader("Content-Type", stream.getContentType())); - put.setEntity(new BufferedHttpEntity( - new InputStreamEntity( - stream.getInputStream(), - stream.getContentLength()))); + put.setEntity( + new BufferedHttpEntity( + new InputStreamEntity(stream.getInputStream(), stream.getContentLength()))); return new RestResponse(getClient().execute(put)); } @@ -79,9 +76,9 @@ HttpPost post = new HttpPost(url + "/a" + endPoint); if (content != null) { post.addHeader(new BasicHeader("Content-Type", "application/json")); - post.setEntity(new StringEntity( - OutputFormat.JSON_COMPACT.newGson().toJson(content), - Charsets.UTF_8.name())); + post.setEntity( + new StringEntity( + OutputFormat.JSON_COMPACT.newGson().toJson(content), Charsets.UTF_8.name())); } return new RestResponse(getClient().execute(post)); }
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/ResumeCopyCommand.java b/src/main/java/com/googlesource/gerrit/plugins/importer/ResumeCopyCommand.java index fa70cba..17f186e 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/ResumeCopyCommand.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/ResumeCopyCommand.java
@@ -23,7 +23,6 @@ import com.google.gerrit.sshd.CommandMetaData; import com.google.gerrit.sshd.SshCommand; import com.google.inject.Inject; - import org.kohsuke.args4j.Argument; import org.kohsuke.args4j.Option; @@ -37,22 +36,18 @@ @Option(name = "--quiet", usage = "suppress progress messages") private boolean quiet; - @Argument(index = 0, required = true, metaVar = "NAME", - usage = "name of the target project") + @Argument(index = 0, required = true, metaVar = "NAME", usage = "name of the target project") private String project; - @Inject - private ResumeCopyProject resume; + @Inject private ResumeCopyProject resume; - @Inject - private ProjectsCollection projects; + @Inject private ProjectsCollection projects; @Override protected void run() throws UnloggedFailure, Failure, Exception { try { ProjectResource rsrc = - projects.parse(TopLevelResource.INSTANCE, - IdString.fromDecoded(project)); + projects.parse(TopLevelResource.INSTANCE, IdString.fromDecoded(project)); if (!quiet) { resume.setErr(stderr); }
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/ResumeCopyProject.java b/src/main/java/com/googlesource/gerrit/plugins/importer/ResumeCopyProject.java index f58d421..d43f5a9 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/ResumeCopyProject.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/ResumeCopyProject.java
@@ -26,26 +26,23 @@ import com.google.gerrit.server.CurrentUser; import com.google.gerrit.server.account.CapabilityControl; import com.google.gerrit.server.config.ConfigResource; -import com.google.gerrit.server.update.UpdateException; import com.google.gerrit.server.project.NoSuchChangeException; import com.google.gerrit.server.project.ProjectCache; import com.google.gerrit.server.project.ProjectResource; +import com.google.gerrit.server.update.UpdateException; import com.google.gerrit.server.validators.ValidationException; import com.google.gwtorm.server.OrmException; import com.google.inject.Inject; import com.google.inject.Provider; - import com.googlesource.gerrit.plugins.importer.ResumeCopyProject.Input; - +import java.io.IOException; +import java.io.Writer; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.errors.ConfigInvalidException; -import java.io.IOException; -import java.io.Writer; - @RequiresCapability(CopyProjectCapability.ID) -class ResumeCopyProject implements RestModifyView<ProjectResource, Input>, - UiAction<ProjectResource> { +class ResumeCopyProject + implements RestModifyView<ProjectResource, Input>, UiAction<ProjectResource> { public static class Input { public boolean force; } @@ -79,23 +76,17 @@ @Override public ResumeImportStatistic apply(ProjectResource rsrc, Input input) - throws RestApiException, IOException, OrmException, ValidationException, - GitAPIException, NoSuchChangeException, NoSuchAccountException, - UpdateException, ConfigInvalidException { + throws RestApiException, IOException, OrmException, ValidationException, GitAPIException, + NoSuchChangeException, NoSuchAccountException, UpdateException, ConfigInvalidException { ImportProjectResource projectResource = - projectsCollection.parse(new ConfigResource(), - IdString.fromDecoded(rsrc.getName())); + projectsCollection.parse(new ConfigResource(), IdString.fromDecoded(rsrc.getName())); ResumeProjectImport.Input in = new ResumeProjectImport.Input(); in.force = input.force; - return resumeProjectImport.get() - .setCopy(true) - .setErr(err) - .apply(projectResource, in); + return resumeProjectImport.get().setCopy(true).setErr(err).apply(projectResource, in); } @Override - public UiAction.Description getDescription( - ProjectResource rsrc) { + public UiAction.Description getDescription(ProjectResource rsrc) { return new UiAction.Description() .setLabel("Resume Copy...") .setTitle(String.format("Resume copy for project %s", rsrc.getName())) @@ -112,8 +103,7 @@ private boolean isCopied(ProjectResource rsrc) { try { ImportProjectResource projectResource = - projectsCollection.parse(new ConfigResource(), - IdString.fromDecoded(rsrc.getName())); + projectsCollection.parse(new ConfigResource(), IdString.fromDecoded(rsrc.getName())); ImportProjectInfo info = projectResource.getInfo(); if (info.from != null) { // no copy, but an import from another system
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/ResumeProjectCommand.java b/src/main/java/com/googlesource/gerrit/plugins/importer/ResumeProjectCommand.java index fb2a4a4..c4fe6b3 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/ResumeProjectCommand.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/ResumeProjectCommand.java
@@ -19,7 +19,6 @@ import com.google.gerrit.sshd.CommandMetaData; import com.google.gerrit.sshd.SshCommand; import com.google.inject.Inject; - import org.kohsuke.args4j.Argument; import org.kohsuke.args4j.Option; @@ -27,11 +26,19 @@ @CommandMetaData(name = "resume-project", description = "Resumes project import") public class ResumeProjectCommand extends SshCommand { - @Option(name = "--user", aliases = {"-u"}, required = true, metaVar = "NAME", + @Option( + name = "--user", + aliases = {"-u"}, + required = true, + metaVar = "NAME", usage = "user on remote system") private String user; - @Option(name = "--pass", aliases = {"-p"}, required = true, metaVar = "-|PASS", + @Option( + name = "--pass", + aliases = {"-p"}, + required = true, + metaVar = "-|PASS", usage = "password of remote user") private String pass; @@ -41,15 +48,16 @@ @Option(name = "--quiet", usage = "suppress progress messages") private boolean quiet; - @Argument(index = 0, required = true, metaVar = "NAME", + @Argument( + index = 0, + required = true, + metaVar = "NAME", usage = "name of the project in target system") private String project; - @Inject - private ResumeProjectImport resume; + @Inject private ResumeProjectImport resume; - @Inject - private ProjectsCollection projects; + @Inject private ProjectsCollection projects; @Override protected void run() throws UnloggedFailure, Failure, Exception {
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/ResumeProjectImport.java b/src/main/java/com/googlesource/gerrit/plugins/importer/ResumeProjectImport.java index 40e0d26..80d2dd3 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/ResumeProjectImport.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/ResumeProjectImport.java
@@ -27,21 +27,18 @@ import com.google.gerrit.server.CurrentUser; import com.google.gerrit.server.account.CapabilityControl; import com.google.gerrit.server.config.ConfigResource; -import com.google.gerrit.server.update.UpdateException; import com.google.gerrit.server.project.NoSuchChangeException; import com.google.gerrit.server.project.ProjectResource; +import com.google.gerrit.server.update.UpdateException; import com.google.gerrit.server.validators.ValidationException; import com.google.gwtorm.server.OrmException; import com.google.inject.Inject; import com.google.inject.Provider; - import com.googlesource.gerrit.plugins.importer.ResumeProjectImport.Input; - -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.errors.ConfigInvalidException; - import java.io.IOException; import java.io.Writer; +import org.eclipse.jgit.api.errors.GitAPIException; +import org.eclipse.jgit.errors.ConfigInvalidException; @RequiresCapability(ImportCapability.ID) public class ResumeProjectImport implements RestModifyView<ImportProjectResource, Input> { @@ -93,24 +90,23 @@ @Override public ResumeImportStatistic apply(ImportProjectResource rsrc, Input input) - throws RestApiException, IOException, OrmException, ValidationException, - GitAPIException, NoSuchChangeException, NoSuchAccountException, - UpdateException, ConfigInvalidException { + throws RestApiException, IOException, OrmException, ValidationException, GitAPIException, + NoSuchChangeException, NoSuchAccountException, UpdateException, ConfigInvalidException { if (copy) { input.validateResumeCopy(); } else { input.validateResumeImport(); } - return importProjectFactory.create(rsrc.getName()) + return importProjectFactory + .create(rsrc.getName()) .setCopy(copy) .setErr(err) - .resume(input.user, input.pass, input.force, - rsrc.getImportStatus()); + .resume(input.user, input.pass, input.force, rsrc.getImportStatus()); } - public static class OnProjects implements - RestModifyView<ProjectResource, Input>, UiAction<ProjectResource> { + public static class OnProjects + implements RestModifyView<ProjectResource, Input>, UiAction<ProjectResource> { private final ProjectsCollection projectsCollection; private final ResumeProjectImport resumeProjectImport; private final Provider<CurrentUser> currentUserProvider; @@ -130,12 +126,10 @@ @Override public ResumeImportStatistic apply(ProjectResource rsrc, Input input) - throws RestApiException, IOException, OrmException, ValidationException, - GitAPIException, NoSuchChangeException, NoSuchAccountException, - UpdateException, ConfigInvalidException { + throws RestApiException, IOException, OrmException, ValidationException, GitAPIException, + NoSuchChangeException, NoSuchAccountException, UpdateException, ConfigInvalidException { ImportProjectResource projectResource = - projectsCollection.parse(new ConfigResource(), - IdString.fromDecoded(rsrc.getName())); + projectsCollection.parse(new ConfigResource(), IdString.fromDecoded(rsrc.getName())); return resumeProjectImport.apply(projectResource, input); } @@ -157,8 +151,7 @@ private boolean isImported(ProjectResource rsrc) { try { ImportProjectResource projectResource = - projectsCollection.parse(new ConfigResource(), - IdString.fromDecoded(rsrc.getName())); + projectsCollection.parse(new ConfigResource(), IdString.fromDecoded(rsrc.getName())); ImportProjectInfo info = projectResource.getInfo(); if (info.from == null) { // no import, but a copy within the same system
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/client/AccountInfo.java b/src/main/java/com/googlesource/gerrit/plugins/importer/client/AccountInfo.java index 18b44fa..7beb7aa 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/client/AccountInfo.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/client/AccountInfo.java
@@ -18,10 +18,12 @@ public class AccountInfo extends JavaScriptObject { public final native int _account_id() /*-{ return this._account_id || 0; }-*/; + public final native String name() /*-{ return this.name; }-*/; + public final native String username() /*-{ return this.username; }-*/; + public final native String email() /*-{ return this.email; }-*/; - protected AccountInfo() { - } + protected AccountInfo() {} }
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/client/CompleteImportDialog.java b/src/main/java/com/googlesource/gerrit/plugins/importer/client/CompleteImportDialog.java index e0339fa..a67964d 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/client/CompleteImportDialog.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/client/CompleteImportDialog.java
@@ -33,7 +33,7 @@ private final Button completeButton; public CompleteImportDialog(final String project, final boolean copy) { - super(/* auto hide */false, /* modal */true); + super(/* auto hide */ false, /* modal */ true); setGlassEnabled(true); setText("Complete Project " + (copy ? "Copy" : "Import")); @@ -41,40 +41,43 @@ completeButton = new Button(); completeButton.setText("Complete"); - completeButton.addClickHandler(event -> { - hide(); + completeButton.addClickHandler( + event -> { + hide(); - new RestApi("config").id("server") - .view(Plugin.get().getName(), "projects").id(project) - .delete(new AsyncCallback<NoContent>() { - @Override - public void onSuccess(NoContent result) { - Plugin.get().go("/x/" + Plugin.get().getName() + "/list"); + new RestApi("config") + .id("server") + .view(Plugin.get().getName(), "projects") + .id(project) + .delete( + new AsyncCallback<NoContent>() { + @Override + public void onSuccess(NoContent result) { + Plugin.get().go("/x/" + Plugin.get().getName() + "/list"); - final DialogBox successDialog = new DialogBox(); - successDialog.setText("Project " - + (copy ? "Copy" : "Import") + " Completed"); - successDialog.setAnimationEnabled(true); + final DialogBox successDialog = new DialogBox(); + successDialog.setText("Project " + (copy ? "Copy" : "Import") + " Completed"); + successDialog.setAnimationEnabled(true); - Panel p = new VerticalPanel(); - p.setStyleName("importer-message-panel"); - p.add(new Label("The project " - + (copy ? "copy" : "import") + " was completed.")); - Button okButton = new Button("OK"); - okButton.addClickHandler(event -> successDialog.hide()); + Panel p = new VerticalPanel(); + p.setStyleName("importer-message-panel"); + p.add( + new Label( + "The project " + (copy ? "copy" : "import") + " was completed.")); + Button okButton = new Button("OK"); + okButton.addClickHandler(event -> successDialog.hide()); - p.add(okButton); - successDialog.add(p); + p.add(okButton); + successDialog.add(p); - successDialog.center(); - successDialog.show(); - } + successDialog.center(); + successDialog.show(); + } - @Override - public void onFailure(Throwable caught) { - } - }); - }); + @Override + public void onFailure(Throwable caught) {} + }); + }); buttons.add(completeButton); cancelButton = new Button(); @@ -84,8 +87,8 @@ buttons.add(cancelButton); FlowPanel center = new FlowPanel(); - Label msg = new Label("Complete " + (copy ? "copy" : "import") - + " of project '" + project + "'"); + Label msg = + new Label("Complete " + (copy ? "copy" : "import") + " of project '" + project + "'"); msg.addStyleName("importer-complete-message"); center.add(msg);
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/client/ImportActionPanel.java b/src/main/java/com/googlesource/gerrit/plugins/importer/client/ImportActionPanel.java index 2dc3e57..7ee5431 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/client/ImportActionPanel.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/client/ImportActionPanel.java
@@ -22,11 +22,12 @@ ImportActionPanel(final String project, final boolean copy) { setStyleName("importer-action-panel"); - add(new Button("Resume...", - (ClickHandler) event -> (new ResumeImportDialog(project, copy)) - .center())); - add(new Button("Complete...", - (ClickHandler) event -> (new CompleteImportDialog(project, copy)) - .center())); + add( + new Button( + "Resume...", (ClickHandler) event -> (new ResumeImportDialog(project, copy)).center())); + add( + new Button( + "Complete...", + (ClickHandler) event -> (new CompleteImportDialog(project, copy)).center())); } }
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/client/ImportGroupInput.java b/src/main/java/com/googlesource/gerrit/plugins/importer/client/ImportGroupInput.java index 4c12a81..6832e23 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/client/ImportGroupInput.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/client/ImportGroupInput.java
@@ -18,15 +18,18 @@ public class ImportGroupInput extends JavaScriptObject { final native void from(String f) /*-{ this.from = f; }-*/; + final native void user(String u) /*-{ this.user = u; }-*/; + final native void pass(String p) /*-{ this.pass = p; }-*/; + final native void importOwnerGroup(boolean i) /*-{ this.import_owner_group = i; }-*/; + final native void importIncludedGroups(boolean i) /*-{ this.import_included_groups = i; }-*/; static ImportGroupInput create() { return (ImportGroupInput) createObject(); } - protected ImportGroupInput() { - } + protected ImportGroupInput() {} }
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/client/ImportGroupScreen.java b/src/main/java/com/googlesource/gerrit/plugins/importer/client/ImportGroupScreen.java index a4e9cea..eef8892 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/client/ImportGroupScreen.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/client/ImportGroupScreen.java
@@ -52,12 +52,16 @@ ImportGroupScreen() { setStyleName("importer-import-panel"); - fromTxt = addTextBox(this, "From*", "URL of the remote system from where the group should be imported"); + fromTxt = + addTextBox( + this, "From*", "URL of the remote system from where the group should be imported"); nameTxt = addTextBox(this, "Group Name*", "name of the group"); userTxt = addTextBox(this, "Remote User*", "user on remote system"); passTxt = addPasswordTextBox(this, "Password*", "password of remote user"); - importOwnerGroupCheckBox = addCheckBox(this, "import owner group", "also import missing owner groups"); - importIncludedGroupsCheckBox = addCheckBox(this, "import included groups", "also import missing included groups"); + importOwnerGroupCheckBox = + addCheckBox(this, "import owner group", "also import missing owner groups"); + importIncludedGroupsCheckBox = + addCheckBox(this, "import included groups", "also import missing included groups"); HorizontalPanel buttons = new HorizontalPanel(); add(buttons); @@ -82,35 +86,39 @@ in.importIncludedGroups(importIncludedGroupsCheckBox.getValue()); final String groupName = getValue(nameTxt); - new RestApi("config").id("server").view(Plugin.get().getName(), "groups") - .id(groupName).put(in, new AsyncCallback<JavaScriptObject>() { + new RestApi("config") + .id("server") + .view(Plugin.get().getName(), "groups") + .id(groupName) + .put( + in, + new AsyncCallback<JavaScriptObject>() { - @Override - public void onSuccess(JavaScriptObject result) { - clearForm(); - Plugin.get().go("/admin/groups/" + groupName); + @Override + public void onSuccess(JavaScriptObject result) { + clearForm(); + Plugin.get().go("/admin/groups/" + groupName); - final DialogBox successDialog = new DialogBox(); - successDialog.setText("Group Import"); - successDialog.setAnimationEnabled(true); + final DialogBox successDialog = new DialogBox(); + successDialog.setText("Group Import"); + successDialog.setAnimationEnabled(true); - Panel p = new VerticalPanel(); - p.setStyleName("importer-message-panel"); - p.add(new Label("The group was imported.")); - Button okButton = new Button("OK"); - okButton.addClickHandler(event -> successDialog.hide()); + Panel p = new VerticalPanel(); + p.setStyleName("importer-message-panel"); + p.add(new Label("The group was imported.")); + Button okButton = new Button("OK"); + okButton.addClickHandler(event -> successDialog.hide()); - p.add(okButton); - successDialog.add(p); + p.add(okButton); + successDialog.add(p); - successDialog.center(); - successDialog.show(); - } + successDialog.center(); + successDialog.show(); + } - @Override - public void onFailure(Throwable caught) { - } - }); + @Override + public void onFailure(Throwable caught) {} + }); } private void clearForm() {
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/client/ImportInfo.java b/src/main/java/com/googlesource/gerrit/plugins/importer/client/ImportInfo.java index 82978f0..812236b 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/client/ImportInfo.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/client/ImportInfo.java
@@ -18,9 +18,10 @@ public class ImportInfo extends JavaScriptObject { public final native String timestamp() /*-{ return this.timestamp; }-*/; + public final native AccountInfo user() /*-{ return this.user; }-*/; + public final native String remoteUser() /*-{ return this.remote_user; }-*/; - protected ImportInfo() { - } + protected ImportInfo() {} }
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/client/ImportProjectInfo.java b/src/main/java/com/googlesource/gerrit/plugins/importer/client/ImportProjectInfo.java index e89f058..3d93c91 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/client/ImportProjectInfo.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/client/ImportProjectInfo.java
@@ -19,10 +19,12 @@ public class ImportProjectInfo extends JavaScriptObject { public final native String from() /*-{ return this.from; }-*/; + public final native String name() /*-{ return this.name; }-*/; + public final native String parent() /*-{ return this.parent; }-*/; + public final native JsArray<ImportInfo> imports() /*-{ return this.imports; }-*/; - protected ImportProjectInfo() { - } + protected ImportProjectInfo() {} }
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/client/ImportProjectInput.java b/src/main/java/com/googlesource/gerrit/plugins/importer/client/ImportProjectInput.java index a355e6a..6ae25cf 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/client/ImportProjectInput.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/client/ImportProjectInput.java
@@ -18,15 +18,18 @@ public class ImportProjectInput extends JavaScriptObject { final native void from(String f) /*-{ this.from = f; }-*/; + final native void name(String n) /*-{ this.name = n; }-*/; + final native void user(String u) /*-{ this.user = u; }-*/; + final native void pass(String p) /*-{ this.pass = p; }-*/; + final native void parent(String p) /*-{ this.parent = p; }-*/; static ImportProjectInput create() { return (ImportProjectInput) createObject(); } - protected ImportProjectInput() { - } + protected ImportProjectInput() {} }
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/client/ImportProjectListScreen.java b/src/main/java/com/googlesource/gerrit/plugins/importer/client/ImportProjectListScreen.java index bd86574..3239acb 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/client/ImportProjectListScreen.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/client/ImportProjectListScreen.java
@@ -25,7 +25,6 @@ import com.google.gwt.user.client.ui.FlexTable.FlexCellFormatter; import com.google.gwt.user.client.ui.InlineHyperlink; import com.google.gwt.user.client.ui.VerticalPanel; - import java.util.List; public class ImportProjectListScreen extends VerticalPanel { @@ -40,19 +39,21 @@ ImportProjectListScreen() { setStyleName("importer-imports-panel"); - new RestApi("config").id("server") + new RestApi("config") + .id("server") .view(Plugin.get().getPluginName(), "projects") - .get(new AsyncCallback<NativeMap<ImportProjectInfo>>() { - @Override - public void onSuccess(NativeMap<ImportProjectInfo> info) { - display(info); - } + .get( + new AsyncCallback<NativeMap<ImportProjectInfo>>() { + @Override + public void onSuccess(NativeMap<ImportProjectInfo> info) { + display(info); + } - @Override - public void onFailure(Throwable caught) { - // never invoked - } - }); + @Override + public void onFailure(Throwable caught) { + // never invoked + } + }); } private void display(NativeMap<ImportProjectInfo> map) { @@ -82,16 +83,17 @@ fmt.addStyleName(row, 0, "leftMostCell"); } - t.setWidget(row, 0, new InlineHyperlink( - project, "/x/" + Plugin.get().getName() + "/projects/" + project)); + t.setWidget( + row, + 0, + new InlineHyperlink(project, "/x/" + Plugin.get().getName() + "/projects/" + project)); t.setText(row, 1, info.from() != null ? "IMPORT" : "COPY"); if (info.from() != null) { String srcProjectUrl = projectUrl(info, project); t.setWidget(row, 2, new Anchor(srcProjectUrl, srcProjectUrl)); } else { - t.setWidget(row, 2, - new InlineHyperlink(project, "/admin/projects/" + project)); + t.setWidget(row, 2, new InlineHyperlink(project, "/admin/projects/" + project)); } List<ImportInfo> importList = Natives.asList(info.imports());
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/client/ImportProjectScreen.java b/src/main/java/com/googlesource/gerrit/plugins/importer/client/ImportProjectScreen.java index 206f12d..6f3c785 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/client/ImportProjectScreen.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/client/ImportProjectScreen.java
@@ -49,14 +49,24 @@ ImportProjectScreen() { setStyleName("importer-import-panel"); - fromTxt = addTextBox(this, "From*", "URL of the remote system from where the project should be imported"); + fromTxt = + addTextBox( + this, "From*", "URL of the remote system from where the project should be imported"); srcNameTxt = addTextBox(this, "Project Name in Source*", "name of project in source system"); - targetNameTxt = addTextBox(this, "Target Project Name", "name of project in target system" - + " (if not specified it is assumed to be the same name as in the source system)"); + targetNameTxt = + addTextBox( + this, + "Target Project Name", + "name of project in target system" + + " (if not specified it is assumed to be the same name as in the source system)"); userTxt = addTextBox(this, "Remote User*", "user on remote system"); passTxt = addPasswordTextBox(this, "Password*", "password of remote user"); - parentTxt = addTextBox(this, "Parent", "name of parent project in target system" - + "(if not specified it is assumed to be the same parent as in the source system)"); + parentTxt = + addTextBox( + this, + "Parent", + "name of parent project in target system" + + "(if not specified it is assumed to be the same parent as in the source system)"); HorizontalPanel buttons = new HorizontalPanel(); add(buttons); @@ -73,8 +83,8 @@ } private void doImport() { - final String targetName = getValue(targetNameTxt).length() == 0 - ? getValue(srcNameTxt) : getValue(targetNameTxt); + final String targetName = + getValue(targetNameTxt).length() == 0 ? getValue(srcNameTxt) : getValue(targetNameTxt); ImportProjectInput in = ImportProjectInput.create(); in.from(getValue(fromTxt)); @@ -83,36 +93,40 @@ in.pass(getValue(passTxt)); in.parent(getValue(parentTxt)); - new RestApi("config").id("server").view(Plugin.get().getName(), "projects") - .id(targetName).put(in, new AsyncCallback<ImportStatisticInfo>() { + new RestApi("config") + .id("server") + .view(Plugin.get().getName(), "projects") + .id(targetName) + .put( + in, + new AsyncCallback<ImportStatisticInfo>() { - @Override - public void onSuccess(ImportStatisticInfo result) { - clearForm(); - Plugin.get().go("/admin/projects/" + targetName); + @Override + public void onSuccess(ImportStatisticInfo result) { + clearForm(); + Plugin.get().go("/admin/projects/" + targetName); - final DialogBox successDialog = new DialogBox(); - successDialog.setText("Project Import"); - successDialog.setAnimationEnabled(true); + final DialogBox successDialog = new DialogBox(); + successDialog.setText("Project Import"); + successDialog.setAnimationEnabled(true); - Panel p = new VerticalPanel(); - p.setStyleName("importer-message-panel"); - p.add(new Label("The project was imported.")); - p.add(new Label("Created Changes: " + result.numChangesCreated())); - Button okButton = new Button("OK"); - okButton.addClickHandler(event -> successDialog.hide()); + Panel p = new VerticalPanel(); + p.setStyleName("importer-message-panel"); + p.add(new Label("The project was imported.")); + p.add(new Label("Created Changes: " + result.numChangesCreated())); + Button okButton = new Button("OK"); + okButton.addClickHandler(event -> successDialog.hide()); - p.add(okButton); - successDialog.add(p); + p.add(okButton); + successDialog.add(p); - successDialog.center(); - successDialog.show(); - } + successDialog.center(); + successDialog.show(); + } - @Override - public void onFailure(Throwable caught) { - } - }); + @Override + public void onFailure(Throwable caught) {} + }); } private void clearForm() {
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/client/ImportStatisticInfo.java b/src/main/java/com/googlesource/gerrit/plugins/importer/client/ImportStatisticInfo.java index 2d82432..dfd5daf 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/client/ImportStatisticInfo.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/client/ImportStatisticInfo.java
@@ -19,6 +19,5 @@ public class ImportStatisticInfo extends JavaScriptObject { public final native int numChangesCreated() /*-{ return this.num_changes_created; }-*/; - protected ImportStatisticInfo() { - } + protected ImportStatisticInfo() {} }
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/client/InputUtil.java b/src/main/java/com/googlesource/gerrit/plugins/importer/client/InputUtil.java index 1f9d55d..da7402d 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/client/InputUtil.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/client/InputUtil.java
@@ -53,21 +53,23 @@ private static TextBox createTextBox(boolean isPassword) { TextBox tb; if (isPassword) { - tb = new PasswordTextBox() { - @Override - public void onBrowserEvent(Event event) { - super.onBrowserEvent(event); - handlePaste(this, event); - } - }; + tb = + new PasswordTextBox() { + @Override + public void onBrowserEvent(Event event) { + super.onBrowserEvent(event); + handlePaste(this, event); + } + }; } else { - tb = new TextBox() { - @Override - public void onBrowserEvent(Event event) { - super.onBrowserEvent(event); - handlePaste(this, event); - } - }; + tb = + new TextBox() { + @Override + public void onBrowserEvent(Event event) { + super.onBrowserEvent(event); + handlePaste(this, event); + } + }; } tb.addKeyPressHandler(event -> event.stopPropagation()); tb.sinkEvents(Event.ONPASTE); @@ -77,11 +79,13 @@ private static void handlePaste(final TextBox tb, Event event) { if (event.getTypeInt() == Event.ONPASTE) { - Scheduler.get().scheduleDeferred(() -> { - if (getValue(tb).length() != 0) { - tb.setEnabled(true); - } - }); + Scheduler.get() + .scheduleDeferred( + () -> { + if (getValue(tb).length() != 0) { + tb.setEnabled(true); + } + }); } }
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/client/OnEditEnabler.java b/src/main/java/com/googlesource/gerrit/plugins/importer/client/OnEditEnabler.java index d632652..986fc64 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/client/OnEditEnabler.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/client/OnEditEnabler.java
@@ -31,22 +31,23 @@ import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.TextBoxBase; import com.google.gwt.user.client.ui.ValueBoxBase; - import java.util.HashMap; import java.util.Map; - -/** Enables a FocusWidget (e.g. a Button) if an edit is detected from any - * registered input widget. +/** + * Enables a FocusWidget (e.g. a Button) if an edit is detected from any registered input widget. */ -public class OnEditEnabler implements KeyPressHandler, KeyDownHandler, - MouseUpHandler, ChangeHandler, ValueChangeHandler<Object> { +public class OnEditEnabler + implements KeyPressHandler, + KeyDownHandler, + MouseUpHandler, + ChangeHandler, + ValueChangeHandler<Object> { private final FocusWidget widget; private Map<TextBoxBase, String> strings = new HashMap<>(); private String originalValue; - // The first parameter to the contructors must be the FocusWidget to enable, // subsequent parameters are widgets to listenTo. @@ -70,7 +71,6 @@ widget = w; } - // Register input widgets to be listened to public void listenTo(final TextBoxBase tb) { @@ -101,7 +101,6 @@ cb.addValueChangeHandler((ValueChangeHandler) this); } - // Handlers @Override @@ -131,16 +130,18 @@ } private void on(final GwtEvent<?> e) { - if (widget.isEnabled() || - ! (e.getSource() instanceof FocusWidget) || - ! ((FocusWidget) e.getSource()).isEnabled() ) { + if (widget.isEnabled() + || !(e.getSource() instanceof FocusWidget) + || !((FocusWidget) e.getSource()).isEnabled()) { if (e.getSource() instanceof ValueBoxBase) { final TextBoxBase box = ((TextBoxBase) e.getSource()); - Scheduler.get().scheduleDeferred(() -> { - if (box.getValue().trim().equals(originalValue)) { - widget.setEnabled(false); - } - }); + Scheduler.get() + .scheduleDeferred( + () -> { + if (box.getValue().trim().equals(originalValue)) { + widget.setEnabled(false); + } + }); } return; } @@ -157,14 +158,16 @@ private void onTextBoxBase(final TextBoxBase tb) { // The text appears to not get updated until the handlers complete. - Scheduler.get().scheduleDeferred(() -> { - String orig = strings.get(tb); - if (orig == null) { - orig = ""; - } - if (! orig.equals(tb.getText().trim())) { - widget.setEnabled(true); - } - }); + Scheduler.get() + .scheduleDeferred( + () -> { + String orig = strings.get(tb); + if (orig == null) { + orig = ""; + } + if (!orig.equals(tb.getText().trim())) { + widget.setEnabled(true); + } + }); } }
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/client/ProjectImportsScreen.java b/src/main/java/com/googlesource/gerrit/plugins/importer/client/ProjectImportsScreen.java index 8cbb2eb..879b09c 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/client/ProjectImportsScreen.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/client/ProjectImportsScreen.java
@@ -29,7 +29,6 @@ import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; - import java.util.Collections; import java.util.List; @@ -45,18 +44,22 @@ ProjectImportsScreen(final String project) { setStyleName("importer-import-panel"); - new RestApi("config").id("server").view(Plugin.get().getPluginName(), "projects") - .id(project).get(new AsyncCallback<ImportProjectInfo>() { - @Override - public void onSuccess(ImportProjectInfo importProjectInfo) { - display(project, importProjectInfo); - } + new RestApi("config") + .id("server") + .view(Plugin.get().getPluginName(), "projects") + .id(project) + .get( + new AsyncCallback<ImportProjectInfo>() { + @Override + public void onSuccess(ImportProjectInfo importProjectInfo) { + display(project, importProjectInfo); + } - @Override - public void onFailure(Throwable caught) { - // never invoked - } - }); + @Override + public void onFailure(Throwable caught) { + // never invoked + } + }); } private void display(final String project, ImportProjectInfo info) { @@ -69,11 +72,9 @@ String srcProjectUrl = projectUrl(info, project); t.addRow("From", new Anchor(srcProjectUrl, srcProjectUrl)); } else { - t.addRow("From", - new InlineHyperlink(project, "/admin/projects/" + project)); + t.addRow("From", new InlineHyperlink(project, "/admin/projects/" + project)); } - t.addRow("Parent", info.parent()); t.addRow("Actions", new ImportActionPanel(project, info.from() == null)); add(t);
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/client/ResumeCopyProjectInput.java b/src/main/java/com/googlesource/gerrit/plugins/importer/client/ResumeCopyProjectInput.java index fa101f0..cc1f880 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/client/ResumeCopyProjectInput.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/client/ResumeCopyProjectInput.java
@@ -23,6 +23,5 @@ return (ResumeCopyProjectInput) createObject(); } - protected ResumeCopyProjectInput() { - } + protected ResumeCopyProjectInput() {} }
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/client/ResumeImportDialog.java b/src/main/java/com/googlesource/gerrit/plugins/importer/client/ResumeImportDialog.java index b56f46d..a8264c1 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/client/ResumeImportDialog.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/client/ResumeImportDialog.java
@@ -42,7 +42,7 @@ private CheckBox forceCheckBox; public ResumeImportDialog(final String project, final boolean copy) { - super(/* auto hide */false, /* modal */true); + super(/* auto hide */ false, /* modal */ true); setGlassEnabled(true); setText("Resume Project " + (copy ? "Copy" : "Import")); @@ -50,52 +50,57 @@ resumeButton = new Button(); resumeButton.setText("Resume"); - resumeButton.addClickHandler(event -> { - hide(); + resumeButton.addClickHandler( + event -> { + hide(); - RestApi restApi; - ResumeImportProjectInput in = ResumeImportProjectInput.create(); - in.force(forceCheckBox.getValue()); - if (copy) { - restApi = new RestApi("projects").id(project) - .view(Plugin.get().getName(), "copy.resume"); - } else { - restApi = new RestApi("config").id("server") - .view(Plugin.get().getName(), "projects").id(project) - .view("resume"); - in.user(getValue(userTxt)); - in.pass(getValue(passTxt)); - } + RestApi restApi; + ResumeImportProjectInput in = ResumeImportProjectInput.create(); + in.force(forceCheckBox.getValue()); + if (copy) { + restApi = + new RestApi("projects").id(project).view(Plugin.get().getName(), "copy.resume"); + } else { + restApi = + new RestApi("config") + .id("server") + .view(Plugin.get().getName(), "projects") + .id(project) + .view("resume"); + in.user(getValue(userTxt)); + in.pass(getValue(passTxt)); + } - restApi.put(in, new AsyncCallback<ResumeImportStatisticInfo>() { - @Override - public void onSuccess(ResumeImportStatisticInfo result) { - Plugin.get().go("/x/" + Plugin.get().getName() + "/list"); + restApi.put( + in, + new AsyncCallback<ResumeImportStatisticInfo>() { + @Override + public void onSuccess(ResumeImportStatisticInfo result) { + Plugin.get().go("/x/" + Plugin.get().getName() + "/list"); - final DialogBox successDialog = new DialogBox(); - successDialog.setText("Resume " + (copy ? "Copy" : "Import") + " Import"); - successDialog.setAnimationEnabled(true); + final DialogBox successDialog = new DialogBox(); + successDialog.setText("Resume " + (copy ? "Copy" : "Import") + " Import"); + successDialog.setAnimationEnabled(true); - Panel p = new VerticalPanel(); - p.setStyleName("importer-message-panel"); - p.add(new Label("The project " + (copy ? "copy" : "import") + " was resumed.")); - p.add(new Label("Created Changes: " + result.numChangesCreated())); - p.add(new Label("Updated Changes: " + result.numChangesUpdated())); - Button okButton = new Button("OK"); - okButton.addClickHandler(event -> successDialog.hide()); + Panel p = new VerticalPanel(); + p.setStyleName("importer-message-panel"); + p.add(new Label("The project " + (copy ? "copy" : "import") + " was resumed.")); + p.add(new Label("Created Changes: " + result.numChangesCreated())); + p.add(new Label("Updated Changes: " + result.numChangesUpdated())); + Button okButton = new Button("OK"); + okButton.addClickHandler(event -> successDialog.hide()); - p.add(okButton); - successDialog.add(p); + p.add(okButton); + successDialog.add(p); - successDialog.center(); - successDialog.show(); - } + successDialog.center(); + successDialog.show(); + } - @Override - public void onFailure(Throwable caught) { - } - }); - }); + @Override + public void onFailure(Throwable caught) {} + }); + }); buttons.add(resumeButton); cancelButton = new Button(); @@ -105,8 +110,7 @@ buttons.add(cancelButton); FlowPanel center = new FlowPanel(); - Label msg = new Label("Resume " + (copy ? "copy" : "import") - + " of project '" + project + "'"); + Label msg = new Label("Resume " + (copy ? "copy" : "import") + " of project '" + project + "'"); msg.addStyleName("importer-resume-message"); center.add(msg);
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/client/ResumeImportProjectInput.java b/src/main/java/com/googlesource/gerrit/plugins/importer/client/ResumeImportProjectInput.java index 47bdaf7..cb8d20f 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/client/ResumeImportProjectInput.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/client/ResumeImportProjectInput.java
@@ -16,12 +16,12 @@ public class ResumeImportProjectInput extends ResumeCopyProjectInput { final native void user(String u) /*-{ this.user = u; }-*/; + final native void pass(String p) /*-{ this.pass = p; }-*/; static ResumeImportProjectInput create() { return (ResumeImportProjectInput) createObject(); } - protected ResumeImportProjectInput() { - } + protected ResumeImportProjectInput() {} }
diff --git a/src/main/java/com/googlesource/gerrit/plugins/importer/client/ResumeImportStatisticInfo.java b/src/main/java/com/googlesource/gerrit/plugins/importer/client/ResumeImportStatisticInfo.java index 73d99f1..354e682 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/importer/client/ResumeImportStatisticInfo.java +++ b/src/main/java/com/googlesource/gerrit/plugins/importer/client/ResumeImportStatisticInfo.java
@@ -14,10 +14,8 @@ package com.googlesource.gerrit.plugins.importer.client; - public class ResumeImportStatisticInfo extends ImportStatisticInfo { public final native int numChangesUpdated() /*-{ return this.num_changes_updated; }-*/; - protected ResumeImportStatisticInfo() { - } + protected ResumeImportStatisticInfo() {} }