auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private Indexer indexStream(InputStream stream) { try { Indexer indexer = new Indexer(); indexer.index(stream); return indexer; } catch (IOException e) { throw new IllegalStateException(e); } }

Target:
This stream is not closed
Source:
public String invoke(String id) { String interceptorInvocationCounterKey = id + "-COUNT"; log.info("Test Invoked"); String clientInterceptor = wasClientInterceptorInvoked(); log.info(String.format("clientInterceptorInvoked: %b %s", (clientInterceptor!=null), clientInterceptor)); context.getContextData().put("ClientInterceptorInvoked", clientInterceptor); return "" + context.getContextData().get(interceptorInvocationCounterKey); }

Target:
What is the purpose of this? you just pulled it out of the same map key?
Source:
LegacyProtocolResourceDefinition(String name, String targetName, JGroupsModel deprecation, Consumer<ResourceDescriptor> descriptorConfigurator, ResourceServiceBuilderFactory<ChannelFactory> parentBuilderFactory) { super(pathElement(name), descriptorConfigurator.andThen(descriptor -> descriptor.setAddOperationTransformation(new OperationTransformation(targetName)).setOperationTransformation(new OperationTransformation(targetName))), null, parentBuilderFactory); this.setDeprecated(deprecation.getVersion()); }

Target:
lambda
Source:
public static JavaArchive createDeployment() { final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, MODULE_NAME + ".jar"); jar.addPackage(UserTransactionAccessTestCase.class.getPackage()); jar.as(ZipExporter.class).exportTo(new File(TestSuiteEnvironment.getTmpDir(), jar.getName()), true); return jar; }

Target:
I think this like should have just been deleted, there is no reason to export the archive
Source:
public ServiceBuilder<SecurityConfiguration> build(ServiceTarget target) { ServiceBuilder<SecurityConfiguration> builder = target.addService(this.getServiceName(), new ValueService<>(this)).setInitialMode(ServiceController.Mode.ON_DEMAND); if (sslContextDependency != null) { this.sslContextDependency.register(builder); } return builder; }

Target:
return (this.sslContextDependency != null) ? this.sslContextDependency.register(builder) : builder; :)
Source:
public ResourceDescriptor addRequiredChildren(Set<? extends ResourceDefinition> set) { set.forEach(definition -> this.requiredChildren.add(definition.getPathElement())); return this; }

Target:
Use normal for-each loop instead of lambda.
Source:
public ServiceBuilder<PersistenceConfiguration> build(ServiceTarget target) { ServiceBuilder<PersistenceConfiguration> builder = super.build(target); this.remoteCacheContainer.register(builder); return builder; }

Target:
return this.remoteCacheContainer.register(super.build(target));
Source:
public void setSocketAddresses(List<InetSocketAddress> addresses) { List<PhysicalAddress> list = new ArrayList<>(); for (InetSocketAddress address : addresses) { IpAddress ipAddress = new IpAddress(address.getAddress(), address.getPort()); list.add(ipAddress); } this.setInitialHosts(list); }

Target:
ArrayList should be constructed with fixed capacity.
Source:
public void addCapabilityRequirements(OperationContext context, Resource resource, String attributeName, String... values) { String dependentName = this.capability.resolve(context.getCurrentAddress()).getName(); for (String value : values) { this.requirementResolver.apply(context, value).ifPresent(requirementName -> context.registerAdditionalCapabilityRequirement(requirementName, dependentName, attributeName)); } }

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

Target:
This lambda can also be eliminated.
Source:
public List<RemoteSiteConfiguration> getRemoteSites() { List<RemoteSiteConfiguration> list = new ArrayList<>(); for (ValueDependency<RemoteSiteConfiguration> site : this.sites) { RemoteSiteConfiguration value = site.getValue(); list.add(value); } return list; }

Target:
ArrayList should be constructed with fixed capacity.
Source:
public void writeObject(ObjectOutput output, T collection) throws IOException { Optional<Object> found = Optional.empty(); for (Object o : collection) { found = Optional.of(o); break; } output.writeObject(found.get()); }

Target:
output.writeObject(collection.iterator().next());
Source:
public void addConnectionEventListener(ConnectionEventListener listener) { log.debug("addConnectionEventListener()"); if (listener == null) { throw new IllegalArgumentException("Listener is null"); } listeners.add(listener); }

Target:
remove all useless debugging messsages
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); } catch (Exception 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); }

Target:
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
Source:
public <K, V> RemoteCache<K, V> getCache(boolean forceReturnValue) { return remoteCacheManager.getCache(); }

