auphong2707/dl4se-code-review-dataset huggingface dataset:
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() { START return testClassInstances.get(0); END } public String getTestMethodName() { return null; } }); //Finally, validate user's misuse of Mockito framework. Mockito.validateMockitoUsage(); } This is unfortunate. We probably have to fix #1232 first to improve our API and then base this PR on that change.

Target:
public void finishMocking() { finishMocking(null); }
Source:
public MockitoSessionBuilder strictness(Strictness strictness) { START if (strictness==null){ END strictness = STRICT_STUBS; } this.strictness = strictness; return this; } Spaces around the `==`

Target:
public MockitoSessionBuilder strictness(Strictness strictness) { this.strictness = strictness; return this; }
Source:
public List<T> getAllValues() { readLock.lock(); try { START return Arrays.asList((T[]) arguments.toArray()); END } finally { readLock.unlock(); } } 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).

Target:
public List<T> getAllValues() { readLock.lock(); try { return new ArrayList<T>((List) arguments); } finally { readLock.unlock(); } }
Source:
START public void creates_instances_with_arguments() { END assertEquals(new ConstructorInstantiator("someString").newInstance(SomeClass2.class).getClass(), SomeClass2.class); } Fantastic coverage, thank you!

Target:
public void creates_instances_with_arguments() { assertEquals(new ConstructorInstantiator(false, "someString").newInstance(SomeClass2.class).getClass(), SomeClass2.class); }
Source:
public void should_call_single_listener_on_verify() throws NoSuchMethodException { //given RememberingListener listener = new RememberingListener(); MockitoFramework mockitoFramework = Mockito.framework(); mockitoFramework.addListener(listener); START Method invocationWanted = Foo.class.getDeclaredMethod("doSomething", String.class); END Foo foo = mock(Foo.class); //when VerificationMode never = never(); verify(foo, never).doSomething(""); //then assertThat(listener).is(notifiedFor(foo, never, invocationWanted)); } I would say to keep the setUp. It is cleaner and more DRY.

Target:
public void should_call_single_listener_on_verify() { //given Foo foo = mock(Foo.class); //when VerificationMode never = never(); verify(foo, never).doSomething(""); //then assertThat(listener).is(notifiedFor(foo, never, invocationWanted)); }
Source:
public void should_create_mock_from_final_class_in_the_JDK() throws Exception { START assumeTrue(ClassFileVersion.ofThisVm().isLessThan(ClassFileVersion.JAVA_V9)); // Change when ByteBuddy has ASM6 END MockCreationSettings<Pattern> settings = settingsFor(Pattern.class); Pattern proxy = mockMaker.createMock(settings, new MockHandlerImpl<Pattern>(settings)); assertThat(proxy.pattern()).isEqualTo("bar"); } 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.

Target:
public void should_create_mock_from_final_class_in_the_JDK() throws Exception { assumeTrue(ClassFileVersion.ofThisVm().isLessThan(JAVA_V9)); // Change when ByteBuddy has ASM6 - see #788 MockCreationSettings<Pattern> settings = settingsFor(Pattern.class); Pattern proxy = mockMaker.createMock(settings, new MockHandlerImpl<Pattern>(settings)); assertThat(proxy.pattern()).isEqualTo("bar"); }
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); START return 45 > Integer.valueOf(updateVersion); END } 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 :)

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

Target:
public void addListener(MockitoListener listener) { assertNotNull(listener); mockingProgress().addListener(listener); }
Source:
public void addListener(MockitoListener listener) { assertNotNull(listener); if (listener instanceof MockCreationListener) { mockingProgress().addListener(listener); } START } END Why the instance check ?

Target:
public void addListener(MockitoListener listener) { assertNotNull(listener); mockingProgress().addListener(listener); }
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()); } START return (List<TestResult>)failedTests; END } Instead of casting, I would prefer to use the same return type.

Target:
private List<? extends 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 failedTests; }
Source:
protected void appendDetail(final StringBuffer buffer, final String fieldName, final Collection<?> coll) { if (coll != null && !coll.isEmpty()) { coll.stream().findFirst() .map(Object::getClass) START .filter(Class::isEnum) END .ifPresent((clazz) -> appendDetail(buffer, fieldName, coll.toArray())); return; } buffer.append(coll); } 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)

