auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected Supplier<?> putSupplier(Map<String,String> map, int key) { return (()-> { try { lock.lock(); map.put("key" + key, "value" + key); } catch (Exception e) { this.putSupplier(map, key); } finally { try { lock.unlock(); } catch (Exception e) } return null; }); }

Target:
Wouldn't this be an infinite loop? Seems risky to just infinitely try again. I'd recommend doing: ```java lock.lock(); try { return map.put("key" + key, "value" + key); } finally { lock.unlock(); } ``` This is what the JavaDoc recommends. Also, if you return the result of `map.put`, then you don't need the extra `return null;` at the bottom.
Source:
public Credentials convert(String source) { String data[] = source.split(","); return new Credentials(data[0], data[1]); }

Target:
Typically we would put Array designators "[]" on the type, not the variable.
Source:
public void whenConsumeWithJsonb_thenGetPerson() { String url = BASE_URL + API_PERSON + "/1"; String result = RestConsumer.consumeWithJsonb(url); Person person = JsonbBuilder.create().fromJson(result, Person.class); assertEquals(person.getId(), 1); assertEquals(person.getUsername(), "normanlewis"); assertEquals(person.getEmail(), "normanlewis@email.com"); }

Target:
Switch the order of the arguments. assertEquals(expected, actual) assertEquals(1, person.getId()); assertEquals("normanlewis", person.getUsername()); assertEquals("normanlewis@email.com", person.getEmail());
Source:
public void whenSwitchingOnOperationSquareMe_thenWillReturnSquare() { var me = 4; var operation = "squareMe"; var result = switch (operation) { case "doubleMe" -> { yield me * 2; } case "squareMe" -> { yield me * me; } default -> me; }; assertEquals(result, 16); }

Target:
```suggestion assertEquals(16, result); ```
Source:
@Override protected Application provideApplication() { return new GuiceApplicationBuilder().build(); }

Target:
Usually `@Override` is on the line before the function
Source:
public void traverseList() { // Start traversing from the head Node currentNode = head; if (head != null) { do { System.out.print(currentNode.value + " "); currentNode = currentNode.nextNode; } while (currentNode != head); } }

Target:
Avoid calls to System.out... and use a proper logger.
Source:
public void resetPrintHistory() { for (Vertex vertex : graph) { Iterator it = vertex.getEdges() .entrySet() .iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry) it.next(); ((Edge) pair.getValue()).setPrinted(false); } } }

Target:
Couldn't we use a typed Iterator here so that we don't have to do the casting inside the loop?
Source:
public String getSuccess(HttpServletRequest request) { java.util.Map<String, ?> inputFlashMap = RequestContextUtils.getInputFlashMap(request); if (inputFlashMap != null) { Poem poem = (Poem) inputFlashMap.get("poem"); return "success"; } else { return "redirect:/poem/submit"; } }

Target:
Couldn't we just import java.util.Map so that we don't have to fully qualify it here?
Source:
public void someUnitTest() { assertTrue(this::doSomething); }

Target:
This seems needlessly complex. You're using a boolean supplier to `assertTrue`. Why not just call `doSomething()` directly?
Source:
private void discardEntity(HttpResponse httpResponse, Materializer materializer) { final HttpMessage.DiscardedEntity discarded = httpResponse.discardEntityBytes(materializer); discarded.completionStage() .whenComplete((done, ex) -> log.info("Entity discarded completely!")); }

Target:
Do we need the `discarded` temp variable ? Can we not just call fluently from `httpResponse.discardEntityBytes(...)`?
Source:
private boolean isCounterUpdateRequired(NotificationCache nCache) { if (new Date().getTime() - nCache.getLastCounterUpdate().getTime() > COUNTER_UPDATE_INTERVAL_IN_MS) { return true; } else { return false; } }

Target:
Yes, I will change it.
Source:
public void testLoadingDefaultPropertiesFile() throws IOException { reader.loadDefaultPropertyFile(DEFAULT_PROPERTIES_FILE, topologyProperties); assertNotNull(topologyProperties); assertFalse(topologyProperties.isEmpty()); for (final Map.Entry<Object, Object> e : topologyProperties.entrySet()) { assertNotNull(e.getKey()); } }

Target:
What is the idea behind checking whether all the keys in the map are not null? This applies to all tests here...
Source:
public void loadProvidedPropertyFile(String fileName, Properties topologyProperties) throws IOException { File file = new File(fileName); FileInputStream fileInput = new FileInputStream(file); topologyProperties.load(fileInput); fileInput.close(); }

