auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private static boolean isValidGroupId(String idStr) { return idStr.matches("^G[0-9a-fA-F]{40}$") && !idStr.matches("^G00*$"); }

Target:
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).
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(); h = h * 31 + isRebaseTransparent.hashCode(); return h; }

Target:
h =h * 31 + (isRebaseTransparent ? 1 : 0)
Source:
private DependencyAttribute newDependsOn(Change c, PatchSet ps) { DependencyAttribute d = newDependencyAttribute(c, ps); d.isCurrentPatchSet = new Boolean(c.currPatchSetId().equals(ps.getId())); return d; }

Target:
Nit: This is autoboxed so you dont need to call the constructor explicitly
Source:
private Collection<File> getPluginFiles() throws IOException { if (pluginsDir == null || !pluginsDir.exists()) return Collections.emptyList(); return FileUtils.listFiles(pluginsDir, new String[] {"jar"}, false); }

Target:
style-nit: wrap the then block in curly braces
Source:
public void setStatus(Status newStatus) { this.status = newStatus; }

Target:
Not sure this should be public. Package visible?
Source:
} catch (Exception e) { LOG.error("Unable to expose RPS/JSON result field"); resultField = null; }

Target:
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.
Source:
public static String toAccountQuery(final String fullname) { String user = KeyUtil.encode(fullname).replaceAll("%3[Aa]", ":"); return "/q/owner:\"" + user + "\"," + TOP; }

Target:
Why you would need to this replacement of "%3[Aa]" to ":"?
Source:
public boolean isOwner() { if (isOwner == null) { AccountGroup g = groupCache.get(group.getOwnerGroupUUID()); AccountGroup.UUID ownerUUID = g != null ? g.getGroupUUID() : null; isOwner = getCurrentUser().getEffectiveGroups().contains(ownerUUID) || getCurrentUser().getCapabilities().canAdministrateServer(); } return isOwner; }

Target:
Simplify this to: AccountGroup.UUID ownerUUID = group.getOwnerGroupUUID() This may let you drop GroupCache from here.
Source:
public static Module module() { return new CacheModule() { @Override protected void configure() { cache(ID_CACHE, Project.NameKey.class, new TypeLiteral<List<Change>>() {}) .maximumWeight(1024) .expireAfterWrite(120, TimeUnit.MINUTES) .loader(Loader.class); } }; }

Target:
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.
Source:
private ObjectId createNoteContent(String reason, ObjectInserter inserter) throws UnsupportedEncodingException, IOException { String noteContent = reason != null ? reason : ""; if (!noteContent.endsWith("\n")) { noteContent = noteContent + "\n"; } return inserter.insert(Constants.OBJ_BLOB, noteContent.getBytes("UTF-8")); }

Target:
Should the new line also be appended if the noteContent is empty because no reason was specified?
Source:
CommitValidationResult(boolean validated, String why) { this.validated = validated; this.why = why; }

Target:
consider making this protected so plugins could subclass if they want to.
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) { super.onFailure(caught); } }); }

Target:
This method isn't necessary if all you are doing is using the super implementation.
Source:
ProjectBasicAuthFilter(Provider<WebSession> session, AccountCache accountCache, AccountManager accountManager) throws XsrfException { this.session = session; this.accountCache = accountCache; this.accountManager = accountManager; }

Target:
this exception is not thrown in the constructor
Source:
private boolean isRequestAllowed(HttpServletRequest httpRequest) { CurrentUser currentUser = userProvider.get(); if(httpRequest.getRequestURI().equals(getMonitoringUrl(httpRequest))) { return currentUser instanceof IdentifiedUser && currentUser.getCapabilities().canAdministrateServer(); } return true; }

Target:
Why do you need to check if currentUser instanceof IdentifiedUser?
Source:
static String hostname(String hostname) { if (Strings.isNullOrEmpty(hostname)) { hostname = "localhost"; } else if (hostname.contains(":") && !hostname.startsWith("[")) { hostname = "[" + hostname + "]"; } return hostname; }

