auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void observerMethodNotOverridingNotifyMethodTreatedAsDefinitionError() { deployer.deploy(CONFIGURATOR); }

Target:
I can see compilation problem for `ExtensionAddingCustomObserver` but to your question - well maybe it would be safer to wrap this to try/catch block and do undeploy in the case of test failure (deployment will pass). This would also mean you can remove `@ShouldThrowException`.
Source:
public void syntheticEventInvokedAndReturningSourceTest() { assertTrue(extension.timesInvoked() == 3); Map<Type, Extension> map = extension.getSources(); assertTrue(map.get(Peach.class) instanceof ProcessSyntheticObserverMethodObserver); assertTrue(map.get(Banana.class) instanceof ProcessSyntheticObserverMethodObserver); assertTrue(map.get(Melon.class) instanceof ProcessSyntheticObserverMethodObserver); }

Target:
I would use `assertEquals` comparing Class of given extension.
Source:
public Object intercept(InvocationContext ctx) throws Exception { try { beanManager.getContext(RequestScoped.class).isActive(); isRequestContextActive.set(true); return ctx.proceed(); } catch (ContextNotActiveException e) { } return ctx.proceed(); }

Target:
I would probably merge the two lines into one: `isRequestContextActive.set(beanManager.getContext(RequestScoped.class).isActive());` Same goes for the other interceptor (`AfterActivationInterceptor`). Though its just my preference I guess :)
Source:
public DefaultMultiFactorAuthenticationSupportingWebApplicationService(final String id, final String originalUrl, final String artifactId, final ResponseType responseType, final HttpClient httpClient, @NotNull final String authnMethod) { super(cleanupUrl(id), originalUrl, artifactId, httpClient); this.wrapperService = new SimpleWebApplicationServiceImpl(id, originalUrl, artifactId, responseType, httpClient); this.authenticationMethod = authnMethod; }

Target:
You have got a factory that creates DefaultMultiFactorAuthenticationSupportingWebApplicationService objects, right? It needs to be passed into the factory, and from the factory down here.
Source:
public String translate(final WebApplicationService targetService, final String triggerValue) { for (final Pattern pattern : translationMap.keySet()) { if (pattern.matcher(triggerValue).matches()) { return this.translationMap.get(pattern); } } if (this.ignoreIfNoMatchIsFound) { return defaultMfaMethod; } throw new UnrecognizedAuthenticationMethodException("MFA Method for " + triggerValue, targetService.getId()); }

Target:
This needs to be just the triggerValue, not a message. As in `throw new UnrecognizedAuthenticationMethodException(triggerValue, targetService.getId());`
Source:
public void testNoCredentials() { assertNull(this.action.createCredentials(requestContext, null, "helloWorld")); }

Target:
This isn't going to return null, so it would be better not to wrap it with `assertNull`.
Source:
public void testNoCredentialId() { assertNull(this.action.createCredentials(requestContext, getCredentials(), null)); }

Target:
This isn't going to return null, so it would be better not to wrap it with `assertNull`.
Source:
public void testNoAuthentication() { assertNull(this.action.createCredentials(requestContext, getCredentials(), "usrPsw")); }

Target:
This isn't going to return null, so it would be better not to wrap it with `assertNull`.
Source:
public void signal(String sessionId, SignalProperties props) throws OpenTokException , RequestException, InvalidArgumentException { if (sessionId == null || sessionId == "" ) { throw new InvalidArgumentException("Session string null or empty"); } try { this.client.signal(sessionId,null,props); } catch (Exception e) { throw e; } }

Target:
Should we use `isEmpty()` instead of the empty string comparison?
Source:
public void signal(String sessionId, String connectionId, SignalProperties props) throws OpenTokException , RequestException , InvalidArgumentException { if (sessionId == null || sessionId == "" || connectionId == null || connectionId == "") { throw new InvalidArgumentException("Session or Connection string null or empty"); } try { this.client.signal(sessionId, connectionId, props); } catch (Exception e) { throw e; } }

Target:
Should we use `isEmpty()` instead of the empty string comparison?
Source:
private OpenTok(int apiKey, String apiSecret, HttpClient httpClient) { this.apiKey = apiKey; this.apiSecret = apiSecret; this.client=httpClient; }

Target:
spacing
Source:
private void createServer(Module module, boolean queryParamsAsFormParams) throws Exception { Injector injector = bootstrapTest() .withModules( new ApplicationNameModule("test-application"), new TestingNodeModule(), explicitJaxrsModule(), new JsonModule(), new ReportingModule(), new TestingHttpServerModule(), module) .setRequiredConfigurationProperty("jaxrs.query-params-as-form-params", String.valueOf(queryParamsAsFormParams)) .initialize(); lifeCycleManager = injector.getInstance(LifeCycleManager.class); server = injector.getInstance(TestingHttpServer.class); }