Target:
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.
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); final ModelNode result = executeOnMaster(operation); return executeOnMaster(operation).get(0).get("hash").asBytes(); }

Target:
"result" variable is never used so it could be removed too, right? Currently, executeOnMaster(operation) method is called twice ...
Source:
public String testTransaction(int transactionCount, int timeoutCount) throws RemoteException, NamingException { TxTestUtil.checkTransactionExists(tm, false); for(int i = 1; i <= transactionCount; i++) { boolean isTimeout = (timeoutCount - i >= 0) ? true : false; runTransaction(isTimeout); } try { return TxTestUtil.getStatusAsString(txn.getStatus()); } catch (SystemException se) { throw new EJBException("Can't get status of transaction", se); } }

Target:
Why not simply? (timeoutCount - i >= 0) or simpler: i <= timeoutCount And in a simple test ver see this becoming
Source:
public void testTransaction() throws RemoteException, SystemException { log.info("Method stateful #testTransaction called"); Transaction txn; txn = tm.getTransaction(); TxTestUtil.enlistTestXAResource(txn); TxTestUtil.enlistTestXAResource(txn); }

Target:
log.tracef
Source:
public void touch() { log.debug("Stateful bean instance has been touched"); }

Target:
log.trace
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) { throw new EJBException("Can't get status of transaction", se); } }

Target:
Why not allow the SystemException up?
Source:
public void writeItems(java.util.List<Object> items) throws Exception { for(Object o : items){ LOG.info(o.toString()); } }

Target:
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.
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 if (mode.isTransactional()) { try { Thread.sleep(GRACE_TIME_TO_REPLICATE); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } }; }

Target:
Missing negation.
Source:
public MyFacesInjectionProvider() { if (StartupContext.getInjectionContainer() != null) { this.injectionContainer = StartupContext.getInjectionContainer(); } }

Target:
No need to check the value of StartupContext.getInjectionContainer() here before assigning it to this.injectionContainer.
Source:
public void postConstruct(Object instance, Object creationMetaData) throws InjectionProviderException { try { injectionContainer.newInstance(instance); } catch (Exception e) { throw new InjectionProviderException(e); } }

Target:
A check is needed at the beginning of this method to make sure injectionContainer is not null.
Source:
public static void setProperty(String name, String value, ModelControllerClient client) { ModelNode modelNode = createOpNode("system-property=" + name, ADD); modelNode.get(VALUE).set(value); modelNode.get(OPERATION_HEADERS).get(ALLOW_RESOURCE_SERVICE_RESTART).set(true); ModelNode result = executeOp(modelNode, client); log.debugf("Added property %s, result: %s", name, result); }

Target:
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.
Source:
public static void removeProperty(String name, ModelControllerClient client) { ModelNode modelNode = createOpNode("system-property=" + name, REMOVE); ModelNode result = executeOp(modelNode, client); modelNode.get(OPERATION_HEADERS).get(ALLOW_RESOURCE_SERVICE_RESTART).set(true); log.debugf("Removing property %s. Result: %s.", name, result); }

Target:
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.
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); modelNode.get(OPERATION_HEADERS).get(ALLOW_RESOURCE_SERVICE_RESTART).set(true); ModelNode result = executeOp(modelNode, client); log.debugf("Redefine property %s to value %s. Result: %s.", name, value, result); }

Target:
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.
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()) { JSFResourceDefinition.registerTransformers(subsystem); } }

Target:
There's a new ServiceLoader based way of registering transformers that should be used -- see implementations of org.jboss.as.controller.transform.ExtensionTransformerRegistration
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()); assertEquals(true, city.getRegisteredCountry().isInEuropeanUnion()); }

Target:
These two could be `assertTrue`.
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()); assertEquals( "city.getRepresentedCountry().isInEuropeanUnion() does not return true", true, this.insights.getRepresentedCountry().isInEuropeanUnion()); }

Target:
`assertTrue`
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) { return false; } }

Target:
You might want to add `debug` if you ever want to debug whey backup name is not being validated (could be special characters etc.,)
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()) { logger.error("Snapshot Operation is already running! Try again later."); throw new Exception("Snapshot Operation already running"); } try { executeSnapshot(); } finally { lock.unlock(); } }

Target:
nit: maybe a warn, since this is not necessary caused by application, but rather due to crons?
Source:
public PriamConfigurationPersister(IConfiguration config) { super(config); mergedConfigDirectory = Paths.get(config.getMergedConfigurationDirectory()); structuredPath = Paths.get(config.getMergedConfigurationDirectory(), "structured.json"); initialized = false; canWrite = false; }