Target:
Instead of creating a File object you can use another FileInputStream constructor that accepts file name.
Source:
private List<Revision> getRevisions(String cloudId, String representationName) throws MCSException { Representation representation = sourceRecordServiceClient.getRepresentation(cloudId, representationName); return representation.getRevisions(); }

Target:
no need to create representation variable
Source:
private List<CloudIdAndTimestampResponse> intersectCloudIdAndTimestampResponsesBasedOnCloudId(List<CloudIdAndTimestampResponse> dereferenceCloudIdAndTimestampResponseList, List<CloudIdAndTimestampResponse> publishedCloudIdAndTimestampResponseList) { List<CloudIdAndTimestampResponse> intesectCloudIds = new ArrayList<>(); for (CloudIdAndTimestampResponse dereferenceCloudIdAndTimestamp : dereferenceCloudIdAndTimestampResponseList) { String dereferenceCloudId = dereferenceCloudIdAndTimestamp.getCloudId(); for (CloudIdAndTimestampResponse publishedCloudIdAndTimestamp : publishedCloudIdAndTimestampResponseList) { String publishCloudId = publishedCloudIdAndTimestamp.getCloudId(); if (dereferenceCloudId.equals(publishCloudId)) { intesectCloudIds.add(dereferenceCloudIdAndTimestamp); } } } return intesectCloudIds; }

Target:
No need to create a variable when it's used once.
Source:
public static MediaType detectMediaType(InputStream inputStream) throws IOException { if (!inputStream.markSupported()) throw new UnsupportedOperationException("InputStream marking support is required!"); Detector detector = new AutoDetectParser().getDetector(); return detector.detect(inputStream, new Metadata()); }

Target:
You can skip storing detector in a variable and call return new AutoDetectParser().getDetector().detect(inputStream, new Metadata());
Source:
private void createProviderIdIfNotExists(UISClient uisClient, String providerId) throws CloudException { try { uisClient.getDataProvider(providerId); LOGGER.info("A provider already existed " + providerId); } catch (Exception e) { DataProviderProperties dataProviderProperties = new DataProviderProperties(); uisClient.createProvider(providerId, dataProviderProperties); LOGGER.info("A new provider is created " + providerId); } }

Target:
Is it really needed to log information like this? In my opinion it's not that useful information to log it on info level.
Source:
public JedisPool(final GenericObjectPoolConfig poolConfig, final URI uri, final int timeout, final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) { this(poolConfig, uri, timeout, timeout); }

