auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void run() { if (comparator == null) { START Arrays.sort(array); END } else { Arrays.sort(array, comparator); } } Arrays.sort допускает null в качестве компаратора.

Target:
public void run() { Arrays.sort(array, comparator); }
Source:
public void format(StringBuilder buffer, String format, Object... args) throws FormatterException { START position = 0; END nextFormat(buffer, format, args); } Наличие поля StringFormatter делает его не thread safe.

Target:
public void format(StringBuilder buffer, String format, Object... args) throws FormatterException { nextFormat(buffer, 0, format, args); }
Source:
public void close() { try { START bufferedReader.close(); END } catch (Exception e) { } out.flush(); out.close(); } Закрывать System.in - плохо.

Target:
public void close() { // bufferedReader // if fileInput then is already closed // else no need to close cin out.flush(); out.close(); }
Source:
START public synchronized String format(String format, Object... args) END throws FormatterException { StringBuilder buffer = new StringBuilder(); format(buffer, format, args); return buffer.toString(); } Объясни-таки, зачем нужен synchronized здесь.

Target:
public String format(String format, Object... args) throws FormatterException { StringBuilder buffer = new StringBuilder(); format(buffer, format, args); return buffer.toString(); }
Source:
public void format(StringBuilder buffer, Object o, String pattern) { Formatter formatter = new Formatter(); START buffer.append(formatter.format("%" + pattern + "d", o)); END } Должны поддерживаться все форматы для целых чисел. Например, "o", "10x".

Target:
public void format(StringBuilder buffer, Object o, String pattern) { Formatter formatter = new Formatter(); buffer.append(formatter.format("%" + pattern, o)); }
Source:
START private void close() { END try { reader.close(); } catch (Exception e) { // corrupted input stream. So bad. } } Всегда надо иметь возможность закрывать ресурс снаружи. См. интерфейс Closeable

Target:
public void close() { try { reader.close(); } catch (Exception e) { // corrupted input stream. So bad. } }
Source:
public void add(String string) { if (persnicketiness == Persnicketiness.ALL) { count++; return; } if (persnicketiness == Persnicketiness.UNIQUE_ANYCASE) { START string = string.toLowerCase(); END } Integer res = map.get(string); if (res == null) { map.put(string, 1); } else { map.put(string, res + 1); } } Изменять данные некорректно. Надо использовать String.CASE_INSENSITIVE_ORDER

Target:
public void add(String string) { if (persnicketiness == Persnicketiness.ALL) { count++; return; } Integer res = map.get(string); if (res == null) { map.put(string, 1); } else { map.put(string, res + 1); } }
Source:
public static boolean isNumber(String s) { START if (s.length() != 0) { END if (Character.isDigit(s.charAt(0))) { return true; } } return false; } Метод можно сократить до `return s.length() > 0 && Character.isDigit(s.charAt(0));`

Target:
public static boolean isNumber(String s) { return ((s.length() > 0) && (Character.isDigit(s.charAt(0)))); }
Source:
START public static Boolean getMessage(SocketChannel sc, ByteBuffer message, END Map<String, SocketChannel> clients) { try { int count = sc.read(message); if (count == -1) { // проверка на случай экстренного выхода клиента closeClient(clients, sc); return true; } } catch (Exception e) { printErrorAndExit("Bad geting message!" + e.getMessage()); } return false; } Почему не boolean?

Target:
public static boolean getMessage(SocketChannel sc, ByteBuffer message, Map<String, SocketChannel> clients) { try { int count = sc.read(message); if (count == -1) { // проверка на случай экстренного выхода клиента closeClient(clients, sc); return true; } } catch (Exception e) { printErrorAndExit("Bad geting message!" + e.getMessage()); } return false; }
Source:
private static boolean checkRpn(String[] parsedInput) { int countOfDigits = 0; int countOfOperands = 0; for (String s : parsedInput) { if (s.equals("+") || s.equals("-") || s.equals("/") || s.equals("*")) { ++countOfOperands; } else { ++countOfDigits; } } START if ((countOfDigits - countOfOperands) == 1) { END return true; } else { return false; } } Можно упростить: `return countOfDigits - countOfOperands == 1`

Target:
private static boolean checkRpn(String[] parsedInput) { int countOfDigits = 0; int countOfOperands = 0; for (String s : parsedInput) { if (s.equals("+") || s.equals("-") || s.equals("/") || s.equals("*")) { ++countOfOperands; } else { ++countOfDigits; } } return ((countOfDigits - countOfOperands) == 1); }
Source:
static void interactiveRegime() throws Exception{ while(true) { System.out.print("$ "); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String command = reader.readLine(); try { recognizeCommand(command); } catch (Exception e) { START System.err.print(e.getMessage()); END System.exit(1); } } } shell/bash работают не так. Они пишут сообщение об ошибке и можно продолжить работу. Мало ли - пользователь ошибся.

Target:
static void interactiveRegime() throws Exception{ while(true) { System.out.print("$ "); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String command = reader.readLine(); try { recognizeCommand(command); } catch (Exception e) { System.err.println(e.getMessage()); } } }
Source:
public String getIpAddress() { START String publicIpv4Addr = amazonInfoHolder.get().get(MetaDataKey.publicIpv4); END return this.shouldBroadcastPublicIpv4Addr() ? getPublicIpv4Addr() : getPrivateIpv4Addr(); } Dead code.

Target:
public String getIpAddress() { return this.shouldBroadcastPublicIpv4Addr() ? getPublicIpv4Addr() : getPrivateIpv4Addr(); }
Source:
private static void tryCatchLog(Callable<Void> callable) { try { callable.call(); START } catch (Throwable th) { END logger.error("Error in unmarshalling the object:", th); } } Catch `Exception` instead.

Target:
private static void tryCatchLog(Callable<Void> callable) { try { callable.call(); } catch (Exception ex) { logger.error("Error in unmarshalling the object:", ex); } }
Source:
public void shutdown() { try { DefaultMonitorRegistry.getInstance().unregister(Monitors.newObjectMonitor(this)); } catch (Throwable t) { logger.error("Cannot shutdown monitor registry", t); } try { if (peerEurekaNodes != null) { START for (PeerEurekaNode node : this.peerEurekaNodes.getPeerEurekaNodes()) { END node.shutDown(); } } } catch (Throwable t) { logger.error("Cannot shutdown ReplicaAwareInstanceRegistry", t); } super.shutdown(); } PeerEurekaNodes has shutdown method.

Target:
public void shutdown() { try { DefaultMonitorRegistry.getInstance().unregister(Monitors.newObjectMonitor(this)); } catch (Throwable t) { logger.error("Cannot shutdown monitor registry", t); } try { peerEurekaNodes.shutdown(); } catch (Throwable t) { logger.error("Cannot shutdown ReplicaAwareInstanceRegistry", t); } super.shutdown(); }
Source:
public EurekaArchaius2InstanceConfig(Config config, String namespace) { START this(config, "eureka", new DataCenterInfo() { END @Override public Name getName() { return Name.MyOwn; } }); } use namespace instead of "eureka".

Target:
public EurekaArchaius2InstanceConfig(Config config, String namespace) { this(config, namespace, new DataCenterInfo() { @Override public Name getName() { return Name.MyOwn; } }); }
Source:
public EurekaArchaius2ClientConfig(Config config, String namespace) { this.defaultRegion = config.getString("@region", null); START this.config = config.getPrefixedView(DEFAULT_NAMESPACE); END } use namespace instead of DEFAULT

Target:
public EurekaArchaius2ClientConfig(Config config, String namespace) { this.defaultRegion = config.getString("@region", null); this.config = config.getPrefixedView(namespace); }
Source:
public Observable<ChangeNotification<InstanceInfo>> changeNotifications() { START return aggregatedStream.share(); END } There is no need for that as channel contract guarantees single subscription only.

Target:
public Observable<ChangeNotification<InstanceInfo>> changeNotifications() { return aggregatedStream; }
Source:
private boolean allowedToEvict() { boolean allowed = evictionStrategy.allowedToEvict(expectedRegistrySize, eurekaRegistry.size()) >= 0; START moveHealthTo(allowed ? Status.UP : Status.DOWN); END return allowed; } Per our discussion, we should not mark servers as DOWN even when they are in selfPreservation. Otherwise we may redirect all traffic to a (possibly) much smaller set of UP servers and take them down.

Target:
private boolean allowedToEvict() { boolean allowed = evictionStrategy.allowedToEvict(expectedRegistrySize, eurekaRegistry.size()) >= 0; // TODO We decided that self preservation should not trigger component DOWN transition. Health check from PreservableEurekaRegistry might be not needed // moveHealthTo(allowed ? Status.UP : Status.DOWN); return allowed; }
Source:
public void shutdown() { cancelScheduledTasks(); // If APPINFO was registered if (instanceInfo != null && shouldRegister(instanceInfo)) { instanceInfo.setStatus(InstanceStatus.DOWN); unregister(); } START DiscoveryManager.getInstance().setDiscoveryClient(null); END DiscoveryManager.getInstance().setEurekaClientConfig(null); } I think we should not do this. Instead if we are paranoid about people not using this after shutdown(), we can add checks of isShutdown() but I think its not required.

Target:
public void shutdown() { cancelScheduledTasks(); // If APPINFO was registered if (instanceInfo != null && shouldRegister(instanceInfo)) { instanceInfo.setStatus(InstanceStatus.DOWN); unregister(); } }
Source:
START public Builder setAppGroupName(String appGroupName) { END result.appGroupName = appGroupName; if (result.appGroupName != null) { result.appGroupName = result.appGroupName.toUpperCase(); } return this; } Seems like the appGroupName upper case invariant can be violated here and this may be an issue since appGroupName is volatile, hinting that it may be accessed by multiple threads. A safer way to implement this function would be, if (appGroupName == null) result.appGroupName = null; else result.appGroupName = appGroupName.toUpperCase(); It appears that we have several existing methods that should also be corrected this way

Target:
public Builder setAppGroupName(String appGroupName) { if (appGroupName != null) { result.appGroupName = appGroupName.toUpperCase(); } else { result.appGroupName = null; } return this; }
Source:
protected Object doExecute() throws Exception { START checkNotNull(template, "You must choose a template for the image you are trying to create."); END Provisionr service = getService(); final Pool pool = createPoolOfOne(service); final String processInstanceId = service.startPoolManagementProcess("j-" + UUID.randomUUID().toString(), pool); return String.format("Pool management process started (id: %s)", processInstanceId); } I don't think a template should be mandatory. you can always specify the list of packages on the command line

Target:
protected Object doExecute() throws Exception { Provisionr service = getService(); final Pool pool = createPoolOfOne(service); // TODO: create service.startCachingProcess(uuid, pool) in the Provisionr class return null; }
Source:
protected List<Instance> collectInstancesFromReservations(List<Reservation> reservation) { /* Make a copy as an ArrayList to force lazy collection evaluation */ START List<List<Instance>> allInstances = Lists.newArrayList(Lists.transform(reservation, new Function<Reservation, List<Instance>>() { END @Override public List<Instance> apply(Reservation reservation) { return reservation.getInstances(); } })); return Lists.newArrayList(Iterables.concat(allInstances)); } A defensive copy is not needed here

Target:
protected List<Instance> collectInstancesFromReservations(List<Reservation> reservation) { /* Make a copy as an ArrayList to force lazy collection evaluation */ List<List<Instance>> allInstances = Lists.transform(reservation, new Function<Reservation, List<Instance>>() { @Override public List<Instance> apply(Reservation reservation) { return reservation.getInstances(); } }); return Lists.newArrayList(Iterables.concat(allInstances)); }
Source:
private static String loadResource(String fileName) { try { return Resources.toString(Resources.getResource(TestConstants.class, fileName), Charsets.UTF_8); } catch (IOException e) { START Throwables.propagate(e); END } throw new RuntimeException("Resource not available " + fileName); } use -> throw Throwables.propagate(e); and remove the last throw statement

Target:
private static String loadResource(String fileName) { try { return Resources.toString(Resources.getResource(TestConstants.class, fileName), Charsets.UTF_8); } catch (IOException e) { throw Throwables.propagate(e); } }
Source:
static void deleteByName(CloudStackClient cloudStackClient, String securityGroupName) { try { SecurityGroup securityGroup = getByName(cloudStackClient, securityGroupName); LOG.info("Deleting SecurityGroup {}", securityGroup.getName()); cloudStackClient.getSecurityGroupClient().deleteSecurityGroup(securityGroup.getId()); } catch (NoSuchElementException e) { START LOG.debug("Exception retrieving SecurityGroup (most likely it does not yet exist){}: {}", securityGroupName, e); END } } asta cred ca trebuie sa fie WARN

Target:
static void deleteByName(CloudStackClient cloudStackClient, String securityGroupName) { try { SecurityGroup securityGroup = getByName(cloudStackClient, securityGroupName); LOG.info("Deleting SecurityGroup {}", securityGroup.getName()); cloudStackClient.getSecurityGroupClient().deleteSecurityGroup(securityGroup.getId()); } catch (NoSuchElementException e) { LOG.warn("Exception retrieving SecurityGroup (most likely it does not yet exist){}: {}", securityGroupName, e); } }
Source:
void send(Feature feature, FeatureStateStorageWrapper storageWrapper) { String featureName = feature.name(); try { LOG.info("Starting to update state of feature {}.", featureName); String featureStateAsString = serialize(storageWrapper); LOG.info("Successfully serialized state of feature {}.", featureName); producer.send(buildRecord(featureName, featureStateAsString), buildCallback(featureName)); START } catch (Exception e) { END LOG.error("An error occurred while updating state of feature {}.", featureName, e); } } `RuntimeException` will be sufficient

Target:
private void send(Feature feature, FeatureStateStorageWrapper storageWrapper) { String featureName = feature.name(); try { LOG.debug("Starting to update state of feature {}.", featureName); String featureStateAsString = serialize(storageWrapper); LOG.debug("Successfully serialized state of feature {}.", featureName); producer.send(buildRecord(featureName, featureStateAsString), buildCallback(featureName)); } catch (Exception e) { LOG.error("An error occurred while updating state of feature {}.", featureName, e); } }
Source:
public static WebArchive createDeployment() { return Deployments.getBasicWebArchive() .addClass(HttpServletRequestHolderServlet.class) START .addClass(TogglzFilterServlet.class) END // we don't need to bootstrap Togglz here as we only test the request holder .setWebXML(Packaging.webAppDescriptor() .contextParam("org.togglz.FEATURE_MANAGER_PROVIDED", "true") .filter(TogglzFilter.class, "/*") .filter(TogglzFilter.class, "/*") .exportAsAsset()); } I'm wondering if the test wouldn't be easier, if we simply have a single Servlet for the test. If `HttpServletRequestHolderServlet` would also output the value of the `EXECUTED` attribute, we would only have a single servlet. The servlet could output something like: ``` Query: number=42 Executed: true ``` Then we just need to adjust the asserts to check for `Query: number=42` instead of just `number=42`.

Target:
public static WebArchive createDeployment() { return Deployments.getBasicWebArchive() .addClass(HttpServletRequestHolderServlet.class) // we don't need to bootstrap Togglz here as we only test the request holder .setWebXML(Packaging.webAppDescriptor() .contextParam("org.togglz.FEATURE_MANAGER_PROVIDED", "true") // the Togglz filter is added twice to test if it fails when called multiple times for the same request .filter(TogglzFilter.class, "/*") .filter(TogglzFilter.class, "/*") .exportAsAsset()); }
Source:
public FeatureState getFeatureState(Feature feature) { for (StateRepository repository : iterationOrder.getSelected(repositories)) { FeatureState featureState = repository.getFeatureState(feature); if (featureState != null) { START return featureState END } } return null; } There is a `;` missing...

Target:
public FeatureState getFeatureState(Feature feature) { for (StateRepository repository : iterationOrder.getSelected(repositories)) { FeatureState featureState = repository.getFeatureState(feature); if (featureState != null) { return featureState; } } return null; }
Source:
public boolean matches(Object item) { boolean found = false; @SuppressWarnings("unchecked") Set<Feature> features = (Set<Feature>) item; for (Feature f : features) { if (f.name().equals(feature.name())) { found = true; break; } } START return found; END } Nice catch Kamil. Btw, couldn't it be done even easier with the following code? ``` for (Feature f : features) { if (f.name().equals(feature.name())) { return true; } } return false; ```

Target:
public boolean matches(Object item) { @SuppressWarnings("unchecked") Set<Feature> features = (Set<Feature>) item; for (Feature f : features) { if (f.name().equals(feature.name())) { return true; } } return false; }
Source:
public void beforeCreateCollection(DBBroker broker, Txn txn, XmldbURI uri) throws TriggerException { START if (!triggersSuspended) { END for (CollectionTrigger trigger : triggers) { trigger.beforeCreateCollection(broker, txn, uri); } } } These `triggersSuspended` checks should not be used here. Such checks are already present at the call site in DBBroker. This kinda breaks the responsibility pattern

Target:
public void beforeCreateCollection(DBBroker broker, Txn txn, XmldbURI uri) throws TriggerException { for (CollectionTrigger trigger : triggers) { trigger.beforeCreateCollection(broker, txn, uri); } }
Source:
protected void declareNamespaces(XQueryContext context) throws XPathException { Map.Entry<String, String> entry; for (Map.Entry<String, String> stringStringEntry : namespaces.entrySet()) { entry = stringStringEntry; context.declareNamespace( entry.getKey(), entry.getValue()); START } END } I think this needs tidying up. `entry` is redundant, and then `stringStringEntry` should be renamed as `entry`.

Target:
protected void declareNamespaces(XQueryContext context) throws XPathException { for (Map.Entry<String, String> entry : namespaces.entrySet()) { context.declareNamespace(entry.getKey(), entry.getValue()); } }
Source:
public void resetState(boolean postOptimization) { super.resetState(postOptimization); // clear closure variables set on inline function START calls.forEach(call -> { END if (!postOptimization) { call.getFunction().setClosureVariables(null); } }); calls.clear(); function.resetState(postOptimization); } I think this could be reformulated to be more efficient, i.e.: ```java if (!postOptimization) { calls.forEach(call -> call.getFunction().setClosureVariables(null)); } ```

Target:
public void resetState(boolean postOptimization) { super.resetState(postOptimization); // clear closure variables set on inline function if (!postOptimization) { calls.forEach(call -> call.getFunction().setClosureVariables(null)); } calls.clear(); function.resetState(postOptimization); }
Source:
void doesNotOverwriteConfigSourceProviderIfNotProvidedInConstructor() throws Exception { DropwizardTestSupport<TestConfiguration> support = new DropwizardTestSupport<>( TestApplication.class, "test-config.yaml"); try { support.before(); assertThat(TEST_CONFIG_SOURCE_PROVIDER.openCalled).isTrue(); } catch (Exception e) { START Assert.fail(); END } finally { support.after(); } } This catch statement isn't needed, no?

Target:
void doesNotOverwriteConfigSourceProviderIfNotProvidedInConstructor() throws Exception { DropwizardTestSupport<TestConfiguration> support = new DropwizardTestSupport<>( TestApplication.class, "test-config.yaml"); try { support.before(); assertThat(TEST_CONFIG_SOURCE_PROVIDER.openCalled).isTrue(); } finally { support.after(); } }
Source:
public Handler[] getHandlers() { START return handlers.keySet().stream().map(key -> handlers.get(key)).toArray(Handler[]::new); END } Changing `Trie` to `ArrayTernaryTrie` introduces `entrySet` which will eliminate the lookup in a loop. ```java private final ArrayTernaryTrie<Handler> handlers; handlers.entrySet().stream().map(Map.Entry::getValue).toArray(Handler[]::new); ``` https://www.eclipse.org/jetty/javadoc/9.4.11.v20180605/org/eclipse/jetty/util/ArrayTernaryTrie.html#entrySet--

Target:
public Handler[] getHandlers() { return handlers.entrySet().stream().map(e -> e.getValue()).toArray(Handler[]::new); }
Source:
public ScheduledExecutorService build() { final ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(this.poolSize, this.threadFactory, this.handler); START if (this.removeOnCancel != null) { END executor.setRemoveOnCancelPolicy(this.removeOnCancel.booleanValue()); } this.environment.manage(new ExecutorServiceManager(executor, this.shutdownTime, this.nameFormat)); return executor; } If `removeOnCancel` were a boolean primitive we could avoid a condition block.

Target:
public ScheduledExecutorService build() { final ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(this.poolSize, this.threadFactory, this.handler); executor.setRemoveOnCancelPolicy(this.removeOnCancel); this.environment.manage(new ExecutorServiceManager(executor, this.shutdownTime, this.nameFormat)); return executor; }
Source:
public String checkOptionalAuth(@Auth Optional<Principal> principalOpt) { START return "principal was " + ((principalOpt.isPresent()) ? "" : "not ") + "present"; END } I guess we could omit the parentheses around `principalOpt.isPresent`

Target:
public String checkOptionalAuth(@Auth Optional<Principal> principalOpt) { return "principal was " + (principalOpt.isPresent() ? "" : "not ") + "present"; }
Source:
public void configure(Map<String, String> options) { useCache = Optional.ofNullable(options.get("cache")) .map(Boolean::parseBoolean) .orElse(true); if (options.containsKey("fileRoot")) { START fileRoot = new File(options.get("fileRoot")); END } } If we declare `fileRoot` as `Optional`, we can initialize it with one-liner: ```java Optional.ofNullable(options.get("fileRoot")).map(File::new) ```

Target:
public void configure(Map<String, String> options) { useCache = Optional.ofNullable(options.get("cache")).map(Boolean::parseBoolean).orElse(true); fileRoot = Optional.ofNullable(options.get("fileRoot")).map(File::new); }
Source:
public DropwizardSSLConnectionSocketFactory(TlsConfiguration configuration) { this.configuration = configuration; START this.verifier = null; END } I think we could reduce this constructor to a call to another constructor: ``` java this(configuration, null); ```

Target:
public DropwizardSSLConnectionSocketFactory(TlsConfiguration configuration) { this(configuration, null); }
Source:
private HostnameVerifier chooseHostnameVerifier() { HostnameVerifier hostnameVerifier; if (configuration.isVerifyHostname()) { START if (verifier == null) { END hostnameVerifier = SSLConnectionSocketFactory.getDefaultHostnameVerifier(); } else { hostnameVerifier = verifier; } } else { hostnameVerifier = new NoopHostnameVerifier(); } return hostnameVerifier; } What do you think about reducing the size of this method by using the ternary operator and several returns? Something like that: ``` java if (configuration.isVerifyHostname()) { return verifier != null ? verifier : SSLConnectionSocketFactory.getDefaultHostnameVerifier(); } else { return new NoopHostnameVerifier(); } ```

Target:
private HostnameVerifier chooseHostnameVerifier() { if (configuration.isVerifyHostname()) { return verifier != null ? verifier : SSLConnectionSocketFactory.getDefaultHostnameVerifier(); } else { return new NoopHostnameVerifier(); } }
Source:
public void testInitialSizeIsZero() throws Exception { factory.setUrl("nonsense invalid url"); factory.setInitialSize(0); ManagedDataSource dataSource = factory.build(metricRegistry, "test"); try { START dataSource.start(); END } catch (Exception e) { fail(); } } Surrounding the statement with try-catch doesn't gain anything. The test will fail anyway, if any uncaught exception occurs.

Target:
public void testInitialSizeIsZero() throws Exception { factory.setUrl("nonsense invalid url"); factory.setInitialSize(0); ManagedDataSource dataSource = factory.build(metricRegistry, "test"); dataSource.start(); }
Source:
public void testInitialSizeZeroIsAllowed() throws Exception { try { START DataSourceFactory ds = getDataSourceFactory("yaml/empty_initial_pool.yml"); END assertThat(ds.getInitialSize()).isEqualTo(0); } catch (ConfigurationValidationException e) { e.printStackTrace(); fail(e.getMessage()); } } Surrounding the statement with try-catch doesn't gain anything. The test will fail anyway, if any uncaught exception occurs.

Target:
public void testInitialSizeZeroIsAllowed() throws Exception { DataSourceFactory ds = getDataSourceFactory("yaml/empty_initial_pool.yml"); assertThat(ds.getInitialSize()).isEqualTo(0); }
Source:
public void createDefaultFactory() throws Exception { ConfigurationFactory<Example> factory = factoryFactory.create(Example.class, validator, Jackson.newObjectMapper(), "dw"); START final Example example = factory.build(new FileConfigurationSourceProvider(), validFile.getPath()); END assertThat(example.getName()) .isEqualTo("Coda Hale"); } Is this change required now that we have the default method in the interface?

Target:
public void createDefaultFactory() throws Exception { ConfigurationFactory<Example> factory = factoryFactory.create(Example.class, validator, Jackson.newObjectMapper(), "dw"); final Example example = factory.build(validFile); assertThat(example.getName()) .isEqualTo("Coda Hale"); }
Source:
public void before() { START when(this.environment.jersey()).thenReturn(this.jerseyEnvironment); END } I think you could avoid to use `this` to reference the fields in the unit test, because there are no name conflicts.

Target:
public void before() { when(environment.jersey()).thenReturn(jerseyEnvironment); }
Source:
START protected String name() { END return DEFAULT_NAME; } can you make this `public`?

Target:
public String name() { return DEFAULT_NAME; }
Source:
START public static synchronized void initXmlParser() throws Exception { END xmlParser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); attributeNames = ImmutableList.of("columns", "foreign-keys", "indexes", "primary-keys", "sequences", "tables", "unique-constraints", "views"); } I'm quite sure this is a false positive. `@BeforeClass` methods will be invoked only once per class, this is guaranteed by JUnit. I would just moved the variable assignments from this method directly to theirs declaration.

Target:
public static void initXmlParser() throws Exception { xmlParser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); attributeNames = ImmutableList.of("columns", "foreign-keys", "indexes", "primary-keys", "sequences", "tables", "unique-constraints", "views"); }
Source:
public OAuthTestResourceConfig() { START super(); END register(AuthResource.class); } Ditto for `super()`

Target:
public OAuthTestResourceConfig() { register(AuthResource.class); }
Source:
public NoAuthPrincipalInjectedResourceConfig() { START super(); END register(NoAuthPrincipalEntityResource.class); packages("io.dropwizard.jersey.jackson"); } Ditto for `super()`

Target:
public NoAuthPrincipalInjectedResourceConfig() { register(NoAuthPrincipalEntityResource.class); packages("io.dropwizard.jersey.jackson"); }
Source:
public String toString() { return MoreObjects.toStringHelper(this) .add("level", level) .add("loggers", loggers) .add("appenders", appenders) .add("loggerContext", loggerContext) START .add("configurationErrorsStream", configurationErrorsStream) END .toString(); } I don't think that printing the configurationErrorsStream or the loggerContext is really useful here.

Target:
public String toString() { return MoreObjects.toStringHelper(this) .add("level", level) .add("loggers", loggers) .add("appenders", appenders) .toString(); }
Source:
START public void setOutputStream(PrintStream outputStream) { END this.outputStream = outputStream; } should this be package private?

Target:
void setOutputStream(PrintStream outputStream) { this.outputStream = outputStream; }
Source:
public void close() throws Exception { try { database.close(); START } catch (LiquibaseException e){ END LOGGER.warn("Failed to close liquibase", e); } dataSource.stop(); } I think it would be better to remove the `catch` block just let the exception propagate (the method already declares to throw `Exception`) and put the `dataSource.stop()` call into the `finally` block of the `try-finally` statement.

Target:
public void close() throws Exception { try { database.close(); } finally { dataSource.stop(); } }
Source:
public int compareTo(Duration other) { if (count == 0 && other.count == 0) { return 0; } // this is negative, other is non-negative START if (count < 0 && other.count >= 0) { END return -1; } // this is non-negative, other is negative if (count >= 0 && other.count < 0) { return 1; } if (unit == other.unit) { return Long.compare(count, other.count); } return Long.compare(toNanoseconds(), other.toNanoseconds()); } I see that this is symmetric to the implementation in `Size` but are these short circuits really necessary? `Long#compare()` will usually just do the right thing™.

Target:
public int compareTo(Duration other) { if (unit == other.unit) { return Long.compare(count, other.count); } return Long.compare(toNanoseconds(), other.toNanoseconds()); }
Source:
protected Factory<?> createValueFactory(final Parameter parameter) { final Class<?> classType = parameter.getRawType(); START Auth auth = parameter.getAnnotation(Auth.class); END if (auth == null) { return null; } if (classType.isAssignableFrom(this.factory.getGeneratedClass())) { return this.factory.clone(auth.required()); } else { return null; } } this could be made `final`

Target:
protected Factory<?> createValueFactory(final Parameter parameter) { final Class<?> classType = parameter.getRawType(); final Auth auth = parameter.getAnnotation(Auth.class); if (auth != null && classType.isAssignableFrom(factory.getGeneratedClass())) { return factory.clone(auth.required()); } else { return null; } }
Source:
public HttpClient build(String name) { final BasicHttpParams params = createHttpParams(name); final InstrumentedClientConnManager manager = createConnectionManager(registry, name); final InstrumentedHttpClient client = new InstrumentedHttpClient(metricRegistry, manager, params, name); START client.setCredentialsProvider(credentialsProvider); END setStrategiesForClient(client); return client; } Could you please move this into `setStrategiesForClient` and only set the credentials provider if `credentialsProvider` is not `null`? While the latter is currently the default behaviour of Apache HttpClient, it might change in the future and we don't want to get NPEs all of a sudden. :wink:

Target:
public HttpClient build(String name) { final BasicHttpParams params = createHttpParams(name); final InstrumentedClientConnManager manager = createConnectionManager(registry, name); final InstrumentedHttpClient client = new InstrumentedHttpClient(metricRegistry, manager, params, name); setStrategiesForClient(client); return client; }
Source:
public ViewBundle() { START this(ImmutableList.copyOf(ServiceFinder.find(ViewRenderer.class))); END } I think it would make more sense to create an immutable copy of the `Iterable` in the `ViewBundle(Iterable<ViewRenderer>)` constructor instead of here.

Target:
public ViewBundle() { this(ServiceFinder.find(ViewRenderer.class)); }
Source:
private void checkDuplicateRegistration(String name, Set<String> items, String type) { if(items.contains(name)) { LOGGER.warn("Overriding the existing registered with the name: {}", type, name); } START items.add(name); END } Just a small note: the add(...) method on Set<T> returns false if the element already exists in the set so the contains check here is actually superfluous. The code could be changed to: ``` if (!items.add(name)) { LOGGER.warn("Overriding the existing registered with the name: {}", type, name); } ```

Target:
private void checkDuplicateRegistration(String name, Set<String> items, String type) { if(!items.add(name)) { LOGGER.warn("Overriding the existing registered with the name: {}", type, name); } }
Source:
public T build(String configurationPath, InputStream inputStream) throws IOException, ConfigurationException { START final JsonNode node = mapper.readTree(inputStream); END return build(node, configurationPath != null ? configurationPath : "InputStream configuration"); } We should ensure the stream is closed.

Target:
public T build(String configurationPath, InputStream inputStream) throws IOException, ConfigurationException { T configuration = null; try { final JsonNode node = mapper.readTree(inputStream); configuration = build(node, configurationPath != null ? configurationPath : "InputStream configuration"); } finally { inputStream.close(); } return configuration; }
Source:
public JobStatus permanentlyDeleteTicket(Ticket ticket) { checkHasId(ticket); START deleteTicket(ticket.getId()); END return permanentlyDeleteTicket(ticket.getId()); } deleteTicket is invoked twice, once here then again in permanentlyDeleteTicket.

Target:
public JobStatus permanentlyDeleteTicket(Ticket ticket) { checkHasId(ticket); return permanentlyDeleteTicket(ticket.getId()); }
Source:
public User permanentlyDeleteUser(User user) { checkHasId(user); START deleteUser(user.getId()); END return permanentlyDeleteUser(user.getId()); } Same issue here, double delete user.

Target:
public User permanentlyDeleteUser(User user) { checkHasId(user); return permanentlyDeleteUser(user.getId()); }
Source:
public static ObjectMapper createMapper() { ObjectMapper mapper = new ObjectMapper(); mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); mapper.setDateFormat(new ISO8601DateFormat()); START mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY); END return mapper; } @aheritier looks like the Action deserializer is doing exactly what you are trying to achieve :+1: might be nice to use the same approach to keep the models consistent.

Target:
public static ObjectMapper createMapper() { ObjectMapper mapper = new ObjectMapper(); mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); mapper.setDateFormat(new ISO8601DateFormat()); return mapper; }
Source:
public String toString() { return "CustomFieldValue{" + "id=" + id + START ", value=" + (value == null ? "null" : Arrays.asList(value).toString()) + END '}'; } can be simplier: showing empty array even if the value is `null` is not really a big deal imo. Also, `toString` are usually only used for logger..

Target:
public String toString() { return "CustomFieldValue{" + "id=" + id + ", value=" + Arrays.toString(value) + '}'; }
Source:
START public static boolean isRecoveryProblems() { END return recoveryProblems.get(); } if there is no particular reason to make anything public then it should be `private` (or package-private in case)

Target:
boolean isRecoveryProblems() { return this.recoveryProblems.get(); }
Source:
private int atEnd(int res) { // Only run the post LRA actions if both the LRA and participant are in an end state // check the participant first since it will have been removed from one of the lists if (!isFinished() || !lra.isFinished()) { if (afterURI != null) { return TwoPhaseOutcome.HEURISTIC_HAZARD; } return res; } // run post LRA actions START if (afterURI == null || afterLRARequest(afterURI, lra, lra.getLRAStatus().name())) { END afterURI = null; // the post LRA actions succeeded so remove the participant from the intentions list otherwise retry return TwoPhaseOutcome.FINISH_OK; } return TwoPhaseOutcome.HEURISTIC_HAZARD; } @mmusgrov please can you expand on the situation where afterURI can be null at this point and what the value of res could be? If afterURI is null we will return TwoPhaseOutcome.FINISH_OK but res might not always be that from what I can see in above calls to atEnd(int) - including at least one call that might pass in HEURISTIC_HAZARD. Maybe in those cases afterURI could never be null? But then what about the one which uses a value from retryGetEndStatus or reportFailure

Target:
private int atEnd(int res) { // Only run the post LRA actions if both the LRA and participant are in an end state // check the participant first since it will have been removed from one of the lists if (!isFinished() || !lra.isFinished()) { if (afterURI != null) { return TwoPhaseOutcome.HEURISTIC_HAZARD; } return res; } // run post LRA actions if (afterURI == null || afterLRARequest(afterURI, lra.getLRAStatus().name())) { afterURI = null; // the post LRA actions succeeded so remove the participant from the intentions list otherwise retry return TwoPhaseOutcome.FINISH_OK; } return TwoPhaseOutcome.HEURISTIC_HAZARD; }
Source:
public RequestBuilder(URI baseURI) { builder = new URIBuilder(baseURI); paths = new ArrayList<>(); START Collections.addAll(paths, strip(strip(baseURI.getPath())).split("/")); END } Nested strip invocation seems unnecessary. But maybe I am missing something?

Target:
public RequestBuilder(URI baseURI) { builder = new URIBuilder(baseURI); paths = new ArrayList<>(); Collections.addAll(paths, strip(baseURI.getPath()).split("/")); }
Source:
public long getSize(ParticipantStatus participantStatus, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { START return 0; END } The spec says: ``` As of JAX-RS 2.0, the method has been deprecated and the value returned by the method is ignored by a JAX-RS runtime. All MessageBodyWriter implementations are advised to return -1 from the method. ```

Target:
public long getSize(ParticipantStatus participantStatus, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return -1; }
Source:
public Response compensate(@PathParam("participantId") String participantId, @HeaderParam(LRA_HTTP_CONTEXT_HEADER) String lraId, @HeaderParam(LRA_HTTP_PARENT_CONTEXT_HEADER) String parentId) { START return lraParticipantRegistry.getParticipant(participantId).compensate(createURI(lraId), createURI(parentId)); END } If the participant isn't found the registry will throw a null pointer which should be caught and reported as an HTTP 404 status code

Target:
public Response compensate(@PathParam("participantId") String participantId, @HeaderParam(LRA_HTTP_CONTEXT_HEADER) String lraId, @HeaderParam(LRA_HTTP_PARENT_CONTEXT_HEADER) String parentId) { return getParticipant(participantId).compensate(createURI(lraId), createURI(parentId)); }
Source:
START public LRAParticipantRegistry(Map<String, LRAParticipant> lraParticipants) { END this.lraParticipants = new HashMap<>(lraParticipants); } this can be package private

Target:
LRAParticipantRegistry(Map<String, LRAParticipant> lraParticipants) { this.lraParticipants = new HashMap<>(lraParticipants); }
Source:
void processAnnotatedType(@Observes ProcessAnnotatedType<NoAnnotationBean> bean) { START if(classToProcess.contains(bean.getAnnotatedType().getJavaClass())) { END AnnotatedTypeWrapper<NoAnnotationBean> wrapper = new AnnotatedTypeWrapper<NoAnnotationBean>(bean); wrapper.addAnnotation(new TransactionalLiteral()); bean.setAnnotatedType(wrapper); } } This `if` and the list above can be removed completely.

Target:
void processAnnotatedType(@Observes ProcessAnnotatedType<NoAnnotationBean> bean) { AnnotatedTypeWrapper<NoAnnotationBean> wrapper = new AnnotatedTypeWrapper<NoAnnotationBean>(bean); wrapper.addAnnotation(new TransactionalLiteral()); bean.setAnnotatedType(wrapper); }
Source:
START protected RESTRecord findParticipant(String participantUrl) { END if (pendingList != null) { RecordListIterator i = new RecordListIterator(pendingList); AbstractRecord r; while ((r = i.iterate()) != null) { if (r instanceof RESTRecord) { RESTRecord rr = (RESTRecord) r; if (rr.getParticipantURI().equals(participantUrl)) return rr; } } } return null; } I don't think this needed to be protected?

Target:
private RESTRecord findParticipant(String participantUrl) { if (pendingList != null) { RecordListIterator i = new RecordListIterator(pendingList); AbstractRecord r; while ((r = i.iterate()) != null) { if (r instanceof RESTRecord) { RESTRecord rr = (RESTRecord) r; if (rr.getParticipantURI().equals(participantUrl)) return rr; } } } return null; }
Source:
public Transaction getTransactionById(Object id) { START return com.arjuna.ats.internal.jta.transaction.jts.TransactionImple.getTransaction((Uid) id); END } Try remove package

Target:
public Transaction getTransactionById(Object id) { return TransactionImple.getTransaction((Uid) id); }
Source:
private final void endAssociation(int xaState, int txInfoState) throws XAException { START if (_doEnd && _theTransaction != null) { END _theTransaction.endAssociation(_tranID, _theXAResource, xaState, txInfoState); } } _doEnd looks like an unused variable (ie remove it)

Target:
private final void endAssociation(int xaState, int txInfoState) throws XAException { if (_theTransaction != null) { _theTransaction.endAssociation(_tranID, _theXAResource, xaState, txInfoState); } }
Source:
START public void start() throws XAException, SystemException, InvalidTransactionException, IllegalStateException, NamingException END { txbridgeLogger.logger.trace("InboundBridge.start(Xid="+xid+")"); Transaction tx = getTransaction(); TransactionManager.transactionManager(new InitialContext()).resume(tx); } This is changing a public interface and deprecation rules apply.

Target:
public void start() throws XAException, SystemException, InvalidTransactionException { txbridgeLogger.logger.trace("InboundBridge.start(Xid="+xid+")"); Transaction tx = getTransaction(); TransactionManager.transactionManager(ctx).resume(tx); }
Source:
START public void stop() throws XAException, SystemException, InvalidTransactionException, NamingException END { txbridgeLogger.logger.trace("InboundBridge.stop("+xid+")"); TransactionManager.transactionManager(new InitialContext()).suspend(); } This is changing a public interface and deprecation rules apply.

Target:
public void stop() throws XAException, SystemException, InvalidTransactionException { txbridgeLogger.logger.trace("InboundBridge.stop("+xid+")"); TransactionManager.transactionManager(ctx).suspend(); }
Source:
public Object getCurrentTransactionId() { if(com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionImple.getTransaction() == null) START return null; END return com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionImple.getTransaction().get_uid(); } There should be a new line after the return.

Target:
public Object getCurrentTransactionId() { com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionImple transaction = com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionImple.getTransaction(); if (transaction == null) return null; return transaction.get_uid(); }
Source:
public static String getThreadId(final Thread thread) { START final Object id = THREAD_ID.get(thread) ; END if (id != null) { return (String)id ; } final String newId = getNextId() ; THREAD_ID.put(thread,newId) ; return newId ; } This is a String so use final String id = THREAD_ID.get(thread) ; and then you don't need to do the cast on the next line.

Target:
public static String getThreadId(final Thread thread) { final String id = THREAD_ID.get(thread) ; if (id != null) { return id ; } final String newId = getNextId() ; THREAD_ID.put(thread,newId) ; return newId ; }
Source:
public int cancel () { if (parent() != null) parent().removeChildAction(this); // beforeCompletion(); int outcome; START synchronized (_cancelLock) { // https://issues.jboss.org/browse/JBTM-2643 END if (TxStats.enabled() && running()) TxStats.getInstance().incrementApplicationRollbacks(); outcome = super.Abort(); } if (outcome == ActionStatus.ABORTED) { afterCompletion(outcome); } return outcome; } I don't like having yet another lock in here. Why not put the conditional stat increment in BasicAction::Abort which is already synchronized.

Target:
public int cancel () { if (parent() != null) parent().removeChildAction(this); // beforeCompletion(); int outcome = super.Abort(true); if (outcome == ActionStatus.ABORTED) { afterCompletion(outcome); } return outcome; }
Source:
public void commit(Xid xid, boolean b) throws XAException { START assertIfRecoveryScanWasStarted(); END delegate.commit(xid, b); } RMERR out of this is not good - check the spec

Target:
public void commit(Xid xid, boolean b) throws XAException { delegate.commit(xid, b); }
Source:
public void rollback(Xid xid) throws XAException { START assertIfRecoveryScanWasStarted(); END delegate.rollback(xid); } RMERR Is not great here - not as bad as commit but not compatible either

Target:
public void rollback(Xid xid) throws XAException { delegate.rollback(xid); }
Source:
private void connect() throws XAException { if (delegate != null) { return; } try { xaConnection = xaConnectionFactory.createXAConnection(); xaSession = xaConnection.createXASession(); delegate = xaSession.getXAResource(); } catch (JMSException e) { LOGGER.warn("Failed to create connection", e); START throw new XAException(XAException.XAER_PROTO); END } } RMFAIL

Target:
private boolean connect() { if (delegate != null) { return true; } try { xaConnection = createXAConnection(); xaSession = xaConnection.createXASession(); delegate = xaSession.getXAResource(); } catch (JMSException e) { LOGGER.warn("Failed to create connection", e); return false; } return true; }
Source:
private void disconnect() throws XAException { try { xaConnection.close(); } catch (JMSException e) { LOGGER.warn("Failed to close connection", e); START throw new XAException(XAException.XAER_PROTO); END } finally { xaConnection = null; xaSession = null; delegate = null; } } RMFAIL

Target:
private void disconnect() { try { xaConnection.close(); } catch (JMSException e) { LOGGER.warn("Failed to close connection", e); } finally { xaConnection = null; xaSession = null; delegate = null; } }
Source:
public boolean containsValue(final TransactionLocal transactionLocal, final Transaction transaction) { com.arjuna.ats.jta.transaction.Transaction transactionImple = (com.arjuna.ats.jta.transaction.Transaction) transaction; if(transactionImple.isAlive()) { START return (transactionImple.getTxLocalResource(transactionLocal) != null); END } else { return false; } } what has this got to do with listeners :) (maybe split it to a separate commit if you really absolutely must)

Target:
public boolean containsValue(final TransactionLocal transactionLocal, final Transaction transaction) { com.arjuna.ats.jta.transaction.Transaction transactionImple = (com.arjuna.ats.jta.transaction.Transaction) transaction; if(transactionImple.isAlive()) { return (transactionImple.getTxLocalResource(transactionLocal) != null ? true : false); } else { return false; } }
Source:
public Options getOpts() { Options opts = new Options(); opts.addOption("appname", true, "Application Name. Default value - Storm-on-Yarn"); opts.addOption("queue", true, "RM Queue in which this application is to be submitted"); opts.addOption("rmAddr", true, "YARN RM's IPC address"); START opts.addOption("schedulerAddr", true, "YARN scheduler's IPC address"); END opts.addOption("stormHome", true, "Storm Home Directory"); opts.addOption("output", true, "Output file"); opts.addOption("stormZip", true, "file path of storm.zip"); return opts; } Why do we need the scheduler address? It should come from the Hadoop configuration.

Target:
public Options getOpts() { Options opts = new Options(); opts.addOption("appname", true, "Application Name. Default value - Storm-on-Yarn"); opts.addOption("queue", true, "RM Queue in which this application is to be submitted"); opts.addOption("stormHome", true, "Storm Home Directory"); opts.addOption("output", true, "Output file"); opts.addOption("stormZip", true, "file path of storm.zip"); return opts; }