Target:
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.
Source:
public void setRestoring(boolean isRestoring) { this.isRestore.set(isRestoring); }

Target:
Are you setting these anywhere?
Source:
public org.radargun.traits.Query.Builder subquery() { return this; }

Target:
Why is this needed? Can't you import the class with the name `Query` to avoid this on line 3 above?
Source:
protected <T> TransactionManager getTransactionManager(T resource) { if (resource instanceof HotRodOperations.HotRodCache) { return ((HotRodOperations.HotRodCache) resource).noReturn.getTransactionManager(); } else { throw new IllegalArgumentException("Invalid resource: " + String.valueOf(resource)); } }

Target:
@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.
Source:
public void reset() { super.reset(); traits = null; clearlisteners(); }

Target:
this should go to super.reset(), shouldn't it?
Source:
public synchronized boolean containsValuesOfType(Category.Type type) { return values.keySet().stream().anyMatch(e -> e.getType().equals(type)); }

Target:
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.
Source:
public void run(MasterConfig masterConfig, Collection<Report> reports) { 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); } }

Target:
Would it be possible to add this config to the ones that are uploaded to PerfRepo in the uploadAttachments method?
Source:
private Category(String name, Type type) { Objects.nonNull(name); Objects.nonNull(type); this.name = name; this.type = type; }

Target:
This can be removed.
Source:
public Object generateValue(Object key, int size, Random random) { return new RandomStream(key.hashCode(), size); }

Target:
Generating identical streams for the same key is not a good property of a *random value* generator.
Source:
public void onNext(Frame frame) { log.append(new String(frame.getPayload())); }

Target:
Shouldn't you rather log directly?
Source:
protected Completion createCompletion() { Completion completion = new TimeStressorCompletion(duration); if (numOperations > 0) { long countPerNode = numOperations / getExecutingSlaves().size(); long modCountPerNode = numOperations % getExecutingSlaves().size(); if (getExecutingSlaveIndex() + 1 <= modCountPerNode) { countPerNode++; } completion = new CountStressorCompletion(countPerNode); } return completion; }

Target:
Please put the creation of `TimeStressorCompletion` to else branch (you can omit the variable and return new instance right away).
Source:
protected Map<String, Object> getStats(Protocol protocol){ return stack.dumpStats(); }

Target:
why does this need an override?
Source:
public void finished(boolean successful, Operation operation) { statistics.record(this, operation); this.successful = successful; }

Target:
Looks redundant.
Source:
private String buildUrl(String cache, K key) { String s = new StringBuffer(buildCacheUrl(cache)).append("/").append(key).toString(); log.trace("buildUrl(String cache, K key) = " + s); return s; }

Target:
StringBuilder please
Source:
public void createReportDirectory() { File dir = new File(directory); if (dir.exists() && !dir.isDirectory()) { throw new IllegalArgumentException(dir.getAbsolutePath() + " is not a directory"); } else if (!dir.exists()) { dir.mkdirs(); } }

Target:
The check is not necessary, File.mkdirs doesn't attempt to create the directory when one already exists.
Source:
public SortedMap<String, SortedMap<Integer, String>> getProperties() { return properties; }

Target:
What about returning generic Map interface?
Source:
public long next() { long result = (long) (random.nextGaussian() * standardDeviation + mean); while (result < 0 || result >= numEntries) { result = (long) (random.nextGaussian() * standardDeviation + mean); } return result; }

Target:
This might be a good fit for do-while cycle.
Source:
public static Properties loadProperties(Properties properties, InputStream inputStream) throws IOException { try { properties.load(inputStream); return properties; } finally { close(inputStream); } }

Target:
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.
Source:
public V getAndRemove(K key) { boolean startedTx = startTxAndLock(key); super.remove(key); V prev = super.getAndRemove(key); stopTx(startedTx); return prev; }

Target:
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.
Source:
public void created(ClientCacheEntryCreatedEvent e) { for (CreatedListener listener : created) { try { listener.created(e.getKey(), e.getVersion()); } catch (Throwable t) { log.error("Listener " + listener + " has thrown an exception", t); } } }

Target:
I am starting to be reluctant to catching Throwable without rethrowing: could you change this to Exception both here and in embedded listeners?
Source:
protected int getExpectedNumEntries() { return getNumEntries() * (backupValueGenerator != null ? backupCacheInstances.length + 1 : 1); }

Target:
backupCacheInstances != null ? backupCacheInstances.length + 1 : 1 would make more sense
Source:
public void stop() { managerNoReturn.stop(); managerNoReturn = null; managerForceReturn.stop(); managerForceReturn.stop(); }