Target:
It is not clear to me why you are not passing the SSL context to the constructor. *(even of the test pass in my environment, it looks odd to me..)
Source:
public void clientIdmultipleConnection() { Jedis client2 = new Jedis(hnp.getHost(), hnp.getPort(), 500); client2.auth("foobared"); client2.clientSetname("fancy_jedis_another_name"); long clientId1 = client.clientId(); long clientId2 = client2.clientId(); ///client-id is monotonically increasing Assert.assertTrue(clientId1 < clientId2); client2.close(); }

Target:
```suggestion assertTrue(clientId1 < clientId2); ```
Source:
public StreamConsumersInfo(Map<String,Object> map) { if (map!= null && map.size()>0) { consumerInfo = map; name = (String) map.get(NAME); idle = (long) map.get(IDLE); pending = (long) map.get(PENDING); } else throw new IllegalArgumentException(); }

Target:
If we are throwing runtime exception anyway when map is null isn't it better to just let it throw NullPointerException?
Source:
public JedisSentinelPool(String masterName, Set<String> sentinels, final GenericObjectPoolConfig poolConfig, final int timeout, final int soTimeout, final String password, final int database, final Boolean isRedisSslEnabled) { this(masterName, sentinels, poolConfig, timeout, soTimeout, password, database, null, isRedisSslEnabled); }

Target:
Don't you think there's a need to add a constructor with `final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier`
Source:
public JedisClusterInfoCache(final GenericObjectPoolConfig poolConfig, int timeout) { this(poolConfig, timeout, timeout, null, null, false, null, null, null, null); }

Target:
This won't not be required if following constructor is kept.
Source:
public void useWithoutConnecting() { jedis.auth("foobared"); Jedis jedis = new Jedis("localhost"); jedis.dbSize(); }

Target:
I think this is by accident. Could you revert it, or could you explain why this change is necessary?
Source:
int count() { if (params.containsKey(COUNT)) { return params.get(COUNT).getInt(); } else { return SCAN_COUNT_DEFAULT.getInt(); } }

Target:
It should return null when not set by user.
Source:
public static boolean isClusterCompliantMatchPattern(String matchPattern) { String tag = extractHashTag(matchPattern, true, true); if (tag != null && !tag.isEmpty() && matchPattern.startsWith(tag)) { return matchPattern.substring(tag.length()).equals("*"); } else { return false; } }

Target:
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.
Source:
int count() { if (params.containsKey(COUNT)) { return params.get(COUNT).getInt(); } else { return 0; } }

Target:
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.
Source:
public void zrevrangeByScoreWithScores(final byte[] key, final double max, final double min) { sendCommand(ZREVRANGEBYSCORE, key, toByteArray(min), toByteArray(max), WITHSCORES.raw); }

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

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

Target:
parameter sequence swapped: max, min is correct.
Source:
public Long del(final String key) { return new JedisClusterCommand<Long>(connectionHandler, timeout, maxRedirections) { @Override public Long execute(Jedis connection) { return connection.del(key); } }.run(key); }

Target:
This guys weren't marked as `@Deprecated` but I believe there is no problem to delete it since `JedisCommands` marked it as `@Deprecated`. :+1:
Source:
public static void removeSlots() throws InterruptedException { String[] nodes = node1.clusterNodes().split("\n"); String node1Id = nodes[0].split(" ")[0]; node1.clusterReset(Reset.SOFT); node2.clusterReset(Reset.SOFT); }

Target:
We can remove unused local variables nodes and node1Id.
Source:
public String set(final byte[] key, final byte[] value) { return new JedisClusterCommand<String>(connectionHandler, timeout, maxRedirections) { @Override public String execute(Jedis connection) { return connection.set(key, value); } }.runBinary(key); }

Target:
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?
Source:
public byte[] echo(final byte[] arg) { return new JedisClusterCommand<byte[]>(connectionHandler, timeout, maxRedirections) { @Override public byte[] execute(Jedis connection) { return connection.echo(arg); } }.runBinary(null); }

Target:
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?
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); } }.runBinary(null); }

Target:
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.
Source:
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(key); }

Target:
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?
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); } }.run(1, key); }

Target:
I think .run(key) is more faster than this if we keep JedisClusterCommand.run(String or byte[]).
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); } }.run(1, key); }

Target:
I think .run(key) is more faster than this if we keep JedisClusterCommand.run(String or byte[]).
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); } }.run(1, key); }

Target:
I think .run(key) is more faster than this if we keep JedisClusterCommand.run(String or byte[]).
Source:
public ScanResult(byte[] cursor, List<T> results) { this.cursor = SafeEncoder.encode(cursor); this.results = results; }

Target:
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 ?
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); Jedis jedis = jp.getResource(); discoverClusterNodesAndSlots(jedis); jp.returnResource(jedis); } }

Target:
We should probably add a try & finally block, to return the resource always, even in case of a RuntimeException
Source:
private File createWindowsGitSSH(File key, String user) throws IOException { File ssh = createTempFile("ssh", ".bat"); File sshexe = getSSHExecutable(); 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; }

Target:
No trailing white space on lines.
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, Iterables.transform(branches, (Branch from) -> Util.fixNull(from.getName()))); } s.append(')'); return s.toString(); }

Target:
Or even simpler: ```java Iterables.transform(branches, from -> Util.fixNull(from.getName()))); ```
Source:
public void clean() throws GitException, InterruptedException { reset(true); String cmd = "-fdx"; launchCommand("clean", cmd); }

