auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void useWithoutConnecting() { jedis.auth("foobared"); START Jedis jedis = new Jedis("localhost"); END jedis.dbSize(); } I think this is by accident. Could you revert it, or could you explain why this change is necessary?

Target:
public void useWithoutConnecting() { Jedis jedis = new Jedis("localhost"); jedis.auth("foobared"); jedis.dbSize(); }
Source:
START int count() { END if (params.containsKey(COUNT)) { return params.get(COUNT).getInt(); } else { return SCAN_COUNT_DEFAULT.getInt(); } } It should return null when not set by user.

Target:
Integer count() { if (params.containsKey(COUNT)) { return params.get(COUNT).getInt(); } else { return null; } }
Source:
public static boolean isClusterCompliantMatchPattern(String matchPattern) { String tag = extractHashTag(matchPattern, true, true); if (tag != null && !tag.isEmpty() && matchPattern.startsWith(tag)) { START return matchPattern.substring(tag.length()).equals("*"); END } else { return false; } } AFAIK, pattern doesn't need to be restricted by "*". Keys with same hashtag will be placed to same slot, which is only one condition for scan with Redis cluster.

Target:
public static boolean isClusterCompliantMatchPattern(String matchPattern) { String tag = extractHashTag(matchPattern, false); return tag != null && !tag.isEmpty(); }
Source:
int count() { if (params.containsKey(COUNT)) { return params.get(COUNT).getInt(); } else { START return 0; END } } Let's have consistent between match() and count(). I think it's better to change return type to Integer (to let users know it can be null), and also return null when it's not presented by user.

Target:
Integer count() { if (params.containsKey(COUNT)) { return params.get(COUNT).getInt(); } else { return null; } }
Source:
public void zrevrangeByScoreWithScores(final byte[] key, final double max, final double min) { START sendCommand(ZREVRANGEBYSCORE, key, toByteArray(min), toByteArray(max), WITHSCORES.raw); END } parameter sequence swapped: max, min is correct.

Target:
public void zrevrangeByScoreWithScores(final byte[] key, final double max, final double min) { sendCommand(ZREVRANGEBYSCORE, key, toByteArray(max), toByteArray(min), WITHSCORES.raw); }
Source:
public void zrevrangeByScore(final byte[] key, final double max, final double min, final int offset, int count) { START sendCommand(ZREVRANGEBYSCORE, key, toByteArray(min), toByteArray(max), LIMIT.raw, toByteArray(offset), END toByteArray(count)); } parameter sequence swapped: max, min is correct.

Target:
public void zrevrangeByScore(final byte[] key, final double max, final double min, final int offset, int count) { sendCommand(ZREVRANGEBYSCORE, key, toByteArray(max), toByteArray(min), LIMIT.raw, toByteArray(offset), toByteArray(count)); }
Source:
public void zrevrangeByScore(final byte[] key, final double max, final double min) { START sendCommand(ZREVRANGEBYSCORE, key, toByteArray(min), toByteArray(max)); END } parameter sequence swapped: max, min is correct.

Target:
public void zrevrangeByScore(final byte[] key, final double max, final double min) { sendCommand(ZREVRANGEBYSCORE, key, toByteArray(max), toByteArray(min)); }
Source:
START public Long del(final String key) { END return new JedisClusterCommand<Long>(connectionHandler, timeout, maxRedirections) { @Override public Long execute(Jedis connection) { return connection.del(key); } }.run(key); } This guys weren't marked as `@Deprecated` but I believe there is no problem to delete it since `JedisCommands` marked it as `@Deprecated`. :+1:

Target:
public Long del(final String key) { return new JedisClusterCommand<Long>(connectionHandler, maxRedirections) { @Override public Long execute(Jedis connection) { return connection.del(key); } }.run(key); }
Source:
public static void removeSlots() throws InterruptedException { START String[] nodes = node1.clusterNodes().split("\n"); END String node1Id = nodes[0].split(" ")[0]; node1.clusterReset(Reset.SOFT); node2.clusterReset(Reset.SOFT); } We can remove unused local variables nodes and node1Id.

Target:
public static void removeSlots() throws InterruptedException { node1.clusterReset(Reset.SOFT); node2.clusterReset(Reset.SOFT); }
Source:
public String set(final byte[] key, final byte[] value) { START return new JedisClusterCommand<String>(connectionHandler, timeout, maxRedirections) { END @Override public String execute(Jedis connection) { return connection.set(key, value); } }.runBinary(key); } I don't really like these `new JedisClusterCommand` repetition everywhere but I also don't see any alternative to it. Maybe if we could use some lambda here?

Target:
public String set(final byte[] key, final byte[] value) { return new JedisClusterCommand<String>(connectionHandler, maxRedirections) { @Override public String execute(Jedis connection) { return connection.set(key, value); } }.runBinary(key); }
Source:
public byte[] echo(final byte[] arg) { return new JedisClusterCommand<byte[]>(connectionHandler, timeout, maxRedirections) { @Override public byte[] execute(Jedis connection) { return connection.echo(arg); } START }.runBinary(null); END } Calling `runBinary(null)` leads to `JedisClusterException` due to the null / length check there. Would it be possible to dispatch the command to an arbitrary cluster node as a dedicated slot is not required for this operation?