Target:
Is this double invocation performed on purpose?
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); resultObjects.add(obj); return obj; }

Target:
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.
Source:
private Address findHostPhysicalAddress(String nodeAddress) { Address result = null; Transport t = cacheManager.getTransport(); if (t == null) { result = cacheManager.getAddress(); } else { for (Address add : t.getPhysicalAddresses()) { if (add.toString().contains(nodeAddress)) { result = add; break; } } } return result; }

Target:
Looking into getAddress() implementation this returns null if Transport is null...
Source:
public void setUseIntermediateSharedCache(boolean useIntermediateSharedCache) { //Not used by Infinispan 5.1 }

Target:
Shouldn't we rather throw UnsupportedOperationException() in this case? Or rather create interface without the support and extend it with interface with these methods?
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)); } catch (Exception e) { return false; } }

Target:
let's add: LOGGER.debug(e)
Source:
default boolean isAppRunning(String apk) { AndroidService androidService = AndroidService.getInstance(); 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; } }

Target:
remove reference to AbdroidService please. All functionality step-by-step should be moved to interface
Source:
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(); }

Target:
Let's make it `v.cov < minAvgCov || c.cov > maxAvgCov`.
Source:
public void compute(Iterator<RayMessage> msgIterator) throws Exception { if (getSuperstep() == 1) { initVertex(); if (isStartSeed()) { msgIterator = getStartMessage(); } } scaffold(msgIterator); voteToHalt(); }

Target:
Why do you need this initVertex() here? You already add it in confgure.
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; return readHead.getThisReadSequence().getGeneCodeAtPosition(neighborPositionOnRead) == neighbor .getGeneCodeAtPosition(kmerSize - 1); }

Target:
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.
Source:
public Integer getPreKmerLength() { if(preKmerLength == null) preKmerLength = new Integer(0); return preKmerLength; }

Target:
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!)
Source:
public String toString(){ StringBuilder sbuilder = new StringBuilder(); sbuilder.append('{'); sbuilder.append(kmer + " " + et); sbuilder.append('}'); return sbuilder.toString(); }

Target:
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.
Source:
public void compute(Iterator<MessageWritable> msgIterator) throws Exception { initVertex(); if (getSuperstep() == 1 && startSeeds.contains(getVertexId())) { markSelfAndBroadcast(); } else if (getSuperstep() <= numOfHops + 1 && msgIterator.hasNext()) { markSelfAndBroadcast(); } voteToHalt(); }

Target:
what's the different between these if /else branch ?
Source:
public void updateOrderFulfillerStatus_shouldEditFulfillerStatusWithAccessioNumberInOrder() { Order originalOrder = orderService.getOrder(111); String commentText = "We got the new order"; String accessionNumber = "12345"; assertNotEquals(originalOrder.getAccessionNumber(), 0); orderService.updateOrderFulfillerStatus(originalOrder, Order.FulfillerStatus.IN_PROGRESS, commentText, accessionNumber); Order updatedOrder = orderService.getOrder(111); assertEquals(updatedOrder.getAccessionNumber(), accessionNumber); }

Target:
Minor point, but shouldn't we really be testing here that the accession number is not "12345"?
Source:
public void addCondition(Condition condition) { if (condition != null) { condition.setEncounter(this); getConditions().add(condition); } }

Target:
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.
Source:
public void getPrograms_shouldTestGetProgramsIfCohortIsEmpty() { int i = 0; Cohort cohort = new Cohort(); Collection<Program> programs = pws.getAllPrograms(); List<PatientProgram> patientPrograms; cohort.getMemberIds().clear(); patientPrograms = dao.getPatientPrograms(null, programs); assertEquals(patientPrograms.size(), 4); }

Target:
what is this variable?
Source:
public void getAllConceptStateConversion_shouldTestGetAllConceptStateConversion() { List<ConceptStateConversion> conceptStateConversions = pws.getAllConceptStateConversions(); int len = conceptStateConversions.size(); assertEquals(len, 1); }

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

Target:
unnecessary variable
Source:
public void getPrograms_shouldTestGetProgramsIfCohortIsNotEmpty() { int i = 0; 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); }

Target:
Is there a need for this variable ?
Source:
public TaskDefinition getTaskByUuid(String uuid) { if (log.isDebugEnabled()) { log.debug("get task " + uuid); } return getSchedulerDAO().getTaskByUuid(uuid); }