Target:
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)`?
Source:
public <T> T withRepository(RepositoryCallback<T> callable) throws IOException, InterruptedException { Repository repo = getRepository(); try { return callable.invoke(repo, Jenkins.MasterComputer.localChannel); } finally { repo.close(); } }

Target:
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?)
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); } catch (IOException e) { throw new GitException(e); } return oidList; }

Target:
NIT: multi-catch - (surely you can move the parent to 1.625 if it is not already?)
Source:
public Revision(ObjectId sha1, Collection<Branch> branches) { if (sha1 == null) throw new NullPointerException("sha1 can't be null"); this.sha1 = sha1; this.branches = branches; }

Target:
throw IllegalArgumentException
Source:
public void fetch(String remoteName, RefSpec refspec) throws GitException, InterruptedException { fetch(remoteName, refspec); }

Target:
infinite self invocation ?
Source:
protected BatchDeleteClientsRequest getValidRequest() throws Exception { return BatchDeleteClientsRequest.builder() .clientIdentification(ClientIdentification.builder() .clientId("14pnUs") .build()) .clientIdentification(ClientIdentification.builder() .clientId("qECLyr") .build()) .build(); }

Target:
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.
Source:
protected String detect( InputStream inputStream, Metadata metadata ) { try { // we never care about the stream here, but close it anyway IoUtil.closeQuietly(inputStream); 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; } }

Target:
I would move this inside a `finally` block in the same method
Source:
private void batchWriteDocuments(List<String> keys, BackupDocumentWriter contentWriter) { final NodeKey metadataKey = repositoryCache.getRepositoryMetadataDocumentKey(); for (String key : keys) { if (key == null) break; if (!key.equals(metadataKey.toString())) { SchematicEntry entry = documentStore.get(key); if (entry != null) { writeToContentArea(entry, contentWriter); } } } }

Target:
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.
Source:
public boolean lockForWriting( List<String> locks ) { TransactionsHolder.requireActiveTransaction(); if (locks.isEmpty()) { return false; } return runWithConnection(connection -> statements.lockForWriting(connection, locks), true); }

Target:
Should this `if` block be before the `requireActiveTransaction()` call?
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 : return ((DateTime) value).getMilliseconds(); } return value; }

Target:
There is no `default` case here. What about longs or binaries or other `PropertyType`s?
Source:
public void afterEach() throws Exception { try { stopRepository(); } catch (Exception e) { } finally { FileUtil.delete("target/persistent_repository"); } }

Target:
should this exception be left to bubble up and fail the test ? If `afterEach` fails it means the repository was not shutdown properly
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); return nodeTypes.allowsNameSiblings(primaryType, mixinTypes); }

Target:
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.
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; } } return false; }

Target:
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?
Source:
protected synchronized void executeFunctionsUponCompletion() { if (uponCompletionFunctions != null) { executeFunctions(uponCompletionFunctions); uponCompletionFunctions = null; } }

Target:
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?
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); this.listeners.add(adapter); }

Target:
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).
Source:
final void cleanLocks() throws RepositoryException { lockManager.cleanLocks(session); for (String token : new ArrayList<String>(lockTokens.keySet())) { removeLockToken(token); } }

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

Target:
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); ```
Source:
public void close() { if (this.runThread.compareAndSet(true, false)) { try { cursor.signalConsumers(); this.stopLatch.await(); // System.out.println("Ring buffer garbage collection thread has terminated"); } catch (InterruptedException e) { // do nothing ... } } }

Target:
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.
Source:
private void incrementEventQueueStatistic( ChangeSet changeSet ) { changesLock.lock(); 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(); } }

Target:
I'm curious why this change was made. The `repositoryStatistics` should be thread safe, so the lock should only be needed to update `changesReceivedAndDispatched`.
Source:
public void shutdown() { if (enableEvents) { monitoringTask.cancel(true); } }

Target:
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.
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; } if (content != null ? !content.getUUID().equals(record.content.getUUID()) : record.content != null) { return false; } return true; }

Target:
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?)
Source:
protected Segment getSegment( WorkspaceCache cache ) { ChildReference self = parentReferenceToSelf(cache); if (self == null) { self = parentReferenceToSelf(cache); } return self.getSegment(); }

Target:
can this ever happen ? Won't `parentReferenceToSelf(cache)` throw a `NodeNotFoundInParentException` always if a reference is not found ?
Source:
private SimplePrincipal(String name) { this.name = name; }

Target:
When can the `name` be null? If not possible, then add an assertion.
Source:
public int hashCode() { int hash = 5; hash = 79 * hash + (this.path != null ? this.path.hashCode() : 0); return hash; }

Target:
Why not use `return this.path.hashCode()`?
Source:
public final void addContextData( String key, String value ) { this.context = context.with(key, value); this.cache.addContextData(key, value); }

Target:
Woa, I'm not sure I like this being public.
Source:
public final ExecutionContext context() { return context; }

Target:
Does this still need to be public?
Source:
public AbstractJcrNode addAclNode( String relPath, String primaryNodeTypeName ) throws ItemExistsException, PathNotFoundException, NoSuchNodeTypeException, LockException, VersionException, ConstraintViolationException, RepositoryException { checkSession(); return addNode(relPath, primaryNodeTypeName, null, true); }