Target:
protected void appendDetail(final StringBuffer buffer, final String fieldName, final Collection<?> coll) { if (coll != null && !coll.isEmpty()) { appendDetail(buffer, fieldName, coll.toArray()); return; } buffer.append(coll); }
Source:
public static float[] removeAllOccurences(final float[] array, final float element) { START BitSet foundBits = indexesOf(array, element); END return (float[]) removeAll((Object) array, foundBits); } How about inlining all of the 'foundBits'?

Target:
public static float[] removeAllOccurences(final float[] array, final float element) { return (float[]) removeAll((Object) array, indexesOf(array, element)); }
Source:
public static RuntimeException rethrow(Throwable pThrowable) { if (pThrowable == null) { throw new NullPointerException("The Throwable must not be null."); } START if (pThrowable instanceof RuntimeException) { END 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); } } This is a completely different change; please don't mix changes in a pull request.

Target:
public static RuntimeException rethrow(Throwable pThrowable) { if (pThrowable == null) { throw new NullPointerException("The Throwable must not be null."); } else { 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); } } }
Source:
private Object readResolve() { START return ToStringStyle.NO_CLASS_NAME_MULTI_LINE_STYLE; END } 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;`.

Target:
private Object readResolve() { 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 START return obj instanceof MultipartKey && Arrays.equals(keys, ((MultipartKey)obj).keys); END } Please do not include unrelated changes in a single pull request. Thanks!

Target:
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 Arrays.equals(keys, ((MultipartKey)obj).keys); }
Source:
public void minutesOutOfRange() { START Assert.assertEquals(0, new GmtTimeZone(false, 60, 0)); END } 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.

Target:
public void minutesOutOfRange() { new GmtTimeZone(false, 0, 60); }
Source:
public static String appendIfNotEmpty(final String str, final String suffix) { START return isEmpty(str) ? EMPTY : str + defaultString(suffix); END } ```suggestion return isEmpty(str) ? str : str + defaultString(suffix); ```

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

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

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

Target:
public static String prependIfNotBlank(final String str, final String prefix) { if (isEmpty(prefix) || isBlank(str)) { return str; } return prefix + str; }
Source:
public static boolean isAnyNotEmpty(final CharSequence... css) { if (ArrayUtils.isEmpty(css)) { START return true; END } for (final CharSequence cs : css){ if (isNotEmpty(cs)) { return true; } } return false; } Shouldn't this return false? An empty Array does not contain any non empty CharSequences. WDYT?

Target:
public static boolean isAnyNotEmpty(final CharSequence... css) { if (ArrayUtils.isEmpty(css)) { return false; } for (final CharSequence cs : css){ if (isNotEmpty(cs)) { return true; } } return false; }
Source:
public void testToCalendarWithDateNull() { START try { END DateUtils.toCalendar(null, zone); fail("Expected NullPointerException to be thrown when Date is null"); } catch(final NullPointerException npe) { // expected } } you don't need a try-catch here. You can simply use `@Test(expected=NullPointerException.class)`

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

Target:
public void testToCalendarWithTimeZoneNull() { DateUtils.toCalendar(date1, null); }
Source:
public static Thread findThreadById(final long threadId) { final Collection<Thread> result = findThreads(new ThreadIdPredicate(threadId)); START if(!result.iterator().hasNext()) { END return null; } else { return result.iterator().next(); } } result.isEmpty() can be used instead to avoid creating an iterator instance.

Target:
public static Thread findThreadById(final long threadId) { final Collection<Thread> result = findThreads(new ThreadIdPredicate(threadId)); if(result.isEmpty()) { return null; } else { return result.iterator().next(); } }
Source:
public static <T extends Serializable> T roundtrip(final T msg) { START return SerializationUtils.deserialize(SerializationUtils.serialize(msg)); END } whoops, why are we removing this again? :-)

Target:
public static <T extends Serializable> T roundtrip(final T msg) { return (T) SerializationUtils.deserialize(SerializationUtils.serialize(msg)); }
Source:
public boolean contains(Module module, Flow flow) { START logger.info("Check contains: " + module + flow); END return this.cache.containsKey(module.getName()+flow.getName()); } it should be debug

Target:
public boolean contains(Module module, Flow flow) { logger.debug("Check contains: " + module + flow); return this.cache.containsKey(module.getName()+flow.getName()); }
Source:
public List<ModuleMetaData> getAllModule() { START JsonModuleMetaDataProvider provider = new JsonModuleMetaDataProvider(new JsonFlowMetaDataProvider()); END return this.moduleMetadata.values().stream() .map(moduleMetadata -> provider.deserialiseModule(moduleMetadata)) .collect(Collectors.toList()); } done

Target:
public List<ModuleMetaData> getAllModule() { return this.moduleMetadata.values().stream() .map(moduleMetadata -> provider.deserialiseModule(moduleMetadata)) .collect(Collectors.toList()); }
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) { START e.printStackTrace(); END 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); } there is no need to print stacktrace it is being passed to RsponseStatusException

Target:
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) { 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); }
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 START if (!solrConfiguration.isSingleCoreMode()) { END shs.swapActiveCores(solrConfiguration); } } } Should the core swap be inside the optimizeEnabled block? Seems like the core should be swapped regardless if optimize is enabled.

Target:
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); } }
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); START int n = 0; END if(timeZone != null) { return SystemTime.asCalendar(Locale.getDefault(), timeZone, true); } } return SystemTime.asCalendar(true); } ```suggestion ``` This looks like code that was leftover, should this be removed?

Target:
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); if(timeZone != null) { return SystemTime.asCalendar(Locale.getDefault(), timeZone, true); } } return SystemTime.asCalendar(true); }
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 START throw new RuntimeException(e); END } } Just throw `IOException(e)` instead, somebody else could check the cause

Target:
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 IOException(e); } }
Source:
protected WebRequest getWebRequest() { BroadleafRequestContext requestContext = BroadleafRequestContext.getBroadleafRequestContext(); START return new ServletWebRequest(requestContext.getRequest(), requestContext.getResponse()); END } Shouldn't you be able to replace this with: ``` java return requestContext.getWebRequest() ``` If it's unset then there's a bug somewhere.

Target:
protected WebRequest getWebRequest() { return BroadleafRequestContext.getBroadleafRequestContext().getWebRequest(); }
Source:
public <T> T getValue(final OGlobalConfiguration iConfig) { if (config != null && config.containsKey(iConfig.getKey())) START return (T) config.get(iConfig.getKey()); END return iConfig.getValue(); } Unchecked cast warning.

Target:
public Object getValue(final OGlobalConfiguration iConfig) { if (config != null && config.containsKey(iConfig.getKey())) return config.get(iConfig.getKey()); return iConfig.getValue(); }
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); START } END } Try/catch can be removed

Target:
public OSBTreeCollectionManager getSBtreeCollectionManager() { return sbTreeCollectionManager; }
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()); START rollback(microTransaction); END if (e instanceof OException) throw ((OException) e); else throw OException.wrapException(new OStorageException("Error during micro-transaction commit"), e); } Probably would be better to check on RuntimeException not on OException.

Target:
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 RuntimeException) throw ((RuntimeException) e); else throw OException.wrapException(new OStorageException("Error during micro-transaction commit"), e); }
Source:
START private int nextBuf(byte[] buffer, int bufOffset) { END 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; } Keep it public please as mentioned above.

Target:
public 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; }
Source:
START T tupleConvertFilter(List<String> input, Set<String> fields, T result) { END 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; } why introduce an out parameter here?

Target:
void tupleConvertFilter(List<String> input, Set<String> fields, T result) { if (input == null) { return; } 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))); } } }
Source:
public void getHTable(String table) throws IOException { final TableName tName = TableName.valueOf(table); START synchronized (TABLE_LOCK) { END this.currentTable = connection.getTable(tName); if (clientSideBuffering) { final BufferedMutatorParams p = new BufferedMutatorParams(tName); p.writeBufferSize(writeBufferSize); this.bufferedMutator = connection.getBufferedMutator(p); } } } #701 asked for this lock to be removed, if I am reading it correctly.

Target:
public void getHTable(String table) throws IOException { final TableName tName = TableName.valueOf(table); this.currentTable = connection.getTable(tName); if (clientSideBuffering) { final BufferedMutatorParams p = new BufferedMutatorParams(tName); p.writeBufferSize(writeBufferSize); this.bufferedMutator = connection.getBufferedMutator(p); } }
Source:
START private String buildKeyName(long keynum) { END 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; } ``protected``

Target:
protected 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; }
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. START byte a = 0; END } } Hmmm wonder if there is a better way to do this.

Target:
public void run() { try { Thread.sleep(timeout); this.timedout.setIsSatisfied(true); } catch (InterruptedException e) { // Do nothing. } }
Source:
private int handleExceptions(Exception e, String url, String method) { if (logEnabled) { START System.out.println(new StringBuilder(method).append(" Request: ").append(url).append(" | ") END .append(e.getClass().getName()).append(" occured | Error message: ") .append(e.getMessage()).toString()); } if (e instanceof ClientProtocolException) { return 400; } return 500; } 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.

Target:
private int handleExceptions(Exception e, String url, String method) { if (logEnabled) { System.err.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; }
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) { START System.out.println(new StringBuilder("DELETE Request: ").append(urlPrefix).append(endpoint) END .append(" | Response Code: ").append(responseCode).toString()); } return getStatus(responseCode); } `System.out` instead of `System.err`

Target:
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.err.println(new StringBuilder("DELETE Request: ").append(urlPrefix).append(endpoint) .append(" | Response Code: ").append(responseCode).toString()); } return getStatus(responseCode); }
Source:
public static int getUsedMemoryMegaBytes() { START return (int)getUsedMemoryBytes() / 1024 / 1024; END } Should do the division prior to casting to an int.

Target:
public static int getUsedMemoryMegaBytes() { return (int)(getUsedMemoryBytes() / 1024 / 1024); }
Source:
START protected ODatabaseDocumentTx getDB() { END return db; } Should this be package protected so that the test can get it, buy a subclass wouldn't necessarily?

Target:
ODatabaseDocumentTx getDB() { return db; }
Source:
public void cleanup() throws DBException { try { client.close(); START } catch (IOException e) { END e.printStackTrace(); } } Shouldn't we propogate this exception?

Target:
public void cleanup() throws DBException { try { client.close(); } catch (IOException e) { throw new DBException(e); } }
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(); START } catch (DBException e) { END e.printStackTrace(); fail("Could not create OrientDBClient instance"); } } If you just let this exception propogate out of the method, junit will take care of logging the details.

Target:
public void setup() throws DBException { 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(); }
Source:
public synchronized String nextValue() { try { return current = reader.readLine(); } catch(NullPointerException e) { System.err.println("NullPointerException: " + filename + ':' + current); throw e; } catch(IOException e) { START throw new RuntimeException(e); } END } Are these errors caught somewhere else? Is there a reason that exceptions were just printed instead of being thrown previously?

Target:
public synchronized String nextValue() { try { return current = reader.readLine(); } catch(IOException e) { throw new RuntimeException(e); } }
Source:
@Override public int getApi() { START return com.android.tools.lint.detector.api.ApiKt.CURRENT_API; END } Import?

Target:
@Override public int getApi() { return ApiKt.CURRENT_API; }
Source:
private void verifyHBound(H h) { START Truth.assertThat(h.button1).isNotNull(); END Truth.assertThat(h.button2).isNotNull(); Truth.assertThat(h.button3).isNotNull(); } static import

Target:
private void verifyHBound(H h) { assertThat(h.button1).isNotNull(); assertThat(h.button2).isNotNull(); assertThat(h.button3).isNotNull(); }
Source:
@Test public void injectingView() { final JavaFileObject source = JavaFileObjects.forSourceString("test.Test", START Joiner.on('\n').join( END "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) } Awkward indent. Should be four spaced indented from code left column.

Target:
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) }
Source:
START public CellTrait trait(){ END 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); } } }; } is this trait intended to be public?

Target:
private 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); } } }; }
Source:
public TrackStatistics (final long trackId, ContentResolver cr) { this.trackId = trackId; START contentResolver = cr; END length = 0; maxSpeed = 0; pointCount = 0; timeMoving = 0; update(); } Another reason to initialise when declaring the fields I guess, you don't have to repeat the initialisation code there.

Target:
public TrackStatistics (final long trackId, ContentResolver cr) { this.trackId = trackId; contentResolver = cr; // pointCount, length, maxSpeed and timeMoving are all implicitly initialized to // zero, which is what we need update(); }
Source:
public void cleanTriggers() throws Exception { SampleComputedFolder s = r.jenkins.createProject(SampleComputedFolder.class, "s"); START s.addTrigger(new PeriodicFolderTrigger("30m")); END s.removeTrigger(new PeriodicFolderTrigger("30m")); assertEquals(0, s.getTriggers().size()); } 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()); ```