Target:
Done
Source:
protected Class<?> findClass(final String className) throws ClassNotFoundException { final Set<ClassLoader> classLoaders = packageClassLoaderMap.get(getPackageName(className)); if (classLoaders != null) { for (final ClassLoader cl : classLoaders) { try { return Class.forName(className, true, cl); } catch (ClassNotFoundException e) { // ignore } } } throw new ClassNotFoundException(className); }

Target:
Multimap returns an empty collection if the key is not found, which will simplify this code by removing the != null test.
Source:
private void initPlugins() throws Exception { Collection<? extends InitStep> pluginsInitSteps = pluginLoader.getInitSteps(); for (InitStep initStep : pluginsInitSteps) { initStep.run(); } }

Target:
It would have been shorter to inline this variable and not have it in scope. :-)
Source:
public int hashCode() { int h = 0; h = h * 31 + aId.hashCode(); h = h * 31 + bId.hashCode(); h = h * 31 + ignoreWhitespace.hashCode(); return h; }

Target:
h = h * 31 + (ignoreWhitespace ? 1 : 0)
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) // && ignoreWhitespace.equals(k.ignoreWhitespace); } return false; }

Target:
&& ignoreWhitespace == k.ignoreWhitespace
Source:
public void stop() { if (manager != null) { manager.stop(); manager = null; sysInjector = null; sshInjector = null; httpInjector = null; if (webPluginDir != null) { try { FileUtils.delete(webPluginDir, FileUtils.RECURSIVE); } catch (IOException e) { // ignore (?) } } } }

Target:
Not necessary, remove this.
Source:
public void waitForReplication() { try { allPushTasksFinished.await(); } catch (InterruptedException e) { log.error("It is interrupted while waiting replication to be completed");; } }

Target:
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
Source:
public void start() { queue.start(); if (srvInfo.getState() == ServerInformation.State.STARTUP && queue.replicateAllOnPluginStart) { ReplicationState state = new ReplicationState(ReplicationType.START_UP); pushAllFuture.set(pushAll.create(null, state).schedule(30, TimeUnit.SECONDS)); } }

Target:
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.
Source:
public ReplicationState(ReplicationType type) { this(null, type); }

Target:
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?
Source:
public boolean hasPushTask() { taskLock.lock(); try { if (totalPushCount == 0) { return false; } } finally { taskLock.unlock(); } return true; }

Target:
Since we're only reading a single field, do we need to lock?
Source:
private static void setBool(ListBox box, InheritedBoolean val) { if (box != null) { for (int i = 0; i < box.getItemCount(); i++) { if (val.name().equals(box.getValue(i))) { box.setSelectedIndex(i); break; } } } }

Target:
Can box be null? If yes, it should probably also be checked in getBool(ListBox)
Source:
public OrmException convertError(String op, String entity, SQLException err) { switch (err.getErrorCode()) { case 1: case 23000: return new OrmDuplicateKeyException(entity, err); default: return super.convertError(op, entity, err); } }

Target:
Done
Source:
public void start(PluginGuiceEnvironment env) throws Exception { manager = new LifecycleManager(); String fileName = getSrcFile().getName(); httpInjector = Guice.createInjector(new StandaloneJsPluginModule(getName(), fileName)); manager.add(httpInjector); manager.start(); }

Target:
Unnecessary. There is nothing in the Guice world to start or stop.
Source:
public StandaloneJsPluginModule(String pluginName, String fileName) { this.pluginName = pluginName; this.fileName = fileName; }

Target:
package or private access is acceptable since the inner class is private
Source:
public boolean authenticate(String username, PublicKey key, ServerSession session) { final SshSession sd = session.getAttribute(SshSession.KEY); SshAuthRequest sshAuth = new SshAuthRequest(username, sd.getRemoteAddress()); sshAuth.setPubKey(key); return authenticate(sd, sshAuth, session); }

Target:
Done
Source:
public SshAuthRequest(String username, SocketAddress clientAddress) { this(username, null, clientAddress); }

Target:
Done, added two new constructors, one with public key and one with password and public key
Source:
public List<GitReferenceUpdatedListener.Update> getUpdates() { GitReferenceUpdatedListener.Update update = new GitReferenceUpdatedListener.Update() { public String getRefName() { return ref; } @Override public String getOldObjectId() { return oldObjectId; } @Override public String getNewObjectId() { return newObjectId; } }; return ImmutableList.of(update); }

Target:
Why do we need @Override on these, but not on `getRefName`?
Source:
public void fire(Project.NameKey project, String ref, ObjectId oldObjectId, ObjectId newObjectId) { ObjectId old = oldObjectId != null ? oldObjectId : ObjectId.zeroId(); Event event = new Event(project, ref, old.name(), newObjectId.name()); for (GitReferenceUpdatedListener l : listeners) { l.onGitReferenceUpdated(event); } }

Target:
If a branch gets deleted can newObjectId be null so that in this case ObjectId.zeroId() should be used as new objectId?
Source:
static void replyError(HttpServletResponse res, int statusCode, String msg) throws IOException { res.setStatus(statusCode); CacheHeaders.setNotCacheable(res); replyText(null, res, msg); }

Target:
Unnecessary?
Source:
public static <T> LinkedBindingBuilder<T> bind(Binder binder, TypeLiteral<T> type) { return binder.bind(type).annotatedWith(UniqueAnnotations.create()); }

Target:
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.
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) { input.add_member(Integer.toString(id.get())); } call.data(input).delete(cb); }

Target:
id.toString() is also valid here. :-)
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 = db.accountGroupMembers().byGroup(groupId).toList(); for (final AccountGroupMember m : members) { memberMap.put(m.getAccountId(), m); } return memberMap; }

Target:
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.
Source:
public String getRequestURI() { String uri = contextPath + servletPath + path; if (!parameters.isEmpty()) { uri += "?" + GitilesView.paramsToString(parameters); } return uri; }

Target:
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."
Source:
public synchronized ServletOutputStream getOutputStream() { checkState(writer == null, "getWriter() already called"); if (outputStream == null) { final PrintWriter osWriter = new PrintWriter(actualBody); outputStream = new ServletOutputStream() { @Override public void write(int c) throws IOException { osWriter.write(c); osWriter.flush(); } }; } return outputStream; }

Target:
This shouldn't be necessary. Just write the bytes to actualBody.
Source:
public void setParentNames(String names) { parents = new ArrayList<NameKey>(); for (String n : names) parents.add(new NameKey(n)); }

Target:
new ArrayList<NameKey>(names.length)
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 return Response.none(); }

Target:
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.
Source:
private String getComment(ChangeAttribute change, ChangeEvent hook, AccountAttribute who, String what) { String name = formatAccountAttribute(who); return getCommentPrefix(change) + "change " + what + " [by " + name + "]"; }

Target:
variable used only once: better to put inline as the getCommentPrefix(change) below.
Source:
private String formatAccountAttribute(AccountAttribute who) { String name = anonymousCowardName; if (who != null && who.name != null) { name = who.name; } return name; }

Target:
This can be done without the temporary variable. if (who != null && who.name != null) { return who.name; } return anonymousCowardName;
Source:
protected void onLoad() { super.onLoad(); com.google.gwtjsonrpc.common.AsyncCallback<PatchSetPublishDetail> load = 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)); }

