auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void assertTag(Project.NameKey project, String branch, String tagName) throws IOException { Repository r = repoManager.openRepository(project); try { START RevWalk rw = new RevWalk(r); END try { ObjectId headCommit = r.getRef(branch).getObjectId(); ObjectId taggedCommit = r.getRef(tagName).getObjectId(); assertEquals(headCommit, taggedCommit); } finally { rw.release(); } } finally { r.close(); } } Is this RevWalk used? The ObjectReader should be released by r.close(), so I don't think this inner try { } finally block is needed.

Target:
private void assertTag(Project.NameKey project, String branch, String tagName) throws IOException { Repository r = repoManager.openRepository(project); try { ObjectId headCommit = r.getRef(branch).getObjectId(); ObjectId taggedCommit = r.getRef(tagName).getObjectId(); assertEquals(headCommit, taggedCommit); } finally { r.close(); } }
Source:
private boolean isLastValueChangeHandler() { int count = detailCache.getHandlerCount(); int last = count - 1; START for (int i = 0; i < count; i++) { END if (this == detailCache.getHandler(i)) { return i == last; } } return false; } How is a loop better than: int count = detailCache.getHandlerCount(); return count > 0 && detailCache.getHandler(count - 1) == this;

Target:
private boolean isLastValueChangeHandler() { int count = detailCache.getHandlerCount(); return count > 0 && detailCache.getHandler(count - 1) == this; }
Source:
public CapabilityResource parse(ConfigResource parent, IdString id) throws ResourceNotFoundException, Exception { START return null; END } don't return null, throw instead.

Target:
public CapabilityResource parse(ConfigResource parent, IdString id) throws ResourceNotFoundException { throw new ResourceNotFoundException(id); }
Source:
public ConfigResource parse(TopLevelResource root, IdString id) throws ResourceNotFoundException { START if (!"server".equals(id.get())) { END throw new ResourceNotFoundException(id); } return new ConfigResource(); } nit: we usually write id.equals("server")

Target:
public ConfigResource parse(TopLevelResource root, IdString id) throws ResourceNotFoundException { if (id.equals("server")) { return new ConfigResource(); } throw new ResourceNotFoundException(id); }
Source:
public boolean isVisible() { AccountGroup accountGroup = GroupDescriptions.toAccountGroup(group); if (accountGroup != null && accountGroup.isVisibleToAll()) { START return true; END } return user instanceof InternalUser || user.getEffectiveGroups().contains(group.getGroupUUID()) || isOwner(); } Not enough coffee in the world to convince me this delta is necessary.

Target:
public boolean isVisible() { AccountGroup accountGroup = GroupDescriptions.toAccountGroup(group); return (accountGroup != null && accountGroup.isVisibleToAll()) || user instanceof InternalUser || user.getEffectiveGroups().contains(group.getGroupUUID()) || isOwner(); }
Source:
protected void configure() { DynamicMap.mapOf(binder(), CONFIG_KIND); DynamicMap.mapOf(binder(), CAPABILITY_KIND); START DynamicMap.mapOf(binder(), CapabilityDefinition.class); END child(CONFIG_KIND, "capabilities").to(CapabilitiesCollection.class); } This sort of binding goes in GerritGlobalModule. See about line 244 in current master.

Target:
protected void configure() { DynamicMap.mapOf(binder(), CONFIG_KIND); DynamicMap.mapOf(binder(), CAPABILITY_KIND); child(CONFIG_KIND, "capabilities").to(CapabilitiesCollection.class); }
Source:
public Builder setOldRevision(Revision revision) { switch (type) { case DIFF: case LOG: this.oldRevision = revision; break; default: checkState(revision == null, "cannot set old revision on %s view", type); START this.oldRevision = revision; END break; } return this; } nit: it seems to me this should be just before the return at the end of the method.

Target:
public Builder setOldRevision(Revision revision) { switch (type) { case DIFF: case LOG: this.oldRevision = revision; return this; default: throw new IllegalStateException( String.format("cannot set old revision on %s view", type)); } }
Source:
public Builder setPathPart(String path) { switch (type) { case PATH: case DIFF: this.path = maybeTrimLeadingAndTrailingSlash(checkNotNull(path)); break; case DESCRIBE: case REFS: case LOG: this.path = path != null ? maybeTrimLeadingAndTrailingSlash(path) : null; break; default: checkState(path == null, "cannot set path on %s view", type); this.path = path; break; } START return this; END } nit: Same here. Leave the checks in the switch and do the assignment at the end: this.path = path != null ? maybeTrimLeadingAndTrailingSlash(path) : null;

Target:
public Builder setPathPart(String path) { switch (type) { case PATH: case DIFF: this.path = maybeTrimLeadingAndTrailingSlash(checkNotNull(path)); return this; case DESCRIBE: case REFS: case LOG: this.path = path != null ? maybeTrimLeadingAndTrailingSlash(path) : null; return this; default: throw new IllegalStateException(String.format("cannot set path on %s view", type)); } }
Source:
private static String branchToRef(String name) { START if (name.startsWith(Branch.R_HEADS)) END return Branch.R_HEADS + name; return name; } should be: if (!name.startsWith(Branch.R_HEADS))

Target:
private static String branchToRef(String name) { if (!name.startsWith(Branch.R_HEADS)) return Branch.R_HEADS + name; return name; }
Source:
CommitPredicate(Provider<ReviewDb> dbProvider, AbbreviatedObjectId id) { START super(ChangeField.COMMIT, id.toString()); END this.dbProvider = dbProvider; this.abbrevId = id; } id.name()

Target:
CommitPredicate(Provider<ReviewDb> dbProvider, AbbreviatedObjectId id) { super(ChangeField.COMMIT, id.name()); this.dbProvider = dbProvider; this.abbrevId = id; }
Source:
public void stop() { ChangeIndex read = searchIndex.get(); if (read != null) { read.close(); } for (ChangeIndex write : writeIndexes) { if (write != read) { START read.close(); END } } } write.close();

Target:
public void stop() { ChangeIndex read = searchIndex.get(); if (read != null) { read.close(); } for (ChangeIndex write : writeIndexes) { if (write != read) { write.close(); } } }
Source:
START private boolean nullOrEmpty(List<?> list) { END return list == null || list.isEmpty(); } static