Target:
Don't need this with bootstrapTest()
Source:
public int getFreeThreadCount() { return executor.getMaxThreads() + executor.getIdleThreads() - executor.getThreads(); }

Target:
it is not obvious. thx
Source:
public XmlUserList() { binder = new XmlBinder<User>(User.class); try { serializer = XmlBinder.class.getDeclaredMethod("serializeObjectToWriter", Object.class, XMLStreamWriter.class); deserializer = XmlBinder.class.getDeclaredMethod("deserializeToValue", Element.class, Class.class); } catch (NoSuchMethodException e) { throw new RuntimeException("Cannot create object.", e); } serializer.setAccessible(true); deserializer.setAccessible(true); }

Target:
Ой. А нельзя метод public сделать?
Source:
protected BigIntegerExtension() { super(BigInteger.class); }

Target:
Должен быть public
Source:
public void run() { if (comparator == null) { Arrays.sort(array); } else { Arrays.sort(array, comparator); } }

Target:
Arrays.sort допускает null в качестве компаратора.
Source:
public void format(StringBuilder buffer, String format, Object... args) throws FormatterException { position = 0; nextFormat(buffer, format, args); }

Target:
Наличие поля StringFormatter делает его не thread safe.
Source:
public void close() { try { bufferedReader.close(); } catch (Exception e) { } out.flush(); out.close(); }

Target:
Закрывать System.in - плохо.
Source:
public synchronized String format(String format, Object... args) throws FormatterException { StringBuilder buffer = new StringBuilder(); format(buffer, format, args); return buffer.toString(); }

Target:
Объясни-таки, зачем нужен synchronized здесь.
Source:
public void format(StringBuilder buffer, Object o, String pattern) { Formatter formatter = new Formatter(); buffer.append(formatter.format("%" + pattern + "d", o)); }

Target:
Должны поддерживаться все форматы для целых чисел. Например, "o", "10x".
Source:
private void close() { try { reader.close(); } catch (Exception e) { // corrupted input stream. So bad. } }

Target:
Всегда надо иметь возможность закрывать ресурс снаружи. См. интерфейс Closeable
Source:
public void add(String string) { if (persnicketiness == Persnicketiness.ALL) { count++; return; } if (persnicketiness == Persnicketiness.UNIQUE_ANYCASE) { string = string.toLowerCase(); } Integer res = map.get(string); if (res == null) { map.put(string, 1); } else { map.put(string, res + 1); } }

Target:
Изменять данные некорректно. Надо использовать String.CASE_INSENSITIVE_ORDER
Source:
public static boolean isNumber(String s) { if (s.length() != 0) { if (Character.isDigit(s.charAt(0))) { return true; } } return false; }

Target:
Метод можно сократить до `return s.length() > 0 && Character.isDigit(s.charAt(0));`
Source:
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; }

Target:
Почему не boolean?
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; } } if ((countOfDigits - countOfOperands) == 1) { return true; } else { return false; } }