Target:
public byte[] echo(final byte[] arg) { // note that it'll be run from arbitary node return new JedisClusterCommand<byte[]>(connectionHandler, maxRedirections) { @Override public byte[] execute(Jedis connection) { return connection.echo(arg); } }.runBinary(arg); }
Source:
public List<byte[]> blpop(final byte[] arg) { return new JedisClusterCommand<List<byte[]>>(connectionHandler, timeout, maxRedirections) { @Override public List<byte[]> execute(Jedis connection) { return connection.blpop(arg); } START }.runBinary(null); END } According to http://redis.io/commands/blpop, arg is the key. So you should call runBinary with arg. Sorry for confused naming. I think arg should be changed to key.

Target:
public List<byte[]> blpop(final byte[] arg) { return new JedisClusterCommand<List<byte[]>>(connectionHandler, timeout, maxRedirections) { @Override public List<byte[]> execute(Jedis connection) { return connection.blpop(arg); } }.runBinary(arg); }
Source:
START public Long move(final byte[] key, final int dbIndex) { END return new JedisClusterCommand<Long>(connectionHandler, timeout, maxRedirections) { @Override public Long execute(Jedis connection) { return connection.move(key, dbIndex); } }.runBinary(key); } According to Redis Cluster specification, > Redis Cluster does not support multiple databases like the stand alone version of Redis, there is just database 0, and SELECT is not allowed. So move method is not compatible to Redis Cluster. We can let it go and take exception, or separate interface to Cluster commands and finally remove this method (with String version) from (Binary)JedisCluster. What do you think which is more proper?

Target:
public Long move(final byte[] key, final int dbIndex) { return new JedisClusterCommand<Long>(connectionHandler, timeout, maxRedirections) { @Override public Long execute(Jedis connection) { return connection.move(key, dbIndex); } }.runBinary(null); }
Source:
public Object eval(final String script, final String key) { return new JedisClusterCommand<Object>(connectionHandler, timeout, maxRedirections) { @Override public Object execute(Jedis connection) { return connection.eval(script); } START }.run(1, key); END } I think .run(key) is more faster than this if we keep JedisClusterCommand.run(String or byte[]).

Target:
public Object eval(final String script, final String key) { return new JedisClusterCommand<Object>(connectionHandler, timeout, maxRedirections) { @Override public Object execute(Jedis connection) { return connection.eval(script); } }.run(key); }
Source:
public List<Boolean> scriptExists(final String key, final String... sha1) { return new JedisClusterCommand<List<Boolean>>(connectionHandler, timeout, maxRedirections) { @Override public List<Boolean> execute(Jedis connection) { return connection.scriptExists(sha1); } START }.run(1, key); END } I think .run(key) is more faster than this if we keep JedisClusterCommand.run(String or byte[]).

Target:
public List<Boolean> scriptExists(final String key, final String... sha1) { return new JedisClusterCommand<List<Boolean>>(connectionHandler, timeout, maxRedirections) { @Override public List<Boolean> execute(Jedis connection) { return connection.scriptExists(sha1); } }.run(key); }
Source:
public String scriptLoad(final String script, final String key) { return new JedisClusterCommand<String>(connectionHandler, timeout, maxRedirections) { @Override public String execute(Jedis connection) { return connection.scriptLoad(script); } START }.run(1, key); END } I think .run(key) is more faster than this if we keep JedisClusterCommand.run(String or byte[]).

Target:
public String scriptLoad(final String script, final String key) { return new JedisClusterCommand<String>(connectionHandler, timeout, maxRedirections) { @Override public String execute(Jedis connection) { return connection.scriptLoad(script); } }.run(key); }
Source:
public ScanResult(byte[] cursor, List<T> results) { START this.cursor = SafeEncoder.encode(cursor); END this.results = results; } Hmm, it's a bit odd to encode the `byte[]` cursor to a string and then re-decode it to byte[] below. Could the result simply keep both versions in fields ?

Target:
public ScanResult(byte[] cursor, List<T> results) { this.cursor = cursor; this.results = results; }
Source:
private void initializeSlotsCache(Set<HostAndPort> nodes) { for (HostAndPort hostAndPort : nodes) { JedisPool jp = new JedisPool(hostAndPort.getHost(), hostAndPort.getPort()); this.nodes.put(hostAndPort.getHost() + hostAndPort.getPort(), jp); START Jedis jedis = jp.getResource(); END discoverClusterNodesAndSlots(jedis); jp.returnResource(jedis); } } We should probably add a try & finally block, to return the resource always, even in case of a RuntimeException

Target:
private void initializeSlotsCache(Set<HostAndPort> nodes) { for (HostAndPort hostAndPort : nodes) { JedisPool jp = new JedisPool(hostAndPort.getHost(), hostAndPort.getPort()); this.nodes.put(hostAndPort.getHost() + hostAndPort.getPort(), jp); Jedis jedis = jp.getResource(); try { discoverClusterNodesAndSlots(jedis); } finally { jp.returnResource(jedis); } } }
Source:
private File createWindowsGitSSH(File key, String user) throws IOException { File ssh = createTempFile("ssh", ".bat"); File sshexe = getSSHExecutable(); START END try (PrintWriter w = new PrintWriter(ssh, this.encoding)) { w.println("@echo off"); w.println("\"" + sshexe.getAbsolutePath() + "\" -i \"" + key.getAbsolutePath() +"\" -l \"" + user + "\" -o StrictHostKeyChecking=no %* "); } ssh.setExecutable(true, true); return ssh; } No trailing white space on lines.

Target:
private File createWindowsGitSSH(File key, String user) throws IOException { File ssh = createTempFile("ssh", ".bat"); File sshexe = getSSHExecutable(); try (PrintWriter w = new PrintWriter(ssh, encoding)) { w.println("@echo off"); w.println("\"" + sshexe.getAbsolutePath() + "\" -i \"" + key.getAbsolutePath() +"\" -l \"" + user + "\" -o StrictHostKeyChecking=no %* "); } ssh.setExecutable(true, true); return ssh; }
Source:
public String toString() { final String revisionName = sha1 != null ? sha1.name() : "null"; StringBuilder s = new StringBuilder("Revision " + revisionName + " ("); if (branches != null) { Joiner.on(", ").appendTo(s, START Iterables.transform(branches, (Branch from) -> Util.fixNull(from.getName()))); END } s.append(')'); return s.toString(); } Or even simpler: ```java Iterables.transform(branches, from -> Util.fixNull(from.getName()))); ```

Target:
public String toString() { final String revisionName = sha1 != null ? sha1.name() : "null"; StringBuilder s = new StringBuilder("Revision " + revisionName + " ("); if (branches != null) { Joiner.on(", ").appendTo(s, Iterables.transform(branches, from -> Util.fixNull(from.getName()))); } s.append(')'); return s.toString(); }
Source:
public void clean() throws GitException, InterruptedException { reset(true); String cmd = "-fdx"; launchCommand("clean", cmd); START } END I want to first clarify I'm not a Java programmer, so what I say may not make sense or not be a common practice in Java, but can't you just set a default parameter `public void clean(boolean cleanSubmodule = false)`?

Target:
public void clean() throws GitException, InterruptedException { this.clean(false); }
Source:
public <T> T withRepository(RepositoryCallback<T> callable) throws IOException, InterruptedException { Repository repo = getRepository(); START try { END return callable.invoke(repo, Jenkins.MasterComputer.localChannel); } finally { repo.close(); } } NIT: if repository is `AutoCloseable` then try-with-resources is better here - if both the callable and the close fails the initial error would be swallowed with the code as is :-( (surely you can move the parent to 1.625 if it is not already?)

Target:
public <T> T withRepository(RepositoryCallback<T> callable) throws IOException, InterruptedException { try (Repository repo = getRepository()) { return callable.invoke(repo, Jenkins.MasterComputer.localChannel); } }
Source:
public List<ObjectId> revListAll() throws GitException { List<ObjectId> oidList = new ArrayList<>(); RevListCommand revListCommand = revList_(); revListCommand.all(); revListCommand.to(oidList); try { revListCommand.execute(); } catch (InterruptedException e) { throw new GitException(e); START } catch (IOException e) { END throw new GitException(e); } return oidList; } NIT: multi-catch - (surely you can move the parent to 1.625 if it is not already?)

Target:
public List<ObjectId> revListAll() throws GitException { List<ObjectId> oidList = new ArrayList<>(); RevListCommand revListCommand = revList_(); revListCommand.all(); revListCommand.to(oidList); try { revListCommand.execute(); } catch (InterruptedException | IOException e) { throw new GitException(e); } return oidList; }
Source:
public Revision(ObjectId sha1, Collection<Branch> branches) { START if (sha1 == null) throw new NullPointerException("sha1 can't be null"); END this.sha1 = sha1; this.branches = branches; } throw IllegalArgumentException

Target:
public Revision(ObjectId sha1, Collection<Branch> branches) { this.sha1 = sha1; this.branches = branches; }
Source:
public void fetch(String remoteName, RefSpec refspec) throws GitException, InterruptedException { START fetch(remoteName, refspec); END } infinite self invocation ?

Target:
public void fetch(String remoteName, RefSpec refspec) throws GitException, InterruptedException { fetch(remoteName, new RefSpec[] {refspec}); }
Source:
protected BatchDeleteClientsRequest getValidRequest() throws Exception { return BatchDeleteClientsRequest.builder() START .clientIdentification(ClientIdentification.builder() END .clientId("14pnUs") .build()) .clientIdentification(ClientIdentification.builder() .clientId("qECLyr") .build()) .build(); } I'm not sure I like this interface—it is wordy and a little cumbersome for the user. Also there is no prospect of the `ClientIdentification` class being used anywhere else. I'll work on a way of simplifying this.

Target:
protected BatchDeleteClientsRequest getValidRequest() throws Exception { return BatchDeleteClientsRequest.builder() .clientId("14pnUs", "qECLyr") .build(); }
Source:
protected String detect( InputStream inputStream, Metadata metadata ) { try { // we never care about the stream here, but close it anyway START IoUtil.closeQuietly(inputStream); END MediaType detectedMimeType = detector.detect(null, metadata); if (logger.isTraceEnabled()) { logger.trace("MIME type for '" + metadata.get(Metadata.RESOURCE_NAME_KEY) + "' ==> " + detectedMimeType); } return detectedMimeType.toString(); } catch (Exception e) { logger.debug(e, "Unable to extract mime-type"); return null; } } I would move this inside a `finally` block in the same method

Target:
protected String detect( InputStream inputStream, Metadata metadata ) { try { // we never care about the stream here, but close it anyway MediaType detectedMimeType = detector.detect(null, metadata); if (logger.isTraceEnabled()) { logger.trace("MIME type for '" + metadata.get(Metadata.RESOURCE_NAME_KEY) + "' ==> " + detectedMimeType); } return detectedMimeType.toString(); } catch (Exception e) { logger.debug(e, "Unable to extract mime-type"); return null; } finally { IoUtil.closeQuietly(inputStream); } }
Source:
private void batchWriteDocuments(List<String> keys, BackupDocumentWriter contentWriter) { START final NodeKey metadataKey = repositoryCache.getRepositoryMetadataDocumentKey(); END for (String key : keys) { if (key == null) break; if (!key.equals(metadataKey.toString())) { SchematicEntry entry = documentStore.get(key); if (entry != null) { writeToContentArea(entry, contentWriter); } } } } the logic of excluding the `metadataKey` is correct, but it should not be done here on each method call. Instead, it should be done only once in the `keys` list after all the keys have been loaded.

Target:
private void batchWriteDocuments(List<String> keys, BackupDocumentWriter contentWriter) { for (String key : keys) { if (key == null) break; SchematicEntry entry = documentStore.get(key); if (entry != null) { writeToContentArea(entry, contentWriter); } } }
Source:
public boolean lockForWriting( List<String> locks ) { TransactionsHolder.requireActiveTransaction(); if (locks.isEmpty()) { return false; START } END return runWithConnection(connection -> statements.lockForWriting(connection, locks), true); } Should this `if` block be before the `requireActiveTransaction()` call?

Target:
public boolean lockForWriting( List<String> locks ) { if (locks.isEmpty()) { return false; } TransactionsHolder.requireActiveTransaction(); return runWithConnection(connection -> statements.lockForWriting(connection, locks), true); }
Source:
protected Object columnValue(Object value) { switch (type) { case PATH: case NAME: case STRING: case REFERENCE: case SIMPLEREFERENCE: case WEAKREFERENCE: case URI: return valueFactories.getStringFactory().create(value); case DATE : START return ((DateTime) value).getMilliseconds(); END } return value; } There is no `default` case here. What about longs or binaries or other `PropertyType`s?

Target:
protected Object columnValue(Object value) { switch (type) { case PATH: case NAME: case STRING: case REFERENCE: case SIMPLEREFERENCE: case WEAKREFERENCE: case URI: return valueFactories.getStringFactory().create(value); case DATE : return ((DateTime) value).getMilliseconds(); default : return value; } }
Source:
public void afterEach() throws Exception { try { stopRepository(); START } catch (Exception e) { END } finally { FileUtil.delete("target/persistent_repository"); } } should this exception be left to bubble up and fail the test ? If `afterEach` fails it means the repository was not shutdown properly

Target:
public void afterEach() throws Exception { try { stopRepository(); } finally { FileUtil.delete("target/persistent_repository"); } }
Source:
private boolean allowsSNS( NodeCache cache ) { RepositoryEnvironment repositoryEnvironment = workspace(cache).repositoryEnvironment(); if ( repositoryEnvironment == null) { return true; } NodeTypes nodeTypes = repositoryEnvironment.nodeTypes(); if (nodeTypes == null) { return true; } Name primaryType = getPrimaryType(cache); if (nodeTypes.isUnorderedCollection(primaryType)) { return false; } Set<Name> mixinTypes = getMixinTypes(cache); START return nodeTypes.allowsNameSiblings(primaryType, mixinTypes); END } Another option might have been to change `NodeTypes.allowsNameSiblings` to also check whether unordered, since all unordered collections do not allow SNS. That might be better only if the logic above is repeated elsewhere.

Target:
private boolean allowsSNS( NodeCache cache ) { Name primaryType = getPrimaryType(cache); Set<Name> mixinTypes = getMixinTypes(cache); RepositoryEnvironment repositoryEnvironment = workspace(cache).repositoryEnvironment(); if ( repositoryEnvironment == null) { return true; } NodeTypes nodeTypes = repositoryEnvironment.nodeTypes(); return nodeTypes == null || nodeTypes.allowsNameSiblings(primaryType, mixinTypes); }
Source:
public boolean hasNext() { if (last != null) return true; // 'hasNext()' has been called multiple times before 'next()' while (super.hasNext()) { last = super.next(); if (last.getName().equals(name)) { return true; } else { last = null; START } END } return false; } Strictly speaking, the "else" on 230 is completely unnecessary since line 229 is a `return` statement. Why not just keep line 228 as is and add a `last = null;` right after as a new line?

Target:
public boolean hasNext() { if (last != null) return true; // 'hasNext()' has been called multiple times before 'next()' while (super.hasNext()) { last = super.next(); if (last.getName().equals(name)) return true; last = null; } return false; }
Source:
START protected synchronized void executeFunctionsUponCompletion() { END if (uponCompletionFunctions != null) { executeFunctions(uponCompletionFunctions); uponCompletionFunctions = null; } } Why does this need to be `synchronized`? Is it possible for two threads (in the same txn) to hit this at the same time? Isn't the completion state entered only once, regardless of the number of threads participating in the txn?

Target:
protected void executeFunctionsUponCompletion() { if (uponCompletionFunctions != null) { executeFunctions(uponCompletionFunctions); uponCompletionFunctions = null; } }
Source:
public void addEventListener( EventListener listener, int eventTypes, String absPath, boolean isDeep, String[] uuid, String[] nodeTypeName, boolean noLocal ) throws RepositoryException { CheckArg.isNotNull(listener, "listener"); checkSession(); // make sure session is still active // create wrapper and register JcrListenerAdapter adapter = new JcrListenerAdapter(listener, eventTypes, absPath, isDeep, uuid, nodeTypeName, noLocal); this.repositoryObservable.register(adapter); START this.listeners.add(adapter); END } These two lines should probably be: ``` if ( this.repositoryObservable.register(adapter) ) this.listeners.add(adapter); ``` just in case we can't register the adapter (for whatever reason).

Target:
public void addEventListener( EventListener listener, int eventTypes, String absPath, boolean isDeep, String[] uuid, String[] nodeTypeName, boolean noLocal ) throws RepositoryException { CheckArg.isNotNull(listener, "listener"); checkSession(); // make sure session is still active // create wrapper and register JcrListenerAdapter adapter = new JcrListenerAdapter(listener, eventTypes, absPath, isDeep, uuid, nodeTypeName, noLocal); if (this.repositoryObservable.register(adapter)) { this.listeners.add(adapter); } }
Source:
final void cleanLocks() throws RepositoryException { lockManager.cleanLocks(session); for (String token : new ArrayList<String>(lockTokens.keySet())) { removeLockToken(token); START } END } This looks good. @hchiorean, do you think this is better off inside the `lockManager.cleanLocks(session)` call, which is where we do the other cleanup? IMO, it could go either place.

Target:
final void cleanLocks() throws RepositoryException { lockManager.cleanLocks(session); for (String token : lockTokens.keySet()) { removeLockToken(token); } }
Source:
public Iterator<ChildReference> iterator( Name name, Context context ) { if (context != null && context.changes() != null) { //we only want the context-sensitive behavior if there are changes. Otherwise we've already precomputed the SNS index return super.iterator(name, context); } else { return iterator(name); START } END } Ok, I'm going to get picky here. Since you're returning from the `if` block, there is no need for an `else` block. So why not just do this? ``` if (context != null && context.changes() != null) { //we only want the context-sensitive behavior if there are changes. Otherwise we've already precomputed the SNS index return super.iterator(name, context); } return iterator(name); ```

Target:
public Iterator<ChildReference> iterator( Name name, Context context ) { if (context != null && context.changes() != null) { //we only want the context-sensitive behavior if there are changes. Otherwise we've already precomputed the SNS index return super.iterator(name, context); } return iterator(name); }
Source:
public void close() { if (this.runThread.compareAndSet(true, false)) { try { START cursor.signalConsumers(); END this.stopLatch.await(); // System.out.println("Ring buffer garbage collection thread has terminated"); } catch (InterruptedException e) { // do nothing ... } } } is there any benefit to waking all the other consumers when the GC consumer closes ? The way I understand it the GC consumer will only null out entries, so any sleeping consumer shouldn't have any benefit in waking up.

Target:
public void close() { if (this.runThread.compareAndSet(true, false)) { try { this.stopLatch.await(); } catch (InterruptedException e) { // do nothing ... } } }
Source:
private void incrementEventQueueStatistic( ChangeSet changeSet ) { START changesLock.lock(); END try { // whenever a change set is received from the bus, increment the que size if (repositoryStatistics != null) { repositoryStatistics.increment(ValueMetric.EVENT_QUEUE_SIZE); } if (!this.changesReceivedAndDispatched.containsKey(changeSet.hashCode())) { // none of the adapters have processed this change set yet, register it changesReceivedAndDispatched.put(changeSet.hashCode(), new AtomicInteger(listeners.size())); } } finally { changesLock.unlock(); } } I'm curious why this change was made. The `repositoryStatistics` should be thread safe, so the lock should only be needed to update `changesReceivedAndDispatched`.

Target:
private void incrementEventQueueStatistic( ChangeSet changeSet ) { // whenever a change set is received from the bus, increment the que size if (repositoryStatistics != null) { repositoryStatistics.increment(ValueMetric.EVENT_QUEUE_SIZE); } changesLock.lock(); try { if (!this.changesReceivedAndDispatched.containsKey(changeSet.hashCode())) { // none of the adapters have processed this change set yet, register it changesReceivedAndDispatched.put(changeSet.hashCode(), new AtomicInteger(listeners.size())); } } finally { changesLock.unlock(); } }
Source:
public void shutdown() { if (enableEvents) { monitoringTask.cancel(true); START } END } Probably need to change this to `if ( monitoringTask != null ) monitoringTask.cancel(true);`, because if `enableEvents` is true but creating a monitoringTask failed when the watch service is not supported on the current OS, then line 282 would result in an NPE.

Target:
public void shutdown() { if (enableEvents && monitoringTask != null) { try { monitoringTask.cancel(true); } finally { monitoringTask = null; } } }
Source:
public boolean equals( Object o ) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } JournalRecord record = (JournalRecord)o; if (createdTimeMillisUTC != record.createdTimeMillisUTC) { return false; } START if (content != null ? !content.getUUID().equals(record.content.getUUID()) : record.content != null) { END return false; } return true; } This seems strange that `equals` and `hashCode` check _both_ the `createdTimeMillisUTC` (which is likely process-specific) and the content's UUID (which is universal for that ChangeSet). When comparing JournalRecord instances from separate machines, will any of them ever be found as duplicates? (Do we ever do this?)

Target:
public boolean equals( Object o ) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } JournalRecord record = (JournalRecord)o; return content.getUUID().equals(record.content.getUUID()); }
Source:
protected Segment getSegment( WorkspaceCache cache ) { ChildReference self = parentReferenceToSelf(cache); START if (self == null) { END self = parentReferenceToSelf(cache); } return self.getSegment(); } can this ever happen ? Won't `parentReferenceToSelf(cache)` throw a `NodeNotFoundInParentException` always if a reference is not found ?

Target:
protected Segment getSegment( WorkspaceCache cache ) { return parentReferenceToSelf(cache).getSegment(); }
Source:
private SimplePrincipal(String name) { START this.name = name; END } When can the `name` be null? If not possible, then add an assertion.

Target:
private SimplePrincipal(String name) { assert(name != null); this.name = name; }
Source:
public int hashCode() { int hash = 5; hash = 79 * hash + (this.path != null ? this.path.hashCode() : 0); START return hash; END } Why not use `return this.path.hashCode()`?

Target:
public int hashCode() { return this.path.hashCode(); }
Source:
START public final void addContextData( String key, END String value ) { this.context = context.with(key, value); this.cache.addContextData(key, value); } Woa, I'm not sure I like this being public.

Target:
final void addContextData( String key, String value ) { this.context = context.with(key, value); this.cache.addContextData(key, value); }
Source:
START public final ExecutionContext context() { END return context; } Does this still need to be public?

Target:
final ExecutionContext context() { return context; }
Source:
START public AbstractJcrNode addAclNode( String relPath, END String primaryNodeTypeName ) throws ItemExistsException, PathNotFoundException, NoSuchNodeTypeException, LockException, VersionException, ConstraintViolationException, RepositoryException { checkSession(); return addNode(relPath, primaryNodeTypeName, null, true); } This should be `protected` and not `public`. @okulikov, can you go through your changes and change the access modifiers of all modified methods to be as limited as possible?

Target:
protected AbstractJcrNode addAclNode( String relPath, String primaryNodeTypeName ) throws ItemExistsException, PathNotFoundException, NoSuchNodeTypeException, LockException, VersionException, ConstraintViolationException, RepositoryException { checkSession(); return addNode(relPath, primaryNodeTypeName, null, true); }
Source:
START public AccessControlManagerImpl(JcrSession session) { END this.session = session; this.privileges = new Privileges(session); this.defaultACL = JcrAccessControlList.defaultAcl(this); } This should not be public. I'd suggest protected. Plus, remove the not-helpful JavaDoc.

Target:
protected AccessControlManagerImpl(JcrSession session) { this.session = session; this.privileges = new Privileges(session); this.defaultACL = JcrAccessControlList.defaultAcl(this); }
Source:
protected InternalSecurityContext( String username ) { this.username = username; //given user is only known principal for this context START principals.add(SimplePrincipal.newInstance(username)); END } Actually, I'd recommend initializing `principals` using `Collections.singletonList(SimplePrincipal.newInstance(username))`. The resulting list is immutable and an efficient implementation.

Target:
protected InternalSecurityContext( String username ) { this.username = username; }
Source:
public AccessControlPolicy[] getEffectivePolicies(String path) throws PathNotFoundException, AccessDeniedException, RepositoryException { if (session.isReadOnly()) { throw new AccessDeniedException("Session is read only"); START } END AccessControlPolicy[] policies = getPolicies(path); if (policies.length == 0) { return new AccessControlPolicy[]{(AccessControlPolicy) this.getApplicablePolicies(path).next()}; } return policies; } Can you explain why this check is used? Why is a read-only session not able to get any of the effective policies?

Target:
public AccessControlPolicy[] getEffectivePolicies(String path) throws PathNotFoundException, AccessDeniedException, RepositoryException { AccessControlPolicy[] policies = getPolicies(path); if (policies.length == 0) { return new AccessControlPolicy[]{(AccessControlPolicy) this.getApplicablePolicies(path).next()}; } return policies; }
Source:
public final boolean isReadOnly() { START return this.isReadOnly; END } Once the `isReadOnly` field is removed, change this method to ``` return this.cache.isReadOnly(); ```

Target:
public final boolean isReadOnly() { return cache().isReadOnly(); }
Source:
private void addHandle(JcrSessionHandle handle) { synchronized (handles) { handles.add(handle); START } END } You do not need the `synchronized` block.

Target:
private void addHandle(JcrSessionHandle handle) { handles.add(handle); }
Source:
public boolean equals(Object other) { if (other == null) { return false; } if (other == this) { return true; } if (!(other instanceof JcrManagedConnectionFactory)) { return false; } START return this == (JcrManagedConnectionFactory) other; END } This code is correct, but it could be implemented in a more succinct manner that is a bit easier to read: public boolean equals(Object other) { if ( other == this ) return true; if ( other instanceof JcrManagedConnectionFactory ) return this == other; return false; }

Target:
public boolean equals(Object other) { if (other == this) { return true; } if (other instanceof JcrManagedConnectionFactory) { return this == other; } return false; }
Source:
public JcrRepositoryHandle(JcrResourceAdapter ra, JcrManagedConnectionFactory mcf, ConnectionManager cm) throws ResourceException { START System.out.println("Resource adaptor: " + ra); END this.mcf = mcf; this.cm = cm; try { this.repository = ra.getRepository(); } catch (Exception e) { throw new ResourceException(e); } } Oops. Please remove this `System.out.println` call.

Target:
public JcrRepositoryHandle(JcrResourceAdapter ra, JcrManagedConnectionFactory mcf, ConnectionManager cm) throws ResourceException { this.mcf = mcf; this.cm = cm; try { this.repository = ra.getRepository(); } catch (Exception e) { throw new ResourceException(e); } }
Source:
private boolean isAbsolutePath(String uri) { START return !(uri.startsWith("jndi") | uri.startsWith("file")); END } This is a bitwise OR ... shouldn't this be a boolean OR (`||`)?

Target:
private boolean isAbsolutePath(String uri) { return !(uri.startsWith("jndi") || uri.startsWith("file")); }
Source:
public void stop() { if (engine != null) { START engine.shutdown(); END } } Should this also set `engine` to null in a `finally` block? If not, I'm not sure why it checks for null (line 177).

Target:
public synchronized void stop() { if (engine != null) { engine.shutdown(); engine = null; } }
Source:
START protected Repository getRepository() throws ResourceException { END if (this.repository == null) { this.repository = deployRepository(repositoryURL); } return this.repository; } This method probably should be `synchronized` so that multiple concurrent calls will not stomp on each other.

Target:
protected synchronized Repository getRepository() throws ResourceException { if (this.repository == null) { this.repository = deployRepository(repositoryURL); } return this.repository; }
Source:
START public void start() throws Exception { END doStart(); } I don't really like this method being public, since it provides a backdoor around the state management operations in `ModeShapeEngine`. I understand that changing the visibility was required when we move the `RepositoryFactory` implementations into the `org.modeshape.jcr.factories` package. But I think having a cleaner API is more important than having that separate package.

Target:
void start() throws Exception { doStart(); }
Source:
START public Set<String> getRepositoryKeys() { END checkRunning(); final Lock lock = this.lock.readLock(); try { lock.lock(); return new HashSet<String>(repositories.keySet()); } finally { lock.unlock(); } } Same issue with the change in visibility of this method as with `JcrRepository.start()`.

Target:
protected Set<String> getRepositoryKeys() { checkRunning(); final Lock lock = this.lock.readLock(); try { lock.lock(); return new HashSet<String>(repositories.keySet()); } finally { lock.unlock(); } }
Source:
public InfinispanRepository( BaseInfinispanSource source, START BasicCacheContainer cacheContainer ) { END super(source); this.cacheContainer = source.createCacheContainer(); assert this.cacheContainer != null; Set<String> workspaceNames = new HashSet<String>(); for (String workspaceName : source.getPredefinedWorkspaceNames()) { workspaceNames.add(workspaceName); } this.predefinedWorkspaceNames = Collections.unmodifiableSet(workspaceNames); initialize(); } cacheContainer param doesn't seem to be used in the ctr (the source is always used to get the cache container)

Target:
public InfinispanRepository( BaseInfinispanSource source, BasicCacheContainer cacheContainer ) { super(source); this.cacheContainer = cacheContainer; assert this.cacheContainer != null; Set<String> workspaceNames = new HashSet<String>(); for (String workspaceName : source.getPredefinedWorkspaceNames()) { workspaceNames.add(workspaceName); } this.predefinedWorkspaceNames = Collections.unmodifiableSet(workspaceNames); initialize(); }
Source:
public RoleBasedProjectNamingStrategy(boolean forceExistingJobs) { this.forceExistingJobs = forceExistingJobs; START Jenkins.getInstance().setProjectNamingStrategy(this); END } Looks wrong, AFAIR projectnaming strategy is set by core and plugins shouldn't do manual assignment

Target:
public RoleBasedProjectNamingStrategy(boolean forceExistingJobs) { this.forceExistingJobs = forceExistingJobs; }
Source:
private boolean hasGlobalPermission(String userName, Permission permission, RoleBasedAuthorizationStrategy rbas) { START LOGGER.debug("Check the global permission of the user " + userName + " " + rbas.getGrantedRoles(RoleBasedAuthorizationStrategy.GLOBAL)); END return hasPermission(userName, permission, rbas.getGrantedRoles(RoleBasedAuthorizationStrategy.GLOBAL)); } Slow logging

Target:
private boolean hasGlobalPermission(String userName, Permission permission, RoleBasedAuthorizationStrategy rbas) { return hasPermission(userName, permission, rbas.getGrantedRoles(RoleBasedAuthorizationStrategy.GLOBAL)); }
Source:
static Object[][] roleNameProvider() { return new Object[][] { new Object[] {"bbmri_eric", "Manager", "bbmri_eric_MANAGER"}, START new Object[] {"bbmri_eric", "Manager", "bbmri_eric_MANAGER"}, END new Object[] {"patientenfederatie-nederland", "Member", "patientenfederatie-nederland_MEMBER"} }; } In both the old and new situation this line seems duplicated

Target:
static Object[][] roleNameProvider() { return new Object[][] { new Object[] {"bbmri_eric", "Manager", "bbmri_eric_MANAGER"}, new Object[] {"patientenfederatie-nederland", "Member", "patientenfederatie-nederland_MEMBER"} }; }
Source:
public String createToken(User user) { START if (!Boolean.TRUE.equals(user.isActive())) { END throw new PasswordResetTokenCreationException(); } deleteTokenIfExists(user); return addPasswordResetToken(user); } ```User.isActive()``` should return a boolean instead of Boolean since UserMetadata states that active is required.

Target:
public String createToken(User user) { if (!user.isActive()) { throw new PasswordResetTokenCreationException(); } deleteTokenIfExists(user); return addPasswordResetToken(user); }
Source:
private URI createEntitiesResponseUri() { START return ServletUriComponentsBuilder.fromCurrentRequest().build().toUri(); END } Test data shows encoding issues. Possibly using ```.build(true)``` helps here (might have side effects)?

Target:
private URI createEntitiesResponseUri() { return createEntitiesResponseUri(null); }
Source:
public static void setDefaultLookupAttributes(EntityType entityType, int lookupAttributeIndex) { Attribute ownIdAttr = entityType.getOwnIdAttribute(); if (ownIdAttr != null && ownIdAttr.isVisible()) { ownIdAttr.setLookupAttributeIndex(lookupAttributeIndex); lookupAttributeIndex++; } Attribute ownLabelAttr = entityType.getOwnLabelAttribute(); if (ownLabelAttr != null && ownIdAttr != null && !ownIdAttr.getName().equals(ownLabelAttr.getName())) { ownLabelAttr.setLookupAttributeIndex(lookupAttributeIndex); START lookupAttributeIndex++; END } } Sonar reports an error on this line: - Remove this useless assignment to local variable "lookupAttributeIndex"

Target:
public static void setDefaultLookupAttributes(EntityType entityType, int lookupAttributeIndex) { Attribute ownIdAttr = entityType.getOwnIdAttribute(); if (ownIdAttr != null && ownIdAttr.isVisible()) { ownIdAttr.setLookupAttributeIndex(lookupAttributeIndex); lookupAttributeIndex++; } Attribute ownLabelAttr = entityType.getOwnLabelAttribute(); if (ownLabelAttr != null && ownIdAttr != null && !ownIdAttr.getName().equals(ownLabelAttr.getName())) { ownLabelAttr.setLookupAttributeIndex(lookupAttributeIndex); } }
Source:
START protected void parsePackagesSheet( END Repository<Entity> repo, IntermediateParseResults intermediateResults) { if (repo == null) return; // Collect packages int rowIndex = 1; for (Entity packageEntity : resolvePackages(repo)) { rowIndex++; parseSinglePackage(intermediateResults, rowIndex, packageEntity); } } IntelliJ tells me this can be private 🤔 What gives?

Target:
private void parsePackagesSheet( Repository<Entity> repo, IntermediateParseResults intermediateResults) { if (repo == null) return; // Collect packages int rowIndex = 1; for (Entity packageEntity : resolvePackages(repo)) { rowIndex++; parseSinglePackage(intermediateResults, rowIndex, packageEntity); } }
Source:
public static CopyState create(@Nullable Package targetPackage, Progress progress) { return new AutoValue_CopyState( targetPackage, progress, newArrayList(), START newHashMap(), END newHashMap(), newHashMap(), newHashMap(), newHashMap()); } new ArrayList<>();

Target:
public static CopyState create(@Nullable Package targetPackage, Progress progress) { return new CopyState(targetPackage, progress); }
Source:
public static CopyState create(@Nullable Package targetPackage, Progress progress) { return new AutoValue_CopyState( targetPackage, progress, START new ArrayList<>(), END new HashMap<>(), new HashMap<>(), new HashMap<>(), new HashMap<>(), new HashMap<>()); } Autovalue generates immutable classes, so you should use ```ImmutableList``` and ```ImmutableMap``` here to prevent manipulation of the Lists/Maps via the getters. I suspect that you are mutating this class and actually need a normal POJO instead of a immutable class.

Target:
public static CopyState create(@Nullable Package targetPackage, Progress progress) { return new CopyState(targetPackage, progress); }
Source:
private List<String> getExcludedAttrs() { List<String> attrs = new ArrayList<>(); START return attrs; END } This will throw redundancy warnings in IntelliJ

Target:
private List<String> getExcludedAttrs() { return new ArrayList<>(); }
Source:
public void testHasSheetTrue() { Sheet sheet = mock(Sheet.class); when(workbook.getSheet("test")).thenReturn(sheet); START assertEquals(true, excelWriter.hasSheet("test")); END } ```suggestion assertTrue(excelWriter.hasSheet("test")); ```

Target:
public void testHasSheetTrue() { Sheet sheet = mock(Sheet.class); when(workbook.getSheet("test")).thenReturn(sheet); assertTrue(excelWriter.hasSheet("test")); }
Source:
private static String getEnumOptions(Attribute attr) { START return attr.getEnumOptions() != null ? StringUtils.join(attr.getEnumOptions(), ",") : ""; END } Use Java 8 String.join instead of a third party library

Target:
private static String getEnumOptions(Attribute attr) { return attr.getEnumOptions() != null ? String.join(",", attr.getEnumOptions()) : ""; }
Source:
public void failed(Exception ex) { JOB_EXECUTION_LOG.error("Failed. " + ex.getMessage(), ex); jobExecution.setEndDate(Instant.now()); jobExecution.setStatus(FAILED); START jobExecution.setProgressMessage(ex.getLocalizedMessage()); END sendEmail( jobExecution.getFailureEmail(), jobExecution.getType() + " job failed.", jobExecution.getLog()); update(); JobExecutionContext.unset(); } I think this: - should be in a separate PR with GitHub issue - needs a unit test

Target:
public void failed(Exception ex) { JOB_EXECUTION_LOG.error("Failed. " + ex.getMessage(), ex); jobExecution.setEndDate(Instant.now()); jobExecution.setStatus(FAILED); jobExecution.setProgressMessage(ex.getMessage()); sendEmail( jobExecution.getFailureEmail(), jobExecution.getType() + " job failed.", jobExecution.getLog()); update(); JobExecutionContext.unset(); }
Source:
public static Path getAppDataRoot() { if (APP_DATA_ROOT == null) { START throw new RuntimeException("Missing required application data root"); END } return APP_DATA_ROOT; } ![MAJOR](https://sonarsource.github.io/sonar-github/severity-major.png 'Severity: MAJOR') Define and throw a dedicated exception instead of using a generic one. [![rule](https://sonarsource.github.io/sonar-github/rule.png)](https://sonarcloud.io/coding_rules#rule_key=squid%3AS00112)

Target:
public static Path getAppDataRoot() { if (APP_DATA_ROOT == null) { throw new IllegalStateException("Missing required application data root"); } return APP_DATA_ROOT; }
Source:
public String init(Model model) { model.addAttribute("users", this.pluginUserManagerService.getAllUsers()); START if (!model.containsAttribute(VIEW_STATE)) model.addAttribute(VIEW_STATE, "users"); END return "view-usermanager"; } Add curly braces

Target:
public String init(Model model) { model.addAttribute("users", this.pluginUserManagerService.getAllUsers()); if (!model.containsAttribute(VIEW_STATE)) { model.addAttribute(VIEW_STATE, "users"); } return "view-usermanager"; }
Source:
protected Object getResourceAttributeValue(Attribute attr, Entity sourceEntity) { if (attr.getName().equals(GENERALIZED_INHERITANCE.getAttributeName())) { return getGeneralizedInheritance(sourceEntity); } String sourceName = CGDAttributeName.getCgdName(attr.getName()); if (sourceName == null) START throw new IllegalArgumentException(String.format("%s not present in CGD data", attr.getName())); END return sourceEntity.get(sourceName); } This occurs if the CGD resource does not contain the expected attributes, probably "something went wrong" is okay in this case.

Target:
protected Object getResourceAttributeValue(Attribute attr, Entity sourceEntity) { if (attr.getName().equals(GENERALIZED_INHERITANCE.getAttributeName())) { return getGeneralizedInheritance(sourceEntity); } String sourceName = CGDAttributeName.getCgdName(attr.getName()); if (sourceName == null) { throw new IllegalArgumentException(String.format("%s not present in CGD data", attr.getName())); } return sourceEntity.get(sourceName); }
Source:
public void create(@PathVariable("entityTypeId") String entityTypeId, @RequestBody Map<String, Object> entityMap, HttpServletResponse response) { if (entityMap == null) { START throw new MissingValueException("entity", "body"); END } createInternal(entityTypeId, entityMap, response); } Cannot happen. @RequestBody is required by default. Remove check.

Target:
public void create(@PathVariable("entityTypeId") String entityTypeId, @RequestBody Map<String, Object> entityMap, HttpServletResponse response) { createInternal(entityTypeId, entityMap, response); }
Source:
private static LocalDate convertDate(Attribute attr, String valueAsString) { try { return parseLocalDate(valueAsString); } START catch (java.time.format.DateTimeParseException e) END { throw new DateParseException(attr, valueAsString); } } fix imports

Target:
private static LocalDate convertDate(Attribute attr, String valueAsString) { try { return parseLocalDate(valueAsString); } catch (DateTimeParseException e) { throw new DateParseException(attr, valueAsString); } }
Source:
private boolean evaluateExpressionOnEntity(String expression, Entity entity) { if (expression == null) { return true; } else { Object value; try { value = jsMagmaScriptEvaluator.eval(expression, entity); } catch (ScriptExecutionException see) { START return false; END } return value != null ? Boolean.valueOf(value.toString()) : false; } } Null expression evaluates to true, errored exception evaluates to false, I think I'd throw it up

Target:
private boolean evaluateExpressionOnEntity(String expression, Entity entity) { if (expression == null) { return true; } else { Object value = jsMagmaScriptEvaluator.eval(expression, entity); return value != null ? Boolean.valueOf(value.toString()) : false; } }
Source:
public Model handleUnknownCatalogException(UnknownCatalogException e) { START LOG.warn(e.getMessage(), e); END return new LinkedHashModel(); } Why WARN for FAIR and INFO for other unknown entities?

Target:
public Model handleUnknownCatalogException(UnknownCatalogException e) { LOG.info(e.getMessage(), e); return new LinkedHashModel(); }
Source:
public MetaDataService metaDataService() { START return mock(MetaDataService.class, RETURNS_DEEP_STUBS); END } What's a deep stub and why do I need one?

Target:
public MetaDataService metaDataService() { return mock(MetaDataService.class); }