Target:
private static boolean nullOrEmpty(List<?> list) { return list == null || list.isEmpty(); }
Source:
START private List<SkippedLine> checkAndAddSkip(List<SkippedLine> list, END SkippedLine toAdd) { if (toAdd.getSize() > 1) { list.add(toAdd); } return list; } This method can return void.

Target:
private void checkAndAddSkip(List<SkippedLine> list, SkippedLine toAdd) { if (toAdd.getSize() > 1) { list.add(toAdd); } }
Source:
START void updateFileCommentVisibility(boolean forceHide) { END if (forceHide || (fileCommentPanelA.getBoxCount() == 0 && fileCommentPanelB.getBoxCount() == 0)) { UIObject.setVisible(patchsetNavRow, false); UIObject.setVisible(fileCommentRow, false); } else if (patchSelectBoxA.isFileCommentSetVisible()) { UIObject.setVisible(patchsetNavRow, true); UIObject.setVisible(fileCommentRow, true); } host.resizeCodeMirror(); } Whoops that was careless.. Yeah I will just remove the link since it's complicating things a lot.

Target:
void updateFileCommentVisibility(boolean forceHide) { if (forceHide) { UIObject.setVisible(patchsetNavRow, false); } if (forceHide || (fileCommentPanelA.getBoxCount() == 0 && fileCommentPanelB.getBoxCount() == 0)) { UIObject.setVisible(fileCommentRow, false); } else { UIObject.setVisible(patchsetNavRow, true); UIObject.setVisible(fileCommentRow, true); } host.resizeCodeMirror(); }
Source:
void addFileComment(CommentBox box) { boxes.add(box); table.updateFileCommentVisibility(false); START body.add(box); END } Why not add to body before calling table.updateFileCommentVisibility()?