Target:
Можно упростить: `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) { System.err.print(e.getMessage()); System.exit(1); } } }

Target:
shell/bash работают не так. Они пишут сообщение об ошибке и можно продолжить работу. Мало ли - пользователь ошибся.
Source:
public String getIpAddress() { String publicIpv4Addr = amazonInfoHolder.get().get(MetaDataKey.publicIpv4); return this.shouldBroadcastPublicIpv4Addr() ? getPublicIpv4Addr() : getPrivateIpv4Addr(); }

Target:
Dead code.
Source:
private static void tryCatchLog(Callable<Void> callable) { try { callable.call(); } catch (Throwable th) { logger.error("Error in unmarshalling the object:", th); } }

Target:
Catch `Exception` instead.
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) { for (PeerEurekaNode node : this.peerEurekaNodes.getPeerEurekaNodes()) { node.shutDown(); } } } catch (Throwable t) { logger.error("Cannot shutdown ReplicaAwareInstanceRegistry", t); } super.shutdown(); }

Target:
PeerEurekaNodes has shutdown method.
Source:
public EurekaArchaius2InstanceConfig(Config config, String namespace) { this(config, "eureka", new DataCenterInfo() { @Override public Name getName() { return Name.MyOwn; } }); }

Target:
use namespace instead of "eureka".
Source:
public EurekaArchaius2ClientConfig(Config config, String namespace) { this.defaultRegion = config.getString("@region", null); this.config = config.getPrefixedView(DEFAULT_NAMESPACE); }

Target:
use namespace instead of DEFAULT
Source:
public Observable<ChangeNotification<InstanceInfo>> changeNotifications() { return aggregatedStream.share(); }

Target:
There is no need for that as channel contract guarantees single subscription only.
Source:
private boolean allowedToEvict() { boolean allowed = evictionStrategy.allowedToEvict(expectedRegistrySize, eurekaRegistry.size()) >= 0; moveHealthTo(allowed ? Status.UP : Status.DOWN); return allowed; }

Target:
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.
Source:
public void shutdown() { cancelScheduledTasks(); // If APPINFO was registered if (instanceInfo != null && shouldRegister(instanceInfo)) { instanceInfo.setStatus(InstanceStatus.DOWN); unregister(); } DiscoveryManager.getInstance().setDiscoveryClient(null); DiscoveryManager.getInstance().setEurekaClientConfig(null); }

Target:
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.
Source:
public Builder setAppGroupName(String appGroupName) { result.appGroupName = appGroupName; if (result.appGroupName != null) { result.appGroupName = result.appGroupName.toUpperCase(); } return this; }

Target:
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
Source:
protected Object doExecute() throws Exception { checkNotNull(template, "You must choose a template for the image you are trying to create."); 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); }

Target:
I don't think a template should be mandatory. you can always specify the list of packages on the command line
Source:
protected List<Instance> collectInstancesFromReservations(List<Reservation> reservation) { /* Make a copy as an ArrayList to force lazy collection evaluation */ List<List<Instance>> allInstances = Lists.newArrayList(Lists.transform(reservation, new Function<Reservation, List<Instance>>() { @Override public List<Instance> apply(Reservation reservation) { return reservation.getInstances(); } })); return Lists.newArrayList(Iterables.concat(allInstances)); }

Target:
A defensive copy is not needed here
Source:
private static String loadResource(String fileName) { try { return Resources.toString(Resources.getResource(TestConstants.class, fileName), Charsets.UTF_8); } catch (IOException e) { Throwables.propagate(e); } throw new RuntimeException("Resource not available " + fileName); }

Target:
use -> throw Throwables.propagate(e); and remove the last throw statement
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) { LOG.debug("Exception retrieving SecurityGroup (most likely it does not yet exist){}: {}", securityGroupName, e); } }

Target:
asta cred ca trebuie sa fie WARN
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)); } catch (Exception e) { LOG.error("An error occurred while updating state of feature {}.", featureName, e); } }

Target:
`RuntimeException` will be sufficient
Source:
public static WebArchive createDeployment() { return Deployments.getBasicWebArchive() .addClass(HttpServletRequestHolderServlet.class) .addClass(TogglzFilterServlet.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") .filter(TogglzFilter.class, "/*") .filter(TogglzFilter.class, "/*") .exportAsAsset()); }

Target:
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`.
Source:
public FeatureState getFeatureState(Feature feature) { for (StateRepository repository : iterationOrder.getSelected(repositories)) { FeatureState featureState = repository.getFeatureState(feature); if (featureState != null) { return featureState } } return null; }

Target:
There is a `;` missing...
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; } } return found; }

