auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected final Object handleMissingEntryOnRead(TopologyAffectedCommand command) { // If we have the entry in context it means that we are read owners, so we don't have to check the topology CacheTopology cacheTopology = stateTransferManager.getCacheTopology(); int currentTopologyId = cacheTopology.getTopologyId(); int cmdTopology = command.getTopologyId(); if (cmdTopology < currentTopologyId) { START return (Object) UnsuccessfulResponse.INSTANCE; END } else { // If cmdTopology > currentTopologyId: the topology of this node is outdated // TODO: This situation won't happen as soon as we'll implement 4-phase topology change in ISPN-5021 // (then, Tx.readCH and T(x+1).readCH will always have common subset of nodes so we'll be safe here // to return UnsuccessfulResponse // If cmdTopology == currentTopologyId: between STI and BDI this node had different topology, therefore // the entry was not loaded into context. Retry again locally. throw new OutdatedTopologyException(cmdTopology); } } unnecessary cast

Target:
protected final Object handleMissingEntryOnRead(TopologyAffectedCommand command) { // If we have the entry in context it means that we are read owners, so we don't have to check the topology CacheTopology cacheTopology = stateTransferManager.getCacheTopology(); int currentTopologyId = cacheTopology.getTopologyId(); int cmdTopology = command.getTopologyId(); if (cmdTopology < currentTopologyId) { return UnsuccessfulResponse.INSTANCE; } else { // If cmdTopology > currentTopologyId: the topology of this node is outdated // TODO: This situation won't happen as soon as we'll implement 4-phase topology change in ISPN-5021 // (then, Tx.readCH and T(x+1).readCH will always have common subset of nodes so we'll be safe here // to return UnsuccessfulResponse // If cmdTopology == currentTopologyId: between STI and BDI this node had different topology, therefore // the entry was not loaded into context. Retry again locally. throw new OutdatedTopologyException(cmdTopology); } }
Source:
public void testThrowingNullPointerExceptionOnNullGetWithClass() throws Exception { //when START cache.get(null, (Class<Object>) null); END } Shouldn't that be `Class<?>`

Target:
public void testThrowingNullPointerExceptionOnNullGetWithClass() throws Exception { //when cache.get(null, (Class<?>) null); }
Source:
protected boolean addHandler(InvocationComposeHandler composeHandler) { synchronized (this) { if (frozen) { return false; } handlers[tail & mask] = composeHandler; if (((tail + 1 - head) & mask) == 0) { frozen = true; START return false; END } tail++; return true; } } You've managed to add the handler, why are you returning `false`?

Target:
protected boolean addHandler(InvocationComposeHandler composeHandler) { synchronized (this) { if (frozen) { return false; } handlers[tail & mask] = composeHandler; tail++; if (((tail - head) & mask) == 0) { frozen = true; } return true; } }
Source:
String readString() { byte mark = readByte(); switch(mark) { case 0: return ""; // empty string case 1: // small ascii int size = readByte(); String str = new String(bytes, 0, pos, size); pos += size; return str; case 2: // large string return readUTF(); START case 3: END default: throw new RuntimeException("Unknown marker(String). mark=" + mark); } } Case 3 is redundant

Target:
String readString() { byte mark = readByte(); switch(mark) { case 0: return ""; // empty string case 1: // small ascii int size = readByte(); String str = new String(bytes, 0, pos, size); pos += size; return str; case 2: // large string return readUTF(); default: throw new RuntimeException("Unknown marker(String). mark=" + mark); } }
Source:
private static int checkForeignIdLimit(int id, AdvancedExternalizer<?> ext) { if (id < 0) throw log.foreignExternalizerUsingNegativeId(ext, id); START return id; END } As no transformations are happening to id, why not make `checkForeignIdLimit` void

Target:
private static void checkForeignIdLimit(int id, AdvancedExternalizer<?> ext) { if (id < 0) throw log.foreignExternalizerUsingNegativeId(ext, id); }
Source:
BiConsumer<ObjectOutput, Object> findWriter(Object obj) { Class<?> clazz = obj.getClass(); AdvancedExternalizer internalExt = internalExts.get(clazz); if (internalExt != null) return (out, object) -> { writeInternalClean(object, internalExt, out); }; AdvancedExternalizer externalExt = externalExts.get(clazz); if (externalExt != null) return (out, object) -> { START writeExternalClean(object, externalExt, out); END }; return null; } Can be reduced to a single line lambda

Target:
BiConsumer<ObjectOutput, Object> findWriter(Object obj) { Class<?> clazz = obj.getClass(); AdvancedExternalizer internalExt = internalExts.get(clazz); if (internalExt != null) return (out, object) -> { writeInternalClean(object, internalExt, out); }; AdvancedExternalizer externalExt = externalExts.get(clazz); if (externalExt != null) return (out, object) -> writeExternalClean(object, externalExt, out); return null; }
Source:
public long skip(long n) { if (n > 0) { long skip = bytes.length - pos; START if (skip < pos) END skip = n; pos += skip; return skip; } else { int idx = Math.min(bytes.length, pos); long skip = idx + n; pos = (int) (skip + offset); return skip; } } shouldn't be `skip > n`?

Target:
public long skip(long n) { if (n > 0) { long skip = bytes.length - pos; if (skip > n) skip = n; pos += skip; return skip; } else { int idx = Math.min(bytes.length, pos); long skip = idx + n; pos = (int) (skip + offset); return skip; } }
Source:
public void clear() { START Arrays.fill(keys, null); END count = 0; } shouldn't the `values` be fill with `null`? (to help GC)

Target:
public void clear() { Arrays.fill(keys, null); Arrays.fill(values, null); count = 0; }
Source:
void beforeSplit() { conflictKey = new MagicKey(cache(2), cache(0)); START System.out.println(advancedCache(0).getCacheConfiguration().clustering().partitionHandling().getMergePolicy()); END cache(0).put(conflictKey, "BEFORE SPLIT"); } System.out

Target:
void beforeSplit() { conflictKey = new MagicKey(cache(2), cache(0)); cache(0).put(conflictKey, "BEFORE SPLIT"); }
Source:
public MergePolicyCustomTest() { START super(); END this.mergePolicy = ((preferredEntry, otherEntries) -> TestInternalCacheEntryFactory.create(conflictKey, "Custom")); } redundant

Target:
public MergePolicyCustomTest() { this.mergePolicy = ((preferredEntry, otherEntries) -> TestInternalCacheEntryFactory.create(conflictKey, "Custom")); }
Source:
public ConsistentHash getReadConsistentHash() { switch (phase) { START case CONFLICT_RESOLUTION: END assert pendingCH != null; assert unionCH != null; return currentCH; case NO_REBALANCE: assert pendingCH == null; assert unionCH == null; return currentCH; case READ_OLD_WRITE_ALL: assert pendingCH != null; assert unionCH != null; return currentCH; case READ_ALL_WRITE_ALL: assert pendingCH != null; return unionCH; case READ_NEW_WRITE_ALL: assert unionCH != null; return pendingCH; } return currentCH; } Just move the label before READ_OLD_WRITE_ALL, it has the same properties.

Target:
public ConsistentHash getReadConsistentHash() { switch (phase) { case NO_REBALANCE: assert pendingCH == null; assert unionCH == null; return currentCH; case CONFLICT_RESOLUTION: case READ_OLD_WRITE_ALL: assert pendingCH != null; assert unionCH != null; return currentCH; case READ_ALL_WRITE_ALL: assert pendingCH != null; return unionCH; case READ_NEW_WRITE_ALL: assert unionCH != null; return pendingCH; } return currentCH; }
Source:
private Stream<Map<Address, CacheEntry<K, V>>> getConflicts(LocalizedCacheTopology topology) { if (stateConsumer.isStateTransferInProgress()) throw log.getConflictsStateTransferInProgress(cacheName); if (!streamInProgress.compareAndSet(false, true)) throw log.getConflictsAlreadyInProgress(); try { return StreamSupport .stream(new ReplicaSpliterator(topology), false) .filter(filterConsistentEntries()); } finally { START streamInProgress.compareAndSet(true, false); END } } You're returning the stream itself; no terminal operation was called so far on the stream, so it's still in progress, isn't it?

Target:
private Stream<Map<Address, CacheEntry<K, V>>> getConflicts(LocalizedCacheTopology topology) { if (stateConsumer.isStateTransferInProgress()) throw log.getConflictsStateTransferInProgress(cacheName); if (!streamInProgress.compareAndSet(false, true)) throw log.getConflictsAlreadyInProgress(); return StreamSupport .stream(new ReplicaSpliterator(topology), false) .filter(filterConsistentEntries()); }
Source:
private String sanitizedCacheName() { String cacheFileName = ctx.getCache().getName().replaceAll("[^a-zA-Z0-9-_\\.]", "_"); START return cacheFileName; END } `cacheFileName` variable is redundant

Target:
private String sanitizedCacheName() { return ctx.getCache().getName().replaceAll("[^a-zA-Z0-9-_\\.]", "_"); }
Source:
public void generateValidMoves() { START validMoves = new String[operations]; END for (int i = 0; i < operations; i++) { validMoves[i] = "v_" + i; } print("Valid moves ready"); } `operations` is initialized in the constructor, you could also initialize `validMoves` the same way.

Target:
private String[] generateValidMoves() { String[] validMoves = new String[operations]; for (int i = 0; i < operations; i++) { validMoves[i] = "v_" + i; } print("Valid moves ready"); return validMoves; }
Source:
START private static Class<Map> getMapClass(String className) { END return Util.<Map>loadClass(className, Map.class.getClassLoader()); } I think this should return a `Class<? extends Map>`.

Target:
private static Class<? extends Map> getMapClass(String className) { return Util.<Map>loadClass(className, Map.class.getClassLoader()); }
Source:
public ClusterEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException { return new ClusterEvent(input.readObject(), input.readObject(), input.readObject(), START (Metadata)input.readObject(),(Type) MarshallUtil.unmarshallEnum(input, Type::valueOf), END (Address)input.readObject(), (GlobalTransaction)input.readObject(), input.readBoolean()); } unneeded cast :)

Target:
public ClusterEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException { return new ClusterEvent(input.readObject(), input.readObject(), input.readObject(), (Metadata)input.readObject(),MarshallUtil.unmarshallEnum(input, Type::valueOf), (Address)input.readObject(), (GlobalTransaction)input.readObject(), input.readBoolean()); }
Source:
public TransactionInfo readObject(ObjectInput input) throws IOException, ClassNotFoundException { GlobalTransaction globalTransaction = (GlobalTransaction) input.readObject(); int topologyId = input.readInt(); WriteCommand[] modifications = MarshallUtil.unmarshallArray(input, WriteCommand[]::new); START Set<Object> lockedKeys = (Set<Object>) MarshallUtil.unmarshallCollection(input, HashSet::new); END return new TransactionInfo(globalTransaction, topologyId, modifications, lockedKeys); } unneeded cast

Target:
public TransactionInfo readObject(ObjectInput input) throws IOException, ClassNotFoundException { GlobalTransaction globalTransaction = (GlobalTransaction) input.readObject(); int topologyId = input.readInt(); WriteCommand[] modifications = MarshallUtil.unmarshallArray(input, WriteCommand[]::new); Set<Object> lockedKeys = MarshallUtil.unmarshallCollection(input, HashSet::new); return new TransactionInfo(globalTransaction, topologyId, modifications, lockedKeys); }
Source:
public void testGetCacheNames() { START Boolean passed = StreamSupport.stream(cacheManager.getCacheNames().spliterator(), true) END .anyMatch(n -> getCacheNamesTestCacheName.equalsIgnoreCase(n)); assertTrue(getCacheNamesTestCacheName + " cache name was not found in list retrieved from CacheManager", passed); } `boolean` should work

Target:
public void testGetCacheNames() { boolean passed = StreamSupport.stream(cacheManager.getCacheNames().spliterator(), true) .anyMatch(n -> getCacheNamesTestCacheName.equalsIgnoreCase(n)); assertTrue(getCacheNamesTestCacheName + " cache name was not found in list retrieved from CacheManager", passed); }
Source:
public void writeTo(ObjectOutput output) throws IOException { output.writeObject(key); START output.writeInt(topologyId); END output.writeLong(Flag.copyWithoutRemotableFlags(getFlagsBitSet())); } the `topologyId` is written/read in the `ReplicableCommandExternalizer`. no need to write/read it again.

Target:
public void writeTo(ObjectOutput output) throws IOException { output.writeObject(key); output.writeLong(Flag.copyWithoutRemotableFlags(getFlagsBitSet())); }
Source:
public boolean lock(K... keys) { START return cacheImplementation.lock(Arrays.asList(keys), flags, null); END } The methods with ClassLoader are package-private, therefore non-public API - can't you remove the parameter altogether?

Target:
public boolean lock(K... keys) { return cacheImplementation.lock(Arrays.asList(keys), flags); }
Source:
public ClusteredCacheQueryImpl(Query luceneQuery, SearchIntegrator searchFactory, ExecutorService asyncExecutor, AdvancedCache<?, ?> cache, KeyTransformationHandler keyTransformationHandler, Class<?>... classes) { super(luceneQuery, searchFactory, cache, keyTransformationHandler, classes); this.asyncExecutor = asyncExecutor; this.hSearchQuery = searchFactory.createHSQuery().luceneQuery(luceneQuery) .targetedEntities(Arrays.asList(classes)); START this.marshaller = ComponentRegistryUtils.getComponent(cache, END StreamingMarshaller.class); } not related to your changes, but it looks like this field is not used anymore.

Target:
public ClusteredCacheQueryImpl(Query luceneQuery, SearchIntegrator searchFactory, ExecutorService asyncExecutor, AdvancedCache<?, ?> cache, KeyTransformationHandler keyTransformationHandler, Class<?>... classes) { super(luceneQuery, searchFactory, cache, keyTransformationHandler, classes); this.asyncExecutor = asyncExecutor; this.hSearchQuery = searchFactory.createHSQuery().luceneQuery(luceneQuery) .targetedEntities(Arrays.asList(classes)); }
Source:
public InputStream lookupFileStrict(URI uri, ClassLoader cl) throws FileNotFoundException { //in case we have not only file schema, but jar:file schema too, we have to get rid off all schemas int startIndex = uri.toString().lastIndexOf(':'); String fileName = uri.toString().substring(startIndex + 1); START InputStream in = cl.getResourceAsStream(fileName); END if(in != null){ return in; } else { return null; } } You could just `return cl.getResourceAsStream(fileName);`

Target:
public InputStream lookupFileStrict(URI uri, ClassLoader cl) throws FileNotFoundException { //in case we don't have only file schema, but jar:file schema too, we have to get rid of all schemas int startIndex = uri.toString().lastIndexOf(':'); String fileName = uri.toString().substring(startIndex + 1); return cl.getResourceAsStream(fileName); }
Source:
START default void waitForTransactionData(int expectedTopologyId, long timeout, TimeUnit unit) throws InterruptedException, TimeoutException { END try { CompletableFuture<Void> transactionDataFuture = transactionDataFuture(expectedTopologyId); if (transactionDataFuture != null) transactionDataFuture.get(timeout, unit); } catch (ExecutionException e) { throw new CacheException(e.getCause()); } } This isn't an SPI, so I'm not sure it's worth putting the implementation in the interface.

Target:
default void waitForTransactionData(int expectedTopologyId, long timeout, TimeUnit unit) throws InterruptedException, TimeoutException { try { CompletableFuture<Void> transactionDataFuture = transactionDataFuture(expectedTopologyId); transactionDataFuture.get(timeout, unit); } catch (ExecutionException e) { throw new CacheException(e.getCause()); } }
Source:
private ClientAuth requireClientAuth(SslConfiguration sslConfig) { START return sslConfig.enabled() ? ClientAuth.REQUIRE : ClientAuth.NONE; END } This should be `sslConfig.requireClientAuth()` ;) TL;DR After turning on [SSL Debug](https://blogs.oracle.com/java-platform-group/entry/diagnosing_tls_ssl_and_https) it turned out that server challenges client for certificate (which was not associated with the client keystore). This suggested that either client cert file is wrong or server challenge is wrong. I was lucky with the latter :)

Target:
private ClientAuth requireClientAuth(SslConfiguration sslConfig) { return sslConfig.requireClientAuth() ? ClientAuth.REQUIRE : ClientAuth.NONE; }
Source:
public int compareTo(Address o) { START return 0; END } Hrmm, maybe this return 0 only if `o == this`? Otherwise maybe `o.compareTo(this)` to ensure symmetry ?

Target:
public int compareTo(Address o) { return o == this ? 0 : -1; }
Source:
START protected void errorOccurred(ErrorContext context) { END if (operationFailedHandler == null) { throw new IllegalStateException("Uninitialised error handler"); } Throwable throwable = context.getThrowable(); if (throwable instanceof LockObtainFailedException) { List<LuceneWork> failingOperations = context.getFailingOperations(); LuceneWork operationAtFault = context.getOperationAtFault(); List<LuceneWork> failed = new ArrayList<>(failingOperations); failed.add(operationAtFault); operationFailedHandler.lockObtainFailed(failed); } } Should this log a debug as well? An error sounds important :)

Target:
protected void errorOccurred(ErrorContext context) { if (operationFailedHandler != null) { Throwable throwable = context.getThrowable(); if (throwable instanceof LockObtainFailedException) { List<LuceneWork> failingOperations = context.getFailingOperations(); LuceneWork operationAtFault = context.getOperationAtFault(); List<LuceneWork> failed = new ArrayList<>(failingOperations); failed.add(operationAtFault); operationFailedHandler.lockObtainFailed(failed); } } }
Source:
public synchronized void stop(final StopContext context) { START router.ifPresent(r -> r.stop()); END } should be able to pass `r::stop`.

Target:
public synchronized void stop(final StopContext context) { if (router != null) { router.stop(); } }
Source:
public SaslConfigurationBuilder forCredentials(String login, String password) { START this.security().authentication().callbackHandler(new SimpleLoginHandler(login, password, Constants.DEFAULT_TEST_REALM)); END return this; } `Constants` is a way too generic name, have a look at https://github.com/infinispan/infinispan/blob/master/server/integration/endpoint/src/main/java/org/infinispan/server/endpoint/Constants.java#L57 to see what happens when you name a class like that :) You can leave the constants here, and just make them public.

Target:
public SaslConfigurationBuilder forCredentials(String login, String password) { this.security().authentication().callbackHandler(new SimpleLoginHandler(login, password, DEFAULT_TEST_REALM)); return this; }
Source:
public String getPort() { START return nettyPort.orElse(address.getPort()).toString(); END } Can't you use just `address.getPort()`?

Target:
public Integer getPort() { return nettyPort.orElse(address.getPort()); }
Source:
public void stop() { netty.ifPresent(NettyJaxrsServer::stop); netty = Optional.empty(); START server = Optional.empty(); END } Don't you need `server.get().stop()` as well?

Target:
public void stop() { if(netty != null) { netty.stop(); } netty = null; server = null; }
Source:
public MultiTenantRouter(MultiTenantRouterConfiguration routerConfiguration) { this.routerConfiguration = routerConfiguration; routerConfiguration.getHotRodRouterConfiguration().ifPresent(config -> routers.add(new HotRodRouter(config))); START routerConfiguration.getRestRouterConfiguration().ifPresent(config -> routers.add(new RestRouter(config))); END } I think it would be simpler to store each router in a separate field.

Target:
public MultiTenantRouter(MultiTenantRouterConfiguration routerConfiguration) { this.routerConfiguration = routerConfiguration; if(routerConfiguration.getHotRodRouterConfiguration() != null) { routers.add(new HotRodRouter(routerConfiguration.getHotRodRouterConfiguration())); } if(routerConfiguration.getRestRouterConfiguration() != null) { routers.add(new RestRouter(routerConfiguration.getRestRouterConfiguration())); } }
Source:
public void testWeldStandaloneInitialisation() throws Exception { //given WeldContainer weld = new Weld().initialize(); CDITestingBean testedBean = weld.instance().select(CDITestingBean.class).get(); //when testedBean.putValueInCache("test", "abcd"); String retrievedValue = testedBean.getValueFromCache("test"); //then assertEquals(retrievedValue, "abcd"); //cleanup START weld.shutdown(); END } Shouldn't this be in a `finally` block?

Target:
public void testWeldStandaloneInitialisation() throws Exception { WeldContainer weld = null; try { //given weld = new Weld().initialize(); CDITestingBean testedBean = weld.instance().select(CDITestingBean.class).get(); //when testedBean.putValueInCache("test", "abcd"); String retrievedValue = testedBean.getValueFromCache("test"); //then assertEquals(retrievedValue, "abcd"); } finally { if(weld != null) { //cleanup weld.shutdown(); } } }
Source:
START protected boolean interceptorMatches(AsyncInterceptor interceptor, END Class<? extends AsyncInterceptor> clazz) { Class<? extends AsyncInterceptor> interceptorType = interceptor.getClass(); return clazz == interceptorType; } can be private

Target:
private boolean interceptorMatches(AsyncInterceptor interceptor, Class<? extends AsyncInterceptor> clazz) { Class<? extends AsyncInterceptor> interceptorType = interceptor.getClass(); return clazz == interceptorType; }
Source:
public CompletableFuture<Void> visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable { ctx.onReturn(writeSkewReturnHandler); START if (streamSummaryContainer.isEnabled() && ctx.isOriginLocal()) { END streamSummaryContainer.addPut(command.getKey(), isRemote(command.getKey())); } return ctx.continueInvocation(); } you could move the `if` before `ctx.onReturn()` and avoid invoking `ctx.continueInvocation()`

Target:
public CompletableFuture<Void> visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable { if (streamSummaryContainer.isEnabled() && ctx.isOriginLocal()) { streamSummaryContainer.addPut(command.getKey(), isRemote(command.getKey())); } return ctx.onReturn(writeSkewReturnHandler); }
Source:
private boolean isSniEnabled() { START return sniDomains.keySet().size() > 0; END } return !sniDomains.isEmpty();

Target:
private boolean isSniEnabled() { return !sniDomains.isEmpty(); }
Source:
public void serialize(XMLExtendedStreamWriter writer, RemoteStoreConfiguration configuration) throws XMLStreamException { START AttributeSet attributes = configuration.attributes(); END writer.writeStartElement(Element.REMOTE_STORE); writeCommonStoreSubAttributes(writer, configuration); writeAsyncExecutor(writer, configuration.asyncExecutorFactory()); writeConnectionPool(writer, configuration.connectionPool()); writeServers(writer, configuration.servers()); writeCommonStoreElements(writer, configuration); writer.writeEndElement(); } did you forget to serialize the attributes?

Target:
public void serialize(XMLExtendedStreamWriter writer, RemoteStoreConfiguration configuration) throws XMLStreamException { writer.writeStartElement(Element.REMOTE_STORE); configuration.attributes().write(writer); writeCommonStoreSubAttributes(writer, configuration); writeAsyncExecutor(writer, configuration.asyncExecutorFactory()); writeConnectionPool(writer, configuration.connectionPool()); writeServers(writer, configuration.servers()); writeCommonStoreElements(writer, configuration); writer.writeEndElement(); }
Source:
public void serialize(XMLExtendedStreamWriter writer, JdbcStringBasedStoreConfiguration configuration) throws XMLStreamException { writer.writeStartElement(Element.STRING_KEYED_JDBC_STORE); writeJdbcStoreAttributes(writer, configuration); START configuration.attributes().write(writer, JdbcStringBasedStoreConfiguration.KEY2STRING_MAPPER, Attribute.KEY_TO_STRING_MAPPER); END writeCommonStoreSubAttributes(writer, configuration); writeJDBCStoreTable(writer, Element.STRING_KEYED_TABLE, configuration.table()); writeJDBCStoreConnection(writer, configuration); writeCommonStoreElements(writer, configuration); writer.writeEndElement(); } `writeJdbcStoreAttributes` already writes this attribute.

Target:
public void serialize(XMLExtendedStreamWriter writer, JdbcStringBasedStoreConfiguration configuration) throws XMLStreamException { writer.writeStartElement(Element.STRING_KEYED_JDBC_STORE); writeJdbcStoreAttributes(writer, configuration); writeCommonStoreSubAttributes(writer, configuration); writeJDBCStoreTable(writer, Element.STRING_KEYED_TABLE, configuration.table()); writeJDBCStoreConnection(writer, configuration); writeCommonStoreElements(writer, configuration); writer.writeEndElement(); }
Source:
START public Builder autoPersist(boolean autoPersist) { END this.autoPersist = autoPersist; return this; } generics is missing

Target:
public Builder<T> autoPersist(boolean autoPersist) { this.autoPersist = autoPersist; return this; }
Source:
public String toString() { START return new String(b, CHARSET); END } I'm a little concern about this. wouldn't be better to cache the string too?

Target:
public String toString() { if (s == null) { s = new String(b, CHARSET); } return s; }
Source:
public VersionedCommitCommand() { START super(ByteString.emptyString()); END } Might as well use `null`, almost all commands use `super(null)` in the "CommandIdUniquenessTest constructor".

Target:
public VersionedCommitCommand() { super(null); }
Source:
public void testOnlyReduceTaskRun() throws Exception { ScriptingManager scriptingManager = getScriptingManager(manager(0)); Cache<String, String> cache = cache(0); loadData(cache, "/macbeth.txt"); loadScript(scriptingManager, "/wordCountReducer.js"); START CompletableFuture<Object> future = scriptingManager.runScript("wordCountReducer.js", new TaskContext().cache(cache)); END } Could you tell me which line throws `IllegalArgumentException`? Maybe we need do something with this `CompletableFuture` here?

Target:
public void testOnlyReduceTaskRun() throws Exception { ScriptingManager scriptingManager = getScriptingManager(manager(0)); Cache<String, String> cache = cache(0); loadData(cache, "/macbeth.txt"); loadScript(scriptingManager, "/wordCountReducer.js"); scriptingManager.runScript("wordCountReducer.js", new TaskContext().cache(cache)); }
Source:
public void grant(String roleName, String principalName) { START Set<String> roleSet = getClusterRoleMap().computeIfAbsent(principalName, n -> { return new HashSet<>(); }); END roleSet.add(roleName); clusterRoleMap.put(principalName, roleSet); } replace `{ return new HashSet<>(); }` with `new HashSet<>()` ?

Target:
public void grant(String roleName, String principalName) { Set<String> roleSet = getClusterRoleMap().computeIfAbsent(principalName, n -> new HashSet<>() ); roleSet.add(roleName); clusterRoleMap.put(principalName, roleSet); }
Source:
public void testTask() throws Exception { ScriptingManager scriptingManager = cacheManager.getGlobalComponentRegistry().getComponent(ScriptingManager.class); START ScriptingTest.loadScript(scriptingManager, TEST_SCRIPT); END String result = (String) taskManager.runTask(TEST_SCRIPT, new TaskContext().addParameter("a", "a")).get(); assertEquals("a", result); } Maybe move this method to a separate `ScriptingTests` class.

Target:
public void testTask() throws Exception { ScriptingManager scriptingManager = cacheManager.getGlobalComponentRegistry().getComponent(ScriptingManager.class); loadScript(scriptingManager, TEST_SCRIPT); String result = (String) taskManager.runTask(TEST_SCRIPT, new TaskContext().addParameter("a", "a")).get(); assertEquals("a", result); }
Source:
private TaskContext prepareContext() { START TaskContext context = new TaskContext(); END if (parameters != null) context.parameters(parameters); if (cache != null) context.cache(cache); Marshaller marshaller = componentRegistry.getComponent(Marshaller.class); if (marshaller != null) context.marshaller(marshaller); return context; } You can use `Optional.ofNullable(...).ifPresent(...) or flatMap` constructs here.

Target:
private TaskContext prepareContext() { TaskContext context = new TaskContext(); if (parameters.isPresent()) context.parameters(parameters.get()); if (cache != null) context.cache(cache); if (marshaller != null) context.marshaller(marshaller); return context; }
Source:
public T call() throws Exception { START ServerTaskRegistry taskRegistry = componentRegistry.getComponent(ServerTaskRegistry.class); END ServerTaskWrapper<T> task = taskRegistry.getTask(taskName); task.inject(prepareContext()); return task.run(); } I think the ServerTaskRegistry should not be obtained here, but it should be injected by the runner during construction. Also, a cache is optional paramater in the TaskContext and you should not rely on its presence here. Because of a current limitation in the DefaultExecutorService, it is not possible to have a distexec without a distributed cache, but @wburns is adding a new implementation which changes this.

Target:
public T call() throws Exception { ServerTaskWrapper<T> task = taskRegistry.getTask(taskName); task.inject(prepareContext()); return task.run(); }
Source:
public String getGroup(Object instance) { PrivilegedAction<Object> action = () -> invokeAccessibly(instance, method, Util.EMPTY_OBJECT_ARRAY); Object object = System.getSecurityManager() == null ? action.run() : AccessController.doPrivileged(action); START return String.class.cast(object); END } Instead of always invoking the lambda like that I'd rather do if (System.getSecurityManager() == null) { return String.class.cast(invokeAccessibly(instance, method, Util.EMPTY_OBJECT_ARRAY)); } else { ... // priv action }

Target:
public String getGroup(Object instance) { Object object; if (System.getSecurityManager() == null) { object = invokeAccessibly(instance, method, Util.EMPTY_OBJECT_ARRAY); } else { object = AccessController.doPrivileged((PrivilegedAction<Object>) () -> invokeAccessibly(instance, method, Util.EMPTY_OBJECT_ARRAY)); } return String.class.cast(object); }
Source:
protected void mergeCluster(String cacheName) { getLog().debugf("Merging cluster"); partition(0).merge(partition(1)); START TestingUtil.waitForRehashToComplete(caches(cacheName)); END getLog().debugf("Cluster merged"); } you can remove the `TestingUtil.` prefix and the import

Target:
protected void mergeCluster(String cacheName) { getLog().debugf("Merging cluster"); partition(0).merge(partition(1)); waitForRehashToComplete(caches(cacheName)); getLog().debugf("Cluster merged"); }
Source:
public void writeObject(ObjectOutput output, ScriptMetadata object) throws IOException { output.writeUTF(object.name); output.writeUTF(object.extension); output.writeUTF(object.mode.name()); writeSet(output, object.parameters); output.writeObject(object.language); START output.writeObject( object.role); END output.writeObject(object.reducer); output.writeObject(object.collator); output.writeObject(object.combiner); } Extra space.

Target:
public void writeObject(ObjectOutput output, ScriptMetadata object) throws IOException { output.writeUTF(object.name); output.writeUTF(object.extension); output.writeUTF(object.mode.name()); output.writeObject(object.parameters); output.writeObject(object.language); output.writeObject(object.role); output.writeObject(object.reducer); output.writeObject(object.collator); output.writeObject(object.combiner); }
Source:
protected boolean interceptorMatches(SequentialInterceptor interceptor, Class<? extends SequentialInterceptor> clazz) { Class<? extends SequentialInterceptor> interceptorType = interceptor.getClass(); START return clazz == interceptorType || clazz == interceptorType; END } duplicated condition.

Target:
protected boolean interceptorMatches(SequentialInterceptor interceptor, Class<? extends SequentialInterceptor> clazz) { Class<? extends SequentialInterceptor> interceptorType = interceptor.getClass(); return clazz == interceptorType; }
Source:
public void writeScopedState(ScopedPersistentState state) { File stateFile = getStateFile(state.getScope()); try (PrintWriter w = new PrintWriter(stateFile)) { state.forEach((key, value) -> { START w.printf("%s=%s%n", key, Util.unicodeEscapeString(value)); END }); } catch (IOException e) { throw log.failedWritingGlobalState(e, stateFile); } } I think the key should be escaped as well.

Target:
public void writeScopedState(ScopedPersistentState state) { File stateFile = getStateFile(state.getScope()); try (PrintWriter w = new PrintWriter(stateFile)) { state.forEach((key, value) -> { w.printf("%s=%s%n", Util.unicodeEscapeString(key), Util.unicodeEscapeString(value)); }); } catch (IOException e) { throw log.failedWritingGlobalState(e, stateFile); } }
Source:
public void forEach(IntConsumer action) { START if (action instanceof CacheAware) { END ((CacheAware) action).injectCache(registry.getComponent(Cache.class)); } createStream().forEach(action); } why not factor out this code ? It's repeated in quite a few places.

Target:
public void forEach(IntConsumer action) { injectCache(action); createStream().forEach(action); }
Source:
public void checkPermission(AuthorizationPermission perm) { START checkPermission(null, perm, Optional.empty()); END } I don't really like mixing `Optional` with old-style nullable parameters, so I'd rather use `null` for both. (Or `Optional` for both, of course.)

Target:
public void checkPermission(AuthorizationPermission perm) { checkPermission(null, perm, null); }
Source:
public void appendDelta(Delta d) { deltas.add(d); START if (uncommittedChanges instanceof AtomicHashMap) { END uncommittedChanges = (AtomicHashMap<K, ?>) d.merge(uncommittedChanges); } setChanged(true); } this condition is always true.

Target:
public void appendDelta(Delta d) { deltas.add(d); if (uncommittedChanges != null) { uncommittedChanges = (AtomicHashMap<K, ?>) d.merge(uncommittedChanges); } setChanged(true); }
Source:
public MVCCEntry wrapEntryForPut(InvocationContext ctx, Object key, InternalCacheEntry icEntry, boolean undeleteIfNeeded, FlagAffectedCommand cmd, boolean skipRead) { if (icEntry != null) { START throw new IllegalArgumentException("Only addMissingValue can handle external entries"); END } MVCCEntry mvccEntry = wrapEntryForWriting(ctx, key, Wrap.WRAP_ALL, skipRead, false); if (trace) { log.tracef("Wrap %s for put. Entry=%s", key, mvccEntry); } return mvccEntry; } wrong method name?

Target:
public MVCCEntry wrapEntryForPut(InvocationContext ctx, Object key, InternalCacheEntry icEntry, boolean undeleteIfNeeded, FlagAffectedCommand cmd, boolean skipRead) { if (icEntry != null) { throw new IllegalArgumentException("Only addMissingValue can handle external entries"); } return wrapEntryForWriting(ctx, key, Wrap.WRAP_ALL, skipRead, false); }
Source:
public static void attemptObtain(ObtainableLock lock) throws IOException { int attempts = 0; START while (lock.obtain()==false) { END //we could fail immediately, but being Infinispan a bit latency sensitive we give a bit of grace here if (attempts++>MAX_LOCK_ACQUIRE_MILLISECONDS) failLockAcquire(); if (Thread.currentThread().isInterrupted()) failLockAcquire(); try { Thread.sleep(1); } catch (InterruptedException e) { Thread.currentThread().interrupt(); failLockAcquire(); } } } I'll change it

Target:
public static void attemptObtain(ObtainableLock lock) throws IOException { int attempts = 0; while (!lock.obtain()) { //we could fail immediately, but being Infinispan a bit latency sensitive we give a bit of grace here if (attempts++ > MAX_LOCK_ACQUIRE_MILLISECONDS) failLockAcquire(); if (Thread.currentThread().isInterrupted()) failLockAcquire(); try { Thread.sleep(1); } catch (InterruptedException e) { Thread.currentThread().interrupt(); failLockAcquire(); } } }
Source:
public void testSimpleExpirationMaxIdle() throws Exception { for (int i = 0; i < SIZE; i++) { START cache.put("key-" + i, "value-" + i,-1, TimeUnit.MILLISECONDS, 1, TimeUnit.MILLISECONDS); END } timeService.advance(2); assertEquals(0, cache.size()); } I believe the problem should be addressed in the Metadata implementation. Negative time values should not be converted, so the given TimeUnit could be null and not result in an exception.

Target:
public void testSimpleExpirationMaxIdle() throws Exception { for (int i = 0; i < SIZE; i++) { cache.put("key-" + i, "value-" + i,-1, null, 1, TimeUnit.MILLISECONDS); } timeService.advance(2); assertEquals(0, cache.size()); }
Source:
public static void assertNotNullEntries(Collection<?> collection, String name) { Objects.requireNonNull(collection, () -> "Collection '" + name + "' must be non null."); Supplier<String> entrySupplier = () -> "Collection '" + name + "' contains null entry."; START collection.forEach((k) -> Objects.requireNonNull(k, entrySupplier)); END } Nitpick here, but parens aren't required around the k.

Target:
public static void assertNotNullEntries(Collection<?> collection, String name) { Objects.requireNonNull(collection, () -> "Collection '" + name + "' must be non null."); Supplier<String> entrySupplier = () -> "Collection '" + name + "' contains null entry."; collection.forEach(k -> Objects.requireNonNull(k, entrySupplier)); }
Source:
START public static Set<Flag> addFlag(Set<Flag> flags, Flag newFlag) { END if (flags == null) { return EnumSet.of(newFlag); } if (flags.contains(newFlag)) { return flags; } EnumSet<Flag> copy = EnumSet.copyOf(flags); copy.add(newFlag); return copy; } :+1: this is a lot nicer than before

Target:
public static Set<Flag> addFlag(Set<Flag> flags, Flag newFlag) { if (flags == null || flags.isEmpty()) { return EnumSet.of(newFlag); } if (flags.contains(newFlag)) { return flags; } EnumSet<Flag> copy = EnumSet.copyOf(flags); copy.add(newFlag); return copy; }
Source:
public void setParameters(int commandId, Object[] args) { // TODO: Check duplicated in all commands? A better solution is needed. if (commandId != COMMAND_ID) throw new IllegalStateException("Unsupported command id:" + commandId); int i = 0; globalTx = (GlobalTransaction) args[i++]; unlock = (Boolean) args[i++]; keys = (List<Object>) args[i++]; START flags = (EnumSet<Flag>) args[i]; END } This change seems unneeded, did you want to change the declared type of flags as well? Otherwise I could see someone possibly passing in the wrong set impl.

Target:
public void setParameters(int commandId, Object[] args) { // TODO: Check duplicated in all commands? A better solution is needed. if (commandId != COMMAND_ID) throw new IllegalStateException("Unsupported command id:" + commandId); int i = 0; globalTx = (GlobalTransaction) args[i++]; unlock = (Boolean) args[i++]; keys = (List<Object>) args[i++]; flags = (Set<Flag>) args[i]; }
Source:
public static Set<Flag> addFlags(Set<Flag> flags, Set<Flag> newFlags) { if (newFlags == null || newFlags.isEmpty()) { return flags; } START if (flags == null) { END return newFlags; } EnumSet<Flag> copy = EnumSet.copyOf(flags); copy.addAll(newFlags); return copy; } or flags.isEmpty?

Target:
public static Set<Flag> addFlags(Set<Flag> flags, Set<Flag> newFlags) { if (newFlags == null || newFlags.isEmpty()) { return flags; } if (flags == null || flags.isEmpty()) { return newFlags; } EnumSet<Flag> copy = EnumSet.copyOf(flags); copy.addAll(newFlags); return copy; }
Source:
public static <T> void forEach(T[] array, Consumer<T> consumer) { Objects.requireNonNull(array, "Array must be non-null."); final int size = array.length; if (size == 0) { return; } else if (size == 1) { consumer.accept(array[0]); return; } START for (int i = 0; i < size; ++i) { END consumer.accept(array[i]); } } I think only the for loop should be good enough - there's no allocation, and it will do the same `0 < size`, `1 < size` comparisons.

Target:
public static <T> void forEach(T[] array, Consumer<T> consumer) { final int size = Objects.requireNonNull(array, "Array must be non-null.").length; for (int i = 0; i < size; ++i) { consumer.accept(array[i]); } }
Source:
private void invoke(LockListener invoker) { LockState state = lockState; switch (state) { case WAITING: throw new IllegalStateException("WAITING is not a valid state to invoke the listener"); case ACQUIRED: case RELEASED: START invoker.onEvent(LockState.AVAILABLE); END break; default: invoker.onEvent(state); break; } } This looks weird to me, why shouldn't the listener receive the actual state?

Target:
private void invoke(LockListener invoker) { LockState state = lockState; switch (state) { case WAITING: throw new IllegalStateException("WAITING is not a valid state to invoke the listener"); case ACQUIRED: case RELEASED: invoker.onEvent(LockState.ACQUIRED); break; default: invoker.onEvent(state); break; } }
Source:
private boolean setReleased() { do { LockState state = lockState; switch (state) { case WAITING: case AVAILABLE: case ACQUIRED: START if (casState(state, LockState.RELEASED)) { END cleanup(); notifyListeners(); return true; } break; case TIMED_OUT: case DEADLOCKED: if (casState(state, LockState.RELEASED)) { cleanup(); return true; } break; default: return false; } } while (true); } Is it ok to go from WAITING straight to RELEASED?

Target:
private boolean setReleased() { do { LockState state = lockState; switch (state) { case WAITING: case ACQUIRED: if (casState(state, LockState.RELEASED)) { cleanup(); notifyListeners(); return true; } break; case TIMED_OUT: case DEADLOCKED: if (casState(state, LockState.RELEASED)) { cleanup(); return true; } break; default: return false; } } while (true); }
Source:
public void testGroupBy3() throws Exception { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .select("name") .groupBy("name") .orderBy("surname", SortOrder.ASC) .build(); START END q.list(); } What about doing aggregation in a filtered query? Would something conceptually similar to `SELECT name FROM person WHERE name.startsWith("a") GROUP BY name` work? It seems there is no test for it

Target:
public void testGroupBy3() throws Exception { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .select("name") .groupBy("name") .orderBy("surname") .build(); q.list(); }
Source:
public void update(Object[] srcRow, Object[] destRow) { Number value = (Number) srcRow[pos]; if (value != null) { Number sum = (Number) destRow[pos]; if (sum == null) { destRow[pos] = value; } else { START destRow[pos] = sum.intValue() + value.intValue(); //todo [anistor] this handles integers only! END } } } I would say we should use a long and double respectively.

Target:
public void update(Object[] srcRow, Object[] destRow) { Number value = (Number) srcRow[pos]; if (value != null) { Number sum = (Number) destRow[pos]; if (sum == null) { destRow[pos] = value; } else { destRow[pos] = add(value, sum); } } }
Source:
public ControllerThread(String controllerThreadName) { super(controllerThreadName); START readyList = new LinkedList<>(); END semaphore = new Semaphore(0); } I normally prefer ArrayDeque over LinkedList since we aren't adding/removing elements from the middle

Target:
public ControllerThread(String controllerThreadName) { super(controllerThreadName); semaphore = new Semaphore(0); }
Source:
START public static int writeUnsignedInt(byte[] bytes, int offset, int i) { END int localOffset = offset; while ((i & ~0x7F) != 0) { bytes[localOffset++] = (byte) ((i & 0x7f) | 0x80); i >>>= 7; } bytes[localOffset] = (byte) i; return localOffset + 1; } :+1: I am surprised we didn't have this before I wonder if returning the size used may be better, WDYT?

Target:
public static int writeUnsignedInt(byte[] bytes, int offset, int i) { int localOffset = offset; while ((i & ~0x7F) != 0) { bytes[localOffset++] = (byte) ((i & 0x7f) | 0x80); i >>>= 7; } bytes[localOffset++] = (byte) i; return localOffset - offset; }
Source:
protected boolean beforeInvoke() throws Exception { if (0 <= commandTopologyId && commandTopologyId < handler.stateTransferManager.getFirstTopologyAsMember()) { if (handler.isTraceEnabled()) { handler.getLog().tracef("Ignoring command sent before the local node was a member " + "(command topology id is %d)", commandTopologyId); } START response = CacheNotFoundResponse.INSTANCE; END return false; //skip invocation } return true; } I wonder if making this more explicit would be cleaner. What if the beforeInvoke method declaration was changed to return a Response. If that value was null it would be considered to continue running and if not null it would return that response? WDYT?

Target:
protected Response beforeInvoke() throws Exception { if (0 <= commandTopologyId && commandTopologyId < handler.stateTransferManager.getFirstTopologyAsMember()) { if (handler.isTraceEnabled()) { handler.getLog().tracef("Ignoring command sent before the local node was a member " + "(command topology id is %d)", commandTopologyId); } // Skip invocation return CacheNotFoundResponse.INSTANCE; } return null; }
Source:
public void start() { isPessimisticCache = cacheConfiguration.transaction().lockingMode() == LockingMode.PESSIMISTIC; useClusteredWriteSkewCheck = Configurations.isVersioningEnabled(cacheConfiguration); rollbackRpcOptions = createRpcOptionsFor2ndPhase(cacheConfiguration.transaction().syncRollbackPhase() START ); END commitRpcOptions = createRpcOptionsFor2ndPhase(cacheConfiguration.transaction().syncCommitPhase() ); } Line wrap is a bit weird here

Target:
public void start() { isPessimisticCache = cacheConfiguration.transaction().lockingMode() == LockingMode.PESSIMISTIC; useClusteredWriteSkewCheck = Configurations.isVersioningEnabled(cacheConfiguration); }
Source:
private void notifySync(Queue<CountDownLatch> latches) { if (latches == null) { return; } START while (true) { END CountDownLatch latch = latches.poll(); if (latch == null) { break; } latch.countDown(); } } This was the method I was talking about where concurrent writes for the same key, value would notify more than 1 caller at the same time. I wonder if it is okay if we just notify 1 latch and return?

Target:
private void notifySync(Queue<CountDownLatch> latches) { if (latches == null) { return; } CountDownLatch latch = latches.poll(); if (latch != null) { latch.countDown(); } }
Source:
START public void close() throws Exception { END } This shouldn't declare throws Exception.

Target:
public void close() { }
Source:
public V replace(K key, V value) { V v = delegate.replace(key, value); if (v != null) { START stats.incrementCacheHits(); END } else { stats.incrementCacheMisses(); } stats.incrementCachePuts(); return v; } It seems we aren't being very inconsistent with cache hits/misses on writes. The put methods don't increment these counters, is that correct? Is there some sort of unit test for the stats counters? I worry there may be overlap between this class and explicit increments in the JCache class itself. I would think this class would handle all the stats itself, or is there something else I am missing?

Target:
public V replace(K key, V value) { V v = delegate.replace(key, value); if (v != null) { stats.incrementCacheHits(); stats.incrementCachePuts(); } else { stats.incrementCacheMisses(); } return v; }
Source:
public void register(Member member) throws Exception { Search.getFullTextEntityManager(em).persist(member); START initNewMember(); END } 'em.persist(member);' should be enough, you only need to wrap the EntityManager when needing to access methods which are not exposed on the JPA API.

Target:
public void register(Member member) throws Exception { em.persist(member); initNewMember(); }
Source:
private boolean updateCacheTopology(String cacheName, CacheTopology cacheTopology, Address sender, LocalCacheStatus cacheStatus) { // Block if there is a status request in progress // The caller should have already acquired the cacheStatus monitor synchronized (runningCaches) { if (!sender.equals(transport.getCoordinator())) { log.debugf("Ignoring topology %d from old coordinator %s", cacheTopology.getTopologyId(), sender); return false; } else { log.debugf("Updating local topology for cache %s: %s", cacheName, cacheTopology); START cacheStatus.setCurrentTopology(cacheTopology); END } } return true; } is this change really needed?

Target:
private boolean updateCacheTopology(String cacheName, CacheTopology cacheTopology, Address sender, LocalCacheStatus cacheStatus) { // Block if there is a status request in progress // The caller should have already acquired the cacheStatus monitor synchronized (runningCaches) { if (!sender.equals(transport.getCoordinator())) { log.debugf("Ignoring topology %d from old coordinator %s", cacheTopology.getTopologyId(), sender); return false; } } log.debugf("Updating local topology for cache %s: %s", cacheName, cacheTopology); cacheStatus.setCurrentTopology(cacheTopology); return true; }