Target:
why did you put this in a local variable? Why not just inline?
Source:
public Object apply(ReviewerResource rsrc) throws OrmException, NoSuchChangeException { return json.format(rsrc); }

Target:
Unnecessary delta.
Source:
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); } }

Target:
remove !
Source:
public void votable(String label) { if (votable == null) { votable = new HashSet<String>(); } votable.add(label); hasNonZero = 1; }

Target:
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.
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")); LabelType type = new LabelType(name, values); return type; }

Target:
type as a variable is pointless here.
Source:
private LegacyLabelType(String name, List<LabelValue> values) { super(name, values); checkArgument(id.length() <= 4, "Invalid legacy label ID: \"%s\"", id); }

Target:
This is going to NPE. Maybe you mean to do the check within setId() when the supplied id != null?
Source:
boolean requestRunway (PushOne op) { synchronized (stateLock) { if (op.wasCanceled()) { // Return true here so op doesn't reschedule itself. return true; } if (inFlight.containsKey(op.getURI())) { return false; } pending.remove(op.getURI()); inFlight.put(op.getURI(), op); } return true; }

Target:
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?
Source:
public static Id parse(final String str) { final Id r = new Id(); String preparedStr = str; if (preparedStr.endsWith("/")) { preparedStr = preparedStr.substring(0, preparedStr.length() - 1); } r.fromString(preparedStr); return r; }

Target:
This is the wrong place to perform this parsing. I think it belongs in Dispatcher.change (~line 459) and UrlModule.directChangeById (~line 158).
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; relativeDateInChangeTable = true; }

Target:
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.
Source:
public ThemeInfo getTheme() { ThemeInfo theme = this.theme; if (theme == null) { synchronized (this) { if (this.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; }

Target:
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; } } }
Source:
private int getCorrectedMimeSpecificity(MimeType mimeType) { final int ret; final String mimeTypeStr = mimeType.toString(); if (mimeTypeStr.equals("application/octet-stream")) { ret = -1; } else if (mimeTypeStr.equals("text/plain")) { ret = 0; } else { ret = mimeType.getSpecificity(); } return ret; }

Target:
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.
Source:
static RestApi config(Project.NameKey name) { return ProjectApi.project(name).view("config"); }

Target:
ProjectApi. prefix here is unnecessary, you are in the same class.
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(); } return trimTrailingSlashes(host); }