Target:
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?
Source:
public AccessControlManagerImpl(JcrSession session) { this.session = session; this.privileges = new Privileges(session); this.defaultACL = JcrAccessControlList.defaultAcl(this); }

Target:
This should not be public. I'd suggest protected. Plus, remove the not-helpful JavaDoc.
Source:
protected InternalSecurityContext( String username ) { this.username = username; //given user is only known principal for this context principals.add(SimplePrincipal.newInstance(username)); }

Target:
Actually, I'd recommend initializing `principals` using `Collections.singletonList(SimplePrincipal.newInstance(username))`. The resulting list is immutable and an efficient implementation.
Source:
public AccessControlPolicy[] getEffectivePolicies(String path) throws PathNotFoundException, AccessDeniedException, RepositoryException { if (session.isReadOnly()) { throw new AccessDeniedException("Session is read only"); } AccessControlPolicy[] policies = getPolicies(path); if (policies.length == 0) { return new AccessControlPolicy[]{(AccessControlPolicy) this.getApplicablePolicies(path).next()}; } return policies; }

Target:
Can you explain why this check is used? Why is a read-only session not able to get any of the effective policies?
Source:
public final boolean isReadOnly() { return this.isReadOnly; }

Target:
Once the `isReadOnly` field is removed, change this method to ``` return this.cache.isReadOnly(); ```
Source:
private void addHandle(JcrSessionHandle handle) { synchronized (handles) { handles.add(handle); } }

Target:
You do not need the `synchronized` block.
Source:
public boolean equals(Object other) { if (other == null) { return false; } if (other == this) { return true; } if (!(other instanceof JcrManagedConnectionFactory)) { return false; } return this == (JcrManagedConnectionFactory) other; }

Target:
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; }
Source:
public JcrRepositoryHandle(JcrResourceAdapter ra, JcrManagedConnectionFactory mcf, ConnectionManager cm) throws ResourceException { System.out.println("Resource adaptor: " + ra); this.mcf = mcf; this.cm = cm; try { this.repository = ra.getRepository(); } catch (Exception e) { throw new ResourceException(e); } }

Target:
Oops. Please remove this `System.out.println` call.
Source:
private boolean isAbsolutePath(String uri) { return !(uri.startsWith("jndi") | uri.startsWith("file")); }

Target:
This is a bitwise OR ... shouldn't this be a boolean OR (`||`)?
Source:
public void stop() { if (engine != null) { engine.shutdown(); } }

Target:
Should this also set `engine` to null in a `finally` block? If not, I'm not sure why it checks for null (line 177).
Source:
protected Repository getRepository() throws ResourceException { if (this.repository == null) { this.repository = deployRepository(repositoryURL); } return this.repository; }

Target:
This method probably should be `synchronized` so that multiple concurrent calls will not stomp on each other.
Source:
public void start() throws Exception { doStart(); }

Target:
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.
Source:
public Set<String> getRepositoryKeys() { checkRunning(); final Lock lock = this.lock.readLock(); try { lock.lock(); return new HashSet<String>(repositories.keySet()); } finally { lock.unlock(); } }

Target:
Same issue with the change in visibility of this method as with `JcrRepository.start()`.
Source:
public InfinispanRepository( BaseInfinispanSource source, BasicCacheContainer cacheContainer ) { 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(); }

Target:
cacheContainer param doesn't seem to be used in the ctr (the source is always used to get the cache container)
Source:
public RoleBasedProjectNamingStrategy(boolean forceExistingJobs) { this.forceExistingJobs = forceExistingJobs; Jenkins.getInstance().setProjectNamingStrategy(this); }

Target:
Looks wrong, AFAIR projectnaming strategy is set by core and plugins shouldn't do manual assignment
Source:
private boolean hasGlobalPermission(String userName, Permission permission, RoleBasedAuthorizationStrategy rbas) { LOGGER.debug("Check the global permission of the user " + userName + " " + rbas.getGrantedRoles(RoleBasedAuthorizationStrategy.GLOBAL)); return hasPermission(userName, permission, rbas.getGrantedRoles(RoleBasedAuthorizationStrategy.GLOBAL)); }

Target:
Slow logging
Source:
static Object[][] roleNameProvider() { return new Object[][] { new Object[] {"bbmri_eric", "Manager", "bbmri_eric_MANAGER"}, new Object[] {"bbmri_eric", "Manager", "bbmri_eric_MANAGER"}, new Object[] {"patientenfederatie-nederland", "Member", "patientenfederatie-nederland_MEMBER"} }; }

