auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void copy_shouldCopyAllTestOrderFields() throws Exception { OrderTest.assertThatAllFieldsAreCopied(new TestOrder(), null, "orderGroup", "sortWeight"); }

Target:
You need to undo this
Source:
protected TestOrder cloneForRevisionHelper(TestOrder target) { super.cloneForRevisionHelper(target); target.setSpecimenSource(getSpecimenSource()); target.setLaterality(getLaterality()); target.setClinicalHistory(getClinicalHistory()); target.setFrequency(getFrequency()); target.setNumberOfRepeats(getNumberOfRepeats()); target.setOrderGroup(getOrderGroup()); target.setSortWeight(getSortWeight()); return target; }

Target:
Aren't we doing this in the superclass?
Source:
public String getMessage(MessageSourceResolvable resolvable, Locale locale) { if((resolvable.getCodes()[0]) == (activeMessageSource.getMessage(resolvable, locale))){ return (resolvable.getCodes()[(resolvable.getCodes().length) - 1]); } else{ return activeMessageSource.getMessage(resolvable, locale); } }

Target:
I thought you are comparing strings, right? So i would expect use of equals
Source:
public void hasSameOrderableAs_shouldReturnFalseIfTheConceptsMatchAndHaveDifferentDrugNonCoded() throws Exception { DrugOrder order = new DrugOrder(); Concept concept = new Concept(); order.setDrugNonCoded("Chrocine"); DrugOrder otherOrder = new DrugOrder(); otherOrder.setConcept(concept); otherOrder.setDrugNonCoded("paracetemol"); assertFalse(order.hasSameOrderableAs(otherOrder)); }

Target:
You forgot to set concept on this first order
Source:
public void hasSameOrderableAs_shouldReturnTrueIfTheConceptsMatchAndHaveSameDrugNonCoded() throws Exception { DrugOrder order = new DrugOrder(); Concept concept = new Concept(); Drug drug1 = new Drug(); drug1.setConcept(concept); order.setDrug(drug1); order.setDrugNonCoded("Chrocine"); DrugOrder otherOrder = new DrugOrder(); otherOrder.setConcept(concept); otherOrder.setDrug(drug1); otherOrder.setDrugNonCoded("chrocine"); assertTrue(order.hasSameOrderableAs(otherOrder)); }

Target:
I thought drug should be null for a nonCoded order, but i see you are setting it here
Source:
public void hasSameOrderableAs_shouldReturnFalseIfTheConceptsMatchAndEitherOfDrugNonCodedIsNull() throws Exception { DrugOrder order = new DrugOrder(); Concept concept = new Concept(); order.setDrugNonCoded("Chrocine"); DrugOrder otherOrder = new DrugOrder(); otherOrder.setConcept(concept); assertFalse(order.hasSameOrderableAs(otherOrder)); }

Target:
Forgot to set set concept on this order
Source:
private DrugOrder checkDrugOrdersForDiscontinuing(DrugOrder drugOrder1, DrugOrder drugOrder2){ if (OpenmrsUtil.nullSafeEquals(drugOrder1.getDrug(), drugOrder2.getDrug())) { return drugOrder2; }else{ return null; } }

Target:
You don't need the else clause, it is redundant, just return null
Source:
public ServletInputStream getInputStream() throws IOException { if (stream == null) { stream = createInputStream(); } return (stream); }

Target:
Any methods that override should be annotated with @Override. Otherwise I can't quickly say if it is correct or not.
Source:
public static void setStaticUnknownConcept(Concept currentUnknownConcept) { ConceptServiceImpl.unknownConcept = currentUnknownConcept; }

Target:
It should be private.
Source:
public static void setStaticHandlers(Map<String, ComplexObsHandler> currentHandlers) { ObsServiceImpl.handlers = currentHandlers; }

Target:
It should be private.
Source:
public static void setStaticIdentifierValidators( Map<Class<? extends IdentifierValidator>, IdentifierValidator> currentIdentifierValidators) { PatientServiceImpl.identifierValidators = currentIdentifierValidators; }