Target:
Not sure how just the host, especially if extracted from a URL object, could have a trailing slash.
Source:
public SshKeyInfo apply(SshKey rsrc) { SshKeyInfo info = new SshKeyInfo(); AccountSshKey sshKey = rsrc.getSshKey(); 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; }

Target:
Move this all into the constructor of SshKeyInfo so its reused with GetSshKeys?
Source:
private void assertTag(Project.NameKey project, String branch, String tagName) throws IOException { Repository r = repoManager.openRepository(project); try { RevWalk rw = new RevWalk(r); try { ObjectId headCommit = r.getRef(branch).getObjectId(); ObjectId taggedCommit = r.getRef(tagName).getObjectId(); assertEquals(headCommit, taggedCommit); } finally { rw.release(); } } finally { r.close(); } }

Target:
Is this RevWalk used? The ObjectReader should be released by r.close(), so I don't think this inner try { } finally block is needed.
Source:
private boolean isLastValueChangeHandler() { int count = detailCache.getHandlerCount(); int last = count - 1; for (int i = 0; i < count; i++) { if (this == detailCache.getHandler(i)) { return i == last; } } return false; }

Target:
How is a loop better than: int count = detailCache.getHandlerCount(); return count > 0 && detailCache.getHandler(count - 1) == this;
Source:
public CapabilityResource parse(ConfigResource parent, IdString id) throws ResourceNotFoundException, Exception { return null; }

Target:
don't return null, throw instead.
Source:
public ConfigResource parse(TopLevelResource root, IdString id) throws ResourceNotFoundException { if (!"server".equals(id.get())) { throw new ResourceNotFoundException(id); } return new ConfigResource(); }

Target:
nit: we usually write id.equals("server")
Source:
public boolean isVisible() { AccountGroup accountGroup = GroupDescriptions.toAccountGroup(group); if (accountGroup != null && accountGroup.isVisibleToAll()) { return true; } return user instanceof InternalUser || user.getEffectiveGroups().contains(group.getGroupUUID()) || isOwner(); }

Target:
Not enough coffee in the world to convince me this delta is necessary.
Source:
protected void configure() { DynamicMap.mapOf(binder(), CONFIG_KIND); DynamicMap.mapOf(binder(), CAPABILITY_KIND); DynamicMap.mapOf(binder(), CapabilityDefinition.class); child(CONFIG_KIND, "capabilities").to(CapabilitiesCollection.class); }

Target:
This sort of binding goes in GerritGlobalModule. See about line 244 in current master.
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); this.oldRevision = revision; break; } return this; }

Target:
nit: it seems to me this should be just before the return at the end of the method.
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; } return this; }

Target:
nit: Same here. Leave the checks in the switch and do the assignment at the end: this.path = path != null ? maybeTrimLeadingAndTrailingSlash(path) : null;
Source:
private static String branchToRef(String name) { if (name.startsWith(Branch.R_HEADS)) return Branch.R_HEADS + name; return name; }

Target:
should be: if (!name.startsWith(Branch.R_HEADS))
Source:
CommitPredicate(Provider<ReviewDb> dbProvider, AbbreviatedObjectId id) { super(ChangeField.COMMIT, id.toString()); this.dbProvider = dbProvider; this.abbrevId = id; }

Target:
id.name()
Source:
public void stop() { ChangeIndex read = searchIndex.get(); if (read != null) { read.close(); } for (ChangeIndex write : writeIndexes) { if (write != read) { read.close(); } } }

Target:
write.close();
Source:
private boolean nullOrEmpty(List<?> list) { return list == null || list.isEmpty(); }