Target:
In both the old and new situation this line seems duplicated
Source:
public String createToken(User user) { if (!Boolean.TRUE.equals(user.isActive())) { throw new PasswordResetTokenCreationException(); } deleteTokenIfExists(user); return addPasswordResetToken(user); }

Target:
```User.isActive()``` should return a boolean instead of Boolean since UserMetadata states that active is required.
Source:
private URI createEntitiesResponseUri() { return ServletUriComponentsBuilder.fromCurrentRequest().build().toUri(); }

Target:
Test data shows encoding issues. Possibly using ```.build(true)``` helps here (might have side effects)?
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); lookupAttributeIndex++; } }

Target:
Sonar reports an error on this line: - Remove this useless assignment to local variable "lookupAttributeIndex"
Source:
protected 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); } }

Target:
IntelliJ tells me this can be private 🤔 What gives?
Source:
public static CopyState create(@Nullable Package targetPackage, Progress progress) { return new AutoValue_CopyState( targetPackage, progress, newArrayList(), newHashMap(), newHashMap(), newHashMap(), newHashMap(), newHashMap()); }

Target:
new ArrayList<>();
Source:
public static CopyState create(@Nullable Package targetPackage, Progress progress) { return new AutoValue_CopyState( targetPackage, progress, new ArrayList<>(), new HashMap<>(), new HashMap<>(), new HashMap<>(), new HashMap<>(), new HashMap<>()); }

Target:
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.
Source:
private List<String> getExcludedAttrs() { List<String> attrs = new ArrayList<>(); return attrs; }

Target:
This will throw redundancy warnings in IntelliJ
Source:
public void testHasSheetTrue() { Sheet sheet = mock(Sheet.class); when(workbook.getSheet("test")).thenReturn(sheet); assertEquals(true, excelWriter.hasSheet("test")); }

Target:
```suggestion assertTrue(excelWriter.hasSheet("test")); ```
Source:
private static String getEnumOptions(Attribute attr) { return attr.getEnumOptions() != null ? StringUtils.join(attr.getEnumOptions(), ",") : ""; }

Target:
Use Java 8 String.join instead of a third party library
Source:
public void failed(Exception ex) { JOB_EXECUTION_LOG.error("Failed. " + ex.getMessage(), ex); jobExecution.setEndDate(Instant.now()); jobExecution.setStatus(FAILED); jobExecution.setProgressMessage(ex.getLocalizedMessage()); sendEmail( jobExecution.getFailureEmail(), jobExecution.getType() + " job failed.", jobExecution.getLog()); update(); JobExecutionContext.unset(); }

Target:
I think this: - should be in a separate PR with GitHub issue - needs a unit test
Source:
public static Path getAppDataRoot() { if (APP_DATA_ROOT == null) { throw new RuntimeException("Missing required application data root"); } return APP_DATA_ROOT; }

Target:
![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)
Source:
public String init(Model model) { model.addAttribute("users", this.pluginUserManagerService.getAllUsers()); if (!model.containsAttribute(VIEW_STATE)) model.addAttribute(VIEW_STATE, "users"); return "view-usermanager"; }

Target:
Add curly braces
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) throw new IllegalArgumentException(String.format("%s not present in CGD data", attr.getName())); return sourceEntity.get(sourceName); }

Target:
This occurs if the CGD resource does not contain the expected attributes, probably "something went wrong" is okay in this case.
Source:
public void create(@PathVariable("entityTypeId") String entityTypeId, @RequestBody Map<String, Object> entityMap, HttpServletResponse response) { if (entityMap == null) { throw new MissingValueException("entity", "body"); } createInternal(entityTypeId, entityMap, response); }

Target:
Cannot happen. @RequestBody is required by default. Remove check.
Source:
private static LocalDate convertDate(Attribute attr, String valueAsString) { try { return parseLocalDate(valueAsString); } catch (java.time.format.DateTimeParseException e) { throw new DateParseException(attr, valueAsString); } }

Target:
fix imports
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) { return false; } return value != null ? Boolean.valueOf(value.toString()) : false; } }

Target:
Null expression evaluates to true, errored exception evaluates to false, I think I'd throw it up
Source:
public Model handleUnknownCatalogException(UnknownCatalogException e) { LOG.warn(e.getMessage(), e); return new LinkedHashModel(); }