Target:
It should be private.
Source:
public static Thread runInNewDaemonThread(final Runnable runnable) { // make sure we're already in a daemon thread if (!isDaemonThread()) { throw new APIAuthenticationException("Only daemon threads can spawn new daemon threads"); } // we should consider making DaemonThread public, so the caller can access returnedObject and exceptionThrown DaemonThread thread = new DaemonThread() { @Override public void run() { isDaemonThread.set(true); try { Context.openSession(); new Thread(runnable).start(); } finally { Context.closeSession(); } } }; thread.start(); return thread; }

Target:
This is actually intended as you can see the start method is called below in line 189: thread.start() so please revert it. We need to annotate the run method (line 177) with: @SuppressWarnings("squid:3AS1217") //We intentionally do not start a new thread yet, rather wrap the run call in a session.
Source:
public static Thread runInDaemonThread(final Runnable runnable, DaemonToken token) { if (!ModuleFactory.isTokenValid(token)) { throw new ContextAuthenticationException("Invalid token " + token); } DaemonThread thread = new DaemonThread() { @Override public void run() { isDaemonThread.set(true); try { Context.openSession(); new Thread(runnable).start(); } finally { Context.closeSession(); } } }; thread.start(); return thread; }

Target:
This is actually intended as you can see the start method is called below. Please revert it. We need to annotate the run method (line 270) with: @SuppressWarnings("squid:3AS1217") //We intentionally do not start a new thread yet, rather wrap the run call in a session.
Source:
public void saveGlobalProperties_shouldAssignUuidToAllNewProperties() throws Exception { // get the current global properties List<GlobalProperty> globalProperties = Context.getAdministrationService().getAllGlobalProperties(); globalProperties.remove(3); // and now add a new one to it and save it globalProperties.add(new GlobalProperty("new prop", "new prop value", "desc")); Context.getAdministrationService().saveGlobalProperties(globalProperties); Assert.assertNotNull(Context.getAdministrationService().getGlobalPropertyObject("new prop").getUuid()); }

Target:
If you have to remove it then seems like there is something else wrong that needs to get fixed, could be the test data that is invalid because you should never have to do this.
Source:
public boolean isOrderTypeInUse(OrderType orderType) { Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Order.class); criteria.add(Restrictions.eq("orderType", orderType)); if (criteria.list().size() > 0) { return true; } return false; }

Target:
this could all be one line i.e: return criteria.list() > 0
Source:
public OrderType unretireOrderType(OrderType orderType) { orderType.setRetired(false); return dao.saveOrderType(orderType); }

Target:
same here, don't set fields, just call save here
Source:
public Order cloneForDiscontinuing() { DrugOrder newOrder = new DrugOrder(); newOrder.setCareSetting(this.getCareSetting()); newOrder.setConcept(this.getConcept()); newOrder.setAction(Action.DISCONTINUE); newOrder.setPreviousOrder(this); newOrder.setPatient(this.getPatient()); newOrder.setDrug(this.getDrug()); newOrder.setStartDate(this.getStartDate()); newOrder.setOrderer(this.getOrderer()); return newOrder; }

Target:
This is not right because the provider who prescribed the order is not always going to be the same person to discontinue it, so don't copy this field
Source:
public Order cloneForDiscontinuing() { Order newOrder = new Order(); newOrder.setCareSetting(this.getCareSetting()); newOrder.setConcept(this.getConcept()); newOrder.setAction(Action.DISCONTINUE); newOrder.setPreviousOrder(this); newOrder.setPatient(this.getPatient()); newOrder.setOrderer(this.getOrderer()); newOrder.setStartDate(this.getStartDate()); return newOrder; }

Target:
same here, don't copy orderer
Source:
public Collection<DrugReferenceMap> getDrugReferenceMaps() { if (drugReferenceMaps == null) { drugReferenceMaps = Collections.EMPTY_LIST; } return drugReferenceMaps; }

Target:
I think this should be a set, @djazayeri isn't the convention supposed to be a set
Source:
public CustomDatatype.Summary toHtmlSummary(CustomDatatype<T> datatype, String valueReference) { SerializingCustomDatatype<T> dt = (SerializingCustomDatatype<T>) datatype; return new CustomDatatype.Summary(dt.deserialize(valueReference).getName(), true); }

Target:
To avoid duplicating code, you should call to to Html() below to fetch the name
Source:
public EncounterType saveEncounterType(EncounterType encounterType) throws EncounterTypeLockedException { sessionFactory.getCurrentSession().saveOrUpdate(encounterType); return encounterType; }

Target:
In the DAO we don't throw APIExceptions and its subclasses in general, so you can remove this
Source:
public ActiveListItem deleteActiveListItem(ActiveListItem item) throws DAOException { sessionFactory.getCurrentSession().delete(item); return null; }

Target:
No reason to return null. make this a void
Source:
private String setupState(Response response) { String sessionId = UUID.randomUUID().toString(); byte[] secret = new byte[20]; random.nextBytes(secret); String state = java.util.Base64.getEncoder().encodeToString(secret); CookieSetting cs = new CookieSetting("_state", sessionId); response.getCookieSettings().add(cs); getContext().getAttributes().put(sessionId, state); return state; }

Target:
Why the fully qualified class name ?
Source:
public static String processResourceName(String uri) { String processedUri = ""; String[] split = uri.replaceAll("\\{", "").replaceAll("\\}", "") .split("/"); for (String str : split) { processedUri += StringUtils.firstUpper(str); } return processedUri; }

Target:
If you need to build a string on several instruction (other that `"a" + "b" + "c"`), use a `StringBuilder`
Source:
public List<InvoiceItem> createExternalCharges(final Iterable<InvoiceItem> externalCharges, @Nullable final LocalDate requestedDate, final Boolean autoPay, final Boolean autoCommit, final String createdBy, final String reason, final String comment) throws KillBillClientException { return createExternalCharges(externalCharges, requestedDate, autoPay, autoCommit, null, null, RequestOptions.builder() .withCreatedBy(createdBy) .withReason(reason) .withComment(comment).build()); }

Target:
That one should be `@Deprecated` (no `RequestOptions`).
Source:
} catch (ClassNotFoundException onlyIfOpenTestIsNotAvailable) { try { Class.forName("junit.framework.ComparisonFailure"); theFactory = new ExceptionFactoryImpl() { @Override public AssertionError create(String message, String wanted, String actual) { return new org.mockito.exceptions.verification.junit.ArgumentsAreDifferent(message, wanted, actual); } }; } catch (ClassNotFoundException onlyIfJUnitIsNotAvailable) { } }

Target:
Great feedback. Thanks for taking the time. mostly what prompted by suggestion is that I was concerned that `Class.forName(...);` may be optimized away by an aggressive optimizer if its result is unused. Though my concerns may be unfounded, since it throws checked exceptions, so it has a potential side-effect. 🤷‍♂
Source:
protected void validateMatchers(Invocation invocation, List<LocalizedMatcher> lastMatchers) { if (!lastMatchers.isEmpty()) { int recordedMatchersSize = lastMatchers.size(); int expectedMatchersSize = invocation.getArguments().length; if (expectedMatchersSize != recordedMatchersSize) { throw invalidUseOfMatchers(expectedMatchersSize, lastMatchers); } } }

Target:
What is the reasoning for making this protected? It is an internal class, so it should not be subclassed.
Source:
public OngoingStubbing<T> thenThrow(Class<? extends Throwable> toBeThrown, Class<? extends Throwable>... nextToBeThrown) { if (nextToBeThrown == null) { return abortNullExceptionType(); } OngoingStubbing<T> stubbing = thenThrow(toBeThrown); for (Class<? extends Throwable> t : nextToBeThrown) { stubbing = stubbing.thenThrow(t); } return stubbing; }

Target:
This looks like a change in behavior. What is driving this? We are very careful when making changes in behavior that can cause issues when migrating to newer version of Mockito.
Source:
public Object answer(InvocationOnMock invocation) throws Throwable { if (throwable == null) { throw new IllegalStateException("throwable is null: " + "you shall not call #answer if #validateFor fails!"); } if (MockUtil.isMock(throwable)) { throw throwable; } throwable.fillInStackTrace(); filter.filter(throwable); throw throwable; }

