auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void addCapabilityRequirements(OperationContext context, Resource resource, String attributeName, String... values) { String dependentName = this.capability.resolve(context.getCurrentAddress()).getName(); for (String value : values) { START this.requirementResolver.apply(context, value).ifPresent(requirementName -> context.registerAdditionalCapabilityRequirement(requirementName, dependentName, attributeName)); END } } This lambda should also be eliminated.

Target:
public void addCapabilityRequirements(OperationContext context, Resource resource, String attributeName, String... values) { String dependentName = this.capability.resolve(context.getCurrentAddress()).getName(); for (String value : values) { final String requirementName = this.requirementResolver.apply(context, value); if (requirementName != null) { context.registerAdditionalCapabilityRequirement(requirementName, dependentName, attributeName); } } }
Source:
public void removeCapabilityRequirements(OperationContext context, Resource resource, String attributeName, String... values) { String dependentName = this.capability.resolve(context.getCurrentAddress()).getName(); for (String value : values) { START this.requirementResolver.apply(context, value).ifPresent(requirementName -> context.deregisterCapabilityRequirement(requirementName, dependentName)); END } } This lambda can also be eliminated.

Target:
public void removeCapabilityRequirements(OperationContext context, Resource resource, String attributeName, String... values) { String dependentName = this.capability.resolve(context.getCurrentAddress()).getName(); for (String value : values) { final String requirementName = this.requirementResolver.apply(context, value); if (requirementName != null) { context.deregisterCapabilityRequirement(requirementName, dependentName); } } }
Source:
public List<RemoteSiteConfiguration> getRemoteSites() { List<RemoteSiteConfiguration> list = new ArrayList<>(); START for (ValueDependency<RemoteSiteConfiguration> site : this.sites) { END RemoteSiteConfiguration value = site.getValue(); list.add(value); } return list; } ArrayList should be constructed with fixed capacity.

Target:
public List<RemoteSiteConfiguration> getRemoteSites() { List<RemoteSiteConfiguration> list = new ArrayList<>(this.sites.size()); for (ValueDependency<RemoteSiteConfiguration> site : this.sites) { RemoteSiteConfiguration value = site.getValue(); list.add(value); } return list; }
Source:
public void writeObject(ObjectOutput output, T collection) throws IOException { START Optional<Object> found = Optional.empty(); END for (Object o : collection) { found = Optional.of(o); break; } output.writeObject(found.get()); } output.writeObject(collection.iterator().next());

Target:
public void writeObject(ObjectOutput output, T collection) throws IOException { output.writeObject(collection.iterator().next()); }
Source:
public void addConnectionEventListener(ConnectionEventListener listener) { START log.debug("addConnectionEventListener()"); END if (listener == null) { throw new IllegalArgumentException("Listener is null"); } listeners.add(listener); } remove all useless debugging messsages