Target:
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; ```
Source:
public void beforeCreateCollection(DBBroker broker, Txn txn, XmldbURI uri) throws TriggerException { if (!triggersSuspended) { for (CollectionTrigger trigger : triggers) { trigger.beforeCreateCollection(broker, txn, uri); } } }

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

Target:
I think this needs tidying up. `entry` is redundant, and then `stringStringEntry` should be renamed as `entry`.
Source:
public void resetState(boolean postOptimization) { super.resetState(postOptimization); // clear closure variables set on inline function calls.forEach(call -> { if (!postOptimization) { call.getFunction().setClosureVariables(null); } }); calls.clear(); function.resetState(postOptimization); }

Target:
I think this could be reformulated to be more efficient, i.e.: ```java if (!postOptimization) { calls.forEach(call -> call.getFunction().setClosureVariables(null)); } ```
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) { Assert.fail(); } finally { support.after(); } }

Target:
This catch statement isn't needed, no?
Source:
public Handler[] getHandlers() { return handlers.keySet().stream().map(key -> handlers.get(key)).toArray(Handler[]::new); }

Target:
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--
Source:
public ScheduledExecutorService build() { final ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(this.poolSize, this.threadFactory, this.handler); if (this.removeOnCancel != null) { executor.setRemoveOnCancelPolicy(this.removeOnCancel.booleanValue()); } this.environment.manage(new ExecutorServiceManager(executor, this.shutdownTime, this.nameFormat)); return executor; }

Target:
If `removeOnCancel` were a boolean primitive we could avoid a condition block.
Source:
public String checkOptionalAuth(@Auth Optional<Principal> principalOpt) { return "principal was " + ((principalOpt.isPresent()) ? "" : "not ") + "present"; }

Target:
I guess we could omit the parentheses around `principalOpt.isPresent`
Source:
public void configure(Map<String, String> options) { useCache = Optional.ofNullable(options.get("cache")) .map(Boolean::parseBoolean) .orElse(true); if (options.containsKey("fileRoot")) { fileRoot = new File(options.get("fileRoot")); } }

Target:
If we declare `fileRoot` as `Optional`, we can initialize it with one-liner: ```java Optional.ofNullable(options.get("fileRoot")).map(File::new) ```
Source:
public DropwizardSSLConnectionSocketFactory(TlsConfiguration configuration) { this.configuration = configuration; this.verifier = null; }

Target:
I think we could reduce this constructor to a call to another constructor: ``` java this(configuration, null); ```
Source:
private HostnameVerifier chooseHostnameVerifier() { HostnameVerifier hostnameVerifier; if (configuration.isVerifyHostname()) { if (verifier == null) { hostnameVerifier = SSLConnectionSocketFactory.getDefaultHostnameVerifier(); } else { hostnameVerifier = verifier; } } else { hostnameVerifier = new NoopHostnameVerifier(); } return hostnameVerifier; }

Target:
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(); } ```
Source:
public void testInitialSizeIsZero() throws Exception { factory.setUrl("nonsense invalid url"); factory.setInitialSize(0); ManagedDataSource dataSource = factory.build(metricRegistry, "test"); try { dataSource.start(); } catch (Exception e) { fail(); } }

Target:
Surrounding the statement with try-catch doesn't gain anything. The test will fail anyway, if any uncaught exception occurs.
Source:
public void testInitialSizeZeroIsAllowed() throws Exception { try { DataSourceFactory ds = getDataSourceFactory("yaml/empty_initial_pool.yml"); assertThat(ds.getInitialSize()).isEqualTo(0); } catch (ConfigurationValidationException e) { e.printStackTrace(); fail(e.getMessage()); } }

Target:
Surrounding the statement with try-catch doesn't gain anything. The test will fail anyway, if any uncaught exception occurs.
Source:
public void createDefaultFactory() throws Exception { ConfigurationFactory<Example> factory = factoryFactory.create(Example.class, validator, Jackson.newObjectMapper(), "dw"); final Example example = factory.build(new FileConfigurationSourceProvider(), validFile.getPath()); assertThat(example.getName()) .isEqualTo("Coda Hale"); }

Target:
Is this change required now that we have the default method in the interface?
Source:
public void before() { when(this.environment.jersey()).thenReturn(this.jerseyEnvironment); }

Target:
I think you could avoid to use `this` to reference the fields in the unit test, because there are no name conflicts.
Source:
protected String name() { return DEFAULT_NAME; }

Target:
can you make this `public`?
Source:
public static synchronized void initXmlParser() throws Exception { xmlParser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); attributeNames = ImmutableList.of("columns", "foreign-keys", "indexes", "primary-keys", "sequences", "tables", "unique-constraints", "views"); }

Target:
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.
Source:
public OAuthTestResourceConfig() { super(); register(AuthResource.class); }

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

Target:
Ditto for `super()`
Source:
public String toString() { return MoreObjects.toStringHelper(this) .add("level", level) .add("loggers", loggers) .add("appenders", appenders) .add("loggerContext", loggerContext) .add("configurationErrorsStream", configurationErrorsStream) .toString(); }

Target:
I don't think that printing the configurationErrorsStream or the loggerContext is really useful here.
Source:
public void setOutputStream(PrintStream outputStream) { this.outputStream = outputStream; }

Target:
should this be package private?
Source:
public void close() throws Exception { try { database.close(); } catch (LiquibaseException e){ LOGGER.warn("Failed to close liquibase", e); } dataSource.stop(); }

Target:
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.
Source:
public int compareTo(Duration other) { if (count == 0 && other.count == 0) { return 0; } // this is negative, other is non-negative if (count < 0 && other.count >= 0) { 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()); }

Target:
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™.
Source:
protected Factory<?> createValueFactory(final Parameter parameter) { final Class<?> classType = parameter.getRawType(); Auth auth = parameter.getAnnotation(Auth.class); if (auth == null) { return null; } if (classType.isAssignableFrom(this.factory.getGeneratedClass())) { return this.factory.clone(auth.required()); } else { return null; } }

Target:
this could be made `final`
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); client.setCredentialsProvider(credentialsProvider); setStrategiesForClient(client); return client; }

Target:
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:
Source:
public ViewBundle() { this(ImmutableList.copyOf(ServiceFinder.find(ViewRenderer.class))); }