Target:
This exception message is not consistent with how we handle exceptions. Take a look at a Reporter class. Typically we throw an exception that is or derives from MockitoException. The message needs to be very clean, actionable to the end user. I suggest to create a high level unit test that demonstrates this use case from the standpoint of the end user. Run this test, observe the exception, would a newbie Mockito understand the exception message and was able to resolve the problem quickly?
Source:
private static String createAllLocationsMessage(List<Location> locations) { if (locations == null) { return "\n"; } StringBuilder sb = new StringBuilder(); for (Location invocation : locations) { sb.append(invocation).append("\n"); } return sb.toString(); }

Target:
`infocation` → `location`?
Source:
public Invocation createInvocation(Object target, MockCreationSettings settings, Method method, final Callable realMethod, Object... args) { RealMethod.FromCallable superMethod = new RealMethod.FromCallable(realMethod); return MockMethodInterceptor.createInvocation(target, method, args, superMethod, settings); }

Target:
Nit: no need to add `final` here
Source:
public MockMethodAdvice(WeakConcurrentMap<Object, MockMethodInterceptor> interceptors, String identifier) { this.interceptors = interceptors; this.identifier = identifier; try { Field field = WeakConcurrentMap.class.getDeclaredField("target"); field.setAccessible(true); backingMap = field.get(interceptors); } catch (Exception e) { throw new MockitoException("Could not resolve backing map from concurrent hash map", e); } }