Target:
public void addConnectionEventListener(ConnectionEventListener listener) { if (listener == null) { throw new IllegalArgumentException("Listener is null"); } listeners.add(listener); }
Source:
private void processComponentConfig(final EEApplicationClasses applicationClasses, final DeploymentReflectionIndex deploymentReflectionIndex, final ComponentDescription description, DeploymentUnit deploymentUnit) throws DeploymentUnitProcessingException { final Class<?> componentClass; try { componentClass = ClassLoadingUtils.loadClass(description.getComponentClassName(), deploymentUnit); START } catch (Exception e) { END //just ignore the class for now. //if it is an optional component this is ok, if it is not an optional component //it will fail at configure time anyway return; } handleAnnotations(applicationClasses, deploymentReflectionIndex, componentClass, description); } Should this not be `Throwable` rather than `Exception`? The two failures reported in WFLY-8515 were `LinkageError` and `NoClassDefFoundError`, neither of which would be caught as things stand

Target:
private void processComponentConfig(final EEApplicationClasses applicationClasses, final DeploymentReflectionIndex deploymentReflectionIndex, final ComponentDescription description, DeploymentUnit deploymentUnit) throws DeploymentUnitProcessingException { final Class<?> componentClass; try { componentClass = ClassLoadingUtils.loadClass(description.getComponentClassName(), deploymentUnit); } catch (Throwable e) { //just ignore the class for now. //if it is an optional component this is ok, if it is not an optional component //it will fail at configure time anyway return; } handleAnnotations(applicationClasses, deploymentReflectionIndex, componentClass, description); }
Source:
public <K, V> RemoteCache<K, V> getCache(boolean forceReturnValue) { START return remoteCacheManager.getCache(); END } The RemoteCache interface has a getRemoteCacheManager(). However, this method currently returns a RemoteCacheManager (ugh...). I've opened https://issues.jboss.org/browse/ISPN-7192 to rectify this. Once this is in place, we'll need the getCache() methods to return a ManagedRemoteCache decorator whose getRemoteCacheContainer() method returns this instance.

Target:
public <K, V> RemoteCache<K, V> getCache(boolean forceReturnValue) { return this.remoteCacheManager.getCache(); }
Source:
static byte[] getHash(final ModelNode address) throws IOException { final ModelNode operation = new ModelNode(); operation.get(OP).set(READ_ATTRIBUTE_OPERATION); operation.get(OP_ADDR).set(address); operation.get(NAME).set(CONTENT); START final ModelNode result = executeOnMaster(operation); END return executeOnMaster(operation).get(0).get("hash").asBytes(); } "result" variable is never used so it could be removed too, right? Currently, executeOnMaster(operation) method is called twice ...

Target:
static byte[] getHash(final ModelNode address) throws IOException { final ModelNode operation = new ModelNode(); operation.get(OP).set(READ_ATTRIBUTE_OPERATION); operation.get(OP_ADDR).set(address); operation.get(NAME).set(CONTENT); return executeOnMaster(operation).get(0).get("hash").asBytes(); }
Source:
public String testTransaction(int transactionCount, int timeoutCount) throws RemoteException, NamingException { TxTestUtil.checkTransactionExists(tm, false); for(int i = 1; i <= transactionCount; i++) { START boolean isTimeout = (timeoutCount - i >= 0) ? true : false; END runTransaction(isTimeout); } try { return TxTestUtil.getStatusAsString(txn.getStatus()); } catch (SystemException se) { throw new EJBException("Can't get status of transaction", se); } } Why not simply? (timeoutCount - i >= 0) or simpler: i <= timeoutCount And in a simple test ver see this becoming

Target:
public String testTransaction(int transactionCount, int timeoutCount) throws RemoteException, NamingException, SystemException { TxTestUtil.checkTransactionExists(tm, false); for(int i = 1; i <= transactionCount; i++) { boolean isTimeout = (i <= timeoutCount); runTransaction(isTimeout); } return TxTestUtil.getStatusAsString(txn.getStatus()); }
Source:
public void testTransaction() throws RemoteException, SystemException { START log.info("Method stateful #testTransaction called"); END Transaction txn; txn = tm.getTransaction(); TxTestUtil.enlistTestXAResource(txn); TxTestUtil.enlistTestXAResource(txn); } log.tracef

Target:
public void testTransaction() throws RemoteException, SystemException { log.trace("Method stateful #testTransaction called"); Transaction txn; txn = tm.getTransaction(); TxTestUtil.enlistTestXAResource(txn); TxTestUtil.enlistTestXAResource(txn); }
Source:
public void touch() { START log.debug("Stateful bean instance has been touched"); END } log.trace

Target:
public void touch() { log.trace("Stateful bean instance has been touched"); }
Source:
public String testTransaction(int transactionCount, int timeoutCount) throws RemoteException, NamingException { TxTestUtil.checkTransactionExists(tm, false); for(int i = 1; i <= transactionCount; i++) { boolean isTimeout = (i <= timeoutCount); runTransaction(isTimeout); } try { return TxTestUtil.getStatusAsString(txn.getStatus()); } catch (SystemException se) { START throw new EJBException("Can't get status of transaction", se); END } } Why not allow the SystemException up?

Target:
public String testTransaction(int transactionCount, int timeoutCount) throws RemoteException, NamingException, SystemException { TxTestUtil.checkTransactionExists(tm, false); for(int i = 1; i <= transactionCount; i++) { boolean isTimeout = (i <= timeoutCount); runTransaction(isTimeout); } return TxTestUtil.getStatusAsString(txn.getStatus()); }
Source:
public void writeItems(java.util.List<Object> items) throws Exception { for(Object o : items){ START LOG.info(o.toString()); END } } I think we should avoid logging these or log them as debug. CI servers don't always have a lot of disk space and logging unneeded data will increase usage of the disk space.

Target:
public void writeItems(java.util.List<Object> items) throws Exception { // do nothing - if the items are delivered to writer test passes }
Source:
protected AbstractWebFailoverTestCase(String deploymentName, TransactionMode mode) { this.deploymentName = deploymentName; this.nonOwnerTask = () -> { // If the cache is non-transactional, we need to wait for that replication to finish, otherwise the read can be stale START if (mode.isTransactional()) { END try { Thread.sleep(GRACE_TIME_TO_REPLICATE); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } }; } Missing negation.

Target:
protected AbstractWebFailoverTestCase(String deploymentName, TransactionMode mode) { this.deploymentName = deploymentName; this.nonOwnerTask = () -> { // If the cache is non-transactional, we need to wait for that replication to finish, otherwise the read can be stale if (!mode.isTransactional()) { try { Thread.sleep(GRACE_TIME_TO_REPLICATE); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } }; }
Source:
public MyFacesInjectionProvider() { START if (StartupContext.getInjectionContainer() != null) { END this.injectionContainer = StartupContext.getInjectionContainer(); } } No need to check the value of StartupContext.getInjectionContainer() here before assigning it to this.injectionContainer.

Target:
public MyFacesInjectionProvider() { this.injectionContainer = StartupContext.getInjectionContainer(); }
Source:
public void postConstruct(Object instance, Object creationMetaData) throws InjectionProviderException { START try { END injectionContainer.newInstance(instance); } catch (Exception e) { throw new InjectionProviderException(e); } } A check is needed at the beginning of this method to make sure injectionContainer is not null.

Target:
public void postConstruct(Object instance, Object creationMetaData) throws InjectionProviderException { if (injectionContainer != null) { try { injectionContainer.newInstance(instance); } catch (Exception e) { throw new InjectionProviderException(e); } } }
Source:
public static void setProperty(String name, String value, ModelControllerClient client) { ModelNode modelNode = createOpNode("system-property=" + name, ADD); modelNode.get(VALUE).set(value); START modelNode.get(OPERATION_HEADERS).get(ALLOW_RESOURCE_SERVICE_RESTART).set(true); END ModelNode result = executeOp(modelNode, client); log.debugf("Added property %s, result: %s", name, result); } This looks like cruft. SystemPropertyAddHandler does not respect this header, and in any case adding the props used in the test shouldn't trigger reload-required. If they do there's a bug.

Target:
public static void setProperty(String name, String value, ModelControllerClient client) { ModelNode modelNode = createOpNode("system-property=" + name, ADD); modelNode.get(VALUE).set(value); ModelNode result = executeOp(modelNode, client); log.debugf("Added property %s, result: %s", name, result); }
Source:
public static void removeProperty(String name, ModelControllerClient client) { ModelNode modelNode = createOpNode("system-property=" + name, REMOVE); ModelNode result = executeOp(modelNode, client); START modelNode.get(OPERATION_HEADERS).get(ALLOW_RESOURCE_SERVICE_RESTART).set(true); END log.debugf("Removing property %s. Result: %s.", name, result); } This looks like cruft. SystemPropertyRemoveHandler does not respect this header, and in any case removing the props used in the test shouldn't trigger reload-required. If they do there's a bug.

Target:
public static void removeProperty(String name, ModelControllerClient client) { ModelNode modelNode = createOpNode("system-property=" + name, REMOVE); ModelNode result = executeOp(modelNode, client); log.debugf("Removing property %s. Result: %s.", name, result); }
Source:
public static void redefineProperty(String name, String value, ModelControllerClient client) { ModelNode modelNode = createOpNode("system-property=" + name, WRITE_ATTRIBUTE_OPERATION); modelNode.get(NAME).set(VALUE); modelNode.get(VALUE).set(value); START modelNode.get(OPERATION_HEADERS).get(ALLOW_RESOURCE_SERVICE_RESTART).set(true); END ModelNode result = executeOp(modelNode, client); log.debugf("Redefine property %s to value %s. Result: %s.", name, value, result); } This looks like cruft. SystemPropertyValueWriteAttributeHandler does not respect this header, and in any case updating the props used in the test shouldn't trigger reload-required. If they do there's a bug.

Target:
public static void redefineProperty(String name, String value, ModelControllerClient client) { ModelNode modelNode = createOpNode("system-property=" + name, WRITE_ATTRIBUTE_OPERATION); modelNode.get(NAME).set(VALUE); modelNode.get(VALUE).set(value); ModelNode result = executeOp(modelNode, client); log.debugf("Redefine property %s to value %s. Result: %s.", name, value, result); }
Source:
public void initialize(final ExtensionContext context) { JSFLogger.ROOT_LOGGER.debug("Activating JSF(Mojarra) Extension"); final SubsystemRegistration subsystem = context.registerSubsystem(SUBSYSTEM_NAME, CURRENT_MODEL_VERSION); subsystem.registerSubsystemModel(JSFResourceDefinition.INSTANCE); subsystem.registerXMLElementWriter(JSFSubsystemParser_1_1.INSTANCE); // Transformers if (context.isRegisterTransformers()) { START JSFResourceDefinition.registerTransformers(subsystem); END } } There's a new ServiceLoader based way of registering transformers that should be used -- see implementations of org.jboss.as.controller.transform.ExtensionTransformerRegistration

Target:
public void initialize(final ExtensionContext context) { JSFLogger.ROOT_LOGGER.debug("Activating JSF(Mojarra) Extension"); final SubsystemRegistration subsystem = context.registerSubsystem(SUBSYSTEM_NAME, CURRENT_MODEL_VERSION); subsystem.registerSubsystemModel(JSFResourceDefinition.INSTANCE); subsystem.registerXMLElementWriter(JSFSubsystemParser_1_1.INSTANCE); }
Source:
public void testIsInEuropeanUnion() throws Exception { DatabaseReader reader = new DatabaseReader.Builder(this.geoipFile) .build(); CityResponse city = reader.city(InetAddress.getByName("89.160.20.128")); assertEquals(true, city.getCountry().isInEuropeanUnion()); START assertEquals(true, city.getRegisteredCountry().isInEuropeanUnion()); END } These two could be `assertTrue`.

Target:
public void testIsInEuropeanUnion() throws Exception { DatabaseReader reader = new DatabaseReader.Builder(this.geoipFile) .build(); CityResponse city = reader.city(InetAddress.getByName("89.160.20.128")); assertTrue(city.getCountry().isInEuropeanUnion()); assertTrue(city.getRegisteredCountry().isInEuropeanUnion()); }
Source:
public void testRepresentedCountry() { assertNotNull("city.getRepresentedCountry() returns null", this.insights.getRepresentedCountry()); assertEquals( "city.getRepresentedCountry().getType() does not return C<military>", "C<military>", this.insights.getRepresentedCountry().getType()); START assertEquals( END "city.getRepresentedCountry().isInEuropeanUnion() does not return true", true, this.insights.getRepresentedCountry().isInEuropeanUnion()); } `assertTrue`

Target:
public void testRepresentedCountry() { assertNotNull("city.getRepresentedCountry() returns null", this.insights.getRepresentedCountry()); assertEquals( "city.getRepresentedCountry().getType() does not return C<military>", "C<military>", this.insights.getRepresentedCountry().getType()); assertTrue( "city.getRepresentedCountry().isInEuropeanUnion() does not return true", this.insights.getRepresentedCountry().isInEuropeanUnion()); }
Source:
private static boolean isValidBackupDir(Path backupDir) { String backupDirName = backupDir.toFile().getName(); // Check if it of format yyyyMMddHHmm try { DateUtil.getDate(backupDirName); return true; } catch (Exception e) { START return false; END } } You might want to add `debug` if you ever want to debug whey backup name is not being validated (could be special characters etc.,)

Target:
private static boolean isValidBackupDir(Path backupDir) { String backupDirName = backupDir.toFile().getName(); // Check if it of format yyyyMMddHHmm return (DateUtil.getDate(backupDirName) != null); }
Source:
public void execute() throws Exception { // If Cassandra is started then only start Snapshot Backup while (!CassandraMonitor.hasCassadraStarted()) { logger.debug( "Cassandra has not yet started, hence Snapshot Backup will start after [" + WAIT_TIME_MS / 1000 + "] secs ..."); sleeper.sleep(WAIT_TIME_MS); } // Do not allow more than one snapshot to run at the same time. This is possible as this // happens on CRON. if (!lock.tryLock()) { START logger.error("Snapshot Operation is already running! Try again later."); END throw new Exception("Snapshot Operation already running"); } try { executeSnapshot(); } finally { lock.unlock(); } } nit: maybe a warn, since this is not necessary caused by application, but rather due to crons?

Target:
public void execute() throws Exception { // If Cassandra is started then only start Snapshot Backup while (!CassandraMonitor.hasCassadraStarted()) { logger.debug( "Cassandra has not yet started, hence Snapshot Backup will start after [" + WAIT_TIME_MS / 1000 + "] secs ..."); sleeper.sleep(WAIT_TIME_MS); } // Do not allow more than one snapshot to run at the same time. This is possible as this // happens on CRON. if (!lock.tryLock()) { logger.warn("Snapshot Operation is already running! Try again later."); throw new Exception("Snapshot Operation already running"); } try { executeSnapshot(); } finally { lock.unlock(); } }
Source:
public PriamConfigurationPersister(IConfiguration config) { super(config); mergedConfigDirectory = Paths.get(config.getMergedConfigurationDirectory()); structuredPath = Paths.get(config.getMergedConfigurationDirectory(), "structured.json"); START END initialized = false; canWrite = false; } I'm from the church of EAFP, here to spread the good word. Have you considered writing heavenly code, like so? ``` if(directory.mkdirs()) { Files.setPosixFilePermissions(mergedConfigDirectory, 0700); } ``` Doing so would allow you to eliminate the canWrite variable, because you'll throw an exception instead. You could maybe even run this on every iteration (once per minute), as a single mkdir* syscall is not very resource-intensive. * I checked, and the JVM actually LBYLs it into a stat() syscall instead.

Target:
public PriamConfigurationPersister(IConfiguration config) { super(config); mergedConfigDirectory = Paths.get(config.getMergedConfigurationDirectory()); structuredPath = Paths.get(config.getMergedConfigurationDirectory(), "structured.json"); }
Source:
START public void setRestoring(boolean isRestoring) { END this.isRestore.set(isRestoring); } Are you setting these anywhere?

Target:
public void setRestoring(boolean isRestoring) { this.isRestoring.set(isRestoring); }
Source:
START public org.radargun.traits.Query.Builder subquery() { END return this; } Why is this needed? Can't you import the class with the name `Query` to avoid this on line 3 above?

Target:
public Query.Builder subquery() { return this; }
Source:
protected <T> TransactionManager getTransactionManager(T resource) { if (resource instanceof HotRodOperations.HotRodCache) { return ((HotRodOperations.HotRodCache) resource).noReturn.getTransactionManager(); } else { START throw new IllegalArgumentException("Invalid resource: " + String.valueOf(resource)); END } } @diegolovison Can you make this happen or are you just worried it might happen? I'm trying to understand how the wrong type of cache would be passed into the HotRod service.

Target:
protected <T> TransactionManager getTransactionManager(T resource) { return ((HotRodOperations.HotRodCache) resource).noReturn.getTransactionManager(); }
Source:
public void reset() { super.reset(); traits = null; START clearlisteners(); END } this should go to super.reset(), shouldn't it?

Target:
public void reset() { super.reset(); traits = null; }
Source:
START public synchronized boolean containsValuesOfType(Category.Type type) { END return values.keySet().stream().anyMatch(e -> e.getType().equals(type)); } I don't think this can be called concurrently as it's only called from HtmlReporter. I don't mind if you leave it in.

Target:
public boolean containsValuesOfType(Category.Type type) { return values.keySet().stream().anyMatch(e -> e.getType().equals(type)); }
Source:
START public void run(MasterConfig masterConfig, Collection<Report> reports) { END if (perfRepoAuth == null) { log.error("perfRepoAuth parameter has to be set"); return; } if (perfRepoTest == null) { log.error("perfRepoTest parameter has to be set"); return; } for (Report report : reports) { reportTests(report); } } Would it be possible to add this config to the ones that are uploaded to PerfRepo in the uploadAttachments method?

Target:
public void run(MasterConfig masterConfig, Collection<Report> reports) { this.masterConfig = masterConfig; if (perfRepoAuth == null) { log.error("perfRepoAuth parameter has to be set"); return; } if (perfRepoTest == null) { log.error("perfRepoTest parameter has to be set"); return; } for (Report report : reports) { reportTests(report); } }
Source:
private Category(String name, Type type) { Objects.nonNull(name); START Objects.nonNull(type); END this.name = name; this.type = type; } This can be removed.

Target:
private Category(String name, Type type) { this.name = name; this.type = type; }
Source:
public Object generateValue(Object key, int size, Random random) { START return new RandomStream(key.hashCode(), size); END } Generating identical streams for the same key is not a good property of a *random value* generator.

Target:
public Object generateValue(Object key, int size, Random random) { return new RandomStream(size); }
Source:
public void onNext(Frame frame) { START log.append(new String(frame.getPayload())); END } Shouldn't you rather log directly?

Target:
public void onNext(Frame frame) { log.info(frame.toString()); }
Source:
protected Completion createCompletion() { Completion completion = new TimeStressorCompletion(duration); START if (numOperations > 0) { END long countPerNode = numOperations / getExecutingSlaves().size(); long modCountPerNode = numOperations % getExecutingSlaves().size(); if (getExecutingSlaveIndex() + 1 <= modCountPerNode) { countPerNode++; } completion = new CountStressorCompletion(countPerNode); } return completion; } Please put the creation of `TimeStressorCompletion` to else branch (you can omit the variable and return new instance right away).

Target:
protected Completion createCompletion() { if (numOperations > 0) { long countPerNode = numOperations / getExecutingSlaves().size(); long modCountPerNode = numOperations % getExecutingSlaves().size(); if (getExecutingSlaveIndex() + 1 <= modCountPerNode) { countPerNode++; } return new CountStressorCompletion(countPerNode); } else { return new TimeStressorCompletion(duration); } }
Source:
START protected Map<String, Object> getStats(Protocol protocol){ END return stack.dumpStats(); } why does this need an override?

Target:
protected Map<String, Object> getStats(Protocol protocol){ return stack.dumpStats(protocol.getName(), null); }
Source:
START public void finished(boolean successful, Operation operation) { END statistics.record(this, operation); this.successful = successful; } Looks redundant.

Target:
public void finished(boolean successful, Operation operation) { this.successful = successful; statistics.record(this, operation); }
Source:
private String buildUrl(String cache, K key) { START String s = new StringBuffer(buildCacheUrl(cache)).append("/").append(key).toString(); END log.trace("buildUrl(String cache, K key) = " + s); return s; } StringBuilder please

Target:
private String buildUrl(String cache, K key) { String s = new StringBuilder(buildCacheUrl(cache)).append("/").append(key).toString(); log.trace("buildUrl(String cache, K key) = " + s); return s; }
Source:
public void createReportDirectory() { File dir = new File(directory); if (dir.exists() && !dir.isDirectory()) { throw new IllegalArgumentException(dir.getAbsolutePath() + " is not a directory"); START } else if (!dir.exists()) { END dir.mkdirs(); } } The check is not necessary, File.mkdirs doesn't attempt to create the directory when one already exists.

Target:
public void createReportDirectory() { File dir = new File(directory); dir.mkdirs(); }
Source:
START public SortedMap<String, SortedMap<Integer, String>> getProperties() { END return properties; } What about returning generic Map interface?

Target:
public Map<String, SortedMap<Integer, String>> getProperties() { return properties; }
Source:
public long next() { START long result = (long) (random.nextGaussian() * standardDeviation + mean); END while (result < 0 || result >= numEntries) { result = (long) (random.nextGaussian() * standardDeviation + mean); } return result; } This might be a good fit for do-while cycle.

Target:
public long next() { long result; do { result = (long) (random.nextGaussian() * standardDeviation + mean); } while (result < 0 || result >= numEntries); return result; }
Source:
START public static Properties loadProperties(Properties properties, InputStream inputStream) throws IOException { END try { properties.load(inputStream); return properties; } finally { close(inputStream); } } I think that closing resource in different scope than where it is allocated is an anti-pattern. RG is baselined on Java 7, use try-with-resources instead, please.

Target:
public static Properties loadProperties(Properties properties, InputStream inputStream) throws IOException { properties.load(inputStream); return properties; }
Source:
public V getAndRemove(K key) { boolean startedTx = startTxAndLock(key); START super.remove(key); END V prev = super.getAndRemove(key); stopTx(startedTx); return prev; } Seems like you found a bug - you should not call both super.remove and super.getAndRemove. Could you fix that? Also, I think that stopTx should be called in finally block.

Target:
public V getAndRemove(K key) { boolean startedTx = false; V prev = null; try { startedTx = startTxAndLock(key); prev = super.getAndRemove(key); } finally { stopTx(startedTx); } return prev; }
Source:
public void created(ClientCacheEntryCreatedEvent e) { for (CreatedListener listener : created) { try { listener.created(e.getKey(), e.getVersion()); START } catch (Throwable t) { END log.error("Listener " + listener + " has thrown an exception", t); } } } I am starting to be reluctant to catching Throwable without rethrowing: could you change this to Exception both here and in embedded listeners?

Target:
public void created(ClientCacheEntryCreatedEvent e) { for (CreatedListener listener : created) { try { listener.created(e.getKey(), e.getVersion()); } catch (Exception ex) { log.error("Listener " + listener + " has thrown an exception", ex); } } }
Source:
protected int getExpectedNumEntries() { START return getNumEntries() * (backupValueGenerator != null ? backupCacheInstances.length + 1 : 1); END } backupCacheInstances != null ? backupCacheInstances.length + 1 : 1 would make more sense

Target:
protected int getExpectedNumEntries() { return getNumEntries() * (backupCacheInstances != null ? backupCacheInstances.length + 1 : 1); }
Source:
public void stop() { managerNoReturn.stop(); managerNoReturn = null; managerForceReturn.stop(); START managerForceReturn.stop(); END } Is this double invocation performed on purpose?

Target:
public void stop() { managerNoReturn.stop(); managerNoReturn = null; managerForceReturn.stop(); managerForceReturn = null; }
Source:
public Object run(Stressor stressor, int iteration) { Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put(Queryable.QUERYABLE_FIELD, onField); paramMap.put(Queryable.MATCH_STRING, matching); paramMap.put(Queryable.IS_WILDCARD, isWildcardQuery); Object obj = stressor.makeRequest(iteration, Operation.QUERY, paramMap); START resultObjects.add(obj); END return obj; } I am not sure how big is the returned value, but do you plan to use it more than just to compare the sizes as an assert? Otherwise, I'd recommend to do the check right after we get the returned value and store only the last size.

Target:
public Object run(Stressor stressor, int iteration) { Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put(Queryable.QUERYABLE_FIELD, onField); paramMap.put(Queryable.MATCH_STRING, matching); paramMap.put(Queryable.IS_WILDCARD, isWildcardQuery); List obj = (List) stressor.makeRequest(iteration, Operation.QUERY, paramMap); resultObjects.add(obj.size()); return obj; }
Source:
private Address findHostPhysicalAddress(String nodeAddress) { Address result = null; Transport t = cacheManager.getTransport(); if (t == null) { START result = cacheManager.getAddress(); END } else { for (Address add : t.getPhysicalAddresses()) { if (add.toString().contains(nodeAddress)) { result = add; break; } } } return result; } Looking into getAddress() implementation this returns null if Transport is null...

Target:
private Address findHostPhysicalAddress(String nodeAddress) { Address result = null; Transport t = cacheManager.getTransport(); if (t != null) { for (Address add : t.getPhysicalAddresses()) { if (add.toString().contains(nodeAddress)) { result = add; break; } } } return result; }
Source:
public void setUseIntermediateSharedCache(boolean useIntermediateSharedCache) { //Not used by Infinispan 5.1 START } END Shouldn't we rather throw UnsupportedOperationException() in this case? Or rather create interface without the support and extend it with interface with these methods?

Target:
public boolean setUseIntermediateSharedCache(boolean useIntermediateSharedCache) { return false; }
Source:
public static boolean artifactExists(WebDriver driver, String name, long timeout) { String url = getUrl(driver, name); String username = getField(url, 1); String password = getField(url, 2); try { return new WebDriverWait(driver, timeout).until((k) -> checkArtifactUsingHttp(url, username, password)); START } catch (Exception e) { END return false; } } let's add: LOGGER.debug(e)

Target:
public static boolean artifactExists(WebDriver driver, String name, long timeout) { String url = getUrl(driver, name); String username = getField(url, 1); String password = getField(url, 2); try { return new WebDriverWait(driver, timeout).until((k) -> checkArtifactUsingHttp(url, username, password)); } catch (Exception e) { LOGGER.debug(e); return false; } }
Source:
default boolean isAppRunning(String apk) { START AndroidService androidService = AndroidService.getInstance(); END String res = androidService.getCurrentDeviceFocus(); if (res.contains(apk)) { LOGGER.info("Actual device focus is as expected and contains package or activity: '" + apk + "'."); return true; } else { LOGGER.error("Not expected apk '" + apk + "' is in focus. Actual result is: " + res); return false; } } remove reference to AbdroidService please. All functionality step-by-step should be moved to interface

Target:
default boolean isAppRunning(String apk) { String res = getCurrentDeviceFocus(); if (res.contains(apk)) { LOGGER.info("Actual device focus is as expected and contains package or activity: '" + apk + "'."); return true; } else { LOGGER.error("Not expected apk '" + apk + "' is in focus. Actual result is: " + res); return false; } }
Source:
public void detectLowCoverageVertex() { VertexValueWritable vertex = getVertexValue(); START if (vertex.getAverageCoverage() <= minAverageCoverage || vertex.getAverageCoverage() >= maxAverageCoverage) { END //broadcase kill self broadcastKillself(); vertex.setState(State.DEAD_NODE); activate(); } else voteToHalt(); } Let's make it `v.cov < minAvgCov || c.cov > maxAvgCov`.

Target:
public void detectLowCoverageVertex() { VertexValueWritable vertex = getVertexValue(); if (vertex.getAverageCoverage() < minAverageCoverage || vertex.getAverageCoverage() > maxAverageCoverage) { //broadcase kill self broadcastKillself(); vertex.setState(State.DEAD_NODE); activate(); } else voteToHalt(); }
Source:
public void compute(Iterator<RayMessage> msgIterator) throws Exception { if (getSuperstep() == 1) { START initVertex(); END if (isStartSeed()) { msgIterator = getStartMessage(); } } scaffold(msgIterator); voteToHalt(); } Why do you need this initVertex() here? You already add it in confgure.

Target:
public void compute(Iterator<RayMessage> msgIterator) throws Exception { if (getSuperstep() == 1) { if (isStartSeed()) { msgIterator = getStartMessage(); } } scaffold(msgIterator); voteToHalt(); }
Source:
private boolean checkedIfValid(ReadHeadInfo readHead, VKmer neighbor) { //if neighbor exist in read table //How to work with a read? //int neighborPositionOnRead = getVertexValue().walk.size() - getVertexValue().index + 1; int neighborPositionOnRead = getVertexValue().walkSize - getVertexValue().index; START return readHead.getThisReadSequence().getGeneCodeAtPosition(neighborPositionOnRead) == neighbor END .getGeneCodeAtPosition(kmerSize - 1); } this should actually check if all K letters at this position are the same. When I was describing this to you, I meant that the only information needed from the neighbor (in terms of sending a msg) was a single letter. But the ReadHeadInfo should compare the full kmer, not just that single letter.

Target:
private boolean checkedIfValid(ReadHeadInfo readHead, VKmer neighbor) { //if neighbor exist in read table //How to work with a read? //int neighborPositionOnRead = getVertexValue().walk.size() - getVertexValue().index + 1; int neighborPositionOnRead = getVertexValue().walkSize - getVertexValue().index; for (int i = 0; i < kmerSize; i++) { if (readHead.getThisReadSequence().getGeneCodeAtPosition(neighborPositionOnRead + i) != neighbor .getGeneCodeAtPosition(i)) { return false; } } return true; }
Source:
public Integer getPreKmerLength() { START if(preKmerLength == null) END preKmerLength = new Integer(0); return preKmerLength; } Unless you have reason to do otherwise, you should just return an `int` not an `Integer` and you shouldn't set the value to `0` by default. That way, if they call `getPreKmerLength()` before initializing, they'll get a NPE (which is better than the corresponding bug!)

Target:
public Integer getPreKmerLength() { return preKmerLength; }
Source:
public String toString(){ StringBuilder sbuilder = new StringBuilder(); sbuilder.append('{'); START sbuilder.append(kmer + " " + et); END sbuilder.append('}'); return sbuilder.toString(); } If you want to take the benefit of stringbuilder, you should write sbuilder.append(kmer.toString()).append(' ').append(et.toString()). Otherwise, it is the same as string cat.

Target:
public String toString(){ StringBuilder sbuilder = new StringBuilder(); sbuilder.append('{'); sbuilder.append(kmer).append(" ").append(et); sbuilder.append('}'); return sbuilder.toString(); }
Source:
public void compute(Iterator<MessageWritable> msgIterator) throws Exception { initVertex(); START if (getSuperstep() == 1 && startSeeds.contains(getVertexId())) { END markSelfAndBroadcast(); } else if (getSuperstep() <= numOfHops + 1 && msgIterator.hasNext()) { markSelfAndBroadcast(); } voteToHalt(); } what's the different between these if /else branch ?

Target:
public void compute(Iterator<MessageWritable> msgIterator) throws Exception { initVertex(); if ((getSuperstep() == 1 && startSeeds.contains(getVertexId())) || (getSuperstep() <= numOfHops + 1 && msgIterator.hasNext())) { markSelfAndBroadcast(); } voteToHalt(); }
Source:
public void updateOrderFulfillerStatus_shouldEditFulfillerStatusWithAccessioNumberInOrder() { Order originalOrder = orderService.getOrder(111); String commentText = "We got the new order"; String accessionNumber = "12345"; START assertNotEquals(originalOrder.getAccessionNumber(), 0); END orderService.updateOrderFulfillerStatus(originalOrder, Order.FulfillerStatus.IN_PROGRESS, commentText, accessionNumber); Order updatedOrder = orderService.getOrder(111); assertEquals(updatedOrder.getAccessionNumber(), accessionNumber); } Minor point, but shouldn't we really be testing here that the accession number is not "12345"?

Target:
public void updateOrderFulfillerStatus_shouldEditFulfillerStatusWithAccessioNumberInOrder() { Order originalOrder = orderService.getOrder(111); String commentText = "We got the new order"; String accessionNumber = "12345"; assertNotEquals(originalOrder.getAccessionNumber(), accessionNumber); orderService.updateOrderFulfillerStatus(originalOrder, Order.FulfillerStatus.IN_PROGRESS, commentText, accessionNumber); Order updatedOrder = orderService.getOrder(111); assertEquals(updatedOrder.getAccessionNumber(), accessionNumber); }
Source:
public void addCondition(Condition condition) { START if (condition != null) { END condition.setEncounter(this); getConditions().add(condition); } } I would not silently ignore one passing a null parameter. In other words, i would remove the if check and assume that the condition is not null. If it turns out to be null, better for the caller to automatically get a NullPointerException than chewing it quietly.

Target:
public void addCondition(Condition condition) { condition.setEncounter(this); getConditions().add(condition); }
Source:
public void getPrograms_shouldTestGetProgramsIfCohortIsEmpty() { START int i = 0; END Cohort cohort = new Cohort(); Collection<Program> programs = pws.getAllPrograms(); List<PatientProgram> patientPrograms; cohort.getMemberIds().clear(); patientPrograms = dao.getPatientPrograms(null, programs); assertEquals(patientPrograms.size(), 4); } what is this variable?

Target:
public void getPrograms_shouldTestGetProgramsIfCohortIsEmpty() { Cohort cohort = new Cohort(); Collection<Program> programs = pws.getAllPrograms(); List<PatientProgram> patientPrograms; cohort.getMemberIds().clear(); patientPrograms = dao.getPatientPrograms(null, programs); assertEquals(patientPrograms.size(), 4); }
Source:
public void getAllConceptStateConversion_shouldTestGetAllConceptStateConversion() { List<ConceptStateConversion> conceptStateConversions = pws.getAllConceptStateConversions(); START int len = conceptStateConversions.size(); END assertEquals(len, 1); } len is unnecessary variable name

Target:
public void getAllConceptStateConversion_shouldTestGetAllConceptStateConversion() { List<ConceptStateConversion> conceptStateConversions = pws.getAllConceptStateConversions(); assertEquals(conceptStateConversions.size(), 1); }
Source:
public void purgeConceptStateConversion_shouldTestPurgeConceptStateConversion() { ConceptStateConversion conceptStateConversion = pws.getAllConceptStateConversions().get(0); Context.getProgramWorkflowService().purgeConceptStateConversion(conceptStateConversion, false); List<ConceptStateConversion> list = pws.getAllConceptStateConversions(); START int len = list.size(); END assertEquals(len, 0); } unnecessary variable

Target:
public void purgeConceptStateConversion_shouldTestPurgeConceptStateConversion() { ConceptStateConversion conceptStateConversion = pws.getAllConceptStateConversions().get(0); Context.getProgramWorkflowService().purgeConceptStateConversion(conceptStateConversion, false); List<ConceptStateConversion> list = pws.getAllConceptStateConversions(); assertEquals(list.size(), 0); }
Source:
public void getPrograms_shouldTestGetProgramsIfCohortIsNotEmpty() { int i = 0; Cohort cohort = new Cohort(); Collection<Program> programs = pws.getAllPrograms(); START List<PatientProgram> patientPrograms; END cohort.addMember(1); cohort.addMember(2); patientPrograms = dao.getPatientPrograms(cohort, programs); assertEquals(patientPrograms.size(), 2); } Is there a need for this variable ?

Target:
public void getPrograms_shouldTestGetProgramsIfCohortIsNotEmpty() { Cohort cohort = new Cohort(); Collection<Program> programs = pws.getAllPrograms(); List<PatientProgram> patientPrograms; cohort.addMember(1); cohort.addMember(2); patientPrograms = dao.getPatientPrograms(cohort, programs); assertEquals(patientPrograms.size(), 2); }
Source:
public TaskDefinition getTaskByUuid(String uuid) { if (log.isDebugEnabled()) { START log.debug("get task " + uuid); END } return getSchedulerDAO().getTaskByUuid(uuid); } ```suggestion log.debug("get-task uuid:" + uuid); ```

Target:
public TaskDefinition getTaskByUuid(String uuid) { return getSchedulerDAO().getTaskByUuid(uuid); }
Source:
public Concept hydrate(String s) { try { return Context.getConceptService().getConcept(Integer.valueOf(s)); } catch (Exception e) { START logger.error("Error", e); END } //pass return null; } Change this to `log`

Target:
public Concept hydrate(String s) { try { return Context.getConceptService().getConcept(Integer.valueOf(s)); } catch (Exception e) { log.error("Error", e); } //pass return null; }
Source:
public void validate(Object obj, Errors errors) throws APIException { log.debug("{}.validate...", this.getClass().getName()); START if (obj == null || !(obj instanceof Alert)) { END throw new IllegalArgumentException("error.general and must be of type " + Alert.class); } Alert alert = (Alert) obj; ValidationUtils.rejectIfEmptyOrWhitespace(errors, "text", "Alert.text.required"); ValidateUtil.validateFieldLengths(errors, obj.getClass(), "text"); } Is there a unit test to validate the exception when obj is null or its not a instance of Alert ?

Target:
public void validate(Object obj, Errors errors) throws APIException { logger.debug("{}.validate...", this.getClass().getName()); if (obj == null || !(obj instanceof Alert)) { throw new IllegalArgumentException("error.general and must be of type " + Alert.class); } Alert alert = (Alert) obj; ValidationUtils.rejectIfEmptyOrWhitespace(errors, "text", "Alert.text.required"); ValidateUtil.validateFieldLengths(errors, obj.getClass(), "text"); }
Source:
public void runBeforeAllTests() { conceptService = Context.getConceptService(); START executeDataSet(STANDARD_TEST_DATASET_XML); END } Isn't this dataset automatically executed?

Target:
public void runBeforeAllTests() { conceptService = Context.getConceptService(); }
Source:
public void saveConceptProposal_shouldReturnSavedConceptProposalObject() { START String ORIGINAL_TEXT = "OriginalText"; END ConceptProposal conceptProposal = new ConceptProposal(); conceptProposal.setOriginalText(ORIGINAL_TEXT); List<ConceptProposal> existingConceptProposals = conceptService.getConceptProposals(ORIGINAL_TEXT); assertTrue(existingConceptProposals.isEmpty()); ConceptProposal savedConceptProposal = conceptService.saveConceptProposal(conceptProposal); assertEquals(ORIGINAL_TEXT, savedConceptProposal.getOriginalText()); assertEquals(conceptProposal, savedConceptProposal); } Is this a constant? Or is it allowed to change its value?

Target:
public void saveConceptProposal_shouldReturnSavedConceptProposalObject() { final String ORIGINAL_TEXT = "OriginalText"; ConceptProposal conceptProposal = new ConceptProposal(); conceptProposal.setOriginalText(ORIGINAL_TEXT); List<ConceptProposal> existingConceptProposals = conceptService.getConceptProposals(ORIGINAL_TEXT); assertTrue(existingConceptProposals.isEmpty()); ConceptProposal savedConceptProposal = conceptService.saveConceptProposal(conceptProposal); assertEquals(ORIGINAL_TEXT, savedConceptProposal.getOriginalText()); assertEquals(conceptProposal, savedConceptProposal); }
Source:
public void setOnsetDate(Date onsetDate) { START this.onsetDate = new Date(onsetDate.getTime()); END } What happens, if the `onsetDate` is null?

Target:
public void setOnsetDate(Date onsetDate) { this.onsetDate = onsetDate != null ? new Date(onsetDate.getTime()) : null; }
Source:
public Date getEndDate() { START return endDate != null ? (Date) endDate.clone() : new Date(); END } Why you are using diffrent methods here? 1 . `new Date(onsetDate.getTime())` 2. `(Date) endDate.clone()` Better to keep the consistency among the code, and provide your feedback why did you select that among others.

Target:
public Date getEndDate() { return endDate != null ? (Date) endDate.clone() : null; }
Source:
public void getConceptsByClass_shouldGetConceptsByClass() { // replay List<Concept> actualConcepts = conceptService.getConceptsByClass(new ConceptClass(3)); // verify Assert.assertThat(actualConcepts, containsInAnyOrder(conceptService.getConcept(3), conceptService.getConcept(60), conceptService.getConcept(88), conceptService.getConcept(792))); START } END You need to assert that the size is exactly 4, I did specify it in my last review: ```java Assert.assertThat(actualConcepts.size(), is(4)); ```

Target:
public void getConceptsByClass_shouldGetConceptsByClass() { // replay List<Concept> actualConcepts = conceptService.getConceptsByClass(new ConceptClass(3)); // verify Assert.assertThat(actualConcepts.size(), is(4)); Assert.assertThat(actualConcepts, containsInAnyOrder(conceptService.getConcept(3), conceptService.getConcept(60), conceptService.getConcept(88), conceptService.getConcept(792))); }
Source:
public void getVisitsByPatient_shouldReturnEmptyListGivenPatientWithNullPatientIdAndTrue() { Patient p = new Patient(); p.setPatientId(null); START assertThat(visitService.getVisitsByPatient(p, true, true), is(empty())); END } Why not just pass null instead of p?

Target:
public void getVisitsByPatient_shouldReturnEmptyListGivenPatientWithNullPatientIdAndTrue() { Patient p = new Patient(); p.setPatientId(null); assertThat(visitService.getVisitsByPatient(null, true, true), is(empty())); }
Source:
public void closedLow(boolean closedLow) { START this.closedLow = closedLow == true; END } simply having `this.closedLow = closedLow` would be enough

Target:
public void closedLow(boolean closedLow) { this.closedLow = closedLow; }
Source:
public void closedHigh(boolean closedHigh) { START this.closedHigh = closedHigh == false; END } This seems wrong. when the method parameter closedHigh is false you will be assigning true to the this.closedHigh. Is that correct _

Target:
public void closedHigh(boolean closedHigh) { this.closedHigh = closedHigh; }
Source:
public List<Condition> getActiveConditions(Patient patient) { START System.out.println("near query in getActiveConditions in core"); END Query query = sessionFactory.getCurrentSession().createQuery( "from Condition c where c.patient.patientId = :patientId and c.voided = false and c.endDate is null order " + "by c.onsetDate desc"); query.setInteger("patientId", patient.getId()); return query.list(); } Its not a good practice to use sysout. Better to use logs instead

Target:
public List<Condition> getActiveConditions(Patient patient) { Query query = sessionFactory.getCurrentSession().createQuery( "from Condition c where c.patient.patientId = :patientId and c.voided = false and c.endDate is null order " + "by c.onsetDate desc"); query.setInteger("patientId", patient.getId()); return query.list(); }
Source:
public boolean isReady() { // TODO Auto-generated method stub START return false; END } @Irenyak1 why return false here?

Target:
public boolean isReady() { return this.isReady(); }
Source:
public Object methodException(Context context, Class claz, String method, Exception e, Info info) { log.debug("Claz: " + claz.getName() + " method: " + method, e); // if formatting a date (and probably getting an "IllegalArgumentException") if ("format".equals(method)) { return null; } START END // keep the default behavior try { throw e; } catch (Exception x) { x.printStackTrace(); } return info; } @gitcliff , what happens when you leave out this change?

Target:
public Object methodException(Context context, Class claz, String method, Exception e, Info info) { log.debug("Claz: " + claz.getName() + " method: " + method, e); // if formatting a date (and probably getting an "IllegalArgumentException") if ("format".equals(method)) { return null; } return info; }