Target:
static
Source:
private List<SkippedLine> checkAndAddSkip(List<SkippedLine> list, SkippedLine toAdd) { if (toAdd.getSize() > 1) { list.add(toAdd); } return list; }

Target:
This method can return void.
Source:
void updateFileCommentVisibility(boolean forceHide) { 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(); }

Target:
Whoops that was careless.. Yeah I will just remove the link since it's complicating things a lot.
Source:
void addFileComment(CommentBox box) { boxes.add(box); table.updateFileCommentVisibility(false); body.add(box); }

Target:
Why not add to body before calling table.updateFileCommentVisibility()?
Source:
public GitBlitUrlsConfig(Config config) { canonicalWebUrlString = config.getString("gerrit", null, "canonicalWebUrl"); sshdListenAddressString = config.getString("sshd", null, "listenAddress"); httpdListenUrlString = config.getString("httpd", null, "listenUrl"); downloadSchemes = config.getStringList("download", null, "scheme"); }

Target:
... so that you can get it straight as: 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) { return true; } else { return user.getEffectiveGroups().contains(uuid); } }

Target:
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 { ...
Source:
private void addAllToCommentList(JsArray<CommentInfo> in, boolean toDrafts) { if (toDrafts && drafts == null) { drafts = in; } else if (published == null) { published = in; } else { JsArray<CommentInfo> dest = toDrafts ? drafts : published; for (int i = 0; i < in.length(); i++) { dest.push(in.get(i)); } } }

Target:
So if drafts != null and published == null we store the drafts in published?
Source:
protected void configureServlets() { serve("/say-hello").with(HelloWorldServlet.class); serve("/say-hello/*").with(HelloWorldServlet.class); }

Target:
Why both bindings?
Source:
public Object apply(ChangeResource rsrc, Input input) throws AuthException, InterruptedException, ExecutionException { CurrentUser caller = rsrc.getControl().getCurrentUser(); if (!caller.getCapabilities().canAdministrateServer()) { throw new AuthException("index not permitted"); } indexer.index(rsrc.getChange()).get(); return Response.none(); }

Target:
This check is not necessary with @RequiresCapability.
Source:
private static <T extends Annotation> T getClassAnnotation(Class<?> clazz, Class<T> annotationClass) { 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; }

Target:
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;
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, "fatal: cannot check capability"); } }

Target:
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); } } private void redisplay() { Gerrit.display(PageLinks.MINE); } }; }

Target:
Probably shorter to just line this.
Source:
void set(ChangeInfo info, String revision, Labels labels, Element reviewers) { this.changeId = info.legacy_id(); this.info = info; this.revision = revision; this.labels = labels; this.reviewers = reviewers; reviewerSuggestOracle.setChange(changeId); renderReviewers(info); }

Target:
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.
Source:
private String renderInput(Options options, String inputFile) { Asciidoctor asciidoctor = JRubyAsciidoctor.create(); return asciidoctor.renderFile(new File(inputFile), options); }

Target:
return void now as the result is not used
Source:
public ListenableFuture<?> index(ChangeData cd) { return executor.submit(indexTask(cd)); }

Target:
Seems like we could use the check here too?
Source:
String getPluginName() { return pluginName; }

Target:
Maybe this should also be protected?
Source:
void onAllNodesReplicated(int totalPushTasksCount) { if (replicationsCount == 0) { return; } RefReplicationDoneEvent event = new RefReplicationDoneEvent(replicatedProject, replicatedRef, replicationsCount); postEvent(replicatedProject, replicatedRef, event); }

Target:
Still not using the totalPushTasksCount?
Source:
public static List<PluginData> listPluginsAndRemoveTempFiles(SitePaths site) throws IOException { return listPlugins(site, false); }

Target:
Shouldn't this be true? ;-)
Source:
private boolean isAuthorizedCall(HttpServletRequest req) { if (Strings.isNullOrEmpty(req.getServletPath())) { return false; } if (req.getServletPath().startsWith(AUTHORIZED_PREFIX)) { return true; } return false; }

Target:
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()); rApi.submit(new SubmitInput()); }

Target:
/submit is another API commonly called with no input.
Source:
protected void assertResultEquals(Change expected, ChangeInfo actual) { assertEquals(expected.getId().get(), (int) actual._number); }

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

Target:
Unnecessary cast.
Source:
public IsMergeablePredicate(Provider<ReviewDb> dbProvider) { super(ChangeField.MERGEABLE, "1"); this.dbProvider = dbProvider; }