Target:
Can we make the message more actionable? Is there anything the user can do? File a ticket?
Source:
public void finishMocking() { //Cleaning up the state, we no longer need the listener hooked up //The listener implements MockCreationListener and at this point //we no longer need to listen on mock creation events. We are wrapping up the session Mockito.framework().removeListener(listener); //Emit test finished event so that validation such as strict stubbing can take place listener.testFinished(new TestFinishedEvent() { public Throwable getFailure() { return null; } public Object getTestClassInstance() { return testClassInstances.get(0); } public String getTestMethodName() { return null; } }); //Finally, validate user's misuse of Mockito framework. Mockito.validateMockitoUsage(); }

Target:
This is unfortunate. We probably have to fix #1232 first to improve our API and then base this PR on that change.
Source:
public MockitoSessionBuilder strictness(Strictness strictness) { if (strictness==null){ strictness = STRICT_STUBS; } this.strictness = strictness; return this; }

Target:
Spaces around the `==`
Source:
public List<T> getAllValues() { readLock.lock(); try { return Arrays.asList((T[]) arguments.toArray()); } finally { readLock.unlock(); } }

Target:
Why not just return ```new ArrayList()``` or ```new LinkedList()```? This way, we would be a little bit more backwards compatible in some edge cases (like somebody adding stuff the list returned by the capturing matcher).
Source:
public void creates_instances_with_arguments() { assertEquals(new ConstructorInstantiator("someString").newInstance(SomeClass2.class).getClass(), SomeClass2.class); }

Target:
Fantastic coverage, thank you!
Source:
public void should_call_single_listener_on_verify() throws NoSuchMethodException { //given RememberingListener listener = new RememberingListener(); MockitoFramework mockitoFramework = Mockito.framework(); mockitoFramework.addListener(listener); Method invocationWanted = Foo.class.getDeclaredMethod("doSomething", String.class); Foo foo = mock(Foo.class); //when VerificationMode never = never(); verify(foo, never).doSomething(""); //then assertThat(listener).is(notifiedFor(foo, never, invocationWanted)); }

Target:
I would say to keep the setUp. It is cleaner and more DRY.
Source:
public void should_create_mock_from_final_class_in_the_JDK() throws Exception { assumeTrue(ClassFileVersion.ofThisVm().isLessThan(ClassFileVersion.JAVA_V9)); // Change when ByteBuddy has ASM6 MockCreationSettings<Pattern> settings = settingsFor(Pattern.class); Pattern proxy = mockMaker.createMock(settings, new MockHandlerImpl<Pattern>(settings)); assertThat(proxy.pattern()).isEqualTo("bar"); }

Target:
This will be a conflict with current master: https://github.com/mockito/mockito/blob/master/src/test/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMakerTest.java#L42 Let's choose one way or another. I am fine with either way, no specific preference.
Source:
public static boolean isJava8BelowUpdate45() { if(!JAVA_VERSION.equals("1.8")) { return false; } int beginIndex = JVM_VERSION.indexOf('_'); int endIndex = JVM_VERSION.indexOf('b'); if(beginIndex == -1 || endIndex == -1) { return false; } String updateVersion = JVM_VERSION.substring(beginIndex + 1, endIndex - 1); return 45 > Integer.valueOf(updateVersion); }

Target:
Let's make sure this is always safe, regardless of the content of the system properties. Those properties are mutable AFAIK, and/or might change/be different with future versions of java or perhaps even jvm/jdk vendor. Otherwise, love this PR :)
Source:
public void addListener(MockitoListener listener) { if (listener instanceof MockCreationListener) { mockingProgress().addListener(listener); } }

Target:
@szczepiq Is this really needed? [MockingProgressImpl.mockingStarted()](https://github.com/mockito/mockito/pull/527/files#diff-df53f45103af61fe77db9216591b7ad5R146) filters already for `MockCreationListener`.
Source:
public void addListener(MockitoListener listener) { assertNotNull(listener); if (listener instanceof MockCreationListener) { mockingProgress().addListener(listener); } }

Target:
Why the instance check ?
Source:
private List<TestResult> filterTests(List<? extends TestResult> failedTests, String regexPattern) { if(regexPattern.length() != 0) { Pattern pattern = Pattern.compile(regexPattern); failedTests = failedTests.stream().filter(t -> pattern.matcher(t.getFullName()).matches()).collect(Collectors.toList()); } return (List<TestResult>)failedTests; }

Target:
Instead of casting, I would prefer to use the same return type.
Source:
protected void appendDetail(final StringBuffer buffer, final String fieldName, final Collection<?> coll) { if (coll != null && !coll.isEmpty()) { coll.stream().findFirst() .map(Object::getClass) .filter(Class::isEnum) .ifPresent((clazz) -> appendDetail(buffer, fieldName, coll.toArray())); return; } buffer.append(coll); }

Target:
Hello, this will restrict only enums to be appended from a collection, a list of other types (e.g. Collection of Integers or Strings) will be ignored. This filter should be removed to allow all types of collections (or we should allow buffer.append(col1) at last line of method to run for other types, either way)
Source:
public static float[] removeAllOccurences(final float[] array, final float element) { BitSet foundBits = indexesOf(array, element); return (float[]) removeAll((Object) array, foundBits); }

Target:
How about inlining all of the 'foundBits'?
Source:
public static RuntimeException rethrow(Throwable pThrowable) { if (pThrowable == null) { throw new NullPointerException("The Throwable must not be null."); } if (pThrowable instanceof RuntimeException) { throw (RuntimeException) pThrowable; } else if (pThrowable instanceof Error) { throw (Error) pThrowable; } else if (pThrowable instanceof IOException) { throw new UncheckedIOException((IOException) pThrowable); } else { throw new UndeclaredThrowableException(pThrowable); } }

Target:
This is a completely different change; please don't mix changes in a pull request.
Source:
private Object readResolve() { return ToStringStyle.NO_CLASS_NAME_MULTI_LINE_STYLE; }

Target:
Really nit-picking here, but other classes in this file are referencing it without the class name (as this is the same class...). So if possible, for consistency it could be the same, i.e. `return NO_CLASS_NAME_MULTI_LINE_STYLE;`.
Source:
public boolean equals(final Object obj) { // Eliminate the usual boilerplate because // this inner static class is only used in a generic ConcurrentHashMap // which will not compare against other Object types return obj instanceof MultipartKey && Arrays.equals(keys, ((MultipartKey)obj).keys); }

Target:
Please do not include unrelated changes in a single pull request. Thanks!
Source:
public void minutesOutOfRange() { Assert.assertEquals(0, new GmtTimeZone(false, 60, 0)); }

Target:
This test is wrong. Its title states that the minutes will be out of range, but the hour is actually out of range (60). Minute is 0, but never gets checked.
Source:
public static String appendIfNotEmpty(final String str, final String suffix) { return isEmpty(str) ? EMPTY : str + defaultString(suffix); }

Target:
```suggestion return isEmpty(str) ? str : str + defaultString(suffix); ```
Source:
public static String appendIfNotBlank(final String str, final String suffix) { return isBlank(str) ? EMPTY : str + defaultString(suffix); }

Target:
```suggestion return isBlank(str) ? str : str + defaultString(suffix); ```
Source:
public static String prependIfNotEmpty(final String str, final String prefix) { return isEmpty(str) ? EMPTY : defaultString(prefix) + str; }

Target:
```suggestion return isEmpty(str) ? str : defaultString(prefix) + str; ```
Source:
public static String prependIfNotBlank(final String str, final String prefix) { return isBlank(str) ? EMPTY : defaultString(prefix) + str; }

Target:
```suggestion return isBlank(str) ? str : defaultString(prefix) + str; ```
Source:
public static boolean isAnyNotEmpty(final CharSequence... css) { if (ArrayUtils.isEmpty(css)) { return true; } for (final CharSequence cs : css){ if (isNotEmpty(cs)) { return true; } } return false; }

Target:
Shouldn't this return false? An empty Array does not contain any non empty CharSequences. WDYT?
Source:
public void testToCalendarWithDateNull() { try { DateUtils.toCalendar(null, zone); fail("Expected NullPointerException to be thrown when Date is null"); } catch(final NullPointerException npe) { // expected } }

Target:
you don't need a try-catch here. You can simply use `@Test(expected=NullPointerException.class)`
Source:
public void testToCalendarWithTimeZoneNull() { try { DateUtils.toCalendar(date1, null); fail("Expected NullPointerException to be thrown when TimeZone is null"); } catch(final NullPointerException npe) { // expected } }

Target:
you don't need a try-catch here. You can simply use `@Test(expected=NullPointerException.class)`
Source:
public static Thread findThreadById(final long threadId) { final Collection<Thread> result = findThreads(new ThreadIdPredicate(threadId)); if(!result.iterator().hasNext()) { return null; } else { return result.iterator().next(); } }

Target:
result.isEmpty() can be used instead to avoid creating an iterator instance.
Source:
public static <T extends Serializable> T roundtrip(final T msg) { return SerializationUtils.deserialize(SerializationUtils.serialize(msg)); }

Target:
whoops, why are we removing this again? :-)
Source:
public boolean contains(Module module, Flow flow) { logger.info("Check contains: " + module + flow); return this.cache.containsKey(module.getName()+flow.getName()); }

Target:
it should be debug
Source:
public List<ModuleMetaData> getAllModule() { JsonModuleMetaDataProvider provider = new JsonModuleMetaDataProvider(new JsonFlowMetaDataProvider()); return this.moduleMetadata.values().stream() .map(moduleMetadata -> provider.deserialiseModule(moduleMetadata)) .collect(Collectors.toList()); }

Target:
done
Source:
public ResponseEntity harvestConfigurationMetadata(@RequestBody String configurationMetadataJsonPayload) { try { logger.debug(configurationMetadataJsonPayload); List<ConfigurationMetaData> configurationMetaDataList = this.mapper.readValue(configurationMetadataJsonPayload , mapper.getTypeFactory().constructCollectionType(List.class, ConfigurationMetaDataImpl.class)); this.configurationMetaDataBatchInsert.insert(configurationMetaDataList); } catch (Exception e) { e.printStackTrace(); throw new ResponseStatusException( HttpStatus.BAD_REQUEST, "An error has occurred attempting to perform a batch insert of ConfigurationMetaData!", e); } return new ResponseEntity("Configuration metadata successfully captured!", HttpStatus.OK); }

Target:
there is no need to print stacktrace it is being passed to RsponseStatusException
Source:
public void postBuildIndex() throws IOException, ServiceException { if(optimizeEnabled) { // this is required to be at the very very very end after rebuilding the whole index optimizeIndex(solrConfiguration.getReindexCollectionName(), solrConfiguration.getReindexServer()); // Swap the active and the reindex cores if (!solrConfiguration.isSingleCoreMode()) { shs.swapActiveCores(solrConfiguration); } } }

Target:
Should the core swap be inside the optimizeEnabled block? Seems like the core should be swapped regardless if optimize is enabled.
Source:
public Calendar getCurrentTimeCalendar() { BroadleafRequestContext brc = BroadleafRequestContext.getBroadleafRequestContext(); WebRequest webRequest = brc.getWebRequest(); if(BLCRequestUtils.isOKtoUseSession(webRequest)) { HttpSession session = brc.getRequest().getSession(); TimeZone timeZone = (TimeZone) session.getAttribute(CLIENT_TIMEZONE); int n = 0; if(timeZone != null) { return SystemTime.asCalendar(Locale.getDefault(), timeZone, true); } } return SystemTime.asCalendar(true); }

Target:
```suggestion ``` This looks like code that was leftover, should this be removed?
Source:
protected void minify(BufferedReader in, BufferedWriter out, String filename, String type) throws IOException { try { if (JS_TYPE.equals(type)) { jsMinificationService.minifyJs(filename, in, out); } else if (CSS_TYPE.equals(type)) { cssMinificationService.minifyCss(filename, in, out); } else { throw new ResourceMinificationException("Minification is not supported for file: " + filename); } } catch (ResourceMinificationException e) { // We're throwing and catching ResourceMinificationException for backwards compatibility. // In 5.4 this method will throw a ResourceMinificationException throw new RuntimeException(e); } }

Target:
Just throw `IOException(e)` instead, somebody else could check the cause
Source:
protected WebRequest getWebRequest() { BroadleafRequestContext requestContext = BroadleafRequestContext.getBroadleafRequestContext(); return new ServletWebRequest(requestContext.getRequest(), requestContext.getResponse()); }

Target:
Shouldn't you be able to replace this with: ``` java return requestContext.getWebRequest() ``` If it's unset then there's a bug somewhere.
Source:
public <T> T getValue(final OGlobalConfiguration iConfig) { if (config != null && config.containsKey(iConfig.getKey())) return (T) config.get(iConfig.getKey()); return iConfig.getValue(); }

Target:
Unchecked cast warning.
Source:
public OSBTreeCollectionManager getSBtreeCollectionManager() { try { return sbTreeCollectionManager; } catch (RuntimeException e) { throw logAndPrepareForRethrow(e); } catch (Error e) { throw logAndPrepareForRethrow(e); } catch (Throwable t) { throw logAndPrepareForRethrow(t); } }

Target:
Try/catch can be removed
Source:
private void makeRollback(OMicroTransaction microTransaction, Exception e) { // WE NEED TO CALL ROLLBACK HERE, IN THE LOCK OLogManager.instance().debug(this, "Error during micro-transaction commit, micro-transaction will be rolled back (tx-id=%d)", e, microTransaction.getId()); rollback(microTransaction); if (e instanceof OException) throw ((OException) e); else throw OException.wrapException(new OStorageException("Error during micro-transaction commit"), e); }

Target:
Probably would be better to check on RuntimeException not on OException.
Source:
private int nextBuf(byte[] buffer, int bufOffset) { int ret; if (len - off < buffer.length - bufOffset) { ret = (int) (len - off); } else { ret = buffer.length - bufOffset; } int i; for (i = 0; i < ret; i += 6) { fillBytesImpl(buffer, i + bufOffset); } off += ret; return ret + bufOffset; }

Target:
Keep it public please as mentioned above.
Source:
T tupleConvertFilter(List<String> input, Set<String> fields, T result) { if (input == null) { return result; } for (int i = 1; i < input.size(); i += 2) { if (fields == null || fields.contains(input.get(i))) { result.put(input.get(i), new StringByteIterator(input.get(i + 1))); } } return result; }

Target:
why introduce an out parameter here?
Source:
public void getHTable(String table) throws IOException { final TableName tName = TableName.valueOf(table); synchronized (TABLE_LOCK) { this.currentTable = connection.getTable(tName); if (clientSideBuffering) { final BufferedMutatorParams p = new BufferedMutatorParams(tName); p.writeBufferSize(writeBufferSize); this.bufferedMutator = connection.getBufferedMutator(p); } } }

Target:
#701 asked for this lock to be removed, if I am reading it correctly.
Source:
private String buildKeyName(long keynum) { if (!orderedinserts) { keynum = Utils.hash(keynum); } String value = Long.toString(keynum); int fill = zeropadding - value.length(); String prekey = "user"; for (int i = 0; i < fill; i++) { prekey += '0'; } return prekey + value; }

Target:
``protected``
Source:
public void run() { try { Thread.sleep(timeout); this.timedout.setIsSatisfied(true); } catch (InterruptedException e) { // Do nothing. Kept just to remove Check-style build error. byte a = 0; } }

Target:
Hmmm wonder if there is a better way to do this.
Source:
private int handleExceptions(Exception e, String url, String method) { if (logEnabled) { System.out.println(new StringBuilder(method).append(" Request: ").append(url).append(" | ") .append(e.getClass().getName()).append(" occured | Error message: ") .append(e.getMessage()).toString()); } if (e instanceof ClientProtocolException) { return 400; } return 500; }

Target:
The `System.out` in a few places should be `System.err` to make sure that messages go to stderr. I think there are a few examples of this in other bindings.
Source:
public Status delete(String table, String endpoint) { int responseCode; try { responseCode = httpDelete(urlPrefix + endpoint); } catch (Exception e) { responseCode = handleExceptions(e, urlPrefix + endpoint, HttpMethod.DELETE); } if (logEnabled) { System.out.println(new StringBuilder("DELETE Request: ").append(urlPrefix).append(endpoint) .append(" | Response Code: ").append(responseCode).toString()); } return getStatus(responseCode); }

Target:
`System.out` instead of `System.err`
Source:
public static int getUsedMemoryMegaBytes() { return (int)getUsedMemoryBytes() / 1024 / 1024; }

Target:
Should do the division prior to casting to an int.
Source:
protected ODatabaseDocumentTx getDB() { return db; }

Target:
Should this be package protected so that the test can get it, buy a subclass wouldn't necessarily?
Source:
public void cleanup() throws DBException { try { client.close(); } catch (IOException e) { e.printStackTrace(); } }

Target:
Shouldn't we propogate this exception?
Source:
public void setup() { try { orientDBClient = new OrientDBClient(); Properties p = new Properties(); // TODO: Extract the property names into final variables in OrientDBClient p.setProperty("orientdb.url", TEST_DB_URL); orientDBClient.setProperties(p); orientDBClient.init(); orientDBConnection = new ODatabaseDocumentTx(TEST_DB_URL).open("admin","admin"); orientDBDictionary = orientDBConnection.getMetadata().getIndexManager().getDictionary(); } catch (DBException e) { e.printStackTrace(); fail("Could not create OrientDBClient instance"); } }

Target:
If you just let this exception propogate out of the method, junit will take care of logging the details.
Source:
public synchronized String nextValue() { try { return current = reader.readLine(); } catch(NullPointerException e) { System.err.println("NullPointerException: " + filename + ':' + current); throw e; } catch(IOException e) { throw new RuntimeException(e); } }

Target:
Are these errors caught somewhere else? Is there a reason that exceptions were just printed instead of being thrown previously?
Source:
@Override public int getApi() { return com.android.tools.lint.detector.api.ApiKt.CURRENT_API; }

Target:
Import?
Source:
private void verifyHBound(H h) { Truth.assertThat(h.button1).isNotNull(); Truth.assertThat(h.button2).isNotNull(); Truth.assertThat(h.button3).isNotNull(); }

Target:
static import
Source:
@Test public void injectingView() { final JavaFileObject source = JavaFileObjects.forSourceString("test.Test", Joiner.on('\n').join( "package test;", "import android.app.Activity;", "import android.view.View;", "import butterknife.InjectView;", "public class Test extends Activity {", " @InjectView(1) View thing;", "}")); ASSERT.about(javaSource()).that(source) .processedWith(butterknifeProcessors()) .compilesWithoutError(); // TODO: confirm generated source (should expect test.Test$$ViewInjector.java) }

Target:
Awkward indent. Should be four spaced indented from code left column.
Source:
public CellTrait trait(){ return new CellTrait() { @Override public Object get(Cell cell, CellTraitPropertySpec<?> spec) { if (spec == PROPERTY) { return SelectionController.this; } else { return super.get(cell, spec); } } @Override public void onAdd(Cell cell) { SelectionSupport<?> selectionSupport = cell.get(SelectionSupport.SELECTION_SUPPORT); if (selectionSupport != null) { selectionSupport.setSelectionController(SelectionController.this); } } }; }

Target:
is this trait intended to be public?
Source:
public TrackStatistics (final long trackId, ContentResolver cr) { this.trackId = trackId; contentResolver = cr; length = 0; maxSpeed = 0; pointCount = 0; timeMoving = 0; update(); }

Target:
Another reason to initialise when declaring the fields I guess, you don't have to repeat the initialisation code there.
Source:
public void cleanTriggers() throws Exception { SampleComputedFolder s = r.jenkins.createProject(SampleComputedFolder.class, "s"); s.addTrigger(new PeriodicFolderTrigger("30m")); s.removeTrigger(new PeriodicFolderTrigger("30m")); assertEquals(0, s.getTriggers().size()); }

Target:
nit: Just to complete the circle, so in the same test we check that the trigger is added and removed ```suggestion s.addTrigger(new PeriodicFolderTrigger("30m")); assertEquals(1, s.getTriggers().size()); ```
Source:
public synchronized HttpResponse doStop() throws IOException, ServletException { Executor e = Executor.of(this); if (e == null) { for (Computer c : Jenkins.getActiveInstance().getComputers()) { for (Executor e1 : c.getOneOffExecutors()) { if (e1.getCurrentExecutable() == this) e = e1; } } } if (e != null) { return e.doStop(); } else { // nothing is building return HttpResponses.forwardToPreviousPage(); } }

Target:
Unnecessary, `of` already handles this.
Source:
public void onRenamed(I item, String oldName, String newName) throws IOException { items.remove(oldName); items.put(newName, (I) item); // For compatibility with old views: for (View v : views) { v.onJobRenamed(item, oldName, newName); } save(); }

Target:
Remove the cast.
Source:
protected HttpURLConnection openConnection(String url) throws IOException { URL requestedURL; try { requestedURL = new URL(url); } catch (MalformedURLException e) { throw new IOException("Attempted to use malformed url: " + url); } HttpURLConnection connection = (HttpURLConnection)requestedURL.openConnection(); connection.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT_MILLIS); connection.setReadTimeout(DEFAULT_READ_TIMEOUT_MILLIS); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("User-Agent", USER_AGENT); connection.setDoInput(true); return connection; }

Target:
we should propagate the underlying error here.
Source:
@Override public void initialize(Analytics analytics, ValueMap settings) throws IllegalStateException { if (!isOnClassPath("android.support.v4.app.Fragment")) { throw new IllegalStateException("Kahuna requires the support library to be bundled."); } trackAllPages = settings.getBoolean("trackAllPages", true); KahunaAnalytics.onAppCreate(analytics.getApplication(), settings.getString("apiKey"), settings.getString("pushSenderId")); LogLevel logLevel = analytics.getLogLevel(); KahunaAnalytics.setDebugMode(logLevel == INFO || logLevel == VERBOSE); }

Target:
Why trackAllPages default to true if not set by user? This may cause a lot of unintended screen events.
Source:
@Override void initialize(Context context, JsonMap settings) throws InvalidConfigurationException { if (!hasPermission(context, Manifest.permission.ACCESS_NETWORK_STATE)) { throw new InvalidConfigurationException( "AppsFlyer requires the ACCESS_NETWORK_STATE permission"); } AppsFlyerLib.setAppsFlyerKey(settings.getString("appsFlyerDevKey")); AppsFlyerLib.setUseHTTPFalback(settings.getBoolean("httpFallback")); this.context = context; }

Target:
Needs a default value, should be false in this case. `settings.getBoolean("httpFallback", false);`
Source:
public String getTermNameFromOntology(final OntologyDataManager ontologyDataManager) { if (this.termId != null) { final Term term = ontologyDataManager.getTermById(this.termId.getId()); if (term != null && !StringUtil.isEmpty(term.getName())) { return term.getName(); } else { return this.name; } } else { return this.name; } }

Target:
You can eliminate repetition here - please check this logic and see if it does the same thing ``` public String getTermNameFromOntology(final OntologyDataManager ontologyDataManager) { if (this.termId != null) { final Term term = ontologyDataManager.getTermById(this.termId.getId()); if (term != null && !StringUtil.isEmpty(term.getName())) { return term.getName(); } } return this.name; } ```
Source:
protected void iterationConditionResult(boolean result, PendingFeatureIf annotation, IMethodInvocation invocation) throws Throwable { if (result) { new PendingFeatureInterceptor(annotation.exceptions(), annotation.reason(), PENDING_FEATURE_IF, false) .intercept(invocation); } }

Target:
Why is `secondary` always false here?
Source:
private SpockExecutionContext setCurrentFeature(FeatureInfo currentFeature) { if (this.currentFeature != currentFeature) { hadSuccess.set(false); abortions.clear(); failures.clear(); } this.currentFeature = currentFeature; return this; }

Target:
The context is designed to be cloned, not modified without being copied.
Source:
private BootstrapContextCoordinator() { this.bootstrapContexts = new ConcurrentHashMap<String, CloneableBootstrapContext>(); this.defaultBootstrapContext = null; this.workManagerCoordinator = null; this.activeBootstrapContexts = new HashMap<String, CloneableBootstrapContext>(); this.refCountBootstrapContexts = new HashMap<String, Integer>(); }

Target:
public
Source:
public ValidatorFactory getValidatorFactory() { if (validatorFactory == null) { Configuration configuration = Validation.byDefaultProvider().configure(); Configuration<?> conf = configuration.traversableResolver(new IronJacamarTraversableResolver()); validatorFactory = new IronJacamarValidatorFactory(conf.buildValidatorFactory()); } return validatorFactory; }

Target:
Should be passed in through the constructor or a set-method
Source:
@Override public void flush() { flush(FlushMode.IDLE); }

Target:
Lets change the default to GRACEFULLY
Source:
public AbstractPool(ConnectionManager cm, PoolConfiguration pc) { this.cm = cm; this.poolConfiguration = pc; this.pools = new ConcurrentHashMap<Credential, ManagedConnectionPool>(); this.transactionMap = new ConcurrentHashMap<Object, Map<ManagedConnectionPool, ConnectionListener>>(); this.semaphore = new Semaphore(poolConfiguration.getMaxSize()); this.shouldPrefill = pc.isPrefill(); // || pc.isStrictMin(); }

Target:
Remove
Source:
public synchronized void shutdown() { shutdown.set(true); for (ManagedConnectionPool mcp : pools.values()) mcp.shutdown(); pools.clear(); }

Target:
Remove
Source:
public LegacyTxDataSourceImpl buildCommonPool(Integer minPoolSize, Integer initialPoolSize, Integer maxPoolSize, Boolean prefill, Boolean useStrictMin, FlushStrategy flushStrategy) throws Exception { pool = new DsPoolImpl(minPoolSize, initialPoolSize, maxPoolSize, prefill, useStrictMin, flushStrategy, false, null, Defaults.FAIR, null); return this; }

Target:
That doesn't look right
Source:
public LegacyXaDataSourceImp buildCommonPool(Integer minPoolSize, Integer initialPoolSize, Integer maxPoolSize, Boolean prefill, Boolean useStrictMin, FlushStrategy flushStrategy, Boolean isSameRmOverride, Boolean interleaving, Boolean padXid, Boolean wrapXaResource, Boolean noTxSeparatePool) throws Exception { xaPool = new DsXaPoolImpl(minPoolSize, initialPoolSize, maxPoolSize, prefill, useStrictMin, flushStrategy, isSameRmOverride, interleaving, padXid, wrapXaResource, noTxSeparatePool, false, null, Defaults.FAIR, null); return this; }

Target:
That doesn't look right
Source:
public void delete() { setCode(null); setAccessToken(null); setCreationDate(null); setDeviceId(null); setApplicationUserAuthorization(null); setRefreshToken(null); if (getUserPKCEInfoAuthorizationSession() != null) { getUserPKCEInfoAuthorizationSession().delete(); } setUserPKCEInfoAuthorizationSession(null); deleteDomainObject(); }

Target:
This line is redundant.
Source:
private static void storeInSession(final HttpServletRequest request, final AuthenticationContext authenticationContext) { final HttpSession session = request.getSession(); session.setAttribute(LOGGED_USER_ATTRIBUTE, authenticationContext.getUser()); session.setAttribute(LOGGED_USER_AUTHENTICATION_CONTEXT_ATTRIBUTE, authenticationContext.export()); }

Target:
why not store the authenticationContext in the session and avoid json des/serialisation ?
Source:
static void updateFromSession(final HttpSession session) { final String json = (String) session.getAttribute(LOGGED_USER_AUTHENTICATION_CONTEXT_ATTRIBUTE); final AuthenticationContext authenticationContext = AuthenticationContext.importFromJson(json); final User user = authenticationContext.getUser(); if (user != null && FenixFramework.isDomainObjectValid(user)) { loggedUserContext.set(authenticationContext); } else { clear(); } }

Target:
why not retrieve AuthenticationContext object ?
Source:
private boolean isHoldingLease() { final DateTime lease = getLease().withMillisOfSecond(0); return lease != null && lease.equals(latestOwnedLease.withMillisOfSecond(0)) && lease.plusMinutes(getLeaseTimeMinutes()) .isAfterNow(); }

Target:
withMillisOfSecond(0) is not necessary here if it is used above.
Source:
private void changePassword(User user, JsonObject json) { String password = JsonUtils.getString(json, "password"); if (Strings.isNullOrEmpty(password)) { // Dont' change the password throw BennuCoreDomainException.passwordIsEmpty(); } String passwordCheck = JsonUtils.getString(json, "passwordCheck"); if (!Objects.equals(password, passwordCheck)) { throw BennuCoreDomainException.passwordCheckDoesNotMatch(); } //avoid same password if (user.matchesPassword(password)) { throw BennuCoreDomainException.passwordIsTheSame(); } user.changePassword(password); }

Target:
Won't this change prevent the use of the User Management interface without inputting the password? (For when information other than the password is being edited).
Source:
public void onClick(View v) { if(v.getId() == R.id.twitter_login){ TwitterAuthorizationTask task = new TwitterAuthorizationTask(); getInjector().injectMembers(task); task.execute(); } }

Target:
あ、ごめんなさい。`SafeAsyncTask`はInjectをする必要がありません。`(new TwitterAuthorizationTask()).execute()`で問題ないです。 もう一つの`SafeAsyncTask`についても同じですね……
Source:
public void parserShouldReturnGlobPattern() throws Exception { Assert.assertEquals("**/*.csv", locustParser.getDefaultGlobPattern()); }

Target:
use import static method for remove `Assert.`
Source:
private Boolean checkCanSyncSolr(String studyStr, String sessionId) throws CatalogException { String userId = catalogManager.getUserManager().getUserId(sessionId); if ("admin".equals(userId)) { return true; } return authorizationManager.checkCanSyncSolr(studyStr, userId); }

Target:
This if condition should actually be in authorizationManager.checkCanSyncSolr(studyStr, userId).
Source:
private long getClinicalId(boolean silent, String clinicalStrAux) throws CatalogDBException { long clinicalId = Long.parseLong(clinicalStrAux); try { clinicalDBAdaptor.checkId(clinicalId); } catch (CatalogException e) { if (silent) { return -1L; } else { throw e; } } return clinicalId; }

Target:
This method should throw a CatalogException
Source:
protected PairSupplier<Q, E> getPairSupplier(){ if (endpointProvider == null){ throw new NullPointerException("Init endpoint provider!"); } if (queryProvider == null) { logger.info("Query provider is null."); } if (pairSupplier == null){ pairSupplier = pairSupplierFactory.create(queryProvider, endpointProvider); } return pairSupplier; }

Target:
please, don't. it will log for every starting load thread. we have already tried :)
Source:
private boolean isSessionScopeMetric(MetricNameDto metricNameDto) { return (metricNameDto.getOrigin().equals(MetricNameDto.Origin.SESSION_SCOPE_TG) || metricNameDto.getOrigin().equals(MetricNameDto.Origin.SESSION_SCOPE_MONITORING)); }

Target:
in general: it is necessary to review what Origins are still in code. IMHO SESSION_SCOPE_MONITORING should not appear in the code after this commit
Source:
public ResponseEntity<?> deleteProject(@PathVariable Long projectId) { ProjectEntity project = new ProjectEntity(); project.setId(projectId); projectService.delete(project); return ResponseEntity.noContent().build(); }

Target:
I'd extract this to service method deleteProjectById(id)
Source:
private void getData(String sessionId) { if (sessionId.equals(this.sessionId)) { // data already fetched return; } // fetch data this.sessionId = sessionId; SessionMatchingSetup sessionMatchingSetup = new SessionMatchingSetup( databaseService.getWebClientProperties().isShowOnlyMatchedTests(), EnumSet.of(SessionMatchingSetup.MatchBy.ALL)); RootNode controlTree = databaseService.getControlTreeForSessions( new HashSet<String>(Arrays.asList(sessionId)), sessionMatchingSetup); fetchSessionScopeData(controlTree); fetchPerTestData(controlTree); }

Target:
no properties already. please replace with true
Source:
public WebClientStartProperties getWebClientStartProperties() { WebClientProperties webClientProperties = databaseService.getWebClientProperties(); Map<String, Set<String>> defaultMonitoringParameters = databaseService.getDefaultMonitoringParameters(); WebClientStartProperties startProperties = new WebClientStartProperties(); startProperties.setWebClientProperties(webClientProperties); startProperties.setDefaultMonitoringParameters(defaultMonitoringParameters); return startProperties; }

Target:
Why it is so complicated?
Source:
public void addChild(Widget widget) { switch (layout) { case ONE_COLUMN: addChildOneColumn(widget); break; case TWO_COLUMNS: addChildTwoColumns(widget); break; default: Info.display("DynamicLayoutPanel", "addChild with layout " + layout + " not yet implemented"); } }

Target:
is it intended to be so?
Source:
private static Namespace of(List<String> values) { return new Namespace(values); }

Target:
you don't need this function, you can use constructor directly
Source:
public static Namespace of(String... values) { List<String> list = Lists.newArrayList(values); return new Namespace(list); }

Target:
Why we need to change this class at all ? I can not find a reason.
Source:
public void setTreeViewGroupMetricsToNodeRuleProvider(TreeViewGroupMetricsToNodeRuleProvider treeViewGroupMetricsToNodeRuleProvider) { this.treeViewGroupMetricsToNodeRuleProvider = treeViewGroupMetricsToNodeRuleProvider; setDefaultMonitoringParams(this.treeViewGroupMetricsToNodeRuleProvider.getMonitoringPlotGroups()); }

Target:
Please avoid to use another setter in your setter
Source:
public synchronized List<TagDto> getAllTags() { List<TagEntity> tags = (List<TagEntity>) (entityManager.createQuery("select te from TagEntity as te")).getResultList(); List<TagDto> allTags = new ArrayList<TagDto>(); if (!tags.isEmpty()) { for (TagEntity tagEntity : tags) { allTags.add(new TagDto(tagEntity.getName(), tagEntity.getDescription())); } } return allTags; }

Target:
why synchronized?
Source:
private S getService(String url) { S service = services.get(url); if (service == null) { service = initService(url); services.putIfAbsent(url, service); } return service; }

Target:
I would write return services.get(url) here