auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void setWhiteListedRoutes(String s) { START if (s != null && !s.equals("")) END whiteListedRoutes = RouteMatcher.parse(s); else whiteListedRoutes = RouteMatcher.emptyMatcher(); } The canonical way of performing the second check is `String.isEmpty()`. If we are going to check for equality with the empty string, note that by reversing the comparison we can elide the null check: `!("".equals(string))`

Target:
public void setWhiteListedRoutes(String s) { if (!s.isEmpty()) { whiteListedRoutes = RouteMatcher.parse(s); } else { whiteListedRoutes = RouteMatcher.emptyMatcher(); } }
Source:
public String getFeedId() { if (code != null && code.length() > 0) { // The key stored in patternForId is the pattern code that is constructed as. // Agency:RouteId:DirectionId:PatternNumber, the first part is the feed id. START return code.substring(0, code.indexOf(':')); END } // If we cant obtain the feed id from the code, we can get it from the route. return route.getId().getAgencyId(); } What if code is non-empty, but doesn't have a ':' character?

Target:
public String getFeedId() { // The feed id is the same as the agency id on the route, this allows us to obtain it from there. return route.getId().getAgencyId(); }
Source:
public synchronized void trimMemory(int level) { if (level >= android.content.ComponentCallbacks2.TRIM_MEMORY_BACKGROUND) { clearMemory(); } else if (level >= android.content.ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN) { evictToSize(maxSize / 2); START } else if (level == android.content.ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL) { END evictToSize(maxSize / 2); } } Use || instead of duplicating the size logic.

Target:
public synchronized void trimMemory(int level) { if (level >= android.content.ComponentCallbacks2.TRIM_MEMORY_BACKGROUND) { clearMemory(); } else if (level >= android.content.ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN || level == android.content.ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL) { evictToSize(maxSize / 2); } }
Source:
private static boolean isLowMemoryDevice(ActivityManager activityManager) { START return Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT END && activityManager.isLowRamDevice(); } Didn't we have some problems with shortcutting vs Build.VERSION before?

Target:
private static boolean isLowMemoryDevice(ActivityManager activityManager) { // Explicitly check with an if statement, on some devices both parts of boolean expressions // can be evaluated even if we'd normally expect a short circuit. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { return activityManager.isLowRamDevice(); } else { return false; } }
Source:
public void testSetModulesEnabledFalse() throws Exception { // teaDown glide instance first so we have a clean slate and not the Glide.get() call in setUp Glide.tearDown(); Glide.setModulesEnabled(false); try { Glide glide = Glide.get(getContext()); List<ModelLoader<GlideUrl, ?>> modelLoaders = glide.getRegistry().getModelLoaders(mock(GlideUrl.class)); // With modules disabled, SetupModule below should not have been initialized, // so the default modelLoader should remain assertEquals(1, modelLoaders.size()); assertTrue(modelLoaders.get(0) instanceof HttpGlideUrlLoader); } finally { START Glide.setModulesEnabled(true); END } } I think this should be part of Glide.tearDown, it resets Glide to pre-initialized state, which IMO includes both static variables. (It should probably even reset ViewTarget.tagId)

Target:
public void testSetModulesEnabledFalse() throws Exception { // tearDown glide instance first so we have a clean slate and not the Glide.get() call in setUp Glide.tearDown(); Glide.setModulesEnabled(false); Glide glide = Glide.get(getContext()); List<ModelLoader<GlideUrl, ?>> modelLoaders = glide.getRegistry().getModelLoaders(mock(GlideUrl.class)); // With modules disabled, SetupModule below should not have been initialized, // so the default modelLoader should remain assertEquals(1, modelLoaders.size()); assertTrue(modelLoaders.get(0) instanceof HttpGlideUrlLoader); }
Source:
public int getDelay(int n) { int delay = -1; START if (0 <= n && n < header.frameCount) { END delay = header.frames.get(n).delay; } return delay; } nit: I prefer the other ordering for <= or ==, it's easier for me to read "n is greater than or equal to 0" than it is "0 is less than or equal to n".

Target:
public int getDelay(int n) { int delay = -1; if ((n >= 0) && (n < header.frameCount)) { delay = header.frames.get(n).delay; } return delay; }
Source:
public CalibratedPredictiveModel(Classifier wrappedPredictiveModel, PoolAdjacentViolatorsModel PAVFunction) { START Preconditions.checkArgument(!(wrappedPredictiveModel instanceof CalibratedPredictiveModel)); END this.wrappedPredictiveModel = wrappedPredictiveModel; this.pavFunction = PAVFunction; } Seems a little over-cautious, there might be a reason to do a double-wrapped PM.

Target:
public CalibratedPredictiveModel(Classifier wrappedPredictiveModel, PoolAdjacentViolatorsModel PAVFunction) { this.wrappedPredictiveModel = wrappedPredictiveModel; this.pavFunction = PAVFunction; }
Source:
START private boolean newValidationSetExists() { END if (currentTrainingSetSize >= allTrainingData.size()) { return false; } else return true; } You can just return the inverse of your conditional: return currentTrainingSetSize < allTrainingData.size();

Target:
private boolean newValidationSetExists() { return currentTrainingSetSize < allTrainingData.size(); }
Source:
START public static Collection<Integer> getSupportedCountryCodes() END { final Set<Integer> supportedCountryCodes = new HashSet<>(); final PhoneNumberUtil pnUtil = PhoneNumberUtil.getInstance(); for (final String region : pnUtil.getSupportedRegions()) { supportedCountryCodes.add(pnUtil.getCountryCodeForRegion(region)); } return supportedCountryCodes; } Semantic change! We do not want duplicates here.

Target:
public static Collection<Integer> getSupportedCountryCodes() { final Collection<Integer> supportedCountryCodes = new HashSet<>(); final PhoneNumberUtil pnUtil = PhoneNumberUtil.getInstance(); for (final String region : pnUtil.getSupportedRegions()) { supportedCountryCodes.add(pnUtil.getCountryCodeForRegion(region)); } return supportedCountryCodes; }
Source:
public void bbCodesWithTextThatShouldFail(String postBody, String messageIfTestFails) throws Exception { info("Running a test case [" + messageIfTestFails + "]"); try { Topics.postAnswer(TEST_TOPIC, new Post(postBody)); //should throw exception if validation failed fail(messageIfTestFails); } catch (ValidationException e) { //if validation error happened, then the test passed } catch (CouldNotOpenPageException e) { START fail("Something went wrong and user was thrown out of topic."); END } } Why do you catch this kind of exception if the only thin you do is re-throwing an exception?

Target:
public void bbCodesWithTextThatShouldFail(String postBody, String messageIfTestFails) throws Exception { info("Running a test case [" + messageIfTestFails + "]"); try { Topics.postAnswer(TEST_TOPIC, new Post(postBody)); //should throw exception if validation failed fail(messageIfTestFails); } catch (ValidationException e) { //if validation error happened, then the test passed } }
Source:
public void bbCodesWithTextThatShouldPass(String postBody, String messageIfTestFails) throws Exception { info("Running a test case [" + messageIfTestFails + "]"); try { Topics.postAnswer(TEST_TOPIC, new Post(postBody)); //should throw exception if validation failed } catch (ValidationException e) { fail(messageIfTestFails); //if validation error happened, then the test failed } catch (CouldNotOpenPageException e) { START fail("Something went wrong and user was thrown out of topic."); END } } I don't see any reason to catch the exception if you still are going to throw it..

Target:
public void bbCodesWithTextThatShouldPass(String postBody, String messageIfTestFails) throws Exception { info("Running a test case [" + messageIfTestFails + "]"); try { Topics.postAnswer(TEST_TOPIC, new Post(postBody)); //should throw exception if validation failed } catch (ValidationException e) { fail(messageIfTestFails); //if validation error happened, then the test failed } }
Source:
public static void removePmFromOutbox(PrivateMessage pm) { info("Start to remove PM from outbox folder"); mainPage.openPrivateMessages(); START info("Opening outbox folder"); END pmPage.clickOpenOutboxMessages(); removePm(pm); } Can be moved inside `pmPage.clickOpenOutboxMessages()`

Target:
public static void removePmFromOutbox(PrivateMessage pm) { info("Start to remove PM from outbox folder"); mainPage.openPrivateMessages(); pmPage.clickOpenOutboxMessages(); removePm(pm); }
Source:
public static void savePrivateMessageAsDraft(PrivateMessage pm) throws NoSuchElementException, ValidationException { composeMessage(pm); if (pmPage.isSaveButtonEnabled()) { info("Clicking Save PM button"); try { pmPage.clickSaveButton(); } catch (NoSuchElementException e) { info("No such button found!"); START throw new NoSuchElementException("Couldn't find Save button."); END } } assertFormValid(); info("Draft had to be saved"); } Either re-throw the very same exception: `throw e` or add the root exception to the newly created: `throw new NoSuchElementException("blah-blah", e)`

Target:
public static void savePrivateMessageAsDraft(PrivateMessage pm) throws NoSuchElementException, ValidationException { composeMessage(pm); if (pmPage.isSaveButtonEnabled()) { try { pmPage.clickSaveButton(); } catch (NoSuchElementException e) { throw new NoSuchElementException("Couldn't find Save button.", e); } } assertFormValid(); info("Draft had to be saved"); }
Source:
private static void composeMessage(PrivateMessage pm) { info("Opening private messages page"); mainPage.openPrivateMessages(); START info("Clicking compose button"); END pmPage.clickComposeMessage(); info("Start filling PM fields."); pmPage.fillPrivateMessageFields(pm); } Shouldn't this kind of messages be placed inside of `pmPage.clickComponseMessage()`?

Target:
private static void composeMessage(PrivateMessage pm) { mainPage.openPrivateMessages(); pmPage.clickComposeMessage(); pmPage.fillPrivateMessageFields(pm); }
Source:
public void createTopicWithTitleAndMessage_ShouldPass_JC_13() throws Exception { Users.signUpAndSignIn(); START Topic topic = new Topic().withTitle("subject").withBody("message"); END Topic createdTopic = Topics.createTopic(topic); Assert.assertTrue(Topics.isCreated(createdTopic)); } just new Topic() so that subject and body get random

Target:
public void createTopicWithTitleAndMessage_ShouldPass_JC_13() throws Exception { Users.signUpAndSignIn(); Topic topic = new Topic(); Topic createdTopic = Topics.createTopic(topic); Assert.assertTrue(Topics.isCreated(createdTopic)); }
Source:
public void viewUserProfile_shouldPass() throws Exception { User user = Users.signUpAndSignIn(); Users.viewProfile(user); START Users.viewProfile(); END } What do we check in this TC? And what should two "viewProfile" methods do?

Target:
public void viewUserProfile_shouldPass() throws Exception { User user = Users.signUpAndSignIn(); Users.viewProfile(user); }
Source:
public Qualifiers(Qualifiers other) { START this.resolvers.addAll(other.resolvers); END this.registry = null; } Should be package private

Target:
private Qualifiers(Qualifiers other) { this.resolvers.addAll(other.resolvers); this.registry = null; }
Source:
private ReflectionMappers(ReflectionMappers that) { START columnNameMatchers.addAll(that.columnNameMatchers); END strictMatching = that.strictMatching; } Should use the `CopyOnWriteArrayList(Collection)` copy constructor, which reuses the underlying array if the collection is another `CopyOnWriteArrayList`. Then you actually get the copy-on-write benefit.

Target:
private ReflectionMappers(ReflectionMappers that) { columnNameMatchers = new ArrayList<>(that.columnNameMatchers); strictMatching = that.strictMatching; }
Source:
START public MapEntryMappers() { END keyColumn = null; valueColumn = null; } This constructor does nothing.

Target:
public MapEntryMappers()
Source:
public JdbiImmutables registerImmutable(Iterable<Class<?>> specs) { START specs.iterator().forEachRemaining(this::registerImmutable); END return this; } Iterable already has a forEach IIRC

Target:
public JdbiImmutables registerImmutable(Iterable<Class<?>> specs) { specs.forEach(this::registerImmutable); return this; }
Source:
public <R, X extends Exception> R inTransaction(HandleCallback<R, X> callback) throws X { START if (isInTransaction()) { END return callback.withHandle(this); } return transactions.inTransaction(this, callback); } Nitpick: I think a ternary would be nice here. This reads a lot like a guard block, while it's really just a binary decision.

Target:
public <R, X extends Exception> R inTransaction(HandleCallback<R, X> callback) throws X { return isInTransaction() ? callback.withHandle(this) : transactions.inTransaction(this, callback); }
Source:
private TemporalUnitOffset getAllowableOffset() { // PostgreSQL seems to not have as much precision on Windows as it does on Linux. if (SystemUtils.IS_OS_WINDOWS) { START return within(0, ChronoUnit.MICROS); END } else { return within(0, ChronoUnit.NANOS); } } Can we just use the more lenient comparison window always, and get rid of the OS detection? We are not really intending to test the system clock here at all, and OS-specific behavior should be avoided whenever possible.

Target:
private TemporalUnitOffset getAllowableOffset() { // PostgreSQL seems to not have as much precision on Windows as it does on Linux. return within(0, ChronoUnit.MICROS); }
Source:
public String locate(Class<?> sqlObjectType, Method method, ConfigRegistry config) { Function<String, String> valueOrMethodNameToSql = key -> { String filename = key.isEmpty() ? method.getName() : key; START return org.jdbi.v3.core.locator.ClasspathSqlLocator.findSqlOnClasspath(sqlObjectType, filename); END }; return SqlAnnotations.getAnnotationValue(method, valueOrMethodNameToSql) .orElseThrow(() -> new IllegalStateException(String.format("method %s has no query annotations", method))); } Can't this be an import and short reference now?

Target:
public String locate(Class<?> sqlObjectType, Method method, ConfigRegistry config) { Function<String, String> valueOrMethodNameToSql = key -> { String filename = key.isEmpty() ? method.getName() : key; return ClasspathSqlLocator.findSqlOnClasspath(sqlObjectType, filename); }; return SqlAnnotations.getAnnotationValue(method, valueOrMethodNameToSql) .orElseThrow(() -> new IllegalStateException(String.format("method %s has no query annotations", method))); }
Source:
public E map(ResultSet rs, int columnNumber, StatementContext ctx) throws SQLException { String name = ctx.findColumnMapperFor(String.class) .orElseThrow(() -> new UnableToProduceResultException("a String column mapper is required to map Enums from names", ctx)) .map(rs, columnNumber, ctx); START return name == null ? null : nameValueCache.computeIfAbsent(name.toLowerCase(), lowercased -> getValueByName(enumClass, name, ctx)); END } I wonder if the cost of lowercasing outweighs the cost of duplicate entries. Previously I'd operated under the assumption that most users, even if the casing is wrong, will tend to be at least consistently wrong - in which case you'd have few if any truly redundant entries. And even if they aren't, the extra cache entries may well be cheaper than repeatedly lowercasing. Part of the reason for adding this cache in the first place is to avoid case sensitive operations. I worry that this may be a performance regression if that is indeed the common case.

Target:
public E map(ResultSet rs, int columnNumber, StatementContext ctx) throws SQLException { String name = rs.getString(columnNumber); return name == null || name.isEmpty() // some vendors treat null and empty varchar as the same ? null : nameValueCache.computeIfAbsent(name, n -> getValueByName(enumClass, name, ctx)); }
Source:
public SqlStatements define(String key, Object value) { START synchronized (this) { END attributes.put(key, value); } return this; } Prefer using a private field for a mutex to prevent outside code from being able to hold our lock: ```java private final Object mutex = new Object(); public SqlStatement define(String key, Object value) { synchronized (mutex) { attributes.put(key, value); } return this; } ```

Target:
public SqlStatements define(String key, Object value) { attributes.put(key, value); return this; }
Source:
public SqlStatements defineMap(final Map<String, ?> values) { if (values != null) { START synchronized (this) { END attributes.putAll(values); } } return this; } Ditto for mutex

Target:
public SqlStatements defineMap(final Map<String, ?> values) { if (values != null) { attributes.putAll(values); } return this; }
Source:
public static Type resolveType(Type type, Type contextType) { START return GenericTypeReflector.resolveType(GenericTypeReflector.annotate(type), GenericTypeReflector.annotate(contextType)).getType(); END } Please use `GenericTypeReflector.resolveType(Type, Type)` instead of wrapping first using `annotate`. The end result is the same, but it avoids one extra traversal through the type structure, so it should be somewhat faster. Details, in case you care: When calling `GenericTypeReflector.resolveType(AnnotatedType, AnnotatedType)`, the `contextType` first gets its generics expanded (so that each `Class` with type parameters gets wrapped into a `ParameterizedType`), and when calling `GenericTypeReflector.resolveType(Type, Type)` this is done at the same time the `Type` is wrapped into an `AnnotatedType`, so one traversal is skipped.

Target:
public static Type resolveType(Type type, Type contextType) { return GenericTypeReflector.resolveType(type, contextType); }
Source:
public Jackson2Config createCopy() { START return new Jackson2Config().setMapper(mapper); END } perhaps a copy constructor to be consistent with all other Config classes? Would be a shame to divert from the pattern and have to refactor it later anyway.

Target:
public Jackson2Config createCopy() { return new Jackson2Config(this); }
Source:
public static <T> Optional<T> findFirstPresent(Supplier<Optional<T>>... suppliers) { return Stream.of(suppliers) .flatMap(supplier -> toStream(supplier.get())) .findFirst(); START } END Duplicates `JdbiStreams.toStream(Optional<T>)`. Although I'd be okay folding that method into this class.

Target:
public static <T> Optional<T> findFirstPresent(Supplier<Optional<T>>... suppliers) { return Stream.of(suppliers) .flatMap(supplier -> stream(supplier.get())) .findFirst(); }
Source:
START protected BeanMapper(Class<T> type, String prefix) { END this(type, (PojoProperties<T>) BeanPropertiesFactory.propertiesFor(type), prefix); } Could be package private

Target:
BeanMapper(Class<T> type, String prefix) { this(type, (PojoProperties<T>) BeanPropertiesFactory.propertiesFor(type), prefix); }
Source:
public void setUp() { h = dbRule.getSharedHandle(); START h.registerRowMapper(ImmutablesMapperFactory.mapImmutable(Train.class, ImmutableTrain.class, ImmutableTrain::builder)); END h.execute("create table train (name varchar, carriages int, observation_car boolean)"); dao = h.attach(Dao.class); } Feels like we want annotations to register Immutables mappers, e.g. `@RegisterImmutablesMapper(value = Train.class)` annotation. The impl and builder method name could be default attributes that look for `Immutable*` and `Immutable*.builder()`, respectively.

Target:
public void setUp() { h = dbRule.getSharedHandle(); h.execute("create table train (name varchar, carriages int, observation_car boolean)"); dao = h.attach(Dao.class); }
Source:
public static <T, B> Function<Type, PojoProperties<T>> immutable(Class<T> defn, Supplier<B> builder) { START return t -> (PojoProperties<T>) IMMUTABLE_PROPERTIES.computeIfAbsent(t, x -> new ImmutablePojoProperties<>(t, defn, builder)); END } I'm not sure what this indirection with the `t ->` business buys us

Target:
public static <T, B> Function<Type, PojoProperties<?>> immutable(Class<T> defn, Supplier<B> builder) { return t -> (PojoProperties<T>) IMMUTABLE_PROPERTIES.computeIfAbsent(t, x -> new ImmutablePojoProperties<>(t, defn, builder)); }
Source:
public SqlStatements define(String key, Object value) { if (value != null) { attributes.put(key, value); START } END return this; } Should probably `remove(key)` if `value == null`.

Target:
public SqlStatements define(String key, Object value) { if (value == null) { attributes.remove(key); } else { attributes.put(key, value); } return this; }
Source:
public static File findTemplateDirectory(Class<?> type) { try { String classFolder = type.getName().replace(".", "/"); URL resource = type.getClassLoader().getResource(classFolder); if (resource != null) { return new File(resource.toURI()); } } catch (URISyntaxException ignored) START return null; END } Some issues with mixed tabs and spaces? Please configure your IDE project for spaces only.

Target:
private static File findTemplateDirectory(Class<?> type) { try { String classFolder = getPath(type); URL resource = type.getClassLoader().getResource(classFolder); if (resource != null) { return new File(resource.toURI()); } } catch (URISyntaxException ignored) { } return null; }
Source:
public void setUp() throws Exception { Jdbi jdbi = Jdbi.create("jdbc:sqlite::memory:"); jdbi.installPlugin(new SQLitePlugin()); handle = jdbi.open(); handle.useTransaction(handle -> { START handle.execute("DROP TABLE IF EXISTS foo"); END handle.execute("CREATE TABLE foo(url URL);"); }); } I don't think `foo` can ever exist here, right, since the above opens a unique in-memory db?

Target:
public void setUp() throws Exception { Jdbi jdbi = Jdbi.create("jdbc:sqlite::memory:"); jdbi.installPlugin(new SQLitePlugin()); handle = jdbi.open(); handle.useTransaction(handle -> handle.execute("CREATE TABLE foo(url URL);")); }
Source:
public void setUp() throws Exception { Jdbi jdbi = Jdbi.create("jdbc:sqlite::memory:"); jdbi.installPlugin(new SQLitePlugin()); handle = jdbi.open(); START handle.useTransaction(handle -> { END handle.execute("CREATE TABLE foo(url URL);"); }); } Single statements also are implicitly in a transaction, so it might be entirely redundant.

Target:
public void setUp() throws Exception { Jdbi jdbi = Jdbi.create("jdbc:sqlite::memory:"); jdbi.installPlugin(new SQLitePlugin()); handle = jdbi.open(); handle.useTransaction(handle -> handle.execute("CREATE TABLE foo(url URL);")); }
Source:
public static void closeIfNeeded(Handle handle) { START if (UNMANAGED_HANDLES.contains(handle)) END { handle.close(); } } this looks like a memory leak, should this be `remove`?

Target:
public static void closeIfNeeded(Handle handle) { if (UNMANAGED_HANDLES.contains(handle)) { try { handle.close(); } finally { UNMANAGED_HANDLES.remove(handle); } } }
Source:
START public static Method lookupMethod(String methodName, Class<?>... parameterTypes) { END return lookup0(initData().extensionType, methodName, parameterTypes); } should we add suppressions for `unused` on methods only called from reflective code? Better indicates current state on one hand, but adds maintenance to code changes on the other.

Target:
public static Method lookupMethod(String methodName, Class<?>... parameterTypes) { return lookupMethod(initData().extensionType, methodName, parameterTypes); }
Source:
public void testMapMapperOrdering() throws Exception { h.execute("insert into something (id, name) values (?, ?)", 1, "hello"); h.execute("insert into something (id, name) values (?, ?)", 2, "world"); List<Map<String, Object>> rs = h.createQuery("select id, name from something") START .setMaxRows(1) END .mapToMap() .list(); assertThat(rs).hasSize(2); assertThat(rs).hasOnlyElementsOfType(LinkedHashMap.class); } This max rows disagrees with the assertion, which is why the test is failing.

Target:
public void testMapMapperOrdering() throws Exception { h.execute("insert into something (id, name) values (?, ?)", 1, "hello"); h.execute("insert into something (id, name) values (?, ?)", 2, "world"); List<Map<String, Object>> rs = h.createQuery("select id, name from something") .mapToMap() .list(); assertThat(rs).hasSize(2); assertThat(rs).hasOnlyElementsOfType(LinkedHashMap.class); }
Source:
private Comparator<Class<? extends Annotation>> createDecoratorComparator(DecoratorOrder order) { List<Class<? extends Annotation>> ordering = Arrays.asList(order.value()); START ToIntFunction<Class<? extends Annotation>> indexOf = type -> { END int index = ordering.indexOf(type); return index == -1 ? ordering.size() : index; }; return Comparator.comparingInt(indexOf::applyAsInt); } I think the lambda expression could be passed directly to `Comparator.comparingInt`

Target:
private Comparator<Class<? extends Annotation>> createDecoratorComparator(DecoratorOrder order) { List<Class<? extends Annotation>> ordering = Arrays.asList(order.value()); return Comparator.comparingInt(type -> { int index = ordering.indexOf(type); return index == -1 ? ordering.size() : index; }); }
Source:
private static BoundCustomizer defaultParameterCustomizer(Class<?> type, Method method, Parameter parameter, Integer i) { return (stmt, args) -> getDefaultParameterCustomizerFactory(stmt) .createForParameter(null, type, method, parameter, i) START .apply(stmt, args[i]); END } I'd rather we introduce a separate factory interface for the default customizer, similar to what #754 is doing with default handlers. It feels weird to pass a `null` for the annotation, when the use case is specifically for when there _is_ no annotation. e.g. ```java interface DefaultParameterCustomizerFactory { SqlStatementParameterCustomizer createForParameter(Class<?> sqlObjectType, Method method, Parameter param, int index); } ```

Target:
private static BoundCustomizer defaultParameterCustomizer(Class<?> type, Method method, Parameter parameter, Integer i) { return (stmt, args) -> getDefaultParameterCustomizerFactory(stmt) .createForParameter(type, method, parameter, i) .apply(stmt, args[i]); }
Source:
public void testInvalidDuration() { handle.createQuery("select foo from intervals where id=?") .bind(0, 5) .mapTo(Duration.class) START .findOnly(); END } Here is an example of a test that is difficult to understand in isolation, because the critical data (what is in interval id=5?) is in `IntervalTestCommon` instead of in a setup method or a one-off in the test itself.

Target:
public void testInvalidDuration() { handle.createQuery("select foo from intervals where id=?") .bind(0, 3) // The bad one. .mapTo(Duration.class) .findOnly(); }
Source:
public Optional<ColumnMapper<?>> build(Type type, ConfigRegistry config) { Class<?> erasedType = GenericTypes.getErasedType(type); if (ImmutableList.class.equals(erasedType)) { return GenericTypes.findGenericParameter(type, ImmutableList.class) START .flatMap(t -> config.get(ColumnMappers.class).findFor(type, config)) END .map(ImmutableListArrayColumnMapper::new); } return Optional.empty(); } This might be splitting hairs, but it should probably be `findFor(t, config)` (`t` instead of `type`)

Target:
public Optional<ColumnMapper<?>> build(Type type, ConfigRegistry config) { Class<?> erasedType = GenericTypes.getErasedType(type); if (ImmutableList.class.equals(erasedType)) { return GenericTypes.findGenericParameter(type, ImmutableList.class) .flatMap(t -> config.get(ColumnMappers.class).findFor(t)) .map(ImmutableListArrayColumnMapper::new); } return Optional.empty(); }
Source:
public OracleReturning(RowMapper<ResultType> mapper) { this.mapper = mapper; try { START this.oraclePS = Class.forName("oracle.jdbc.OraclePreparedStatement"); END this.registerReturnParameter = oraclePS.getMethod("registerReturnParameter", new Class[]{int.class, int.class}); this.getReturnResultSet = oraclePS.getMethod("getReturnResultSet"); } catch (Exception e) { throw new RuntimeException(e); } } Do we still need to do all this reflective bullshit now that it's in a separate artifact?

Target:
public OracleReturning(RowMapper<ResultType> mapper) { this.mapper = mapper; }
Source:
public Handler buildHandler(Class<?> sqlObjectType, Method method) { START return (obj, m, args, handle) -> { END return "foo"; }; } couldn't this just be `-> "foo"` ?

Target:
public Handler buildHandler(Class<?> sqlObjectType, Method method) { return (obj, m, args, handle) -> "foo"; }
Source:
public <T> T getColumn(String column, GenericType<T> type) { START return (T) getColumn(column, (Type) type); END } Ditto: should be `type.getType()`

Target:
public <T> T getColumn(String column, GenericType<T> type) { return (T) getColumn(column, type.getType()); }
Source:
public void testMapperForDelegatesToRegistry() { ColumnMapper<?> mapper = new FooMapper(); JdbiConfig config = new JdbiConfig(); config.mappingRegistry.addColumnMapper(mapper); final StatementContext context = new StatementContext(config); START assertThat(context.findColumnMapperFor(Foo.class).get()).isEqualTo(mapper); END } `Assertions` has an `Optional<T>` variant you could use: ``` assertThat(context.findColumnMapperFor(Foo.class)).hasValue(mapper); ```

Target:
public void testMapperForDelegatesToRegistry() { ColumnMapper<?> mapper = new FooMapper(); JdbiConfig config = new JdbiConfig(); config.mappingRegistry.addColumnMapper(mapper); final StatementContext context = new StatementContext(config); assertThat(context.findColumnMapperFor(Foo.class)).contains(mapper); }
Source:
public void testCorrectExceptionOnSQLException() throws Exception { Jdbi dbi = Jdbi.create(() -> { throw new SQLException(); }); try { dbi.open(); fail("Should have raised an exception"); } catch (UnableToObtainConnectionException e) { START assertThat(e).isNotNull(); END } } This assertion is probably not buying us anything

Target:
public void testCorrectExceptionOnSQLException() throws Exception { Jdbi dbi = Jdbi.create(() -> { throw new SQLException(); }); dbi.open(); }
Source:
public void testHelpfulErrorOnNothingSet() throws Exception { try { h.createQuery("select * from something where name = :name").list(); fail("should have raised exception"); } catch (UnableToExecuteStatementException e) { START assertThat(e).isNotNull(); END } catch (Exception e) { fail("Raised incorrect exception"); } } Redundant assertion

Target:
public void testHelpfulErrorOnNothingSet() throws Exception { h.createQuery("select * from something where name = :name").list(); }
Source:
public void testThrowingRuntimeExceptionPercolatesOriginal() throws Exception { Handle h = db.openHandle(); try { h.inTransaction((handle, status) -> { throw new IllegalArgumentException(); }); } catch (JdbiException e) { fail("Should have thrown a straight RuntimeException"); } catch (IllegalArgumentException e) { START assertThat(e).isNotNull(); END } catch (Exception e) { fail("Should have been caught at IllegalArgumentException"); } } Redundant assertion

Target:
public void testThrowingRuntimeExceptionPercolatesOriginal() throws Exception { db.openHandle().inTransaction((handle, status) -> { throw new IllegalArgumentException(); }); }
Source:
public boolean nameMatches(String propertyName, String sqlColumnName) { START return sqlColumnName.replace("_", "").toLowerCase(locale).equals(propertyName.toLowerCase(locale)); END } In the absence of a demonstrated problem the other way, let's go with the simple solution. We can always enhance it later to use locales.

Target:
public boolean nameMatches(String propertyName, String sqlColumnName) { return sqlColumnName.replace("_", "").equalsIgnoreCase(propertyName); }
Source:
public void testSomethingByIterableHandleNullWithEmptyList() { final SomethingByIterableHandleNull s = handle.attach(SomethingByIterableHandleNull.class); final List<Something> out = s.get(new ArrayList<Object>()); START Assert.assertEquals(4, out.size()); END } I expect `out` to be empty here, yes?

Target:
public void testSomethingByIterableHandleNullWithEmptyList() { final SomethingByIterableHandleNull s = handle.attach(SomethingByIterableHandleNull.class); final List<Something> out = s.get(new ArrayList<Object>()); Assert.assertEquals(0, out.size()); }
Source:
public void testSomethingByIterableHandleNullWithNull() { final SomethingByIterableHandleNull s = handle.attach(SomethingByIterableHandleNull.class); START final List<Something> out = s.get(null); END Assert.assertEquals(4, out.size()); } This might be considered a programming error -- should we really assume `null` is `empty list` instead of a coding error?

Target:
public void testSomethingByIterableHandleNullWithNull() { final SomethingByIterableHandleNull s = handle.attach(SomethingByIterableHandleNull.class); final List<Something> out = s.get(null); Assert.assertEquals(0, out.size()); }
Source:
static Cleanable forResultSet(final ResultSet rs) { START return () -> rs.close(); END } Meh: you could use `rs::close` instead of a lambda. They're semantically equivalent--I just like the way method handles look. Not critical for merge, obviously.. :)

Target:
static Cleanable forResultSet(final ResultSet rs) { return rs::close; }
Source:
START protected String locateSql(final Handle h) END { return h.getConfig(SqlObjects.class).getSqlLocator().locate(sqlObjectType, method); } Meh: these methods could be package private

Target:
String locateSql(final Handle h) { return h.getConfig(SqlObjects.class).getSqlLocator().locate(sqlObjectType, method); }
Source:
private JpaClass(Class<C> clazz) { START logger.debug("init {}", clazz); END this.members = unmodifiableList(new ArrayList<>(inspectClass(clazz))); logger.debug("init {}: members.", clazz, members.size()); } this is somewhat redundant with the following log statement

Target:
private JpaClass(Class<C> clazz) { this.members = unmodifiableList(new ArrayList<>(inspectClass(clazz))); logger.debug("init {}: members.", clazz, members.size()); }
Source:
public static <T> T open(DBI dbi, Class<T> sqlObjectType) { try { check(OPEN); return (T) OPEN.invoke(dbi, sqlObjectType); } catch (Throwable t) { START throw new RuntimeException("Error during `SqlObjectBuilder.open` invocation", t); END } } this will wrap e.g. `UnableToOpenConnectionException` or other `DbiException` subclasses

Target:
public static <T> T open(DBI dbi, Class<T> sqlObjectType) { try { check(OPEN); return (T) OPEN.invoke(dbi, sqlObjectType); } catch (RuntimeException e) { throw e; } catch (Throwable t) { throw new RuntimeException("Error during `SqlObjectBuilder.open` invocation", t); } }
Source:
START <T, R> Collector<T, ?, R> createCollectorFor(Class<R> type) { END for (CollectorFactory<?, ?, ?> factory : factories) { if (factory.accepts(type)) { return ((CollectorFactory<T, ?, R>) factory).newCollector(type); } } throw new IllegalStateException("No collector builder available for " + type.getName()); } I know you are only mirroring how the existing registries work, but I wonder if it would make sense for these to either return a nullable type or an `Optional<Collector<...>>` so that lookups can be done without necessarily throwing an exception. If so, probably a change that should be done to the existing registries as well.

Target:
<T, R> Collector<T, ?, R> createCollectorFor(Class<R> type) { for (CollectorFactory<?, ?> factory : factories) { if (factory.accepts(type)) { return ((CollectorFactory<T, R>) factory).newCollector(type); } } throw new IllegalStateException("No collector builder available for " + type.getName()); }
Source:
public void testFoo() throws Exception { START assumeTrue(postgresIsInstalled); END DAO dao = dbi.open(DAO.class); Long brian_id = dao.insert("Brian"); long keith_id = dao.insert("Keith"); assertThat(dao.findNameById(brian_id), equalTo("Brian")); assertThat(dao.findNameById(keith_id), equalTo("Keith")); dao.close(); } Would this be better in the `@Before` ? Gets rid of the `if (!postgresIsInstalled)` blocks entirely, and should work just the same: https://github.com/junit-team/junit/wiki/Assumptions-with-assume

Target:
public void testFoo() throws Exception { DAO dao = dbi.open(DAO.class); Long brian_id = dao.insert("Brian"); long keith_id = dao.insert("Keith"); assertThat(dao.findNameById(brian_id), equalTo("Brian")); assertThat(dao.findNameById(keith_id), equalTo("Keith")); dao.close(); }
Source:
private void restoreAutoCommitState(final Handle handle) { try { final LocalStuff stuff = localStuff.remove(handle); if (stuff != null) { handle.getConnection().setAutoCommit(stuff.getInitialAutocommit()); stuff.getCheckpoints().clear(); } } catch (SQLException e) { throw new UnableToRestoreAutoCommitStateException(e); } finally { // prevent memory leak if rollback throws an exception START if (localStuff.containsKey(handle)) { END localStuff.remove(handle); } } } Checking `containsKey` before calling `remove` is redundant and should be removed

Target:
private void restoreAutoCommitState(final Handle handle) { try { final LocalStuff stuff = localStuff.remove(handle); if (stuff != null) { handle.getConnection().setAutoCommit(stuff.getInitialAutocommit()); stuff.getCheckpoints().clear(); } } catch (SQLException e) { throw new UnableToRestoreAutoCommitStateException(e); } finally { // prevent memory leak if rollback throws an exception localStuff.remove(handle); } }
Source:
public Map<String, Object> convertJobGrabToText(@RequestBody Graph graph) { START Map<String, Object> response = new HashMap<String, Object>(); END try { String dslText = graph.toDSLText(); response.put("text", dslText); } catch (JobSpecificationException jse) { response.put("error", jse.toExceptionDescriptor()); } catch (Throwable e) { response.put("error", e.toString()); } return response; } For consistence with the statement higher up, use: `new HashMap<>();`

Target:
public Map<String, Object> convertJobGrabToText(@RequestBody Graph graph) { Map<String, Object> response = new HashMap<>(); try { String dslText = graph.toDSLText(); response.put("text", dslText); } catch (JobSpecificationException jse) { response.put("error", jse.toExceptionDescriptor()); } catch (Throwable e) { response.put("error", e.toString()); } return response; }
Source:
public static boolean isComposedJobDefinition(String definition){ String patternString = "(\\|\\|(?=([^\\\"']*[\\\"'][^\\\"']*[\\\"'])*[^\\\"']*$)) " + START "| (\\&(?=([^\\\"']*[\\\"'][^\\\"']*[\\\"'])*[^\\\"']*$)) "; END Pattern pattern = Pattern.compile(patternString); Matcher matcher = pattern.matcher(definition); return matcher.find(); } Any shot of breaking this up a bit so that someone can understand what we're looking for?

Target:
public static boolean isComposedJobDefinition(String definition){ Matcher matcher = pattern.matcher(definition); return matcher.find(); }
Source:
public static void setUp() { System.setProperty("XD_HOME", "../.."); RandomConfigurationSupport randomConfigSupport = new RandomConfigurationSupport(); application = new SingleNodeApplication().run(); SingleNodeIntegrationTestSupport singleNodeIntegrationTestSupport = new SingleNodeIntegrationTestSupport( START application); END } These variables are not used (randomConfigSupport and singleNodeIntegrationTestSupport) and the tests run ok without them - is there some magic they provide that I am not aware of? Or, can I just remove them?

Target:
public static void setUp() { System.setProperty("XD_HOME", "../.."); new RandomConfigurationSupport(); application = new SingleNodeApplication().run(); }
Source:
public SparkStreamingPlugin(MessageBus messageBus) { START super(messageBus, null); END } I think there is a 1 parameter version of this constructor that you can use instead of passing `null`.

Target:
public SparkStreamingPlugin(MessageBus messageBus) { super(messageBus); }
Source:
public void undeploy(String name) { Assert.hasText(name, "name cannot be blank or null"); START validateBeforeUndeploy(name); END logger.trace("Undeploying {}", name); D definition = getDefinitionRepository().findOne(name); if (definition == null) { throwNoSuchDefinitionException(name); } final I instance = instanceRepository.findOne(name); if (instance == null) { throwNotDeployedException(name); } instanceRepository.delete(instance); undeployResource(name); } Same here, it seems that `validateBeforeUndeploy` is doing the exact same thing as the code below.

Target:
public void undeploy(String name) { validateBeforeUndeploy(name); logger.trace("Undeploying {}", name); instanceRepository.delete(instanceRepository.findOne(name)); undeployResource(name); }
Source:
public int selectPartition(Object key, int partitionCount) { int hashCode = key.hashCode(); if (hashCode == Integer.MIN_VALUE) { hashCode = 0; } START return Math.abs(hashCode) % partitionCount; END } Actually, I think the modulo should not be part of the strategy as it is always applied. Even, on closer inspection, I think there is an issue with ``` if (partition >= meta.partitionCount) { partition = partition % meta.partitionCount; } if (partition < 0) { partition = Math.abs(partition); } ``` => What if partition is less than `-meta.partitionCount` ? The modulo should be always applied, then abs() IMHO

Target:
public int selectPartition(Object key, int partitionCount) { int hashCode = key.hashCode(); if (hashCode == Integer.MIN_VALUE) { hashCode = 0; } return Math.abs(hashCode); }
Source:
public void stop() { logger.info("stopping SparkDriver"); try { // todo: when possible (spark 1.3.0), change to streamingContext.stop(false, true) without the cancel if (javaStreamingContext != null) { javaStreamingContext.ssc().sc().cancelAllJobs(); javaStreamingContext.close(); } if (streamingContext != null) { streamingContext.sc().cancelAllJobs(); START streamingContext.stop(true, false); END } super.stop(); } catch (Exception e) { logger.warn("Exception when stopping the spark module " + e); } } is this what we want here? The first boolean indicates stopping the actual SparkContext and the 2nd boolean is FALSE for "graceful" So, two things jump out: 1) those boolean values are the reverse of what we mention in the TODO above this 2) this is different than the Java version (where we just call close), and that was done that way - along with the cancel call - as a temporary workaround until the proper stop (with false, true) would work

Target:
public void stop() { logger.info("stopping SparkDriver"); try { // todo: when possible (spark 1.3.0), change to streamingContext.stop(true, true) without the cancel if (streamingContext != null) { streamingContext.sc().cancelAllJobs(); streamingContext.stop(true, false); } super.stop(); } catch (Exception e) { logger.warn("Exception when stopping the spark module " + e); } }
Source:
private Module createAndConfigureModuleInstance(ModuleDescriptor moduleDescriptor, ModuleOptions moduleOptions, ModuleDeploymentProperties deploymentProperties) { String name = (String) moduleOptions.asPropertySource().getProperty(MODULE_EXECUTION_FRAMEWORK); if (Processor.MODULE_EXECUTION_FRAMEWORK.equals(name)) { START return createSparkModule(moduleDescriptor, moduleOptions, deploymentProperties); END } Module module = moduleDescriptor.isComposed() ? createCompositeModule(moduleDescriptor, moduleOptions, deploymentProperties) : createSimpleModule(moduleDescriptor, moduleOptions, deploymentProperties); return module; } Should see what Rx/Reactor brings, but the main flow of decisions seems weird here. Also, you're not leveraging the module ClassLoader, which seems wrong.

Target:
private Module createAndConfigureModuleInstance(ModuleDescriptor moduleDescriptor, ModuleOptions moduleOptions, ModuleDeploymentProperties deploymentProperties) { Module module = moduleDescriptor.isComposed() ? createCompositeModule(moduleDescriptor, moduleOptions, deploymentProperties) : createSimpleModule(moduleDescriptor, moduleOptions, deploymentProperties); return module; }
Source:
public void missingConfigThrowsException() { ModuleDefinition moduleDefinition = ModuleDefinitions.simple("missing", ModuleType.processor, "classpath:/ModuleFactoryTests/modules/processor/missing"); START ModuleDescriptor moduleDescriptor = new ModuleDescriptor.Builder() END .setModuleDefinition(moduleDefinition) .setModuleName("missing") .setGroup("group") .setModuleDefinition(moduleDefinition) .build(); createResourceConfiguredModule("missing",ModuleType.processor); } Just browsing through the web interface at the moment, but I don't see `moduleDescriptor` being used in the test

Target:
public void missingConfigThrowsException() { ModuleDefinition moduleDefinition = ModuleDefinitions.simple("missing", ModuleType.processor, "classpath:/ModuleFactoryTests/modules/processor/missing"); createResourceConfiguredModule("missing",ModuleType.processor); }
Source:
public String[] profilesToActivate() { if (this.regexPattern != null) { return new String[] { REGEX_PATTERN_FILTER }; } else if (this.pattern != null) { return new String[] { SIMPLE_PATTERN_FILTER }; } START else { END return new String[] { ACCEPT_ALL_FILES }; } } Don't need last else

Target:
public String[] profilesToActivate() { if (this.regexPattern != null) { return new String[] { REGEX_PATTERN_FILTER }; } else if (this.pattern != null) { return new String[] { SIMPLE_PATTERN_FILTER }; } return new String[] { ACCEPT_ALL_FILES }; }
Source:
boolean isEitherPasswordOrPrivateKeyAndPassPhrase() { if (!StringUtils.hasText(password)) { return StringUtils.hasText(privateKey) && StringUtils.hasText(passPhrase); } else { START return !StringUtils.hasText(privateKey) && !StringUtils.hasText(passPhrase); END } } don't need the else here. Too bad java doesn't have XOR :)

Target:
boolean isEitherPasswordOrPrivateKeyAndPassPhrase() { if (!StringUtils.hasText(password)) { return StringUtils.hasText(privateKey) && StringUtils.hasText(passPhrase); } return !StringUtils.hasText(privateKey) && !StringUtils.hasText(passPhrase); }
Source:
START protected void deployModules(Container container) throws Exception { END String containerName = container.getName(); logger.info("Container arrived: {}", containerName); // before attempting to deploy unallocated modules, // wait to see if any more containers show up; this // will mitigate "overloading" of the container that // just arrived Thread.sleep(1000); deployUnallocatedStreamModules(); deployUnallocatedJobModules(); } When deploying the modules, since we no longer target **only** the arriving container but match all the available containers from the repository, can we have a `scheduled` deployer that performs the redeployment operation on a given time to all the targeting container. What I see from here is that the whole logic doesn't use the `arriving container` info anymore.

Target:
protected void deployModules(Container container) throws Exception { String containerName = container.getName(); logger.info("Container arrived: {}", containerName); deployUnallocatedStreamModules(); deployUnallocatedJobModules(); }
Source:
public String getLocalTime(Date date) { START Assert.notNull(date, "The provided date must not be null."); END return CommonUtils.getLocalTime(date, this.clientTimeZone); } The reason for the NPE in `doStopJobExecution(org.springframework.xd.shell.command.JobCommandTests)` comes from here: ``` final String startTimeAsString = this.configuration.getLocalTime(jobExecutionInfoResource.getJobExecution().getStartTime()); ``` The JobExecution startTime can be null.

Target:
public String getLocalTime(Date date) { return CommonUtils.getLocalTime(date, this.clientTimeZone); }
Source:
public int hashCode() { int result = container.hashCode(); START result = 31 * result + moduleSequence.hashCode(); END result = 31 * result + moduleDescriptorKey.hashCode(); return result; } Should this still include the key's hashCode as well as adding the sequence hashCode?

Target:
public int hashCode() { int result = container.hashCode(); result = 31 * result + moduleSequence; result = 31 * result + moduleDescriptorKey.hashCode(); return result; }
Source:
private boolean hasDeploymentInfo() { boolean hasValue = false; for (String s : deploymentDesc) { hasValue |= StringUtils.hasText(s); } if (!hasValue) { return false; } START if (StringUtils.isEmpty(deploymentDesc[MODULE_LABEL])) { END throw new IllegalStateException("Module label missing"); } if (StringUtils.isEmpty(deploymentDesc[CONTAINER])) { throw new IllegalStateException("Container missing"); } return true; } Could use Assert.state() here (since IllegalStateException is desired) or Assert.hasText(..) (which would instead throw IllegalArgumentException). In either case though, the 6 lines could be replaced by 2, and it improves test coverage (unless we have tests that make it into each of these if blocks).

Target:
private boolean hasDeploymentInfo() { boolean hasValue = false; for (String s : deploymentDesc) { hasValue |= StringUtils.hasText(s); } if (!hasValue) { return false; } Assert.state(StringUtils.hasText(deploymentDesc[MODULE_LABEL]), "Module label missing"); Assert.state(StringUtils.hasText(deploymentDesc[CONTAINER]), "Container missing"); return true; }