Target:
default access
Source:
public boolean match(ChangeData object) throws OrmException { Change c = object.change(dbProvider); if (c == null) { return false; } return c.isMergeable(); }

Target:
return c != null && c.isMergeable();
Source:
public ApprovalsUtil(ReviewDb db) { this.db = db; }

Target:
This no longer needs to be public, that was only for MergeOp.
Source:
GreetInfo( String m, String c, String h) { country = c; message = m; href = h; }

Target:
no space after (
Source:
protected void configureServlets() { install(new FactoryModule() { @Override protected void configure() { factory(ChangeDetailFactory.Factory.class); factory(PatchSetDetailFactory.Factory.class); } }); rpc(ChangeDetailServiceImpl.class); }

Target:
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.
Source:
public boolean equals(Object o) { if (!(o instanceof LabelVote)) { return false; } LabelVote l = (LabelVote) o; return Objects.equal(name, l.name) && value == l.value; }

Target:
I prefer if (o instanceof LabelVote) { LabelVote l = (LabelVote) o; ... } return false;
Source:
protected void configure() { install(new CacheModule() { @Override protected void configure() { cache(PROJECT_DOC_RESOURCES, ResourceKey.class, Resource.class) .maximumWeight(2 << 20) .weigher(ResourceWeigher.class); } }); }

Target:
Why is this needed? You are already subclassing a CacheModule. This method body should only contain the lines 30-32
Source:
private void parseAll() throws ConfigInvalidException, IOException { walk.markStart(walk.parseCommit(tip)); for (RevCommit commit : walk) { walk.parseBody(commit); parse(commit); } pruneReviewers(); for (Collection<PatchSetApproval> v : approvals.asMap().values()) { Collections.sort((List<PatchSetApproval>) v, PSA_BY_TIME); } }

Target:
Unnecessary unless you are rewalking a previously walked graph.
Source:
static NotesMigration allEnabled() { Config cfg = new Config(); cfg.setBoolean("notedb", null, "write", true); cfg.setBoolean("notedb", "patchSetApprovals", "read", true); return new NotesMigration(cfg); }

Target:
Changing this to: cfg.setBoolean("notedb", "patchSetApprovals", "read", false); makes most tests fail.
Source:
private void merge(PushOneCommit.Result r) throws Exception { review(r, 2); SubmitInput input = new SubmitInput(); input.waitForMerge = true; revision(r).submit(input); Repository repo = repoManager.openRepository(project); try { assertEquals(r.getCommitId(), repo.getRef("refs/heads/master").getObjectId()); } finally { repo.close(); } }

Target:
Remove these lines, you don't ned them. There is submit() method that does this standard thing.
Source:
public boolean match(ChangeData cd) throws OrmException { return cd.change().getLastUpdatedOn().getTime() <= cut.getTime(); }

Target:
Backwards? after:foo should match where last updated on is > foo.
Source:
protected void run() throws UnloggedFailure, Failure, Exception { stdout.println("Hello, cookbook administrator"); }

Target:
Not needed, sorry missed it in previous review.
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); } } } catch (IOException e) { log.error(e.getMessage(), e); } }

Target:
the catch could be part of the innter try block, no need to nest two blocks
Source:
private boolean 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--; } return true; } return false; }

Target:
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.
Source:
private static boolean isAbsolute(String url) { String pattern = "^https?://.*"; return url.matches(pattern); }

Target:
This variable is not needed, just use the pattern direct.
Source:
static void toGerrit(final String target, final HttpServletRequest req, final HttpServletResponse rsp) throws IOException { final StringBuilder url = new StringBuilder(); url.append(URLEncoder.encode(req.getContextPath(), "UTF-8")); url.append('/'); url.append('#'); url.append(target); rsp.sendRedirect(url.toString()); }

Target:
I think this stops admins from installing at for example /code/review/ on their server.
Source:
protected void doGet(final HttpServletRequest req, final HttpServletResponse rsp) throws IOException { final StringBuilder rdr = new StringBuilder(); rdr.append(URLEncoder.encode(urlProvider.get(), "UTF-8")); rdr.append('#'); rdr.append(getToken(req)); CacheHeaders.setNotCacheable(rsp); rsp.sendRedirect(rdr.toString()); }