Target:
I think it would make more sense to create an immutable copy of the `Iterable` in the `ViewBundle(Iterable<ViewRenderer>)` constructor instead of here.
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); } items.add(name); }

Target:
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); } ```
Source:
public T build(String configurationPath, InputStream inputStream) throws IOException, ConfigurationException { final JsonNode node = mapper.readTree(inputStream); return build(node, configurationPath != null ? configurationPath : "InputStream configuration"); }

Target:
We should ensure the stream is closed.
Source:
public JobStatus permanentlyDeleteTicket(Ticket ticket) { checkHasId(ticket); deleteTicket(ticket.getId()); return permanentlyDeleteTicket(ticket.getId()); }

Target:
deleteTicket is invoked twice, once here then again in permanentlyDeleteTicket.
Source:
public User permanentlyDeleteUser(User user) { checkHasId(user); deleteUser(user.getId()); return permanentlyDeleteUser(user.getId()); }

Target:
Same issue here, double delete user.
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()); mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY); return mapper; }

Target:
@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.
Source:
public String toString() { return "CustomFieldValue{" + "id=" + id + ", value=" + (value == null ? "null" : Arrays.asList(value).toString()) + '}'; }

Target:
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..
Source:
public static boolean isRecoveryProblems() { return recoveryProblems.get(); }

Target:
if there is no particular reason to make anything public then it should be `private` (or package-private in case)
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 if (afterURI == null || afterLRARequest(afterURI, lra, 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; }

Target:
@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
Source:
public RequestBuilder(URI baseURI) { builder = new URIBuilder(baseURI); paths = new ArrayList<>(); Collections.addAll(paths, strip(strip(baseURI.getPath())).split("/")); }

Target:
Nested strip invocation seems unnecessary. But maybe I am missing something?
Source:
public long getSize(ParticipantStatus participantStatus, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return 0; }

Target:
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. ```
Source:
public Response compensate(@PathParam("participantId") String participantId, @HeaderParam(LRA_HTTP_CONTEXT_HEADER) String lraId, @HeaderParam(LRA_HTTP_PARENT_CONTEXT_HEADER) String parentId) { return lraParticipantRegistry.getParticipant(participantId).compensate(createURI(lraId), createURI(parentId)); }

Target:
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
Source:
public LRAParticipantRegistry(Map<String, LRAParticipant> lraParticipants) { this.lraParticipants = new HashMap<>(lraParticipants); }

Target:
this can be package private
Source:
void processAnnotatedType(@Observes ProcessAnnotatedType<NoAnnotationBean> bean) { if(classToProcess.contains(bean.getAnnotatedType().getJavaClass())) { AnnotatedTypeWrapper<NoAnnotationBean> wrapper = new AnnotatedTypeWrapper<NoAnnotationBean>(bean); wrapper.addAnnotation(new TransactionalLiteral()); bean.setAnnotatedType(wrapper); } }

Target:
This `if` and the list above can be removed completely.
Source:
protected 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; }

Target:
I don't think this needed to be protected?
Source:
public Transaction getTransactionById(Object id) { return com.arjuna.ats.internal.jta.transaction.jts.TransactionImple.getTransaction((Uid) id); }

Target:
Try remove package
Source:
private final void endAssociation(int xaState, int txInfoState) throws XAException { if (_doEnd && _theTransaction != null) { _theTransaction.endAssociation(_tranID, _theXAResource, xaState, txInfoState); } }

Target:
_doEnd looks like an unused variable (ie remove it)
Source:
public void start() throws XAException, SystemException, InvalidTransactionException, IllegalStateException, NamingException { txbridgeLogger.logger.trace("InboundBridge.start(Xid="+xid+")"); Transaction tx = getTransaction(); TransactionManager.transactionManager(new InitialContext()).resume(tx); }

Target:
This is changing a public interface and deprecation rules apply.
Source:
public void stop() throws XAException, SystemException, InvalidTransactionException, NamingException { txbridgeLogger.logger.trace("InboundBridge.stop("+xid+")"); TransactionManager.transactionManager(new InitialContext()).suspend(); }

Target:
This is changing a public interface and deprecation rules apply.
Source:
public Object getCurrentTransactionId() { if(com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionImple.getTransaction() == null) return null; return com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionImple.getTransaction().get_uid(); }

Target:
There should be a new line after the return.
Source:
public static String getThreadId(final Thread thread) { final Object id = THREAD_ID.get(thread) ; if (id != null) { return (String)id ; } final String newId = getNextId() ; THREAD_ID.put(thread,newId) ; return newId ; }