Target:
Why WARN for FAIR and INFO for other unknown entities?
Source:
public MetaDataService metaDataService() { return mock(MetaDataService.class, RETURNS_DEEP_STUBS); }

Target:
What's a deep stub and why do I need one?
Source:
private void addFreemarkerVariables(Map<String, Object> freemarkerVariables) { }

Target:
Overriding is quiet hard now that the method is private ;-)
Source:
private boolean isAttributeAvailable(String attributeName, Iterable<String> attributeNames) { if (attributeName == null || Iterables.contains(attributeNames, attributeName)) { return true; } return false; }

Target:
Can be simplified to ```java return attributeName == null || Iterables.contains(attributeNames, attributeName); ```
Source:
public AmazonBucketIngester(ImportServiceFactory importServiceFactory, FileRepositoryCollectionFactory fileRepositoryCollectionFactory, FileMetaFactory fileMetaFactory, FileStore fileStore, AmazonBucketClient amazonBucketClient) { this.importServiceFactory = requireNonNull(importServiceFactory); this.fileRepositoryCollectionFactory = requireNonNull(fileRepositoryCollectionFactory); this.fileMetaFactory = requireNonNull(fileMetaFactory); this.fileStore = fileStore; this.amazonBucketClient = amazonBucketClient; }

Target:
requireNonNull?
Source:
public void setDefaultValues() { super.setDefaultValues(); setType(SORTA_MATCH_JOB_TYPE); }

Target:
Can we get rid of setDefaultValues? Or move setType to factory class.
Source:
public double getValueByName(String row, String column) { if (!inited) init(); Integer rowIndex = rowMap.get(row); Integer columnIndex = columnMap.get(column); if (rowIndex == null) throw new MolgenisDataException("Unknown row name [" + row + "]"); if (rowIndex == null) throw new MolgenisDataException("Unknown column name [" + column + "]"); return getValueByIndex(rowIndex, columnIndex); }

Target:
Shouldnt this be columnIndex == null?
Source:
private DoubleMatrix getMatrixByEntityTypeId(String entityId) { DoubleMatrix matrix = null; Entity entity = dataService.findOneById(MatrixMetadata.PACKAGE + "_" + MatrixMetadata.SIMPLE_NAME, entityId); if (entity != null) { return getMatrix(entityId, entity); } else { throw new MolgenisDataException("Unknown Matrix Metadata EntityID [" + entityId + "]"); } }

Target:
Variable is never used
Source:
public StandardBuilder ignoreFailure() { ignoreFailure = true; return this; }

Target:
or just call `ignoreFailure(true)` for consistency?
Source:
public void notifyVideoEnd() // Must match Javascript interface method of VideoEnabledWebChromeClient { Log.d("___", "GOT IT"); // This code is not executed in the UI thread, so we must force that to happen new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { if (videoEnabledWebChromeClient != null) { videoEnabledWebChromeClient.onHideCustomView(); } } }); }

Target:
Debug logging accidentally left in?
Source:
public MavenExecutionRequest setPom( File pom ) { this.pom = pom; if ( this.pom != null && this.pom.getParentFile() != null ) { this.setBaseDirectory( this.pom.getParentFile() ); } return this; }

Target:
IIRC this will go wrong. There are a couple of plugins that want to rewrite the pom (maven-shade-plugin, flatten-maven-plugin). This pom will be in the target directory, so it can be cleaned up. However, the basedir should stay the same.
Source:
private void visit( Properties properties ) { if ( properties != null ) { for ( Map.Entry<Object, Object> entry : properties.entrySet() ) { Object v = entry.getValue(); if ( v instanceof String ) { String value = (String) v; String inter = interpolate( value ); if ( value != inter && Objects.nonNull( inter ) ) { entry.setValue( inter ); } } } } }

Target:
`nonNull` is used in Lambda with Method Reference and not like this. That's the reason why `Objects.nonNull` was introduced in Java 1.8. Simple is better. Therefore `!= null`.
Source:
protected ArtifactRepository getLocalRepository() throws Exception { ArtifactRepositoryLayout repoLayout = lookup( ArtifactRepositoryLayout.class, "legacy" ); ArtifactRepository r = repositorySystem.createArtifactRepository( "local", "file://" + getLocalRepositoryPath().getAbsolutePath(), repoLayout, null, null ); return r; }