Target:
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.
Source:
public boolean equals(Object obj) { if (obj instanceof SecureStoreData) { SecureStoreData o = (SecureStoreData) obj; return Objects.equal(storeName, o.storeName); } return equals(obj); }

Target:
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.
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(); if (approvals != null) { return approvals.get(psId); } return Collections.emptyList(); }

Target:
I don't want to return null from getApprovals(). It shouldn't be that hard to modify ChangeNotes.onLoad to handle a null revision.
Source:
public Void get(long timeout, TimeUnit unit) throws InterruptedException, TimeoutException, ExecutionException { if (!isDone()) { if (reopenThread.waitForGeneration(gen, (int) MILLISECONDS.convert(timeout, unit))) { set(null); } } return super.get(timeout, unit); }

Target:
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.
Source:
public void removeIfDone() throws IOException { if (isGenAvailableNowForCurrentSearcher()) { if (!isCancelled()) { notDoneNrtFutures.remove(this); set(null); } } }

Target:
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.
Source:
public void setCurrentFilePaths(List<String> filePaths) throws OrmException { PatchSet ps = currentPatchSet(); if (ps != null) { files.put(Integer.valueOf(ps.getPatchSetId()), ImmutableList.copyOf(filePaths)); } }

Target:
This is redundant, auto-boxing will work just fine and IIRC unlike JGit we don't warn on auto-boxing in Gerrit.
Source:
public UniversalServerPluginProvider(DynamicSet<ServerPluginProvider> sf) { this.serverPluginProviders = sf; }

Target:
Why public? Gerrit conversion is to mark injected constructors as package provided
Source:
public PatchSet getBasePatchSet(RevisionEdit edit, RevCommit commit) throws IOException { checkState(commit.getParentCount() == 1); 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); } }

Target:
Useful error message when this fails?
Source:
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()); ObjectId newEdit = inserter.insert(builder); inserter.flush(); return newEdit; }

Target:
Not obvious what this argument does. It looks like it's just to copy the identity? Why not just pass a PersonIdent instead?
Source:
public GerritConstantsProperties() throws IOException { InputStream constantsStream = GerritTopMenus.class.getResourceAsStream(GERRIT_CONSTANTS_PROPERTIES); if (constantsStream != null) { load(constantsStream); } else { log.error("Cannot locate Gerrit constants from classpath", GERRIT_CONSTANTS_PROPERTIES); } }

Target:
Why not use the class GerritConstantsProperties.class or even: getClass().getResourceAsStream(GERRIT_CONSTANTS_PROPERTIES)
Source:
private GerritTopMenus gerritTopMenusWithModule(AbstractModule module) { Injector injector = baseInjector.createChildInjector(module); return injector.getInstance(GerritTopMenus.class); }

Target:
No need for the variable. Just inline it in one return statement.
Source:
void onClose(ClickEvent e) { onCancel(null); }

Target:
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.
Source:
static boolean isAuthorizedCall(HttpServletRequest req) { return !Strings.isNullOrEmpty(req.getServletPath()) && req.getServletPath().startsWith(AUTHORIZED_PREFIX); }

Target:
make this private?
Source:
static public 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; }

Target:
I think many tests doing something similar and call it grant()? Should we switch to using this convenience method there too?
Source:
public boolean isStale(GerritConfig cfg) { return lastUpdated > cfg.getCreationTime() || (refreshConfig && site.gerrit_config.lastModified() > cfg.getCreationTime()); }

Target:
wrap this line?
Source:
private static String generateRandomState() { byte[] randomState = new byte[32]; new SecureRandom().nextBytes(randomState); return Base64.encodeBase64URLSafeString(randomState); }

Target:
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.
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) + "/" + CharMatcher.is('/').trimLeadingFrom(path); } }

Target:
Use trimTrailingSlash method?
Source:
private 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; }

Target:
Should be static (see below).
Source:
public void stop() { if (scheduledTask != null) { scheduledTask.cancel(true); } }

Target:
I would guess that the work queue itself listens to the stop event and cancels the tasks. But this would have to be verified.
Source:
public static List<ChangeMessage> sortChangeMessages( Iterable<ChangeMessage> changeMessage) { return ChangeNotes.MESSAGE_BY_TIME.sortedCopy(changeMessage); }

Target:
+1, will clarify docs.
Source:
public void fromRange(Range r) { range = range == null ? null : new CommentRange(range.startLine, range.startCharacter, range.endLine, range.endCharacter); }