Target:
public void cleanTriggers() throws Exception { SampleComputedFolder s = r.jenkins.createProject(SampleComputedFolder.class, "s"); s.addTrigger(new PeriodicFolderTrigger("30m")); assertEquals(1, s.getTriggers().size()); s.removeTrigger(new PeriodicFolderTrigger("30m")); assertEquals(0, 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()) { START for (Executor e1 : c.getOneOffExecutors()) { END if (e1.getCurrentExecutable() == this) e = e1; } } } if (e != null) { return e.doStop(); } else { // nothing is building return HttpResponses.forwardToPreviousPage(); } } Unnecessary, `of` already handles this.

Target:
public synchronized HttpResponse doStop() throws IOException, ServletException { Executor e = Executor.of(this); if (e != null) { return e.doStop(); } else { // nothing is building return HttpResponses.forwardToPreviousPage(); } }
Source:
public void onRenamed(I item, String oldName, String newName) throws IOException { items.remove(oldName); START items.put(newName, (I) item); END // For compatibility with old views: for (View v : views) { v.onJobRenamed(item, oldName, newName); } save(); } Remove the cast.

Target:
public void onRenamed(I item, String oldName, String newName) throws IOException { items.remove(oldName); items.put(newName, item); // For compatibility with old views: for (View v : views) { v.onJobRenamed(item, oldName, newName); } save(); }
Source:
protected HttpURLConnection openConnection(String url) throws IOException { URL requestedURL; try { requestedURL = new URL(url); } catch (MalformedURLException e) { START throw new IOException("Attempted to use malformed url: " + url); END } 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; } we should propagate the underlying error here.

Target:
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, e); } 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; }
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."); } START trackAllPages = settings.getBoolean("trackAllPages", true); END KahunaAnalytics.onAppCreate(analytics.getApplication(), settings.getString("apiKey"), settings.getString("pushSenderId")); LogLevel logLevel = analytics.getLogLevel(); KahunaAnalytics.setDebugMode(logLevel == INFO || logLevel == VERBOSE); } Why trackAllPages default to true if not set by user? This may cause a lot of unintended screen events.

Target:
@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", false); KahunaAnalytics.onAppCreate(analytics.getApplication(), settings.getString("apiKey"), settings.getString("pushSenderId")); LogLevel logLevel = analytics.getLogLevel(); KahunaAnalytics.setDebugMode(logLevel == INFO || logLevel == VERBOSE); }
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")); START AppsFlyerLib.setUseHTTPFalback(settings.getBoolean("httpFallback")); END this.context = context; } Needs a default value, should be false in this case. `settings.getBoolean("httpFallback", false);`

Target:
@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", false)); this.context = context; }
Source:
public String getTermNameFromOntology(final OntologyDataManager ontologyDataManager) { START if (this.termId != null) { END 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; } } 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; } ```

Target:
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) { START new PendingFeatureInterceptor(annotation.exceptions(), annotation.reason(), PENDING_FEATURE_IF, false) END .intercept(invocation); } } Why is `secondary` always false here?

Target:
protected void iterationConditionResult(boolean result, PendingFeatureIf annotation, IMethodInvocation invocation) throws Throwable { if (result) { new PendingFeatureInterceptor(annotation.exceptions(), annotation.reason(), PENDING_FEATURE_IF).intercept(invocation); } }
Source:
private SpockExecutionContext setCurrentFeature(FeatureInfo currentFeature) { if (this.currentFeature != currentFeature) { hadSuccess.set(false); START abortions.clear(); END failures.clear(); } this.currentFeature = currentFeature; return this; } The context is designed to be cloned, not modified without being copied.

Target:
private SpockExecutionContext setCurrentFeature(FeatureInfo currentFeature) { this.currentFeature = currentFeature; return this; }
Source:
START private BootstrapContextCoordinator() END { this.bootstrapContexts = new ConcurrentHashMap<String, CloneableBootstrapContext>(); this.defaultBootstrapContext = null; this.workManagerCoordinator = null; this.activeBootstrapContexts = new HashMap<String, CloneableBootstrapContext>(); this.refCountBootstrapContexts = new HashMap<String, Integer>(); } public

Target:
public 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>(); }
Source:
public ValidatorFactory getValidatorFactory() { START if (validatorFactory == null) END { Configuration configuration = Validation.byDefaultProvider().configure(); Configuration<?> conf = configuration.traversableResolver(new IronJacamarTraversableResolver()); validatorFactory = new IronJacamarValidatorFactory(conf.buildValidatorFactory()); } return validatorFactory; } Should be passed in through the constructor or a set-method

Target:
public ValidatorFactory getValidatorFactory() { return validatorFactory; }
Source:
@Override public void flush() { START flush(FlushMode.IDLE); END } Lets change the default to GRACEFULLY

Target:
public void flush() { flush(FlushMode.IDLE); }
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()); START this.shouldPrefill = pc.isPrefill(); // || pc.isStrictMin(); END } Remove

Target:
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()); }
Source:
public synchronized void shutdown() { START shutdown.set(true); END for (ManagedConnectionPool mcp : pools.values()) mcp.shutdown(); pools.clear(); } Remove

Target:
public synchronized void shutdown() { for (ManagedConnectionPool mcp : pools.values()) mcp.shutdown(); pools.clear(); }
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, START useStrictMin, flushStrategy, false, null, Defaults.FAIR, null); END return this; } That doesn't look right

Target:
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, null, null); return this; }
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, START wrapXaResource, noTxSeparatePool, false, null, Defaults.FAIR, null); END return this; } That doesn't look right

Target:
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, null, null); return this; }
Source:
public void delete() { setCode(null); setAccessToken(null); setCreationDate(null); setDeviceId(null); setApplicationUserAuthorization(null); setRefreshToken(null); if (getUserPKCEInfoAuthorizationSession() != null) { getUserPKCEInfoAuthorizationSession().delete(); } START setUserPKCEInfoAuthorizationSession(null); END deleteDomainObject(); } This line is redundant.

Target:
public void delete() { setCode(null); setAccessToken(null); setCreationDate(null); setDeviceId(null); setApplicationUserAuthorization(null); setRefreshToken(null); if (getUserPKCEInfoAuthorizationSession() != null) { getUserPKCEInfoAuthorizationSession().delete(); } deleteDomainObject(); }
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()); START } END why not store the authenticationContext in the session and avoid json des/serialisation ?

Target:
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); }
Source:
static void updateFromSession(final HttpSession session) { final String json = (String) session.getAttribute(LOGGED_USER_AUTHENTICATION_CONTEXT_ATTRIBUTE); START final AuthenticationContext authenticationContext = AuthenticationContext.importFromJson(json); END final User user = authenticationContext.getUser(); if (user != null && FenixFramework.isDomainObjectValid(user)) { loggedUserContext.set(authenticationContext); } else { clear(); } } why not retrieve AuthenticationContext object ?

Target:
static void updateFromSession(final HttpSession session) { if (session != null) { final AuthenticationContext authenticationContext = (AuthenticationContext) session.getAttribute(LOGGED_USER_AUTHENTICATION_CONTEXT_ATTRIBUTE); if (authenticationContext != null) { final User user = authenticationContext.getUser(); if (user != null && FenixFramework.isDomainObjectValid(user)) { loggedUserContext.set(authenticationContext); } else { clear(); } } } }
Source:
private boolean isHoldingLease() { final DateTime lease = getLease().withMillisOfSecond(0); return lease != null && lease.equals(latestOwnedLease.withMillisOfSecond(0)) && lease.plusMinutes(getLeaseTimeMinutes()) START .isAfterNow(); END } withMillisOfSecond(0) is not necessary here if it is used above.

Target:
private boolean isHoldingLease() { final DateTime lease = getLease(); return lease != null && lease.equals(latestOwnedLease) && lease.plusMinutes(getLeaseTimeMinutes()).isAfterNow(); }