auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
START public SerializableProtobuf(T object, ProtobufCodec<T> codec) { END buf = new byte[codec.sizeof(object)]; codec.encode(object, buf); this.object = object; this.codec = codec; hash = object.hashCode(); } Probably doesn't need to be public.

Target:
SerializableProtobuf(T object, ProtobufCodec<T> codec) { this.object = object; this.codec = codec; this.hash = object.hashCode(); }
Source:
START public T toObject(ProtobufCodec<T> codec, Provider<T> provider) { END if (object == null) { this.codec = codec; if (provider == null) { object = codec.decode(buf); } else { object = provider.get(); try { codec.mergeFrom(CodedInputStream.newInstance(buf), object); } catch (IOException e) { throw new RuntimeException("Cannot decode message", e); } } // Free the memory being taken up by the buffer. buf = null; } return object; } Probably doesn't need to be public.

Target:
T toObject(ProtobufCodec<T> codec, Provider<T> provider) { if (object == null) { this.codec = codec; if (provider == null) { object = codec.decode(buf); } else { object = provider.get(); codec.mergeFrom(buf, object); } // Free the memory being taken up by the buffer. buf = null; } return object; }
Source:
private void send(final List<RemoteRefUpdate> cmds, final RefSpec spec) throws IOException { final String src = spec.getSource(); String dst = spec.getDestination(); START if (dst == null) dst = src; END final boolean force = spec.isForceUpdate(); cmds.add(new RemoteRefUpdate(db, src, dst, force, null, null)); } Style-nit: Put curly braces around the then statement.

Target:
private void send(final List<RemoteRefUpdate> cmds, final RefSpec spec) throws IOException { final String src = spec.getSource(); String dst = spec.getDestination(); if (dst == null) { dst = src; } final boolean force = spec.isForceUpdate(); cmds.add(new RemoteRefUpdate(db, src, dst, force, null, null)); }
Source:
START public PrefetchableAndPredicate( END Collection<? extends Predicate<ChangeData>> that) { super(that); } Doesn't need to be public.

Target:
PrefetchableAndPredicate( Collection<? extends Predicate<ChangeData>> that) { super(that); }
Source:
START public PrefetchableAndPredicate(Predicate<ChangeData>... that) { END super(that); } Doesn't need to be public.

Target:
PrefetchableAndPredicate(Predicate<ChangeData>... that) { super(that); }
Source:
private void addSuggestion(Map map, Account account, AccountInfo info, Boolean active) { START if(active != null) { END if(active.booleanValue() != account.isActive()) { return; } } map.put(account.getId(), info); } Style-nit: Space after if. But I think you can write the code more cleanly: if (active == null || active == account.isActive()) { map.put(account.getId(), info); }

Target:
private void addSuggestion(Map map, Account account, AccountInfo info, Boolean active) { if (active == null || active == account.isActive()) { map.put(account.getId(), info); } }
Source:
public void run() { try { final ReviewDb db = schema.open(); try { for (final Project project : db.projects().all()) { START if (!project.getNameKey().equals(wildProject.getNameKey())) { END replication.scheduleFullSync(project.getNameKey(), urlMatch); } } } finally { db.close(); } } catch (OrmException e) { log.error("Cannot enumerate known projects", e); } } Why not compare Project.Ids?

Target:
public void run() { try { final ReviewDb db = schema.open(); try { for (final Project project : db.projects().all()) { if (!project.getId().equals(wildProject.getId())) { replication.scheduleFullSync(project.getNameKey(), urlMatch); } } } finally { db.close(); } } catch (OrmException e) { log.error("Cannot enumerate known projects", e); } }
Source:
private Collection<RefRight> getWildProjectRights() { START final ProjectState s = projectCache.get(wildProject.getNameKey()); END return s != null ? s.getLocalRights() : Collections.<RefRight> emptyList(); } Use getId() instead?

Target:
private Collection<RefRight> getWildProjectRights() { final ProjectState s = projectCache.get(wildProject.getId()); return s != null ? s.getLocalRights() : Collections.<RefRight> emptyList(); }
Source:
private void initCreateButton() { createButton = new Button(Util.C.buttonCreateProject()); createButton.setEnabled(false); createButton.addClickHandler(new ClickHandler() { @Override public void onClick(final ClickEvent event) { START enableForm(false); END doCreateProject(); } }); } I think it is confusing to put this above instead of in doCreateProject (right before the RPC call). If there ends up being another way to trigger the create (via keyboard...), it will be missed, or have to be duplicated.

Target:
private void initCreateButton() { createButton = new Button(Util.C.buttonCreateProject()); createButton.setEnabled(false); createButton.addClickHandler(new ClickHandler() { @Override public void onClick(final ClickEvent event) { doCreateProject(); } }); }
Source:
START public String getProjectName() { END return projectName; } [optional] maybe better to return Project.NameKey here

Target:
public String getProjectName() { return projectName != null ? projectName.get() : null; }
Source:
private void onTextBoxBase(final TextBoxBase tb) { // The text appears to not get updated until the handlers complete. DeferredCommand.add(new Command() { public void execute() { String orig = strings.get(tb); START orig = orig == null ? "" : orig; END if (! orig.equals(tb.getText())) { widget.setEnabled(true); } } }); } This is easier to read: if (orig == null) orig = "";

Target:
private void onTextBoxBase(final TextBoxBase tb) { // The text appears to not get updated until the handlers complete. DeferredCommand.add(new Command() { @Override public void execute() { String orig = strings.get(tb); if (orig == null) { orig = ""; } if (! orig.equals(tb.getText())) { widget.setEnabled(true); } } }); }
Source:
private void setSubmitType(final Project.SubmitType newSubmitType) { if (submitType != null) { for (int i = 0; i < submitType.getItemCount(); i++) { if (newSubmitType.name().equals(submitType.getValue(i))) { START submitType.setSelectedIndex(i); END return; } } submitType.setSelectedIndex(-1); setEnabledForUseContentMerge(); } } We also need to setEnabledForUseContentMerge(); here.

Target:
private void setSubmitType(final Project.SubmitType newSubmitType) { int index = -1; if (submitType != null) { for (int i = 0; i < submitType.getItemCount(); i++) { if (newSubmitType.name().equals(submitType.getValue(i))) { index = i; break; } } submitType.setSelectedIndex(index); setEnabledForUseContentMerge(); } }
Source:
START public void setProjectName(final Project.NameKey projectName) { END suggestBox.setText(projectName.get()); } Passing in a null here should probably be allowed as a way to clear this box.

Target:
public void setProjectName(final Project.NameKey projectName) { suggestBox.setText(projectName != null ? projectName.get() : ""); }
Source:
private void updateParentProject(final ProjectConfig config) throws UpdateParentsFailedException, NoSuchProjectException { final Project parentProject; if (parentProjectName != null) { final ProjectState parentState = projectCache.get(parentProjectName); if (parentState == null) { throw new NoSuchProjectException(parentProjectName); } parentProject = parentState.getProject(); } else { START parentProject = null; END } updateParentsFactory.create(Collections.singleton(config.getProject()), parentProject).validateParentUpdate(); config.getProject().setParentName(parentProjectName); } This could just be done on line 247 avoiding the need for an else.

Target:
private void updateParentProject(final ProjectConfig config) throws UpdateParentsFailedException, NoSuchProjectException { Project parentProject = null; if (parentProjectName != null) { final ProjectState parentState = projectCache.get(parentProjectName); if (parentState == null) { throw new NoSuchProjectException(parentProjectName); } parentProject = parentState.getProject(); } updateParentsFactory.create(Collections.singleton(config.getProject()), parentProject).validateParentUpdate(); config.getProject().setParentName(parentProjectName); }
Source:
private void service() throws IOException, Failure { project = projectControl.getProjectState().getProject(); try { repo = repoManager.openRepository(project.getNameKey()); } catch (RepositoryNotFoundException e) { START final String name = project.getName(); END throw new Failure(1, "fatal: '" + name + "': not a git archive", e); } try { runImpl(); } finally { repo.close(); } } The name is only used in the next statement, could be inlined.

Target:
private void service() throws IOException, Failure { project = projectControl.getProjectState().getProject(); try { repo = repoManager.openRepository(project.getNameKey()); } catch (RepositoryNotFoundException e) { throw new Failure(1, "fatal: '" + project.getName() + "': not a git archive", e); } try { runImpl(); } finally { repo.close(); } }
Source:
public Set<AccountGroup.Id> getEffectiveGroups() { if (effectiveGroups == null) { START Set<AccountGroup.Id> seedGroups = new HashSet<AccountGroup.Id> (); END if (authConfig.isIdentityTrustable(state().getExternalIds())) { seedGroups = realm.groups(state()); } else { seedGroups = authConfig.getRegisteredGroups(); } effectiveGroups = getIncludedGroups(seedGroups); } return effectiveGroups; } There is no need to initialize the variable here, both branch directions below assign to the variable and discard this HashSet.

Target:
public Set<AccountGroup.Id> getEffectiveGroups() { if (effectiveGroups == null) { Set<AccountGroup.Id> seedGroups; if (authConfig.isIdentityTrustable(state().getExternalIds())) { seedGroups = realm.groups(state()); } else { seedGroups = authConfig.getRegisteredGroups(); } effectiveGroups = getIncludedGroups(seedGroups); } return effectiveGroups; }
Source:
public void setTopView(TopView tv) { START topPanel.remove(0); END switch(tv) { case MAIN: topPanel.add(new FlowPanel()); break; case COMMIT: topPanel.add(commitMessageBlock); break; case PREFERENCES: topPanel.add(settingsPanel); break; case PATCH_SETS: topPanel.add(historyTable); break; case FILES: topPanel.add(fileList); break; } } maybe better: topPanel.clear()

Target:
public void setTopView(TopView tv) { topPanel.clear(); switch(tv) { case COMMIT: topPanel.add(commitMessageBlock); break; case PREFERENCES: topPanel.add(settingsPanel); break; case PATCH_SETS: topPanel.add(historyTable); break; case FILES: topPanel.add(fileList); break; } }
Source:
private String getSortValue() { if (accountInfo != null) { if (accountInfo.getPreferredEmail() != null) { return accountInfo.getPreferredEmail(); START } else { END return accountInfo.getFullName().toString(); } } else { return groupReference.getName(); } } My Pref: unneeded else.

Target:
private String getSortValue() { if (accountInfo != null) { if (accountInfo.getPreferredEmail() != null) { return accountInfo.getPreferredEmail(); } return accountInfo.getFullName().toString(); } return groupReference.getName(); }
Source:
START public static boolean isLegalReviewerGroup(final AccountGroup.UUID groupUUID) { END if (AccountGroup.ANONYMOUS_USERS.equals(groupUUID) || AccountGroup.REGISTERED_USERS.equals(groupUUID)) { return false; } return true; } My Nit Pref: eliminate if, just return the boolean evaluation.

Target:
public static boolean isLegalReviewerGroup(final AccountGroup.UUID groupUUID) { return !(AccountGroup.ANONYMOUS_USERS.equals(groupUUID) || AccountGroup.REGISTERED_USERS.equals(groupUUID)); }
Source:
START public MyWalker() { END super(ProjectState.this.wildProject, ProjectState.this.projectCache); } Declare package access.

Target:
MyWalker() { super(ProjectState.this.wildProject, ProjectState.this.projectCache); }
Source:
public boolean isOwnerOf(AccessSection section) { START return RefUtil.isAnySuperSet(getOwnerOf(), section.getRefPattern()); END } I'm not really sure this much accuracy is necessary on the web UI side. We just need to know if the user is an owner of a local section in order to let them edit.

Target:
public boolean isOwnerOf(AccessSection section) { return getOwnerOf().contains(section.getRefPattern()); }
Source:
START protected ObjectId commit(final Merger m, final CommitBuilder mergeCommit) END throws IOException, UnsupportedEncodingException { ObjectInserter oi = m.getObjectInserter(); try { ObjectId id = oi.insert(mergeCommit); oi.flush(); return id; } finally { oi.release(); } } Should subclasses be allowed to override this method?

Target:
protected final ObjectId commit(final Merger m, final CommitBuilder mergeCommit) throws IOException, UnsupportedEncodingException { ObjectInserter oi = m.getObjectInserter(); try { ObjectId id = oi.insert(mergeCommit); oi.flush(); return id; } finally { oi.release(); } }
Source:
public PrologJar (Config config, SitePaths site, Repository git) { this.git = git; START String s = config.getString("cache", null, "directory"); END cacheDir = site.resolve(config.getString("cache", null, "directory")); } This line is unused.

Target:
public PrologJar (Config config, SitePaths site, Repository git) { this.git = git; cacheDir = site.resolve(config.getString("cache", null, "directory")); }
Source:
START PRED_change_branch_1(Term a1, Operation n) { END arg1 = a1; cont = n; } Should be public.

Target:
public PRED_change_branch_1(Term a1, Operation n) { arg1 = a1; cont = n; }
Source:
START PRED_commit_author_3(Term a1, Term a2, Term a3, Operation n) { END super(a1, a2, a3, n); } Should be public.

Target:
public PRED_commit_author_3(Term a1, Term a2, Term a3, Operation n) { super(a1, a2, a3, n); }
Source:
START PRED_commit_delta_4(Term a1, Term a2, Term a3, Term a4, Operation n) { END arg1 = a1; arg2 = a2; arg3 = a3; arg4 = a4; cont = n; } Should be public.

Target:
public PRED_commit_delta_4(Term a1, Term a2, Term a3, Term a4, Operation n) { arg1 = a1; arg2 = a2; arg3 = a3; arg4 = a4; cont = n; }
Source:
public void setCleanup(List<Runnable> cleanup) { START this.cleanup = cleanup; END } If your old cleanup list is non-empty, should we copy the elements into the new cleanup list, or simply discard them and let them leak?

Target:
public void setCleanup(List<Runnable> cleanup) { if (!this.cleanup.isEmpty()) { cleanup.addAll(this.cleanup); } this.cleanup = cleanup; }
Source:
public static String toLongString(final Change.Status status) { if (status == null) { return ""; } switch (status) { case NEW: return C.statusLongNew(); case SUBMITTED: return C.statusLongSubmitted(); case MERGED: return C.statusLongMerged(); case ABANDONED: return C.statusLongAbandoned(); START case DRAFT: END return C.statusLongDraft(); default: return status.name(); } } Nit: seems like this should go above NEW?

Target:
public static String toLongString(final Change.Status status) { if (status == null) { return ""; } switch (status) { case DRAFT: return C.statusLongDraft(); case NEW: return C.statusLongNew(); case SUBMITTED: return C.statusLongSubmitted(); case MERGED: return C.statusLongMerged(); case ABANDONED: return C.statusLongAbandoned(); default: return status.name(); } }
Source:
START public List<PatchLineComment> comments(Provider<ReviewDb> db) END throws OrmException { if (comments == null) { comments = db.get().patchComments().byChange(legacyId).toList(); } return comments; } Wrong place. :) These are unordered during retrieval. Try line 216.

Target:
public Collection<PatchLineComment> comments(Provider<ReviewDb> db) throws OrmException { if (comments == null) { comments = db.get().patchComments().byChange(legacyId).toList(); } return comments; }
Source:
private boolean verify(HttpServletRequest req, HttpServletResponseWrapper rsp) throws IOException { START if (!authConfig.isTrustContainerAuth()) END return true; final String username = req.getRemoteUser(); final AccountState who = accountCache.getByUsername(username); if (who == null || ! who.getAccount().isActive()) { rsp.sendError(SC_UNAUTHORIZED); return false; } session.get().setUserAccountId(who.getAccount().getId()); return true; } Style nit: use brackets even for single statement ifs.

Target:
private boolean verify(HttpServletRequest req, HttpServletResponseWrapper rsp) throws IOException { final String username = req.getRemoteUser(); final AccountState who = (username == null) ? null : accountCache.getByUsername(username); if (who == null || !who.getAccount().isActive()) { rsp.sendError(SC_UNAUTHORIZED); return false; } session.get().setUserAccountId(who.getAccount().getId()); return true; }
Source:
private static boolean isValidGroupId(String idStr) { START return idStr.matches("^G[0-9a-fA-F]{40}$") && !idStr.matches("^G00*$"); END } I don't think you need the !idStr.matches("^G00*$") on this one. I think that is a hack for an old bug in eclipse or something where it used to create such change ids. But since groupids aren't used yet, I think you should be fine without this hack (you might wanna check with Shawn).

Target:
private static boolean isValidGroupId(String idStr) { return idStr.matches("^G[0-9a-fA-F]{40}$"); }
Source:
public int hashCode() { int h = 0; if (oldId != null) { h = h * 31 + oldId.hashCode(); } h = h * 31 + newId.hashCode(); h = h * 31 + whitespace.name().hashCode(); START h = h * 31 + isRebaseTransparent.hashCode(); END return h; } h =h * 31 + (isRebaseTransparent ? 1 : 0)

Target:
public int hashCode() { int h = 0; if (oldId != null) { h = h * 31 + oldId.hashCode(); } h = h * 31 + newId.hashCode(); h = h * 31 + whitespace.name().hashCode(); h = h * 31 + (isRebaseTransparent ? 1 : 0); return h; }
Source:
private DependencyAttribute newDependsOn(Change c, PatchSet ps) { DependencyAttribute d = newDependencyAttribute(c, ps); START d.isCurrentPatchSet = new Boolean(c.currPatchSetId().equals(ps.getId())); END return d; } Nit: This is autoboxed so you dont need to call the constructor explicitly

Target:
private DependencyAttribute newDependsOn(Change c, PatchSet ps) { DependencyAttribute d = newDependencyAttribute(c, ps); d.isCurrentPatchSet = c.currPatchSetId().equals(ps.getId()); return d; }
Source:
private Collection<File> getPluginFiles() throws IOException { START if (pluginsDir == null || !pluginsDir.exists()) END return Collections.emptyList(); return FileUtils.listFiles(pluginsDir, new String[] {"jar"}, false); } style-nit: wrap the then block in curly braces

Target:
private Collection<File> getPluginFiles() throws IOException { if (pluginsDir == null || !pluginsDir.exists()) { return Collections.emptyList(); } return FileUtils.listFiles(pluginsDir, new String[] {"jar"}, false); }
Source:
START public void setStatus(Status newStatus) { END this.status = newStatus; } Not sure this should be public. Package visible?

Target:
void setStatus(Status newStatus) { this.status = newStatus; }
Source:
} catch (Exception e) { LOG.error("Unable to expose RPS/JSON result field"); START resultField = null; END } future calls in getResult are going to unexpectedly NPE because of this. either handle this in getResult or fail harder in the static block with a thrown runtime exception or error to prevent the class from initializing, and thus the server from running.

Target:
} catch (Exception e) { log.error("Unable to expose RPS/JSON result field"); }
Source:
public static String toAccountQuery(final String fullname) { START String user = KeyUtil.encode(fullname).replaceAll("%3[Aa]", ":"); END return "/q/owner:\"" + user + "\"," + TOP; } Why you would need to this replacement of "%3[Aa]" to ":"?

Target:
public static String toAccountQuery(final String fullname) { return "/q/owner:\"" + KeyUtil.encode(fullname) + "\"," + TOP; }
Source:
public boolean isOwner() { if (isOwner == null) { AccountGroup g = groupCache.get(group.getOwnerGroupUUID()); START AccountGroup.UUID ownerUUID = g != null ? g.getGroupUUID() : null; END isOwner = getCurrentUser().getEffectiveGroups().contains(ownerUUID) || getCurrentUser().getCapabilities().canAdministrateServer(); } return isOwner; } Simplify this to: AccountGroup.UUID ownerUUID = group.getOwnerGroupUUID() This may let you drop GroupCache from here.

Target:
public boolean isOwner() { if (isOwner == null) { AccountGroup.UUID ownerUUID = group.getOwnerGroupUUID(); isOwner = getCurrentUser().getEffectiveGroups().contains(ownerUUID) || getCurrentUser().getCapabilities().canAdministrateServer(); } return isOwner; }
Source:
public static Module module() { return new CacheModule() { @Override protected void configure() { cache(ID_CACHE, Project.NameKey.class, new TypeLiteral<List<Change>>() {}) .maximumWeight(1024) START .expireAfterWrite(120, TimeUnit.MINUTES) END .loader(Loader.class); } }; } 2, TimeUnit.HOURS might be more readable. But if we have this tied to a listener, does it make sense to expire at all by default? Most of the other caches don't expire these days and rely on invalidation messages.

Target:
public static Module module() { return new CacheModule() { @Override protected void configure() { cache(ID_CACHE, Project.NameKey.class, new TypeLiteral<List<Change>>() {}) .maximumWeight(1024) .loader(Loader.class); } }; }
Source:
private ObjectId createNoteContent(String reason, ObjectInserter inserter) throws UnsupportedEncodingException, IOException { String noteContent = reason != null ? reason : ""; START if (!noteContent.endsWith("\n")) { END noteContent = noteContent + "\n"; } return inserter.insert(Constants.OBJ_BLOB, noteContent.getBytes("UTF-8")); } Should the new line also be appended if the noteContent is empty because no reason was specified?

Target:
private ObjectId createNoteContent(String reason, ObjectInserter inserter) throws UnsupportedEncodingException, IOException { String noteContent = reason != null ? reason : ""; if (noteContent.length() > 0 && !noteContent.endsWith("\n")) { noteContent = noteContent + "\n"; } return inserter.insert(Constants.OBJ_BLOB, noteContent.getBytes("UTF-8")); }
Source:
START CommitValidationResult(boolean validated, String why) { END this.validated = validated; this.why = why; } consider making this protected so plugins could subclass if they want to.

Target:
protected CommitValidationResult(boolean validated, String why) { this.validated = validated; this.why = why; }
Source:
public void authenticate(SignInMode requestedMode, final String token) { OpenIdUtil.SVC.discover(ssoUrl, requestedMode, /* remember */ false, token, new GerritCallback<DiscoveryResult>() { public void onSuccess(final DiscoveryResult result) { onDiscovery(result); } @Override public void onFailure(final Throwable caught) { START super.onFailure(caught); END } }); } This method isn't necessary if all you are doing is using the super implementation.

Target:
public void authenticate(SignInMode requestedMode, final String token) { OpenIdUtil.SVC.discover(ssoUrl, requestedMode, /* remember */ false, token, new GerritCallback<DiscoveryResult>() { public void onSuccess(final DiscoveryResult result) { onDiscovery(result); } }); }
Source:
ProjectBasicAuthFilter(Provider<WebSession> session, AccountCache accountCache, AccountManager accountManager) START throws XsrfException { END this.session = session; this.accountCache = accountCache; this.accountManager = accountManager; } this exception is not thrown in the constructor

Target:
ProjectBasicAuthFilter(Provider<WebSession> session, AccountCache accountCache, AccountManager accountManager) { this.session = session; this.accountCache = accountCache; this.accountManager = accountManager; }
Source:
private boolean isRequestAllowed(HttpServletRequest httpRequest) { CurrentUser currentUser = userProvider.get(); if(httpRequest.getRequestURI().equals(getMonitoringUrl(httpRequest))) { START return currentUser instanceof IdentifiedUser && currentUser.getCapabilities().canAdministrateServer(); END } return true; } Why do you need to check if currentUser instanceof IdentifiedUser?

Target:
private boolean isRequestAllowed(HttpServletRequest httpRequest) { CurrentUser currentUser = userProvider.get(); if(httpRequest.getRequestURI().equals(getMonitoringUrl(httpRequest))) { return currentUser.getCapabilities().canAdministrateServer(); } return true; }
Source:
static String hostname(String hostname) { if (Strings.isNullOrEmpty(hostname)) { hostname = "localhost"; START END } else if (hostname.contains(":") && !hostname.startsWith("[")) { hostname = "[" + hostname + "]"; } return hostname; } Done

Target:
static String hostname(String hostname) { if (Strings.isNullOrEmpty(hostname)) { return "localhost"; } else if (hostname.contains(":") && !hostname.startsWith("[")) { return "[" + hostname + "]"; } return hostname; }
Source:
protected Class<?> findClass(final String className) throws ClassNotFoundException { final Set<ClassLoader> classLoaders = packageClassLoaderMap.get(getPackageName(className)); START if (classLoaders != null) { END for (final ClassLoader cl : classLoaders) { try { return Class.forName(className, true, cl); } catch (ClassNotFoundException e) { // ignore } } } throw new ClassNotFoundException(className); } Multimap returns an empty collection if the key is not found, which will simplify this code by removing the != null test.

Target:
protected Class<?> findClass(final String className) throws ClassNotFoundException { final Collection<ClassLoader> classLoaders = packageClassLoaderMap.get(getPackageName(className)); for (final ClassLoader cl : classLoaders) { try { return Class.forName(className, true, cl); } catch (ClassNotFoundException e) { // ignore } } throw new ClassNotFoundException(className); }
Source:
private void initPlugins() throws Exception { START Collection<? extends InitStep> pluginsInitSteps = pluginLoader.getInitSteps(); END for (InitStep initStep : pluginsInitSteps) { initStep.run(); } } It would have been shorter to inline this variable and not have it in scope. :-)

Target:
private void initPlugins() throws Exception { for (InitStep initStep : pluginLoader.getInitSteps()) { initStep.run(); } }
Source:
public int hashCode() { int h = 0; h = h * 31 + aId.hashCode(); h = h * 31 + bId.hashCode(); START h = h * 31 + ignoreWhitespace.hashCode(); END return h; } h = h * 31 + (ignoreWhitespace ? 1 : 0)

Target:
public int hashCode() { int h = 0; h = h * 31 + aId.hashCode(); h = h * 31 + bId.hashCode(); h = h * 31 + (ignoreWhitespace ? 1 : 0); return h; }
Source:
public boolean equals(final Object o) { if (o instanceof IntraLineDiffKey) { final IntraLineDiffKey k = (IntraLineDiffKey) o; return aId.equals(k.aId) // && bId.equals(k.bId) // START && ignoreWhitespace.equals(k.ignoreWhitespace); END } return false; } && ignoreWhitespace == k.ignoreWhitespace

Target:
public boolean equals(final Object o) { if (o instanceof IntraLineDiffKey) { final IntraLineDiffKey k = (IntraLineDiffKey) o; return aId.equals(k.aId) // && bId.equals(k.bId) // && ignoreWhitespace == k.ignoreWhitespace; } return false; }
Source:
public void stop() { if (manager != null) { manager.stop(); manager = null; sysInjector = null; sshInjector = null; httpInjector = null; if (webPluginDir != null) { try { START FileUtils.delete(webPluginDir, FileUtils.RECURSIVE); END } catch (IOException e) { // ignore (?) } } } } Not necessary, remove this.

Target:
public void stop() { if (manager != null) { manager.stop(); manager = null; sysInjector = null; sshInjector = null; httpInjector = null; } }
Source:
public void waitForReplication() { try { allPushTasksFinished.await(); } catch (InterruptedException e) { START log.error("It is interrupted while waiting replication to be completed");; END } } We neither show this problem to the user, nor give calling code (i.e.: StartCommand) a chance to detect that we were interrupted. Would either rethrowing, returning a boolean that indicates success, or copying the error over to the pushProcessing be an option? ------------- Nit: Double semi-colon at the end

Target:
public void waitForReplication() throws InterruptedException { allPushTasksFinished.await(); }
Source:
public void start() { queue.start(); if (srvInfo.getState() == ServerInformation.State.STARTUP && queue.replicateAllOnPluginStart) { ReplicationState state = START new ReplicationState(ReplicationType.START_UP); END pushAllFuture.set(pushAll.create(null, state).schedule(30, TimeUnit.SECONDS)); } } ServerInformation.State uses STARTUP (no underscore) in line 47, while we use START_UP (with underscore) here. I do not have a preference either way, but I'd prefer to stay consistent one way or the other.

Target:
public void start() { queue.start(); if (srvInfo.getState() == ServerInformation.State.STARTUP && queue.replicateAllOnPluginStart) { ReplicationState state = new ReplicationState(ReplicationType.STARTUP); pushAllFuture.set(pushAll.create(null, state).schedule(30, TimeUnit.SECONDS)); } }
Source:
START public ReplicationState(ReplicationType type) { END this(null, type); } Currying of the first parameter is at least unusual. If there is no currying of the other parameters as well it typically hints at wrong parameter order in the other method. Would it make sense to reverse the order of the parameters of the constructor in line 43?

Target:
public ReplicationState(ReplicationType type) { this(type, null); }
Source:
public boolean hasPushTask() { START taskLock.lock(); END try { if (totalPushCount == 0) { return false; } } finally { taskLock.unlock(); } return true; } Since we're only reading a single field, do we need to lock?

Target:
public boolean hasPushTask() { return totalPushCount != 0; }
Source:
private static void setBool(ListBox box, InheritedBoolean val) { START if (box != null) { END for (int i = 0; i < box.getItemCount(); i++) { if (val.name().equals(box.getValue(i))) { box.setSelectedIndex(i); break; } } } } Can box be null? If yes, it should probably also be checked in getBool(ListBox)

Target:
private static void setBool(ListBox box, InheritedBoolean val) { for (int i = 0; i < box.getItemCount(); i++) { if (val.name().equals(box.getValue(i))) { box.setSelectedIndex(i); break; } } }
Source:
public OrmException convertError(String op, String entity, SQLException err) { switch (err.getErrorCode()) { START case 1: END case 23000: return new OrmDuplicateKeyException(entity, err); default: return super.convertError(op, entity, err); } } Done

Target:
public OrmException convertError(String op, String entity, SQLException err) { switch (err.getErrorCode()) { case 1: // ORA-00001: unique constraint violated return new OrmDuplicateKeyException(entity, err); default: return super.convertError(op, entity, err); } }
Source:
public void start(PluginGuiceEnvironment env) throws Exception { START manager = new LifecycleManager(); END String fileName = getSrcFile().getName(); httpInjector = Guice.createInjector(new StandaloneJsPluginModule(getName(), fileName)); manager.add(httpInjector); manager.start(); } Unnecessary. There is nothing in the Guice world to start or stop.

Target:
public void start(PluginGuiceEnvironment env) throws Exception { String fileName = getSrcFile().getName(); httpInjector = Guice.createInjector(new StandaloneJsPluginModule(getName(), fileName)); }
Source:
START public StandaloneJsPluginModule(String END pluginName, String fileName) { this.pluginName = pluginName; this.fileName = fileName; } package or private access is acceptable since the inner class is private

Target:
StandaloneJsPluginModule(String pluginName, String fileName) { this.pluginName = pluginName; this.fileName = fileName; }
Source:
public boolean authenticate(String username, PublicKey key, ServerSession session) { final SshSession sd = session.getAttribute(SshSession.KEY); SshAuthRequest sshAuth = new SshAuthRequest(username, sd.getRemoteAddress()); START sshAuth.setPubKey(key); END return authenticate(sd, sshAuth, session); } Done

Target:
public boolean authenticate(String username, PublicKey key, ServerSession session) { final SshSession sd = session.getAttribute(SshSession.KEY); SshAuthRequest sshAuth = new SshAuthRequest(username, key, sd.getRemoteAddress()); return authenticate(sd, sshAuth, session); }
Source:
START public SshAuthRequest(String username, SocketAddress clientAddress) { END this(username, null, clientAddress); } Done, added two new constructors, one with public key and one with password and public key

Target:
public SshAuthRequest(String username, SocketAddress clientAddress) { this(username, null, null, clientAddress); }
Source:
public List<GitReferenceUpdatedListener.Update> getUpdates() { GitReferenceUpdatedListener.Update update = new GitReferenceUpdatedListener.Update() { public String getRefName() { return ref; } START @Override END public String getOldObjectId() { return oldObjectId; } @Override public String getNewObjectId() { return newObjectId; } }; return ImmutableList.of(update); } Why do we need @Override on these, but not on `getRefName`?

Target:
public List<GitReferenceUpdatedListener.Update> getUpdates() { GitReferenceUpdatedListener.Update update = new GitReferenceUpdatedListener.Update() { @Override public String getRefName() { return ref; } @Override public String getOldObjectId() { return oldObjectId; } @Override public String getNewObjectId() { return newObjectId; } }; return ImmutableList.of(update); }
Source:
public void fire(Project.NameKey project, String ref, ObjectId oldObjectId, ObjectId newObjectId) { START ObjectId old = oldObjectId != null ? oldObjectId : ObjectId.zeroId(); END Event event = new Event(project, ref, old.name(), newObjectId.name()); for (GitReferenceUpdatedListener l : listeners) { l.onGitReferenceUpdated(event); } } If a branch gets deleted can newObjectId be null so that in this case ObjectId.zeroId() should be used as new objectId?

Target:
public void fire(Project.NameKey project, String ref, ObjectId oldObjectId, ObjectId newObjectId) { ObjectId o = oldObjectId != null ? oldObjectId : ObjectId.zeroId(); ObjectId n = newObjectId != null ? newObjectId : ObjectId.zeroId(); Event event = new Event(project, ref, o.name(), n.name()); for (GitReferenceUpdatedListener l : listeners) { l.onGitReferenceUpdated(event); } }
Source:
START static void replyError(HttpServletResponse res, int statusCode, END String msg) throws IOException { res.setStatus(statusCode); CacheHeaders.setNotCacheable(res); replyText(null, res, msg); } Unnecessary?

Target:
public static void replyError(HttpServletResponse res, int statusCode, String msg) throws IOException { res.setStatus(statusCode); CacheHeaders.setNotCacheable(res); replyText(null, res, msg); }
Source:
public static <T> LinkedBindingBuilder<T> bind(Binder binder, TypeLiteral<T> type) { START return binder.bind(type).annotatedWith(UniqueAnnotations.create()); END } Because there is only a single item allowed, there is no reason to use annotations of any kind. So you can drop annotatedWith here and drop the next method altogether.

Target:
public static <T> LinkedBindingBuilder<T> bind(Binder binder, TypeLiteral<T> type) { return binder.bind(type); }
Source:
public static void removeMembers(AccountGroup.UUID groupUUID, Set<Account.Id> ids, AsyncCallback<VoidResult> cb) { RestApi call = new RestApi(membersBase(groupUUID)); MemberInput input = MemberInput.create(); for (Account.Id id : ids) { START input.add_member(Integer.toString(id.get())); END } call.data(input).delete(cb); } id.toString() is also valid here. :-)

Target:
public static void removeMembers(AccountGroup.UUID groupUUID, Set<Account.Id> ids, AsyncCallback<VoidResult> cb) { RestApi call = new RestApi(membersBase(groupUUID)); MemberInput input = MemberInput.create(); for (Account.Id id : ids) { input.add_member(id.toString()); } call.data(input).delete(cb); }
Source:
private Map<Account.Id, AccountGroupMember> getMembers( final AccountGroup.Id groupId) throws OrmException, NoSuchGroupException { final Map<Account.Id, AccountGroupMember> memberMap = Maps.newHashMap(); final List<AccountGroupMember> members = START db.accountGroupMembers().byGroup(groupId).toList(); END for (final AccountGroupMember m : members) { memberMap.put(m.getAccountId(), m); } return memberMap; } Inline this into the for loop and avoid the toList(). I don't think it improves readability here and it doesn't help runtime performance.

Target:
private Map<Account.Id, AccountGroupMember> getMembers( final AccountGroup.Id groupId) throws OrmException, NoSuchGroupException { final Map<Account.Id, AccountGroupMember> members = Maps.newHashMap(); for (final AccountGroupMember m : db.accountGroupMembers().byGroup(groupId)) { members.put(m.getAccountId(), m); } return members; }
Source:
public String getRequestURI() { String uri = contextPath + servletPath + path; START if (!parameters.isEmpty()) { END uri += "?" + GitilesView.paramsToString(parameters); } return uri; } IIRC getRequestURI does not include the query parameters. To quote the docs "Returns the part of this request's URL from the protocol name up to the query string in the first line of the HTTP request."

Target:
public String getRequestURI() { return contextPath + servletPath + path; }
Source:
public synchronized ServletOutputStream getOutputStream() { checkState(writer == null, "getWriter() already called"); if (outputStream == null) { START final PrintWriter osWriter = new PrintWriter(actualBody); END outputStream = new ServletOutputStream() { @Override public void write(int c) throws IOException { osWriter.write(c); osWriter.flush(); } }; } return outputStream; } This shouldn't be necessary. Just write the bytes to actualBody.

Target:
public synchronized ServletOutputStream getOutputStream() { checkState(writer == null, "getWriter() already called"); if (outputStream == null) { outputStream = new ServletOutputStream() { @Override public void write(int b) throws IOException { actualBody.write(b); } }; } return outputStream; }
Source:
public void setParentNames(String names) { START parents = new ArrayList<NameKey>(); END for (String n : names) parents.add(new NameKey(n)); } new ArrayList<NameKey>(names.length)

Target:
public void setParentNames(String names) { parents = new ArrayList<NameKey>(names.length); for (String n : names) { parents.add(new NameKey(n)); } }
Source:
public Object apply(MemberResource resource, PutMember.Input input) throws AuthException, MethodNotAllowedException, BadRequestException, OrmException { // nothing to do, the user is already a member of the group START return Response.none(); END } This shouldn't return 204 no content, it should return 200 with a description of the member the way PUT /groups/{id}/members returns a description of the new members.

Target:
public Object apply(MemberResource resource, PutMember.Input input) { // Do nothing, the user is already a member. return get.get().apply(resource); }
Source:
private String getComment(ChangeAttribute change, ChangeEvent hook, AccountAttribute who, String what) { START String name = formatAccountAttribute(who); END return getCommentPrefix(change) + "change " + what + " [by " + name + "]"; } variable used only once: better to put inline as the getCommentPrefix(change) below.

Target:
private String getComment(ChangeAttribute change, ChangeEvent hook, AccountAttribute who, String what) { return getCommentPrefix(change) + "change " + what + " [by " + formatAccountAttribute(who) + "]"; }
Source:
private String formatAccountAttribute(AccountAttribute who) { String name = anonymousCowardName; START if (who != null && who.name != null) { END name = who.name; } return name; } This can be done without the temporary variable. if (who != null && who.name != null) { return who.name; } return anonymousCowardName;

Target:
private String formatAccountAttribute(AccountAttribute who) { if (who != null && who.name != null) { return who.name; } return anonymousCowardName; }
Source:
protected void onLoad() { super.onLoad(); START com.google.gwtjsonrpc.common.AsyncCallback<PatchSetPublishDetail> load = END new ScreenLoadCallback<PatchSetPublishDetail>(this) { @Override protected void preDisplay(final PatchSetPublishDetail result) { send.setEnabled(true); display(result); } @Override protected void postDisplay() { message.setFocus(true); } }; CallbackGroup cbs = new CallbackGroup(); Util.DETAIL_SVC.patchSetPublishDetail(patchSetId, cbs.add(load)); } why did you put this in a local variable? Why not just inline?

Target:
protected void onLoad() { super.onLoad(); CallbackGroup cbs = new CallbackGroup(); Util.DETAIL_SVC.patchSetPublishDetail(patchSetId, cbs.add( (com.google.gwtjsonrpc.common.AsyncCallback<PatchSetPublishDetail>) new ScreenLoadCallback<PatchSetPublishDetail>(this) { @Override protected void preDisplay(final PatchSetPublishDetail result) { send.setEnabled(true); display(result); } @Override protected void postDisplay() { message.setFocus(true); } })); }
Source:
public Object apply(ReviewerResource rsrc) throws OrmException, START NoSuchChangeException { END return json.format(rsrc); } Unnecessary delta.

Target:
public Object apply(ReviewerResource rsrc) throws OrmException { return json.format(rsrc); }
Source:
private void putLabelType(Map<String, LabelType> types, LabelType type) { LabelType old = types.get(type.getName()); START if (old == null || !old.canOverride()) { END types.put(type.getName(), type); } } remove !

Target:
private void putLabelType(Map<String, LabelType> types, LabelType type) { LabelType old = types.get(type.getName()); if (old == null || old.canOverride()) { types.put(type.getName(), type); } }
Source:
public void votable(String label) { if (votable == null) { votable = new HashSet<String>(); } votable.add(label); START hasNonZero = 1; END } If a label is votable it doesn't mean that there is actually a vote. I think hasNonZero should simply not be set in this method.

Target:
public void votable(String label) { if (votable == null) { votable = new HashSet<String>(); } votable.add(label); }
Source:
public static LabelType withDefaultValues(String name) { checkName(name); List<LabelValue> values = new ArrayList<LabelValue>(2); values.add(new LabelValue((short) 0, "Rejected")); values.add(new LabelValue((short) 1, "Approved")); START LabelType type = new LabelType(name, values); END return type; } type as a variable is pointless here.

Target:
public static LabelType withDefaultValues(String name) { checkName(name); List<LabelValue> values = new ArrayList<LabelValue>(2); values.add(new LabelValue((short) 0, "Rejected")); values.add(new LabelValue((short) 1, "Approved")); return new LabelType(name, values); }
Source:
private LegacyLabelType(String name, List<LabelValue> values) { super(name, values); START checkArgument(id.length() <= 4, "Invalid legacy label ID: \"%s\"", id); END } This is going to NPE. Maybe you mean to do the check within setId() when the supplied id != null?

Target:
private LegacyLabelType(String name, List<LabelValue> values) { super(name, values); }
Source:
boolean requestRunway (PushOne op) { synchronized (stateLock) { if (op.wasCanceled()) { // Return true here so op doesn't reschedule itself. START return true; END } if (inFlight.containsKey(op.getURI())) { return false; } pending.remove(op.getURI()); inFlight.put(op.getURI(), op); } return true; } It might be clearer if you returned false here and just checked for the cancel after the failed call to prevent the reschedule. Then I don't think you would even have to check for cancelled in the success case anymore simplifying things a bit potentially?

Target:
boolean requestRunway (PushOne op) { synchronized (stateLock) { if (op.wasCanceled()) { // Return true here so op doesn't reschedule itself. return true; } pending.remove(op.getURI()); if (inFlight.containsKey(op.getURI())) { return false; } inFlight.put(op.getURI(), op); } return true; }
Source:
public static Id parse(final String str) { final Id r = new Id(); String preparedStr = str; START if (preparedStr.endsWith("/")) { END preparedStr = preparedStr.substring(0, preparedStr.length() - 1); } r.fromString(preparedStr); return r; } This is the wrong place to perform this parsing. I think it belongs in Dispatcher.change (~line 459) and UrlModule.directChangeById (~line 158).

Target:
public static Id parse(final String str) { final Id r = new Id(); r.fromString(str); return r; }
Source:
public void resetToDefaults() { maximumPageSize = DEFAULT_PAGESIZE; showSiteHeader = true; useFlashClipboard = true; copySelfOnEmail = false; reversePatchSetOrder = false; showUsernameInReviewCategory = false; downloadUrl = null; downloadCommand = null; dateFormat = null; timeFormat = null; START relativeDateInChangeTable = true; END } I wonder if this should be false. We are going to default to false for all existing users, but you are defaulting to true for new users. We should have the default be consistent for all users.

Target:
public void resetToDefaults() { maximumPageSize = DEFAULT_PAGESIZE; showSiteHeader = true; useFlashClipboard = true; copySelfOnEmail = false; reversePatchSetOrder = false; showUsernameInReviewCategory = false; downloadUrl = null; downloadCommand = null; dateFormat = null; timeFormat = null; relativeDateInChangeTable = false; }
Source:
public ThemeInfo getTheme() { ThemeInfo theme = this.theme; if (theme == null) { synchronized (this) { START if (this.theme == null) { END theme = loadTheme(); this.theme = theme; } } } if (theme == ThemeInfo.INHERIT) { ProjectState parent = Iterables.getFirst(parents(), null); return parent != null ? parent.getTheme() : null; } return theme; } Bad double checked locking idiom. ThemeInfo theme = this.theme; if (theme == null) { synchronized (this) { theme = this.theme; // this is what you missed if (theme == null) { theme = loadTheme(); this.theme = theme; } } }

Target:
public ThemeInfo getTheme() { ThemeInfo theme = this.theme; if (theme == null) { synchronized (this) { theme = this.theme; if (theme == null) { theme = loadTheme(); this.theme = theme; } } } if (theme == ThemeInfo.INHERIT) { ProjectState parent = Iterables.getFirst(parents(), null); return parent != null ? parent.getTheme() : null; } return theme; }
Source:
private int getCorrectedMimeSpecificity(MimeType mimeType) { final int ret; final String mimeTypeStr = mimeType.toString(); if (mimeTypeStr.equals("application/octet-stream")) { START ret = -1; END } else if (mimeTypeStr.equals("text/plain")) { ret = 0; } else { ret = mimeType.getSpecificity(); } return ret; } You can use early return: if (mimeTypeStr.equals("...") { return -1; } else if (...) { return 0; } return mimeType.getSpecificity(); Its a few lines shorter and better matches other cases within Gerrit where this style works.

Target:
private int getCorrectedMimeSpecificity(MimeType mimeType) { // Although the documentation of MimeType's getSpecificity claims that for // example "application/octet-stream" always has a specificity of 0, it // effectively returns 1 for us. This causes problems when trying to get // the correct mime type via sorting. For example in // [application/octet-stream, image/x-icon] both mime types come with // specificity 1 for us. Hence, getMimeType below may end up using // application/octet-stream instead of the more specific image/x-icon. // Therefore, we have to force the specificity of generic types below the // default of 1. // final String mimeTypeStr = mimeType.toString(); if (mimeTypeStr.equals("application/octet-stream")) { return -1; } if (mimeTypeStr.equals("text/plain")) { return 0; } return mimeType.getSpecificity(); }
Source:
static RestApi config(Project.NameKey name) { START return ProjectApi.project(name).view("config"); END } ProjectApi. prefix here is unnecessary, you are in the same class.

Target:
static RestApi config(Project.NameKey name) { return project(name).view("config"); }
Source:
private static String getGerritHost(String canonicalWebUrl) { String host = null; if (canonicalWebUrl != null) { try { host = new URL(canonicalWebUrl).getHost(); } catch (MalformedURLException e) { // Ignore } } if (host == null) { host = SystemReader.getInstance().getHostname(); } START return trimTrailingSlashes(host); END } Not sure how just the host, especially if extracted from a URL object, could have a trailing slash.

Target:
private static String getGerritHost(String canonicalWebUrl) { String host; if (canonicalWebUrl != null) { try { host = new URL(canonicalWebUrl).getHost(); } catch (MalformedURLException e) { host = SystemReader.getInstance().getHostname(); } } else { host = SystemReader.getInstance().getHostname(); } return host; }
Source:
public SshKeyInfo apply(SshKey rsrc) { SshKeyInfo info = new SshKeyInfo(); START AccountSshKey sshKey = rsrc.getSshKey(); END info.id = sshKey.getKey().get(); info.sshPublicKey = sshKey.getSshPublicKey(); info.encodedKey = sshKey.getEncodedKey(); info.algorithm = sshKey.getAlgorithm(); info.comment = Strings.emptyToNull(sshKey.getComment()); info.valid = sshKey.isValid(); return info; } Move this all into the constructor of SshKeyInfo so its reused with GetSshKeys?

Target:
public SshKeyInfo apply(SshKey rsrc) { return new SshKeyInfo(rsrc.getSshKey()); }