Target:
Eclipse is warning that the argument `r` is unused. I guess this should be changed to `r`?
Source:
public CustomIcons get() { CustomIcons customIcons = new CustomIcons(projectIcons); return customIcons; }

Target:
This temp var is unneeded. Return direct.
Source:
private 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; }

Target:
Can be static, and order it down below the public methods
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 (IOException e) { throw error("internal error while reading review input"); } }

Target:
Done
Source:
AbstractChangeNotes(GitRepositoryManager repoManager, Change change) { this.repoManager = repoManager; this.change = change; }

Target:
Defensive copy here instead?
Source:
protected boolean isEmpty() { return approvals.isEmpty() && reviewers.isEmpty() && commentsForBase.isEmpty() && commentsForPs.isEmpty() && status == null && submitRecords == null && changeMessage == null; }

Target:
Leave private.
Source:
public static synchronized void cleanup() throws IOException { System.out.println("deleting dirs"); for(File dir : allDirsCreated) { System.err.println("cleaning up " + dir.getCanonicalPath()); recursivelyDelete(dir); } allDirsCreated.clear(); }

Target:
Left over diagnostic output?
Source:
private List<AccountExternalId.Key> filterKeysByScheme( String keyScheme, ResultSet<AccountExternalId> externalIds) { List<AccountExternalId.Key> filteredExternalIds = Lists.newArrayList(); for (AccountExternalId accountExternalId : externalIds) { if (accountExternalId.isScheme(keyScheme)) { filteredExternalIds.add(accountExternalId.getKey()); } } return filteredExternalIds; }

Target:
new ArrayList<>()
Source:
public 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; }

Target:
Not necessary.
Source:
private List<PatchLineComment> 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); } }) ); }

Target:
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
Source:
public Collection<PatchLineComment> publishedComments() throws OrmException { if (publishedComments == null) { publishedComments = Lists.newArrayList(plcUtil.publishedByChange(db, notes())); } return publishedComments; }

Target:
publishedByChange() already returns list, so just: publishedComments = plcUtil.publishedByChange(db, notes());
Source:
public String getUrl(String baseUrl, String path) throws MalformedURLException { if (baseUrl.indexOf("://") > 0) { return new URL(new URL(baseUrl), path).toExternalForm(); } else { return baseUrl + (baseUrl.endsWith("/") ? "" : "/") + (path.startsWith("/") ? path.substring(1) : path); } }

Target:
It seems to me like the removal of the slash has no effect because its dealt with here no?
Source:
private List<PatchLineComment> sort(List<PatchLineComment> comments) { Collections.sort(comments, ChangeNotes.PatchLineCommentComparator); return comments; }

Target:
private static
Source:
private static void reset() throws MalformedURLException { for (Enumeration<Logger> logger = LogManager.getCurrentLoggers(); logger.hasMoreElements();) { logger.nextElement().setLevel(null); } if (Strings.isNullOrEmpty(System.getProperty(JAVA_OPTIONS_LOG_CONFIG))) { PropertyConfigurator.configure(Loader.getResource(LOG_CONFIGURATION)); } else { PropertyConfigurator.configure( new URL(System.getProperty(JAVA_OPTIONS_LOG_CONFIG))); } }

Target:
Optional: extract this into a var, so that we don't retrieve it twice: here and on line 90.
Source:
private static Term intTerm(String name, int value) { BytesRef bytes = new BytesRef(NumericUtils.BUF_SIZE_INT); BytesRefBuilder builder = new BytesRefBuilder(); builder.append(bytes); NumericUtils.intToPrefixCodedBytes(value, 0, builder); return new Term(name, bytes); }

Target:
Need to use builder.get(). Done.
Source:
public void onProjectDeleted(Event event) { Project.NameKey p = new NameKey(event.getProjectName()); repoSizeCache.evict(p); }

Target:
optional: could be inlined in the next line
Source:
private boolean needPack(Collection<ReceiveCommand> commands) { for (final ReceiveCommand cmd : commands) { if (cmd.getType() != ReceiveCommand.Type.DELETE) return true; } return false; }

Target:
I think we don't use 'final' in this place anymore.
Source:
private ResourceKey(String p, String f, String r) { project = p != null ? new Project.NameKey(p) : null; file = f; revision = r; }

Target:
Can this really happen? If not why care?