Target:
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.
Source:
public int cancel () { if (parent() != null) parent().removeChildAction(this); // beforeCompletion(); int outcome; synchronized (_cancelLock) { // https://issues.jboss.org/browse/JBTM-2643 if (TxStats.enabled() && running()) TxStats.getInstance().incrementApplicationRollbacks(); outcome = super.Abort(); } if (outcome == ActionStatus.ABORTED) { afterCompletion(outcome); } return outcome; }

Target:
I don't like having yet another lock in here. Why not put the conditional stat increment in BasicAction::Abort which is already synchronized.
Source:
public void commit(Xid xid, boolean b) throws XAException { assertIfRecoveryScanWasStarted(); delegate.commit(xid, b); }

Target:
RMERR out of this is not good - check the spec
Source:
public void rollback(Xid xid) throws XAException { assertIfRecoveryScanWasStarted(); delegate.rollback(xid); }

Target:
RMERR Is not great here - not as bad as commit but not compatible either
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); throw new XAException(XAException.XAER_PROTO); } }

Target:
RMFAIL
Source:
private void disconnect() throws XAException { try { xaConnection.close(); } catch (JMSException e) { LOGGER.warn("Failed to close connection", e); throw new XAException(XAException.XAER_PROTO); } finally { xaConnection = null; xaSession = null; delegate = null; } }

Target:
RMFAIL
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()) { return (transactionImple.getTxLocalResource(transactionLocal) != null); } else { return false; } }

Target:
what has this got to do with listeners :) (maybe split it to a separate commit if you really absolutely must)
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"); opts.addOption("schedulerAddr", true, "YARN scheduler's IPC address"); opts.addOption("stormHome", true, "Storm Home Directory"); opts.addOption("output", true, "Output file"); opts.addOption("stormZip", true, "file path of storm.zip"); return opts; }

Target:
Why do we need the scheduler address? It should come from the Hadoop configuration.
Source:
public String apply(HttpResponse from) { String id = from.getFirstHeaderOrNull(GlacierHeaders.JOB_ID); if (id == null) throw new HttpException("Did not receive JobId"); return id; }

Target:
[minor] Write as ``` if (id == null) { throw new HttpException("Did not receive JobId"); } ``` ? Thanks!
Source:
public Builder() { }

Target:
Should this be package-access instead of public-access? Callers should use `ArchiveRetrievalJobRequest.builder` correct?
Source:
public void testValidate() throws UnsupportedEncodingException, IOException { VALIDATOR.validate("VALID_NAME"); VALIDATOR.validate("VALID-NAME"); VALIDATOR.validate("VALID255NAME"); VALIDATOR.validate("255VALID-NAME"); VALIDATOR.validate("VALID.NAME"); VALIDATOR.validate(new String(buildData(255).read(), UTF_8)); }

Target:
Consider `buildData(255).asCharSource(UTF_8).read()` instead.
Source:
protected void configure() { super.configure(); install(new GlacierParserModule()); bind(RequestAuthorizeSignature.class).in(Scopes.SINGLETON); }

Target:
Personally, I prefer to separate modules. This module could work without the parser one, so I'd prefer to remove this line and add the `GlacierParserModule` to the list of the default modules in the `ApiMetadata`.
Source:
private String buildCredentialScope(String dateWithoutTimeStamp) { StringBuilder buffer = new StringBuilder(); buffer.append(dateWithoutTimeStamp).append("/"); buffer.append(REGION).append("/"); buffer.append(SERVICE).append("/"); buffer.append(TERMINATION_STRING); return buffer.toString(); }

Target:
Reuse result of `StringBuffer.append` instead of using `buffer` local variable.
Source:
private String sha256(byte[] unhashedBytes) { return Hashing.sha256().hashBytes(unhashedBytes).toString(); }

Target:
Make method static.
Source:
public static String format(final String format, final String... args) { String[] split = format.split("%s"); final StringBuilder msg = new StringBuilder(); for (int pos = 0; pos < split.length - 1; pos += 1) { msg.append(split[pos]); msg.append(args[pos]); } msg.append(split[split.length - 1]); return msg.toString(); }

Target:
make it private
Source:
public static String generateHtmlSnippet(String id, URI baseUri) { StringBuilder sb = new StringBuilder(); Formatter formatter = new Formatter(sb); formatter.format("<script type=\"text/javascript\" language=\"javascript\" " + "src=\"%1$s/factory/resources/embed.js?%2$s\"></script>", UriBuilder.fromUri(baseUri).replacePath("").build(), id); return sb.toString(); }

Target:
useless string builder, you can use default constructor
Source:
protected boolean shouldExpire(long threshold, long timestamp) { if (threshold > -1) { long currentTime = currentTimeMillis(); if (timestamp > currentTime || currentTime - timestamp > threshold) return true; } return false; }