Target:
void addFileComment(CommentBox box) { boxes.add(box); body.add(box); table.updateFileCommentVisibility(false); }
Source:
public GitBlitUrlsConfig(Config config) { canonicalWebUrlString = config.getString("gerrit", null, "canonicalWebUrl"); sshdListenAddressString = config.getString("sshd", null, "listenAddress"); httpdListenUrlString = config.getString("httpd", null, "listenUrl"); START downloadSchemes = config.getStringList("download", null, "scheme"); END } ... so that you can get it straight as: downloadSchemes = Arrays.asList(config.getStringList("download", null, "scheme");

Target:
public GitBlitUrlsConfig(Config config) { canonicalWebUrlString = config.getString("gerrit", null, "canonicalWebUrl"); sshdListenAddressString = config.getString("sshd", null, "listenAddress"); httpdListenUrlString = config.getString("httpd", null, "listenUrl"); downloadSchemes = Arrays.asList(config.getStringList("download", null, "scheme")); }
Source:
boolean match(AccountGroup.UUID uuid, boolean isChangeOwner) { if (AccountGroup.PROJECT_OWNERS.equals(uuid)) { return isDeclaredOwner(); } else if (AccountGroup.CHANGE_OWNERS.equals(uuid) && isChangeOwner) { START return true; END } else { return user.getEffectiveGroups().contains(uuid); } } Does it make sense to continue with the else branch below if AccountGroup.CHANGE_OWNERS.equals(uuid) but isChangeOwner is false? I think the code should rather be like this: } else if (AccountGroup.CHANGE_OWNERS.equals(uuid)) { return isChangeOwner; } else { ...

Target:
boolean match(AccountGroup.UUID uuid, boolean isChangeOwner) { if (AccountGroup.PROJECT_OWNERS.equals(uuid)) { return isDeclaredOwner(); } else if (AccountGroup.CHANGE_OWNERS.equals(uuid)) { return isChangeOwner; } else { return user.getEffectiveGroups().contains(uuid); } }
Source:
private void addAllToCommentList(JsArray<CommentInfo> in, boolean toDrafts) { if (toDrafts && drafts == null) { drafts = in; START } else if (published == null) { END published = in; } else { JsArray<CommentInfo> dest = toDrafts ? drafts : published; for (int i = 0; i < in.length(); i++) { dest.push(in.get(i)); } } } So if drafts != null and published == null we store the drafts in published?

Target:
private void addAllToCommentList(JsArray<CommentInfo> in, boolean toDrafts) { if (toDrafts && drafts == null) { drafts = in; } else if (!toDrafts && published == null) { published = in; } else { JsArray<CommentInfo> dest = toDrafts ? drafts : published; for (int i = 0; i < in.length(); i++) { dest.push(in.get(i)); } } }
Source:
protected void configureServlets() { serve("/say-hello").with(HelloWorldServlet.class); START serve("/say-hello/*").with(HelloWorldServlet.class); END } Why both bindings?

Target:
protected void configureServlets() { serve("/say-hello/*").with(HelloWorldServlet.class); }
Source:
public Object apply(ChangeResource rsrc, Input input) throws AuthException, InterruptedException, ExecutionException { START CurrentUser caller = rsrc.getControl().getCurrentUser(); if (!caller.getCapabilities().canAdministrateServer()) { throw new AuthException("index not permitted"); } END indexer.index(rsrc.getChange()).get(); return Response.none(); } This check is not necessary with @RequiresCapability.

Target:
public Object apply(ChangeResource rsrc, Input input) throws AuthException, InterruptedException, ExecutionException { indexer.index(rsrc.getChange()).get(); return Response.none(); }
Source:
private static <T extends Annotation> T getClassAnnotation(Class<?> clazz, Class<T> annotationClass) { START if (clazz == null) { return null; } T annot = clazz.getAnnotation(annotationClass); if (annot == null) { annot = getClassAnnotation(clazz.getSuperclass(), annotationClass); if (annot != null) { return annot; } } return annot; END } This can be written as a loop: for (; clazz != null; clazz = clazz.getSuperclass()) { T t = clazz.getAnnotation(annotationClass); if (t != null) { return t; } } return null;

Target:
private static <T extends Annotation> T getClassAnnotation(Class<?> clazz, Class<T> annotationClass) { for (; clazz != null; clazz = clazz.getSuperclass()) { T t = clazz.getAnnotation(annotationClass); if (t != null) { return t; } } return null; }
Source:
private void checkRequiresCapability(Command cmd) throws UnloggedFailure { String pluginName = null; if (cmd instanceof BaseCommand) { pluginName = ((BaseCommand) cmd).getPluginName(); } try { CapabilityUtils.checkRequiresCapability(currentUser, pluginName, cmd.getClass()); } catch (AuthException e) { throw new UnloggedFailure(BaseCommand.STATUS_NOT_ADMIN, START "fatal: cannot check capability"); END } } e.getMessage()

Target:
private void checkRequiresCapability(Command cmd) throws UnloggedFailure { String pluginName = null; if (cmd instanceof BaseCommand) { pluginName = ((BaseCommand) cmd).getPluginName(); } try { CapabilityUtils.checkRequiresCapability(currentUser, pluginName, cmd.getClass()); } catch (AuthException e) { throw new UnloggedFailure(BaseCommand.STATUS_NOT_ADMIN, e.getMessage()); } }
Source:
private static AsyncCallback<JavaScriptObject> mine() { return new GerritCallback<JavaScriptObject>() { public void onSuccess(JavaScriptObject result) { redisplay(); } public void onFailure(Throwable err) { if (SubmitFailureDialog.isConflict(err)) { new SubmitFailureDialog(err.getMessage()).center(); redisplay(); } else { super.onFailure(err); } } START private void redisplay() { Gerrit.display(PageLinks.MINE); } END }; } Probably shorter to just line this.

Target:
private static AsyncCallback<JavaScriptObject> mine() { return new GerritCallback<JavaScriptObject>() { public void onSuccess(JavaScriptObject result) { Gerrit.display(PageLinks.MINE); } public void onFailure(Throwable err) { if (SubmitFailureDialog.isConflict(err)) { new SubmitFailureDialog(err.getMessage()).center(); Gerrit.display(PageLinks.MINE); } else { super.onFailure(err); } } }; }
Source:
void set(ChangeInfo info, String revision, START Labels labels, Element reviewers) { END this.changeId = info.legacy_id(); this.info = info; this.revision = revision; this.labels = labels; this.reviewers = reviewers; reviewerSuggestOracle.setChange(changeId); renderReviewers(info); } These are UI widgets and should be passed through init() not set(). Passing during init() matches the pattern used by Labels.init() from ChangeScreen2 to gain access to additional UiFields outside of itself that its set() controls.

Target:
void set(ChangeInfo info, String revision, Labels labels, Element reviewers) { this.info = info; this.revision = revision; this.labels = labels; this.reviewers = reviewers; reviewerSuggestOracle.setChange(info.legacy_id()); renderReviewers(info); }
Source:
private START String renderInput(Options END options, String inputFile) { Asciidoctor asciidoctor = JRubyAsciidoctor.create(); return asciidoctor.renderFile(new File(inputFile), options); } return void now as the result is not used

Target:
private void renderInput(Options options, String inputFile) { Asciidoctor asciidoctor = JRubyAsciidoctor.create(); asciidoctor.renderFile(new File(inputFile), options); }
Source:
public ListenableFuture<?> index(ChangeData cd) { START return executor.submit(indexTask(cd)); END } Seems like we could use the check here too?

Target:
public ListenableFuture<?> index(ChangeData cd) { return executor != null ? executor.submit(indexTask(cd)) : null; }
Source:
START String getPluginName() { END return pluginName; } Maybe this should also be protected?

Target:
protected String getPluginName() { return pluginName; }
Source:
START void onAllNodesReplicated(int totalPushTasksCount) { END if (replicationsCount == 0) { return; } RefReplicationDoneEvent event = new RefReplicationDoneEvent(replicatedProject, replicatedRef, replicationsCount); postEvent(replicatedProject, replicatedRef, event); } Still not using the totalPushTasksCount?

Target:
void onAllNodesReplicated(int totalPushTasksCount) { if (totalPushTasksCount == 0) { return; } RefReplicationDoneEvent event = new RefReplicationDoneEvent(replicatedProject, replicatedRef, totalPushTasksCount); postEvent(replicatedProject, replicatedRef, event); }
Source:
public static List<PluginData> listPluginsAndRemoveTempFiles(SitePaths site) throws IOException { START return listPlugins(site, false); END } Shouldn't this be true? ;-)

Target:
public static List<PluginData> listPluginsAndRemoveTempFiles(SitePaths site) throws IOException { return listPlugins(site, true); }
Source:
private boolean isAuthorizedCall(HttpServletRequest req) { START if (Strings.isNullOrEmpty(req.getServletPath())) { return false; } if (req.getServletPath().startsWith(AUTHORIZED_PREFIX)) { return true; } return false; END } return !Strings.isNullOrEmpty(req.getServletPath() && req.getServletPath().startsWith(AUTHORIZED_PREFIX);

Target:
private boolean isAuthorizedCall(HttpServletRequest req) { return !Strings.isNullOrEmpty(req.getServletPath()) && req.getServletPath().startsWith(AUTHORIZED_PREFIX); }
Source:
public void submit() throws GitAPIException, IOException, RestApiException { PushOneCommit.Result r = createChange(); RevisionApi rApi = gApi.changes() .id("p~master~" + r.getChangeId()) .revision(r.getCommit().name()); rApi.review(approve()); START rApi.submit(new SubmitInput()); END } /submit is another API commonly called with no input.

Target:
public void submit() throws GitAPIException, IOException, RestApiException { PushOneCommit.Result r = createChange(); RevisionApi rApi = gApi.changes() .id("p~master~" + r.getChangeId()) .revision(r.getCommit().name()); rApi.review(approve()); rApi.submit(new SubmitInput(true)); }
Source:
protected void assertResultEquals(Change expected, ChangeInfo actual) { START assertEquals(expected.getId().get(), (int) actual._number); END } Unnecessary cast.

Target:
protected void assertResultEquals(Change expected, ChangeInfo actual) { assertEquals(expected.getId().get(), actual._number); }
Source:
protected void assertResultEquals(String message, Change expected, ChangeInfo actual) { START assertEquals(message, expected.getId().get(), (int) actual._number); END } Unnecessary cast.

Target:
protected void assertResultEquals(String message, Change expected, ChangeInfo actual) { assertEquals(message, expected.getId().get(), actual._number); }
Source:
START public IsMergeablePredicate(Provider<ReviewDb> END dbProvider) { super(ChangeField.MERGEABLE, "1"); this.dbProvider = dbProvider; } default access

Target:
IsMergeablePredicate(Provider<ReviewDb> dbProvider) { super(ChangeField.MERGEABLE, "1"); this.dbProvider = dbProvider; }
Source:
public boolean match(ChangeData object) throws OrmException { Change c = object.change(dbProvider); START if (c == null) { return false; } return c.isMergeable(); END } return c != null && c.isMergeable();

Target:
public boolean match(ChangeData object) throws OrmException { Change c = object.change(dbProvider); return c != null && c.isMergeable(); }
Source:
START public ApprovalsUtil(ReviewDb END db) { this.db = db; } This no longer needs to be public, that was only for MergeOp.

Target:
ApprovalsUtil(ReviewDb db) { this.db = db; }
Source:
START GreetInfo( String END m, String c, String h) { country = c; message = m; href = h; } no space after (

Target:
GreetInfo(String m, String c, String h) { message = m; country = c; href = h; }
Source:
protected void configureServlets() { install(new FactoryModule() { @Override protected void configure() { START factory(ChangeDetailFactory.Factory.class); END factory(PatchSetDetailFactory.Factory.class); } }); rpc(ChangeDetailServiceImpl.class); } Remove this line. ChangeDetailFactory seems not to be needed any more and can be deleted. The only using files seems to be PatchDetailServiceImpl.java, but there it is also not used and can be removed.

Target:
protected void configureServlets() { install(new FactoryModule() { @Override protected void configure() { factory(PatchSetDetailFactory.Factory.class); } }); rpc(ChangeDetailServiceImpl.class); }
Source:
public boolean equals(Object o) { START if (!(o instanceof LabelVote)) { return false; } END LabelVote l = (LabelVote) o; return Objects.equal(name, l.name) && value == l.value; } I prefer if (o instanceof LabelVote) { LabelVote l = (LabelVote) o; ... } return false;

Target:
public boolean equals(Object o) { if (o instanceof LabelVote) { LabelVote l = (LabelVote) o; return Objects.equal(name, l.name) && value == l.value; } return false; }
Source:
protected void configure() { START install(new CacheModule() { END @Override protected void configure() { cache(PROJECT_DOC_RESOURCES, ResourceKey.class, Resource.class) .maximumWeight(2 << 20) .weigher(ResourceWeigher.class); } }); } Why is this needed? You are already subclassing a CacheModule. This method body should only contain the lines 30-32

Target:
protected void configure() { cache(PROJECT_DOC_RESOURCES, ResourceKey.class, Resource.class) .maximumWeight(2 << 20) .weigher(ResourceWeigher.class); }
Source:
private void parseAll() throws ConfigInvalidException, IOException { walk.markStart(walk.parseCommit(tip)); for (RevCommit commit : walk) { START walk.parseBody(commit); END parse(commit); } pruneReviewers(); for (Collection<PatchSetApproval> v : approvals.asMap().values()) { Collections.sort((List<PatchSetApproval>) v, PSA_BY_TIME); } } Unnecessary unless you are rewalking a previously walked graph.

Target:
private void parseAll() throws ConfigInvalidException, IOException { walk.markStart(walk.parseCommit(tip)); for (RevCommit commit : walk) { parse(commit); } pruneReviewers(); for (Collection<PatchSetApproval> v : approvals.asMap().values()) { Collections.sort((List<PatchSetApproval>) v, PSA_BY_TIME); } }
Source:
static NotesMigration allEnabled() { Config cfg = new Config(); cfg.setBoolean("notedb", null, "write", true); START cfg.setBoolean("notedb", "patchSetApprovals", "read", true); END return new NotesMigration(cfg); } Changing this to: cfg.setBoolean("notedb", "patchSetApprovals", "read", false); makes most tests fail.

Target:
static NotesMigration allEnabled() { Config cfg = new Config(); cfg.setBoolean("notedb", null, "write", true); //cfg.setBoolean("notedb", "patchSetApprovals", "read", true); return new NotesMigration(cfg); }
Source:
private void merge(PushOneCommit.Result r) throws Exception { review(r, 2); START SubmitInput input = new SubmitInput(); input.waitForMerge = true; END revision(r).submit(input); Repository repo = repoManager.openRepository(project); try { assertEquals(r.getCommitId(), repo.getRef("refs/heads/master").getObjectId()); } finally { repo.close(); } } Remove these lines, you don't ned them. There is submit() method that does this standard thing.

Target:
private void merge(PushOneCommit.Result r) throws Exception { review(r, 2); revision(r).submit(); Repository repo = repoManager.openRepository(project); try { assertEquals(r.getCommitId(), repo.getRef("refs/heads/master").getObjectId()); } finally { repo.close(); } }
Source:
public boolean match(ChangeData cd) throws OrmException { START return cd.change().getLastUpdatedOn().getTime() <= cut.getTime(); END } Backwards? after:foo should match where last updated on is > foo.

Target:
public boolean match(ChangeData cd) throws OrmException { return cd.change().getLastUpdatedOn().getTime() >= cut.getTime(); }
Source:
protected void run() START throws UnloggedFailure, Failure, Exception { END stdout.println("Hello, cookbook administrator"); } Not needed, sorry missed it in previous review.

Target:
protected void run() { stdout.println("Hello, cookbook administrator"); }
Source:
protected void execResource(final String p) { try { try (InputStream in = JythonShell.class.getClassLoader().getResourceAsStream(p)) { if (in != null) { execStream(in, "resource " + p); } else { log.error("Cannot load resource " + p); } } START } catch (IOException e) { END log.error(e.getMessage(), e); } } the catch could be part of the innter try block, no need to nest two blocks

Target:
protected void execResource(final String p) { try (InputStream in = JythonShell.class.getClassLoader().getResourceAsStream(p)) { if (in != null) { execStream(in, "resource " + p); } else { log.error("Cannot load resource " + p); } } catch (IOException e) { log.error(e.getMessage(), e); } }
Source:
START private boolean computeMerged() { END if (!merged.contains(revision)) { while (mergedPos > 0) { CommitInfo c = changes.get(mergedPos).commit(); JsArrayString b = changes.get(mergedPos).branches(); if (b.get(0) != null) { merged.add(c.commit()); } mergedPos--; } return true; } return false; } As far as I can see, this method is only called at line 244, and the return value is not checked. If the return value is not used, the method should return void.

Target:
private void computeMerged() { if (!merged.contains(revision)) { while (mergedPos > 0) { CommitInfo c = changes.get(mergedPos).commit(); JsArrayString b = changes.get(mergedPos).branches(); if (b.get(0) != null) { merged.add(c.commit()); } mergedPos--; } } }
Source:
private static boolean isAbsolute(String url) { START String pattern = END "^https?://.*"; return url.matches(pattern); } This variable is not needed, just use the pattern direct.

Target:
private static boolean isAbsolute(String url) { return url.matches("^https?://.*"); }
Source:
static void toGerrit(final String target, final HttpServletRequest req, final HttpServletResponse rsp) throws IOException { final StringBuilder url = new StringBuilder(); START url.append(URLEncoder.encode(req.getContextPath(), "UTF-8")); END url.append('/'); url.append('#'); url.append(target); rsp.sendRedirect(url.toString()); } I think this stops admins from installing at for example /code/review/ on their server.

Target:
static void toGerrit(final String target, final HttpServletRequest req, final HttpServletResponse rsp) throws IOException { final StringBuilder url = new StringBuilder(); url.append(req.getContextPath()); url.append('/'); url.append('#'); url.append(target); rsp.sendRedirect(url.toString()); }
Source:
protected void doGet(final HttpServletRequest req, final HttpServletResponse rsp) throws IOException { final StringBuilder rdr = new StringBuilder(); START rdr.append(URLEncoder.encode(urlProvider.get(), "UTF-8")); END rdr.append('#'); rdr.append(getToken(req)); CacheHeaders.setNotCacheable(rsp); rsp.sendRedirect(rdr.toString()); } If the URL used to access this web application is unsafe you are already hosed. IIRC this string usually comes from gerrit.config. If your admin has p0wn3d gerrit.config you have other problems.

Target:
protected void doGet(final HttpServletRequest req, final HttpServletResponse rsp) throws IOException { final StringBuilder rdr = new StringBuilder(); rdr.append(urlProvider.get()); rdr.append('#'); rdr.append(getToken(req)); CacheHeaders.setNotCacheable(rsp); rsp.sendRedirect(rdr.toString()); }
Source:
public boolean equals(Object obj) { if (obj instanceof SecureStoreData) { SecureStoreData o = (SecureStoreData) obj; START return Objects.equal(storeName, o.storeName); END } return equals(obj); } The only reason to use Objects.equal here would be to handle the null cases for the parameters. As I see the storeName canno be null so: storeName.equals(o.storeName) is good enough.

Target:
public boolean equals(Object obj) { if (obj instanceof SecureStoreData) { SecureStoreData o = (SecureStoreData) obj; return storeName.equals(o.storeName); } return super.equals(obj); }
Source:
public List<PatchSetApproval> byPatchSet(ReviewDb db, ChangeNotes notes, PatchSet.Id psId) throws OrmException { if (!migration.readPatchSetApprovals()) { return sortApprovals(db.patchSetApprovals().byPatchSet(psId)); } ImmutableListMultimap<Id, PatchSetApproval> approvals = notes.load().getApprovals(); START if (approvals != null) { END return approvals.get(psId); } return Collections.emptyList(); } I don't want to return null from getApprovals(). It shouldn't be that hard to modify ChangeNotes.onLoad to handle a null revision.

Target:
public List<PatchSetApproval> byPatchSet(ReviewDb db, ChangeNotes notes, PatchSet.Id psId) throws OrmException { if (!migration.readPatchSetApprovals()) { return sortApprovals(db.patchSetApprovals().byPatchSet(psId)); } return notes.load().getApprovals().get(psId); }
Source:
public Void get(long timeout, TimeUnit unit) throws InterruptedException, TimeoutException, ExecutionException { if (!isDone()) { if START (reopenThread.waitForGeneration(gen, END (int) MILLISECONDS.convert(timeout, unit))) { set(null); } } return super.get(timeout, unit); } Apparently this method returns false when the wait time is exceeded. The old implementation was just buggy. It completed the future anyway and lied to the caller the indexing was done. The new implementation avoids this, but makes the caller potentially wait 2x the timeout. When waitForGeneration returns false the method should throw TimeoutException.

Target:
public Void get(long timeout, TimeUnit unit) throws InterruptedException, TimeoutException, ExecutionException { if (!isDone()) { if (reopenThread.waitForGeneration(gen, (int) MILLISECONDS.convert(timeout, unit))) { set(null); } else { throw new TimeoutException(); } } return super.get(timeout, unit); }
Source:
public void removeIfDone() throws IOException { if (isGenAvailableNowForCurrentSearcher()) { if (!isCancelled()) { START notDoneNrtFutures.remove(this); END set(null); } } } This should be outside of the isCancelled block. The method removeIfDone is only called if the future is inside of the concurrent set. If its in the set and the gen is available, the future should remove itself no matter what state the future is in.

Target:
void removeIfDone() { if (isGenAvailableNowForCurrentSearcher()) { notDoneNrtFutures.remove(this); if (!isCancelled()) { set(null); } } }
Source:
public void setCurrentFilePaths(List<String> filePaths) throws OrmException { PatchSet ps = currentPatchSet(); if (ps != null) { START files.put(Integer.valueOf(ps.getPatchSetId()), END ImmutableList.copyOf(filePaths)); } } This is redundant, auto-boxing will work just fine and IIRC unlike JGit we don't warn on auto-boxing in Gerrit.

Target:
public void setCurrentFilePaths(List<String> filePaths) throws OrmException { PatchSet ps = currentPatchSet(); if (ps != null) { files.put(ps.getPatchSetId(), ImmutableList.copyOf(filePaths)); } }
Source:
START public END UniversalServerPluginProvider(DynamicSet<ServerPluginProvider> sf) { this.serverPluginProviders = sf; } Why public? Gerrit conversion is to mark injected constructors as package provided

Target:
UniversalServerPluginProvider(DynamicSet<ServerPluginProvider> sf) { this.serverPluginProviders = sf; }
Source:
public PatchSet getBasePatchSet(RevisionEdit edit, RevCommit commit) throws IOException { START checkState(commit.getParentCount() == 1); END RevCommit parentCommit = commit.getParent(0); RevId parentRev = new RevId(ObjectId.toString(parentCommit.getId())); try { return Iterables.getOnlyElement(db.get().patchSets() .byRevision(parentRev).toList()); } catch (OrmException e) { throw new IOException(e); } } Useful error message when this fails?

Target:
public PatchSet getBasePatchSet(RevisionEdit edit, RevCommit commit) throws IOException { RevCommit parentCommit = commit.getParent(0); RevId parentRev = new RevId(ObjectId.toString(parentCommit.getId())); try { return Iterables.getOnlyElement(db.get().patchSets() .byRevision(parentRev).toList()); } catch (OrmException e) { throw new IOException(e); } }
Source:
private ObjectId createCommit(IdentifiedUser me, ObjectInserter inserter, START RevCommit prevEdit, RevCommit END base, ObjectId tree) throws IOException { CommitBuilder builder = new CommitBuilder(); builder.setTreeId(tree); builder.setParentIds(base); builder.setAuthor(prevEdit.getAuthorIdent()); builder.setCommitter(getCommitterIdent(me)); builder.setMessage(prevEdit.getFullMessage()); ObjectId newEdit = inserter.insert(builder); inserter.flush(); return newEdit; } Not obvious what this argument does. It looks like it's just to copy the identity? Why not just pass a PersonIdent instead?

Target:
private ObjectId createCommit(IdentifiedUser me, ObjectInserter inserter, RevCommit prevEdit, RevCommit base, ObjectId tree) throws IOException { CommitBuilder builder = new CommitBuilder(); builder.setTreeId(tree); builder.setParentIds(base); builder.setAuthor(prevEdit.getAuthorIdent()); builder.setCommitter(getCommitterIdent(me)); builder.setMessage(prevEdit.getFullMessage()); return inserter.insert(builder); }
Source:
public GerritConstantsProperties() throws IOException { InputStream constantsStream = START GerritTopMenus.class.getResourceAsStream(GERRIT_CONSTANTS_PROPERTIES); END if (constantsStream != null) { load(constantsStream); } else { log.error("Cannot locate Gerrit constants from classpath", GERRIT_CONSTANTS_PROPERTIES); } } Why not use the class GerritConstantsProperties.class or even: getClass().getResourceAsStream(GERRIT_CONSTANTS_PROPERTIES)

Target:
public GerritConstantsProperties() throws IOException { InputStream constantsStream = getClass().getResourceAsStream(GERRIT_CONSTANTS_PROPERTIES); if (constantsStream != null) { try { load(constantsStream); } finally { constantsStream.close(); } } else { log.error("Cannot locate Gerrit constants from classpath", GERRIT_CONSTANTS_PROPERTIES); } }
Source:
private GerritTopMenus gerritTopMenusWithModule(AbstractModule module) { START Injector injector = END baseInjector.createChildInjector(module); return injector.getInstance(GerritTopMenus.class); } No need for the variable. Just inline it in one return statement.

Target:
private GerritTopMenus gerritTopMenusWithModule(AbstractModule module) { return baseInjector.createChildInjector(module).getInstance( GerritTopMenus.class); }
Source:
void onClose(ClickEvent e) { START onCancel(null); END } If it's likely that we'll ever want to do something with the event in onCancel, it would be better to pass `e` here rather than null.

Target:
void onClose(ClickEvent e) { onCancel(e); }
Source:
START static boolean isAuthorizedCall(HttpServletRequest req) { END return !Strings.isNullOrEmpty(req.getServletPath()) && req.getServletPath().startsWith(AUTHORIZED_PREFIX); } make this private?

Target:
private static boolean isAuthorizedCall(HttpServletRequest req) { return !Strings.isNullOrEmpty(req.getServletPath()) && req.getServletPath().startsWith(AUTHORIZED_PREFIX); }
Source:
static public PermissionRule START allow(ProjectConfig END project, String capabilityName, AccountGroup.UUID group) { PermissionRule rule = newRule(project, group); project.getAccessSection(AccessSection.GLOBAL_CAPABILITIES, true) .getPermission(capabilityName, true) .add(rule); return rule; } I think many tests doing something similar and call it grant()? Should we switch to using this convenience method there too?

Target:
public static PermissionRule allow(ProjectConfig project, String capabilityName, AccountGroup.UUID group) { PermissionRule rule = newRule(project, group); project.getAccessSection(AccessSection.GLOBAL_CAPABILITIES, true) .getPermission(capabilityName, true) .add(rule); return rule; }
Source:
public boolean isStale(GerritConfig cfg) { return lastUpdated > cfg.getCreationTime() START || (refreshConfig && site.gerrit_config.lastModified() > cfg.getCreationTime()); END } wrap this line?

Target:
public boolean isStale(GerritConfig cfg) { return refreshConfig && site.gerrit_config.lastModified() > cfg.getCreationTime(); }
Source:
private static String generateRandomState() { byte[] randomState = new byte[32]; START new SecureRandom().nextBytes(randomState); END return Base64.encodeBase64URLSafeString(randomState); } This may exhaust entropy on the local server and cause login stalls and general denial of service until enough entropy builds up again to start another RNG. You should create the SecureRandom once at server startup and retain it long term through a singleton. This helps avoid depleting local high quality entropy on each login request. In the early early days of Gerrit we had such issues with SSH where users just couldn't login for hours or days because the SSH server was depleting entropy at every connection.

Target:
static String generateRandomState() { byte[] state = new byte[32]; randomState.nextBytes(state); return Base64.encodeBase64URLSafeString(state); }
Source:
private String getUrl(String baseUrl, String path) throws MalformedURLException { if (baseUrl.indexOf("://") > 0) { return new URL(new URL(baseUrl), path).toExternalForm(); } else { return baseUrl + trimTrailingSlash(baseUrl) + "/" + START CharMatcher.is('/').trimLeadingFrom(path); END } } Use trimTrailingSlash method?

Target:
private String getUrl(String baseUrl, String path) { return trimTrailingSlash(baseUrl) + path; }
Source:
START private long END interval(Config rc, String section) { long interval = -1; try { interval = ConfigUtil.getTimeUnit(rc, section, null, KEY_INTERVAL, -1, TimeUnit.MILLISECONDS); if (interval == -1) { log.info(MessageFormat.format("{0} schedule parameter \"{0}.{1}\" is not configured", section, KEY_INTERVAL)); } } catch (IllegalArgumentException e) { log.error(MessageFormat.format("Invalid {0} schedule parameter \"{0}.{1}\"", section, KEY_INTERVAL), e); } return interval; } Should be static (see below).

Target:
private static long interval(Config rc, String section) { long interval = -1; try { interval = ConfigUtil.getTimeUnit(rc, section, null, KEY_INTERVAL, -1, TimeUnit.MILLISECONDS); if (interval == -1) { log.info(MessageFormat.format("{0} schedule parameter \"{0}.{1}\" is not configured", section, KEY_INTERVAL)); } } catch (IllegalArgumentException e) { log.error(MessageFormat.format("Invalid {0} schedule parameter \"{0}.{1}\"", section, KEY_INTERVAL), e); } return interval; }
Source:
public void stop() { START if (scheduledTask != null) { scheduledTask.cancel(true); } END } I would guess that the work queue itself listens to the stop event and cancels the tasks. But this would have to be verified.

Target:
public void stop() { // handled by WorkQueue.stop() already }
Source:
START public static List<ChangeMessage> sortChangeMessages( Iterable<ChangeMessage> changeMessage) { return ChangeNotes.MESSAGE_BY_TIME.sortedCopy(changeMessage); } END +1, will clarify docs.

Target:
private static List<ChangeMessage> sortChangeMessages( Iterable<ChangeMessage> changeMessage) { return ChangeNotes.MESSAGE_BY_TIME.sortedCopy(changeMessage); }
Source:
public void fromRange(Range r) { range = START range == END null ? null : new CommentRange(range.startLine, range.startCharacter, range.endLine, range.endCharacter); } Eclipse is warning that the argument `r` is unused. I guess this should be changed to `r`?

Target:
public void fromRange(Range r) { range = r == null ? null : new CommentRange(range.startLine, range.startCharacter, range.endLine, range.endCharacter); }
Source:
public CustomIcons get() { START CustomIcons customIcons = END new CustomIcons(projectIcons); return customIcons; } This temp var is unneeded. Return direct.

Target:
public CustomIcons get() { return new CustomIcons(projectIcons); }
Source:
START private Collection<PatchLineComment> addCommentsInFile( END Collection<PatchLineComment> commentsOnFile, Collection<PatchLineComment> allComments, String file) { for (PatchLineComment c : allComments) { String currentFilename = c.getKey().getParentKey().getFileName(); if (currentFilename.equals(file)) { commentsOnFile.add(c); } } return commentsOnFile; } Can be static, and order it down below the public methods

Target:
private static Collection<PatchLineComment> addCommentsInFile( Collection<PatchLineComment> commentsOnFile, Collection<PatchLineComment> allComments, String file) { for (PatchLineComment c : allComments) { String currentFilename = c.getKey().getParentKey().getFileName(); if (currentFilename.equals(file)) { commentsOnFile.add(c); } } return commentsOnFile; }
Source:
private ReviewInput reviewFromJson() throws UnloggedFailure { try { InputStreamReader r = new InputStreamReader(in, StandardCharsets.UTF_8); return OutputFormat.JSON.newGson(). fromJson(CharStreams.toString(r),ReviewInput.class); } catch START (IOException e) END { throw error("internal error while reading review input"); } } Done

Target:
private ReviewInput reviewFromJson() throws UnloggedFailure { try (InputStreamReader r = new InputStreamReader(in, StandardCharsets.UTF_8)) { return OutputFormat.JSON.newGson(). fromJson(CharStreams.toString(r),ReviewInput.class); } catch (IOException e) { throw error("internal error while reading review input"); } }
Source:
AbstractChangeNotes(GitRepositoryManager repoManager, Change change) { this.repoManager = repoManager; START this.change = change; END } Defensive copy here instead?

Target:
AbstractChangeNotes(GitRepositoryManager repoManager, Change change) { this.repoManager = repoManager; this.change = new Change(change); }
Source:
START protected boolean isEmpty() { END return approvals.isEmpty() && reviewers.isEmpty() && commentsForBase.isEmpty() && commentsForPs.isEmpty() && status == null && submitRecords == null && changeMessage == null; } Leave private.

Target:
private boolean isEmpty() { return approvals.isEmpty() && reviewers.isEmpty() && commentsForBase.isEmpty() && commentsForPs.isEmpty() && status == null && submitRecords == null && changeMessage == null; }
Source:
public static synchronized void cleanup() throws IOException { START System.out.println("deleting dirs"); END for(File dir : allDirsCreated) { System.err.println("cleaning up " + dir.getCanonicalPath()); recursivelyDelete(dir); } allDirsCreated.clear(); } Left over diagnostic output?

Target:
public static synchronized void cleanup() throws IOException { for (File dir : allDirsCreated) { recursivelyDelete(dir); } allDirsCreated.clear(); }
Source:
private List<AccountExternalId.Key> filterKeysByScheme( String keyScheme, ResultSet<AccountExternalId> externalIds) { List<AccountExternalId.Key> filteredExternalIds = START Lists.newArrayList(); END for (AccountExternalId accountExternalId : externalIds) { if (accountExternalId.isScheme(keyScheme)) { filteredExternalIds.add(accountExternalId.getKey()); } } return filteredExternalIds; } new ArrayList<>()

Target:
private List<AccountExternalId.Key> filterKeysByScheme( String keyScheme, ResultSet<AccountExternalId> externalIds) { List<AccountExternalId.Key> filteredExternalIds = new ArrayList<>(); for (AccountExternalId accountExternalId : externalIds) { if (accountExternalId.isScheme(keyScheme)) { filteredExternalIds.add(accountExternalId.getKey()); } } return filteredExternalIds; }
Source:
START public static GitPerson toGitPerson(UserIdentity committer) { END GitPerson p = new GitPerson(); p.name = committer.getName(); p.email = committer.getEmail(); p.date = committer.getDate(); p.tz = committer.getTimeZone(); return p; } Not necessary.

Target:
private static GitPerson toGitPerson(UserIdentity committer) { GitPerson p = new GitPerson(); p.name = committer.getName(); p.email = committer.getEmail(); p.date = committer.getDate(); p.tz = committer.getTimeZone(); return p; }
Source:
START private List<PatchLineComment> END byCommentStatus( ResultSet<PatchLineComment> comments, final PatchLineComment.Status status) throws OrmException { return Lists.newArrayList( Iterables.filter(comments, new Predicate<PatchLineComment>() { @Override public boolean apply(PatchLineComment input) { return (input.getStatus() == status); } }) ); } private static Note that without static qualifier the method order in class is wrong. Private methods expected below public. Dave clarified the order of methods in this change [1]. But still i would place the helper method below the methods it help. Around line 146 in this ps. [1] https://gerrit-review.googlesource.com/#/c/57811/1/Documentation/dev-contributing.txt

Target:
private static List<PatchLineComment> byCommentStatus( ResultSet<PatchLineComment> comments, final PatchLineComment.Status status) { return Lists.newArrayList( Iterables.filter(comments, new Predicate<PatchLineComment>() { @Override public boolean apply(PatchLineComment input) { return (input.getStatus() == status); } }) ); }
Source:
public Collection<PatchLineComment> publishedComments() throws OrmException { if (publishedComments == null) { START publishedComments = Lists.newArrayList(plcUtil.publishedByChange(db, notes())); END } return publishedComments; } publishedByChange() already returns list, so just: publishedComments = plcUtil.publishedByChange(db, notes());

Target:
public Collection<PatchLineComment> publishedComments() throws OrmException { if (publishedComments == null) { publishedComments = plcUtil.publishedByChange(db, notes()); } return publishedComments; }
Source:
public String getUrl(String baseUrl, String path) throws MalformedURLException { if (baseUrl.indexOf("://") > 0) { return new URL(new URL(baseUrl), path).toExternalForm(); } else { START return baseUrl + (baseUrl.endsWith("/") ? "" : "/") END + (path.startsWith("/") ? path.substring(1) : path); } } It seems to me like the removal of the slash has no effect because its dealt with here no?

Target:
private static String getUrl(String baseUrl, String path) throws MalformedURLException { return new URL(new URL(baseUrl), path).toExternalForm(); }
Source:
START private List<PatchLineComment> END sort(List<PatchLineComment> comments) { Collections.sort(comments, ChangeNotes.PatchLineCommentComparator); return comments; } private static

Target:
private static List<PatchLineComment> sort(List<PatchLineComment> comments) { Collections.sort(comments, ChangeNotes.PatchLineCommentComparator); return comments; }
Source:
private static void reset() throws MalformedURLException { for (Enumeration<Logger> logger = LogManager.getCurrentLoggers(); logger.hasMoreElements();) { logger.nextElement().setLevel(null); } if START (Strings.isNullOrEmpty(System.getProperty(JAVA_OPTIONS_LOG_CONFIG))) END { PropertyConfigurator.configure(Loader.getResource(LOG_CONFIGURATION)); } else { PropertyConfigurator.configure( new URL(System.getProperty(JAVA_OPTIONS_LOG_CONFIG))); } } Optional: extract this into a var, so that we don't retrieve it twice: here and on line 90.

Target:
private static void reset() throws MalformedURLException { for (Enumeration<Logger> logger = LogManager.getCurrentLoggers(); logger.hasMoreElements();) { logger.nextElement().setLevel(null); } String path = System.getProperty(JAVA_OPTIONS_LOG_CONFIG); if (Strings.isNullOrEmpty(path)) { PropertyConfigurator.configure(Loader.getResource(LOG_CONFIGURATION)); } else { PropertyConfigurator.configure(new URL(path)); } }
Source:
private static Term intTerm(String name, int value) { BytesRef bytes = new BytesRef(NumericUtils.BUF_SIZE_INT); BytesRefBuilder builder = new BytesRefBuilder(); builder.append(bytes); START NumericUtils.intToPrefixCodedBytes(value, 0, builder); END return new Term(name, bytes); } Need to use builder.get(). Done.

Target:
private static Term intTerm(String name, int value) { BytesRefBuilder builder = new BytesRefBuilder(); NumericUtils.intToPrefixCodedBytes(value, 0, builder); return new Term(name, builder.get()); }
Source:
public void onProjectDeleted(Event event) { Project.NameKey START p = END new NameKey(event.getProjectName()); repoSizeCache.evict(p); } optional: could be inlined in the next line

Target:
public void onProjectDeleted(Event event) { repoSizeCache.evict(new Project.NameKey(event.getProjectName())); }
Source:
private boolean needPack(Collection<ReceiveCommand> commands) { for START (final ReceiveCommand END cmd : commands) { if (cmd.getType() != ReceiveCommand.Type.DELETE) return true; } return false; } I think we don't use 'final' in this place anymore.

Target:
private boolean needPack(Collection<ReceiveCommand> commands) { for (ReceiveCommand cmd : commands) { if (cmd.getType() != ReceiveCommand.Type.DELETE) return true; } return false; }
Source:
private ResourceKey(String p, String f, String r) { project = START p != null ? END new Project.NameKey(p) : null; file = f; revision = r; } Can this really happen? If not why care?

Target:
private ResourceKey(String p, String f, String r) { project = new Project.NameKey(p); file = f; revision = r; }
Source:
START public XDocResourceKey(Project.NameKey END project, String r, ObjectId revId) { this.project = project; this.resource = r; this.revId = revId; } Why this is needed?

Target:
XDocResourceKey(Project.NameKey project, String r, ObjectId revId) { this.project = project; this.resource = r; this.revId = revId; }