Target:
```suggestion log.debug("get-task uuid:" + uuid); ```
Source:
public Concept hydrate(String s) { try { return Context.getConceptService().getConcept(Integer.valueOf(s)); } catch (Exception e) { logger.error("Error", e); } //pass return null; }

Target:
Change this to `log`
Source:
public void validate(Object obj, Errors errors) throws APIException { log.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"); }

Target:
Is there a unit test to validate the exception when obj is null or its not a instance of Alert ?
Source:
public void runBeforeAllTests() { conceptService = Context.getConceptService(); executeDataSet(STANDARD_TEST_DATASET_XML); }

Target:
Isn't this dataset automatically executed?
Source:
public void saveConceptProposal_shouldReturnSavedConceptProposalObject() { 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); }

Target:
Is this a constant? Or is it allowed to change its value?
Source:
public void setOnsetDate(Date onsetDate) { this.onsetDate = new Date(onsetDate.getTime()); }

Target:
What happens, if the `onsetDate` is null?
Source:
public Date getEndDate() { return endDate != null ? (Date) endDate.clone() : new Date(); }

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

Target:
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)); ```
Source:
public void getVisitsByPatient_shouldReturnEmptyListGivenPatientWithNullPatientIdAndTrue() { Patient p = new Patient(); p.setPatientId(null); assertThat(visitService.getVisitsByPatient(p, true, true), is(empty())); }

Target:
Why not just pass null instead of p?
Source:
public void closedLow(boolean closedLow) { this.closedLow = closedLow == true; }

Target:
simply having `this.closedLow = closedLow` would be enough
Source:
public void closedHigh(boolean closedHigh) { this.closedHigh = closedHigh == false; }

Target:
This seems wrong. when the method parameter closedHigh is false you will be assigning true to the this.closedHigh. Is that correct _
Source:
public List<Condition> getActiveConditions(Patient patient) { System.out.println("near query in getActiveConditions in core"); 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(); }

Target:
Its not a good practice to use sysout. Better to use logs instead
Source:
public boolean isReady() { // TODO Auto-generated method stub return false; }

Target:
@Irenyak1 why return false here?
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; } // keep the default behavior try { throw e; } catch (Exception x) { x.printStackTrace(); } return info; }

Target:
@gitcliff , what happens when you leave out this change?
Source:
public Collection<CohortMembership> getMemberships() { if (memberships == null) { memberships = new TreeSet<>(); } return memberships; return memberships.stream().filter(m -> !m.isVoided()).collect(Collectors.toList()); }

Target:
I think you may have forgotten to delete this line.
Source:
public void authenticate_shouldAuthenticateUserWithAlternateScheme() { // replay Context.logout(); Authenticated authenticated = Context.authenticate(new TestUsernameCredentials("admin")); // verif Assert.assertEquals("test-scheme", authenticated.getAuthenticationScheme()); Assert.assertEquals(Context.getAuthenticatedUser().getUuid(), authenticated.getUser().getUuid()); Assert.assertEquals("admin", Context.getAuthenticatedUser().getUsername()); }

Target:
Do we need the above line? What happens if we get rid of it?
Source:
public void equal_shouldReturnFalseIfObjectIsNull() { // A null argument to equal should not lead to an exception CohortMembership cohortMembership = new CohortMembership(12); boolean result = cohortMembership.equals(null); assertFalse(result); }

Target:
I guess we could just assert without the temporary result variable.
Source:
public void confirmNoKnownAllergies() throws RuntimeException { if (!allergies.isEmpty()) { throw new APIException("Cannot confirm no known allergies if allergy list is not empty"); } allergyStatus = NO_KNOWN_ALLERGIES; }

Target:
@manuelkollus Are you sure this is what was required? According to me, Its quiet superfluous to add a `throws` clause of a ` RuntimeException` since as a matter of fact its an unchecked `Exception`.
Source:
public Optional<String> getLatestSchemaSnapshotFilename() { Optional<String> snapshotVersion = getLatestSnapshotVersion(); if (snapshotVersion.isPresent()) { return Optional .of(SCHEMA_ONLY_FOLDER_NAME + File.separator + SCHEMA_ONLY_BASE_NAME + snapshotVersion.get() + DOT_XML); } return Optional.empty(); }

Target:
This can be reduced to: ```java return getLatestLiquibaseSnapshotVersion().map( snapshotVersion -> LIQUIBASE_SNAPSHOTS_FOLDER + File.separator + snapshotVersion + File.separator + LIQUIBASE_CORE_DATA_FILENAME); ``` Not that you need to make that change.
Source:
protected void dropAllDatabaseObjects() throws SQLException { Statement statement = null; try { statement = connection.createStatement(); String query = "DROP ALL OBJECTS"; statement.execute(query); } catch (JdbcSQLNonTransientException e) { log.info("connection is already closed, most likely a test method already dropped all database objects"); } finally { connection.close(); } }

Target:
`log.info` or `log.error`?
Source:
public User getUserByUsernameOrEmail(String usernameOrEmail) { if (StringUtils.isNotBlank(usernameOrEmail)) { User user = dao.getUserByEmail(usernameOrEmail); if (user == null) { return getUserByUsername(usernameOrEmail); } else { return user; } } throw new APIException("error.usernameOrEmail.notNullOrBlank", (Object[]) null); }

Target:
This else clause is redundant since the else clause always returns, just return the user
Source:
public void removeGlobalPropertyListener_shouldNotFailOnNullListener() { GlobalPropertyListener globalPropertyListener = null; assertNull(globalPropertyListener); adminService.removeGlobalPropertyListener(globalPropertyListener); }

Target:
no need to assert its null, you set it to null the line above. you can simply inline this temp variable to ```java adminService.removeGlobalPropertyListener(null) ```
Source:
public List<Diagnosis> getDiagnoses(Patient patient, Date fromDate) { return diagnosisDAO.getActiveDiagnoses(patient); }

Target:
Did you intentionally ignore the fromDate parameter?
Source:
public void shouldGetDiagnoses() { Encounter encounter = new Encounter(3); List<Diagnosis> firstDiagnoses= diagnosisDAO.getDiagnoses(encounter); assertEquals(2, firstDiagnoses.size()); Encounter otherEncounter = new Encounter(9); List<Diagnosis> secondDiagnoses= diagnosisDAO.getDiagnoses(otherEncounter); assertEquals(0, secondDiagnoses.size()); }

Target:
Does the patient actually have any voided diagnoses to make this test more solid?
Source:
public void shouldGetActiveDiagnoses() { Patient patient = new Patient(2); List<Diagnosis> activeDiagnosis = diagnosisDAO.getActiveDiagnoses(patient); assertEquals(2, activeDiagnosis.size()); }

Target:
We can get rid of the above variable
Source:
public Condition getConditionByUuid(String uuid) { if(log.isInfoEnabled()){ log.info("Getting condition with uuid " + uuid); } return conditionDAO.getConditionByUuid(uuid); }

Target:
This is unncessary
Source:
public List<Condition> getActiveConditions(Patient patient) { if(log.isInfoEnabled()){ log.info("Getting active conditions with patient " + patient); } return conditionDAO.getActiveConditions(patient); }

Target:
Can you remove this too
Source:
public Condition unvoidCondition(Condition condition) throws APIException { condition.setVoided(false); condition.setVoidedBy(null); condition.setDateVoided(null); condition.setVoidReason(null); Context.getConditionService().saveCondition(condition); return condition; }

Target:
Did you look at the ObsServiceImpl's unvoidObs()?
Source:
public Condition saveCondition(Condition condition) throws APIException { return conditionDAO.saveCondition(condition); }

Target:
You will not need this after putting it at the class level
Source:
public void purgeCondition(Condition condition) throws APIException { conditionDAO.deleteCondition(condition); }

Target:
Actually it's pointless to include the throws clause since APIException is a runtime exception that doesn't need to be caught.
Source:
public User getUserByUsername(String username) throws APIException { User user = dao.getUserByUsername(username); if (isDaemon(user)) { log.warn("requested User '" + username + "' is Daemon"); return null; } return user; }

Target:
This should not be changed, you should only be changing search methods
Source:
public User getUser(Integer userId) throws APIException { User user = dao.getUser(userId); if (isDaemon(user)) { log.warn("requested User of Id '" + userId + "' is Daemon"); return null; } return user; }

Target:
This should not be changed, you should only be changing search methods
Source:
public List<User> getUsersByRole(Role role) throws APIException { List<Role> roles = new ArrayList<>(); roles.add(role); return removeDaemonUsers(Context.getUserService().getUsers(null, roles, false)); }

Target:
Shouldn't you be doing in this DAO in the query?
Source:
public void validate(Object object, Errors errors) { ValidationUtils.rejectIfEmptyOrWhitespace(errors, "condition", "field.required"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "clinicalStatus", "field.required"); if(object == null){ throw new IllegalArgumentException("The object parameter should not be null"); } if(!(object instanceof Condition)){ throw new IllegalArgumentException("The object parameter should be of type " + Condition.class); } }

Target:
Are you in position to create some tests for this class? Take a look at these examples: https://github.com/openmrs/openmrs-core/tree/master/api/src/test/java/org/openmrs/validator
Source:
public void getGlobalPropertyValue_shouldFailIfDefaultValueIsNull() { exception.expect(IllegalArgumentException.class); exception.expectMessage("The defaultValue argument cannot be null"); adminService.getGlobalPropertyValue("valid.double", null); }

Target:
in this test I suggest not to use the junit rule. since `getGlobalPropertyValue` only throws an `IllegalArgumentException` in one case, therefore its clear what case you are testing and we do not have to bind our test to the exception message. you can thus remove the junit rule code and replace it with ```java @Test(expected = IllegalArgumentException.class) ```
Source:
private static String getPasswordEncodeFailMessage(String algo) { String errorMessage = "Can't encode password because the given algorithm: " + algo + " was not found! (fail)"; return errorMessage; }

Target:
Why assign to a variable just for the sake of returning?
Source:
public void setPatientProgram(PatientProgram patientProgram) { setOwner(new PatientProgram()); }

Target:
Did you intentionally ignore the patientProgram parameter?
Source:
public static List<Integer> delimitedStringToIntegerList(String delimitedString, String delimiter) { List<Integer> ret = new ArrayList<>(); String[] tokens = delimitedString.split(delimiter); for (String token : tokens) { token = token.trim(); if (token.length() == 0) { } else { ret.add(Integer.valueOf(token)); } } return ret; }

Target:
Can't we simplify this by only having an if statement without else?
Source:
public void setPatientProgram(PatientProgram patientProgram) { setOwner(new PatientProgram(patientProgram)); }

Target:
This should just set patientProgram without creating another instance
Source:
private void ensureProgramIsSet(ProgramWorkflow workflow, Program program) throws APIException { if (workflow.getConcept() == null) { throw new APIException("ProgramWorkflow.concept.required", (Object[]) null); } if (workflow.getProgram() == null) { workflow.setProgram(program); } else if (!workflow.getProgram().equals(program)) { throw new APIException("Program.error.contains.ProgramWorkflow", new Object[] { workflow.getProgram() }); } }

Target:
please move the getConcept branch out of this one since this has nothing to do with ensuring the program is set. sorry for this, was probably due to the line numbers in the issue have moved since the code changed in the meanwhile.
Source:
public Obs getRevisionObs(Obs initialObs) { Obs revisedObs = dao.getRevisionObs(initialObs); if (revisedObs != null && revisedObs.getVoided()) { revisedObs = getRevisionObs(revisedObs); } return revisedObs; }

Target:
The api shouldn't be the one to recursively fetch revisions, the api caller could actually be interested in the immediate revision for some reason, so it's up to the client code to recursively do this.
Source:
public void retireConcept_shouldRetireTheGivenConcept() throws Exception { int drugId = 3; String retireReason = "dummy reason"; Concept concept = conceptService.getConcept(drugId); assertFalse(concept.isRetired()); conceptService.retireConcept(concept, retireReason); assertTrue(concept.isRetired()); assertEquals(retireReason, concept.getRetireReason()); }

Target:
you dont need this local variable, only when using the same value more than once. like you did with the retireReason.
Source:
public static boolean copyFile(InputStream inputStream, OutputStream outputStream) throws IOException { if (inputStream == null || outputStream == null) { if (outputStream != null) { IOUtils.closeQuietly(outputStream); } return false; } try { IOUtils.copy(inputStream, outputStream); } finally { IOUtils.closeQuietly(outputStream); return true; } }

Target:
dear @lkukielka changing the method signature was not part of the ticket. this would break compatibility with users of this method so please revert that change.
Source:
public void expandJar_shouldExpandEntireJarIfNameIsNull() throws IOException { // Arrange final int numberOfFilesInJar = 6; File destinationFolder = this.getEmptyJarDestinationFolder(); // Act ModuleUtil.expandJar(getJarFile(), destinationFolder, null, false); // Assert Assert.assertEquals(numberOfFilesInJar, FileUtils.listFiles(destinationFolder, null, true).size()); // Clean up FileUtils.deleteDirectory(destinationFolder); }

Target:
Can you please use the openmrs generate test case plugin, see https://wiki.openmrs.org/display/docs/Generate+Test+Case+Plugin You used the old test style and the generator will easily create the scaffold for you in the new style :)
Source:
public boolean contains(Patient patient) { return getMembers() != null && getMembers().stream() .anyMatch(m -> m.getPatientId().getPatientId().equals(patient.getPatientId())); }

Target:
Probably we should add a TODO item here that this needs to be changed to compare the Patient objects instead of their ids when we finally remove the deprecated methods that take ids
Source:
private void setCohort(Cohort cohort) { this.cohort = cohort; }

Target:
With access set to field in the hbm file you probably don't need this private setter
Source:
private Cohort getCohort() { return cohort; }

Target:
The getter has to be public, only the setter should be private
Source:
public Cohort addMembershipToCohort(Cohort cohort, CohortMembership cohortMembership) throws APIException { if (!cohort.contains(cohortMembership)) { ValidateUtil.validate(cohortMembership); cohort.addMembership(cohortMembership); Context.getCohortService().saveCohort(cohort); } return cohort; }

Target:
All validation should be handled in the CohortValidator, if it doesn't exist we need to add it
Source:
public void removePatientFromCohort_shouldNotFailIfCohortDoesNotContainPatient() throws Exception { executeDataSet(COHORT_XML); // make a patient Patient patientToAddThenRemove = new Patient(4); // verify that the patient is not already in the Cohort assertFalse(service.getCohort(2).contains(patientToAddThenRemove.getPatientId())); // try to remove it from the cohort without failing try { service.removePatientFromCohort(service.getCohort(2), patientToAddThenRemove); } catch (Exception e) { Assert.fail("removePatientFromCohort(Cohort,Patient) should not fail if cohort doesn't contain patient"); } }

Target:
I would imagine that you have a new contains method that takes in patient object that internally delegates to the old one so you wouldn't need these changes
Source:
public void addMembershipToCohort_shouldAddMembershipToCohort() throws Exception { executeDataSet(COHORT_XML); CohortMembership memberToAdd = new CohortMembership(new Patient(4)); service.addMembershipToCohort(service.getCohort(1), memberToAdd); assertTrue(service.getCohort(1).contains(memberToAdd)); }

Target:
Would nice to have a sanity check that the cohort doesn't contain an active membership for the patient before
Source:
public boolean isMemberActive() { return this.getStartDate().before(new Date()) && this.getEndDate() == null; }

Target:
End could be null and the memebership is active depending on the passed in asOfDate that I mentioned above
Source:
public void getAttribute_shouldReturnNullWhenExistingPersonAttributeTypeIsVoided () throws Exception { Person person = personHelper(true, 1, 2, 3, "name1", "name2", "name3", "value1", "value2", "value3"); PersonAttributeType type = new PersonAttributeType(new Integer(3)); type.setName("name3"); Assert.assertNull(null, person.getAttribute(type)); }

Target:
This is incorrect, it should be `Assert.assertNull(person.getAttribute(type));`
Source:
public OrderSet retireOrderSet(OrderSet orderSet, String retireReason) throws APIException { if (!StringUtils.hasLength(retireReason)) { throw new IllegalArgumentException("reitreReason cannot be empty or null"); } orderSet.setRetireReason(retireReason); return saveOrderSetInternal(orderSet); }

Target:
AOP around retire methods i believe already sets the reason
Source:
public void copy_shouldCopyAllDrugOrderFields() throws Exception { DrugOrder drugOrder = new DrugOrder(); Drug drug = new Drug(); drug.setConcept(new Concept()); drugOrder.setDrug(drug); OrderTest.assertThatAllFieldsAreCopied(drugOrder, null, "orderGroup", "sortWeight"); }

Target:
This is not correct, orderGroup and sortWeight need to be copied too, this should stay unchanged instead you update Order.copy to copy over these fields too
Source:
public void cloneForRevision_shouldSetAllTheRelevantFields() throws Exception { DrugOrder drugOrder = new DrugOrder(); Drug drug = new Drug(); drug.setConcept(new Concept()); drugOrder.setDrug(drug); OrderTest.assertThatAllFieldsAreCopied(drugOrder, "cloneForRevision", "creator", "dateCreated", "action", "changedBy", "dateChanged", "voided", "dateVoided", "voidedBy", "voidReason", "encounter", "orderNumber", "orderer", "previousOrder", "dateActivated", "dateStopped", "accessionNumber", "orderGroup", "sortWeight"); }

Target:
Same here, orderGroup and sortWeight need to be cloned and you undo this change
Source:
public void copy_shouldCopyAllFields() throws Exception { assertThatAllFieldsAreCopied(new Order(), null, "orderGroup", "sortWeight"); assertThatAllFieldsAreCopied(new TestOrder(), null, "orderGroup", "sortWeight"); }

Target:
This needs to be undone