Target:
This is wrong. You cannot construct a URI like that. Please do: `toPath().toUri().toASCIIString()`.
Source:
public boolean equals( Object obj ) { if ( this == obj ) { return true; } if ( ( obj == null ) || !( obj instanceof FileModelSource ) ) { return false; } FileModelSource other = ( FileModelSource ) obj; return getFile().equals( other.getFile() ); }

Target:
Compare with null not necessary since `null instanceof FileModelSource` is `false`
Source:
public MetadataResolutionResult addError( Exception e ) { if ( exceptions == null ) { exceptions = initList( exceptions ); } exceptions.add( e ); return this; }

Target:
Please remove that whitespace
Source:
void setOnTop() { System.out.println("set on top!!"); setAlwaysOnTop(false); repaint(); setAlwaysOnTop(true); repaint(); }

Target:
Why is this necessay? it is called every 20ms! Why is it not sufficient to set it on top once?
Source:
public void storeData(String data, String filepath) throws AREAsapiException { this.storeData(data, filepath, RES_TYPE.DATA, Charsets.UTF_8); }

Target:
so only the UTF-8 version will be supported? what about the version with the given charset name?
Source:
private String parseCodeName() { if (this.major == 10) { MACOS_VERSIONS_PROPERTIES = "macos.versions.properties"; Properties verProps = FileUtil.readPropertiesFromFilename(MACOS_VERSIONS_PROPERTIES); String version_number = this.major + "." + this.minor; String version_name = verProps.getProperty(version_number); return version_name; } LOG.warn("Unable to parse version {}.{} to a codename.", this.major, this.minor); return ""; }

Target:
Sorry I wasn't more clear here. Need to keep the `oshi` to prevent conflicting with any other possible properties files on the class path. But define the string `final` up above instead of changing it here.
Source:
private void finishAllThreads(Collection<Future<Void>> results) throws Throwable { for (final Future<Void> result : results) { try { result.get(); } catch (final ExecutionException e) { throw e.getCause(); } } }

Target:
Now that this is not a part of the original method anymore, it makes even more sense to not unwrap the original exception in order to not lose the whole trace leading not only to the executor thread but also to this `finishAllThreads` method. I think my original attempt to make the stack trace shorter has the potential of reducing clarity rather than improving it (in other words, I did a stupid thing originally).
Source:
public static Double get(String key, double def) { String value = configuration.getProperty(key); return value == null ? def : ParseUtil.parseDoubleOrDefault(value, def); }

Target:
Why are we returning the boxed Double?
Source:
static String findOuiByMacAddressIfPossible(String mac) { return vmMacAddressOUI.entrySet().stream() .filter(entry -> mac.startsWith(entry.getKey())) .map(Map.Entry::getValue) .collect(Collectors.joining()); }

Target:
Can you make this public or private?
Source:
public HWDiskStore() { name = ""; model = ""; serial = ""; size = 0L; reads = 0L; readBytes = 0L; writes = 0L; writeBytes = 0L; currentQueueLength = 0L; transferTime = 0L; partitions = new HWPartition[0]; timeStamp = 0L; }

Target:
this is probably unnecessary as it's the default initialization.
Source:
private Boolean listElementStarts(List<String> aList, String charSeq) { for (String match : aList) { if (match.startsWith(match)){ return Boolean.TRUE; } } return Boolean.FALSE; }

Target:
Is this line (`match.startsWith(match)`) correct? You aren't ever checking `charSeq`.
Source:
private List<CustomAction> customActions() { List<CustomAction> actions = new LinkedList<>(); CustomAction pos = new CustomAction("org.finra.datagenerator", "transform", Transform.class); actions.add(pos); pos = new CustomAction("org.finra.datagenerator", "positive", Assign.class); actions.add(pos); return actions; }

Target:
Why do we have to touch the positive engine?
Source:
protected InputStream doGetInputStream() throws Exception { if (this.stat == null) { throw new FileSystemException("vfs.provider/read-not-file.error", getName()); } final byte[] data = (this.stat.getDataLength() == 0) ? new byte[0] : framework.getData().forPath(this.path); return new ByteArrayInputStream(data); }

Target:
Extra ()'s are superfluous.
Source:
private static File getCanonicalFile(final File file) { try { return file.getCanonicalFile(); } catch (final IOException e) { return file.getAbsoluteFile(); } }

Target:
There is no need to hide methods in tests, it just makes reusing code more difficult when using discovery features in IDEs like CTRL-space for method names.