Target:
Should this be (currentTime > timestamp && currentTime - timestamp > threshold) The current check expires any timestamp after the currentTimeMillis() in the iterator. Seems like you are assuming that the times are synced perfectly between the server that wrote a mutation and the one this iterator is running on during scan/compaction.
Source:
public void setSystemPurposeStatus(String systemPurposeStatus) { this.systemPurposeStatus = systemPurposeStatus; this.setRHCloudProfileModified(new Date()); }

Target:
Why update the profile timestamp here? This isn't one of the required fields? And regardless, it is redundant, because this is recalculated and set if any of the syspurpose attributes change anyway
Source:
protected void populateEntities(List<GuestId> entities, List<String> guestIds) { if (entities == null) { throw new IllegalArgumentException("the guestId model entity is null"); } if (guestIds == null) { throw new IllegalArgumentException("the list of guestId is null"); } for (String guestId : guestIds) { if (guestId == null) { continue; } GuestId guestIdEntity = new GuestId(); populateEntity(guestIdEntity, new GuestIdDTO().guestId(guestId)); entities.add(guestIdEntity); } }

Target:
This is still creating a GuestIdDTO object, and calling populateEntity, both of which are not needed. All these 3 lines of code can be condensed into one: `entities.add(new GuestId(guestId));`
Source:
public Stream<DeletedConsumerDTO> listByDate(String dateStr) { CandlepinQuery<DeletedConsumerDTO> query = this.translator.translateQuery(dateStr != null ? this.deletedConsumerCurator.findByDate(ResourceDateParser.parseDateString(dateStr)) : this.deletedConsumerCurator.listAll(), DeletedConsumerDTO.class); return StreamSupport.stream(query.spliterator(), false); }

Target:
This doesn't actually work in all cases. Since the processing of the stream occurs later, the connection backing the CPQ can close and it'll trigger an exception instead of returning the result. For now, just return the CandlepinQuery object as normal, and set the container type to "Iterable" in the yaml.
Source:
private static void verifyProductsOutput(Collection<Product> originalProducts, Set<ProductDTO> dtoProducts) { for (Product productSource : originalProducts) { for (ProductDTO productDTO : dtoProducts) { assertNotNull(productDTO); assertNotNull(productDTO.getId()); if (productDTO.getId().equals(productSource.getId())) { assertTrue(productDTO.getName().equals(productSource.getName())); } } } }

Target:
Why is this function static?
Source:
public Product() { this.attributes = new HashMap<>(); this.productContent = new LinkedList<>(); this.dependentProductIds = new HashSet<>(); this.branding = new HashSet<>(); this.providedProducts = new HashSet<>(); this.derivedProvidedProducts = new HashSet<>(); this.providedProductDtos = null; this.derivedProvidedProductDtos = null; }

Target:
The DTOs thing is legacy code from loooong ago. Let's try to avoid carrying these into the updated model.
Source:
public Consumer setUuid(String uuid) { if (this.uuid == null) { this.uuid = uuid; } return this; }

Target:
What's the intent behind this? Generally we want to allow this to be changed at any point. Is there something in particular that requires this with the update?
Source:
private CPMProducer getProducer() throws CPMException { if (this.cpmProducer == null || this.cpmProducer.isClosed()) { log.debug("Creating new CPM producer for job message dispatch..."); CPMSession session = this.getSession(); CPMProducerConfig config = session.createProducerConfig(); // TODO: Add any other job-system-specific producer configuration here this.cpmProducer = session.createProducer(config); log.debug("Created new CPM producer: {}", this.cpmProducer); } return this.cpmProducer; }

Target:
Lots of other methods in this class are synchronized. Does this method need to be too?
Source:
public Pool createAndEnrichPools(Pool pool, List<Pool> existingPools) { List<Pool> pools = poolRules.createAndEnrichPools(pool, existingPools); log.debug("Creating pools: ", pools.size()); boolean isPoolLocked = pool.isLocked(); for (Pool p : pools) { createPool(p); } for (Pool tempPool : pools) { if (isPoolLocked) { tempPool.setLocked(true); } } return pool; }

Target:
You can skip the declaration above and just query the value here. Since the locked flag is a simple boolean that is returned from the Pool object, the call gets optimized down to basically what you're doing here without needing to write it out yourself. There are cases where you'll want to explicitly cache stuff locally, but since we're not dealing with unboxing and it's a simple accessor on what is little more than a data store, this is not such a case.
Source:
public InputStream getInputStream(boolean buffered) { if (inputStream != null) { return inputStream; } InputStream inputStream = requestContext.getInputStream(); return inputStream; }

Target:
When you're using a local variable that shares a name with a class or instance variable, try to be explicit as to which you're referencing by using ```this.inputStream``` (or similar as appropriate). As an aside, the instance variable is never set, so this check will never succeed.
Source:
public InputStream getInputStream(boolean buffered) { if (this.inputStream != null) { return this.inputStream; } InputStream inputStream = requestContext.getInputStream(); return inputStream; }

Target:
Good, but this still is never used, so it serves no purpose. The input stream will always be fetched from the requestContext.
Source:
public ClientSession getClientSession(boolean transacted) throws Exception { log.debug("Creating new ActiveMQ session..."); ClientSessionFactory csf = this.getClientSessionFactory(); ClientSession session = transacted ? csf.createTransactedSession() : csf.createSession(true, false); log.debug("Created new ActiveMQ session: {}", session); return session; }

Target:
Rather than change this here, you could just flip the flag in the JobMessageReceiver to true for transacted on line 59: ```session = this.sessionFactory.getIngressSession(true);``` If there's a reason I'm not seeing that we need to control both of these, I'd rather see the interface wrapping this change such that both flags can be set independently.
Source:
public EntitlerJobConfig setConsumer(final Consumer consumer) { if (consumer == null) { throw new IllegalArgumentException("Consumer is null"); } final String uuid = consumer.getUuid(); this.addConstraint(new ThrottlingConstraint(this.throttle, new AggregateJobMatcher( new MatchByJobKey(JOB_KEY), new MatchByArgument(CONSUMER_UUID_KEY, uuid) ))) .setJobArgument(CONSUMER_UUID_KEY, uuid); return this; }

Target:
Given the complexity of constructing a Constraint object here, it would be good to utilize the `JobConstraints` class in a similar way the uniqueByArgument class is constructed. As a user of the constraints API, I shouldn't have to worry about implementation details like `AggregateJobMatcher`, `MatchByJobKey` and `MatchByJobKey`, and simply be able to do something like ``` .addConstraint(JobConstraints.uniqueByArgumentAndThrottle( conf.getInt(ConfigProperties.ENTITLER_JOB_THROTTLE), CONSUMER_UUID_KEY) ); ```
Source:
public EntitleByProductsJobConfig() { this.setJobKey(JOB_KEY) .setJobName(JOB_NAME) .addConstraint(JobConstraints.uniqueByArguments(OWNER_KEY)); }

Target:
The original job does not seem to extend `UniqueByEntityJob`, or implement the `isSchedulable/scheduleJob` methods, so there is no need for constraints on this job.
Source:
public ActivationKeyDTO setAddOns(Set<String> addOns) { this.addOns = addOns; return this; }

Target:
We should decouple from the inbound collection here. A simple ```this.addOns = addOns != null ? new HashSet<>(addOns) : null;``` will work.
Source:
public Collection<Consumer> findByUuids(Collection<String> uuids) { Set<Consumer> consumers = new HashSet<>(); for (List<String> block : this.partition(uuids)) { // Unfortunately, this needs to be a secure criteria due to the contexts in which this // is called. Criteria criteria = this.createSecureCriteria() .add(Restrictions.in("uuid", uuids)); consumers.addAll(criteria.list()); } return consumers; }

Target:
Why is block unused? Isn't it then doing the same thing on every iteration?
Source:
public QpidConnection(QpidConfigBuilder config, Configuration candlepinConfiguration) { try { this.producerMap = new HashMap<>(); this.config = config; this.candlepinConfig = candlepinConfiguration; this.producerMap = new HashMap<>(); ctx = createInitialContext(); connectionFactory = createConnectionFactory(); } catch (NamingException e) { throw new RuntimeException(e); } }

Target:
This is initialized below on line 97
Source:
public void sendEvents() { log.debug("Committing ActiveMQ transaction"); try { ClientSession session = this.getClientSession(); session.commit(); session.close(); } catch (Exception e) { // This would be pretty bad, but we always try not to let event errors // interfere with the operation of the overall application. log.error("Error committing ActiveMQ transaction", e); } }

Target:
Put the close() into a finally block so that an attempt is always made to close the session, even on commit failure. If closing the session fails, there's not really anything we can do -- log and move on.
Source:
public void rollback() { log.warn("Rolling back ActiveMQ transaction"); try { ClientSession session = this.getClientSession(); session.rollback(); session.close(); } catch (ActiveMQException e) { log.error("Error rolling back ActiveMQ transaction", e); } }

Target:
Put the close() into a finally block so that an attempt is always made to close the session, even on rollback fails. If closing the session fails, there's not really anything we can do -- log and move on.