auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public String apply(HttpResponse from) { String id = from.getFirstHeaderOrNull(GlacierHeaders.JOB_ID); if (id == null) START throw new HttpException("Did not receive JobId"); END return id; } [minor] Write as ``` if (id == null) { throw new HttpException("Did not receive JobId"); } ``` ? Thanks!

Target:
public String apply(HttpResponse from) { String id = from.getFirstHeaderOrNull(GlacierHeaders.JOB_ID); if (id == null) { throw new HttpException("Did not receive JobId"); } return id; }
Source:
START public Builder() { END } Should this be package-access instead of public-access? Callers should use `ArchiveRetrievalJobRequest.builder` correct?

Target:
protected Builder() { }
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"); START VALIDATOR.validate(new String(buildData(255).read(), UTF_8)); END } Consider `buildData(255).asCharSource(UTF_8).read()` instead.

Target:
public void testValidate() { VALIDATOR.validate("VALID_NAME"); VALIDATOR.validate("VALID-NAME"); VALIDATOR.validate("VALID255NAME"); VALIDATOR.validate("255VALID-NAME"); VALIDATOR.validate("VALID.NAME"); }
Source:
protected void configure() { super.configure(); START install(new GlacierParserModule()); END bind(RequestAuthorizeSignature.class).in(Scopes.SINGLETON); } 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`.

Target:
protected void configure() { super.configure(); bind(RequestAuthorizeSignature.class).in(Scopes.SINGLETON); }
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); START return buffer.toString(); END } Reuse result of `StringBuffer.append` instead of using `buffer` local variable.

Target:
private static String buildCredentialScope(String dateWithoutTimeStamp) { return dateWithoutTimeStamp + "/" + REGION + "/" + SERVICE + "/" + TERMINATION_STRING; }
Source:
START private String sha256(byte[] unhashedBytes) { END return Hashing.sha256().hashBytes(unhashedBytes).toString(); } Make method static.

Target:
private static String sha256(byte[] unhashedBytes) { return Hashing.sha256().hashBytes(unhashedBytes).toString(); }
Source:
START public static String format(final String format, final String... args) { END 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(); } make it private

Target:
private 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(); }
Source:
public static String generateHtmlSnippet(String id, URI baseUri) { START StringBuilder sb = new StringBuilder(); END 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(); } useless string builder, you can use default constructor

Target:
public static String generateHtmlSnippet(String id, URI baseUri) { Formatter formatter = new Formatter(); formatter.format("<script type=\"text/javascript\" language=\"javascript\" " + "src=\"%1$s/factory/resources/embed.js?%2$s\"></script>", UriBuilder.fromUri(baseUri).replacePath("").build().toString(), id); return formatter.toString(); }
Source:
protected boolean shouldExpire(long threshold, long timestamp) { if (threshold > -1) { long currentTime = currentTimeMillis(); START if (timestamp > currentTime || currentTime - timestamp > threshold) END return true; } return false; } 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.

Target:
public static boolean shouldExpire(long threshold, long timestamp) { if (threshold > -1 && timestamp > -1) { long currentTime = currentTimeMillis(); if (currentTime - timestamp > threshold) return true; } return false; }
Source:
public void setSystemPurposeStatus(String systemPurposeStatus) { this.systemPurposeStatus = systemPurposeStatus; START this.setRHCloudProfileModified(new Date()); END } 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

Target:
public void setSystemPurposeStatus(String systemPurposeStatus) { this.systemPurposeStatus = systemPurposeStatus; }
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; } START GuestId guestIdEntity = new GuestId(); populateEntity(guestIdEntity, new GuestIdDTO().guestId(guestId)); entities.add(guestIdEntity); END } } 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));`

Target:
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; } 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); START return StreamSupport.stream(query.spliterator(), false); END } 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.

Target:
public CandlepinQuery<DeletedConsumerDTO> listByDate(String dateStr) { return this.translator.translateQuery(dateStr != null ? this.deletedConsumerCurator.findByDate(ResourceDateParser.parseDateString(dateStr)) : this.deletedConsumerCurator.listAll(), DeletedConsumerDTO.class); }
Source:
START private static void verifyProductsOutput(Collection<Product> originalProducts, END 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())); } } } } Why is this function static?

Target:
private 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())); } } } }
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; START this.derivedProvidedProductDtos = null; END } The DTOs thing is legacy code from loooong ago. Let's try to avoid carrying these into the updated model.

Target:
public Product() { this.attributes = new HashMap<>(); this.productContent = new LinkedList<>(); this.dependentProductIds = new HashSet<>(); this.branding = new HashSet<>(); this.providedProducts = new HashSet<>(); }
Source:
public Consumer setUuid(String uuid) { START if (this.uuid == null) { END this.uuid = uuid; } return this; } 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?

Target:
public Consumer setUuid(String uuid) { this.uuid = uuid; return this; }
Source:
START private CPMProducer getProducer() throws CPMException { END 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; } Lots of other methods in this class are synchronized. Does this method need to be too?

Target:
private synchronized 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; }
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) { START if (isPoolLocked) { END tempPool.setLocked(true); } } return pool; } 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.

Target:
public Pool createAndEnrichPools(Pool pool, List<Pool> existingPools) { List<Pool> pools = poolRules.createAndEnrichPools(pool, existingPools); log.debug("Creating pools: ", pools.size()); for (Pool p : pools) { createPool(p); } return pool; }
Source:
public InputStream getInputStream(boolean buffered) { START if (inputStream != null) { END return inputStream; } InputStream inputStream = requestContext.getInputStream(); return inputStream; } 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.

Target:
public InputStream getInputStream(boolean buffered) { return requestContext.getInputStream(); }
Source:
public InputStream getInputStream(boolean buffered) { if (this.inputStream != null) { START return this.inputStream; END } InputStream inputStream = requestContext.getInputStream(); return inputStream; } Good, but this still is never used, so it serves no purpose. The input stream will always be fetched from the requestContext.

Target:
public InputStream getInputStream(boolean buffered) { return requestContext.getInputStream(); }
Source:
public ClientSession getClientSession(boolean transacted) throws Exception { log.debug("Creating new ActiveMQ session..."); ClientSessionFactory csf = this.getClientSessionFactory(); ClientSession session = transacted ? csf.createTransactedSession() : START csf.createSession(true, false); END log.debug("Created new ActiveMQ session: {}", session); return session; } 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.

Target:
public ClientSession getClientSession(boolean transacted) throws Exception { log.debug("Creating new ActiveMQ session..."); ClientSessionFactory csf = this.getClientSessionFactory(); ClientSession session = transacted ? csf.createTransactedSession() : csf.createSession(); log.debug("Created new ActiveMQ session: {}", session); return session; }
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), START new MatchByArgument(CONSUMER_UUID_KEY, uuid) END ))) .setJobArgument(CONSUMER_UUID_KEY, uuid); return this; } 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) ); ```

Target:
public EntitlerJobConfig setConsumer(final Consumer consumer) { if (consumer == null) { throw new IllegalArgumentException("Consumer is null"); } this.setJobArgument(CONSUMER_UUID_KEY, consumer.getUuid()); return this; }
Source:
public EntitleByProductsJobConfig() { this.setJobKey(JOB_KEY) .setJobName(JOB_NAME) START .addConstraint(JobConstraints.uniqueByArguments(OWNER_KEY)); END } 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.

Target:
public EntitleByProductsJobConfig() { this.setJobKey(JOB_KEY) .setJobName(JOB_NAME); }
Source:
public ActivationKeyDTO setAddOns(Set<String> addOns) { START this.addOns = addOns; END return this; } We should decouple from the inbound collection here. A simple ```this.addOns = addOns != null ? new HashSet<>(addOns) : null;``` will work.

Target:
public ActivationKeyDTO setAddOns(Set<String> addOns) { this.addOns = addOns != null ? new HashSet<>(addOns) : null; return this; }
Source:
public Collection<Consumer> findByUuids(Collection<String> uuids) { Set<Consumer> consumers = new HashSet<>(); START for (List<String> block : this.partition(uuids)) { END // 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; } Why is block unused? Isn't it then doing the same thing on every iteration?

Target:
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", block)); consumers.addAll(criteria.list()); } return consumers; }
Source:
public QpidConnection(QpidConfigBuilder config, Configuration candlepinConfiguration) { try { START this.producerMap = new HashMap<>(); END this.config = config; this.candlepinConfig = candlepinConfiguration; this.producerMap = new HashMap<>(); ctx = createInitialContext(); connectionFactory = createConnectionFactory(); } catch (NamingException e) { throw new RuntimeException(e); } } This is initialized below on line 97

Target:
public QpidConnection(QpidConfigBuilder config, Configuration candlepinConfiguration) { try { this.config = config; this.candlepinConfig = candlepinConfiguration; this.producerMap = new HashMap<>(); ctx = createInitialContext(); connectionFactory = createConnectionFactory(); } catch (NamingException e) { throw new RuntimeException(e); } }
Source:
public void sendEvents() { log.debug("Committing ActiveMQ transaction"); try { ClientSession session = this.getClientSession(); session.commit(); START session.close(); END } 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); } } 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.

Target:
public void sendEvents() { log.debug("Committing ActiveMQ transaction"); try (ClientSession session = this.getClientSession()) { session.commit(); } 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); } }
Source:
public void rollback() { log.warn("Rolling back ActiveMQ transaction"); try { ClientSession session = this.getClientSession(); session.rollback(); START session.close(); END } catch (ActiveMQException e) { log.error("Error rolling back ActiveMQ transaction", e); } } 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.

Target:
public void rollback() { log.warn("Rolling back ActiveMQ transaction"); try (ClientSession session = this.getClientSession()) { session.rollback(); } catch (ActiveMQException e) { log.error("Error rolling back ActiveMQ transaction", e); } }
Source:
public DeveloperProducts(String expectedSku, Map<String, Product> products) { this.sku = products.remove(expectedSku); this.provided = products; START log.debug("Test?? {}", this.sku); END } If this isn't left in by accident, can you change the message to be a little more informative?

Target:
public DeveloperProducts(String expectedSku, Map<String, Product> products) { this.sku = products.remove(expectedSku); this.provided = products; }
Source:
protected Object getOutputValueForAccessor(String field, Object input) { // Since we're returning primitives for two methods, we need to convert them as necessary if (field != null && (field.equals("Result") || field.equals("Standalone")) && input == null) { return false; START } END return input; } leftovers from `StatusDTOTest`. just `return input;` is enough here since this DTO has no primitives.

Target:
protected Object getOutputValueForAccessor(String field, Object input) { return input; }
Source:
public StatusDTO setManagerCapabilities(Collection<String> capabilities) { if (capabilities != null) { if (this.capabilities == null) { START this.capabilities = new HashSet<String>(); END } this.capabilities.clear(); this.capabilities.addAll(capabilities); } else { this.capabilities = null; } return this; } Something else that I missed. I know it's not that important, but we don't have to set the type when creating new objects any more. We can just use the diamond operator `new HashSet<>`.

Target:
public StatusDTO setManagerCapabilities(Collection<String> capabilities) { if (capabilities != null) { if (this.capabilities == null) { this.capabilities = new HashSet<>(); } this.capabilities.clear(); this.capabilities.addAll(capabilities); } else { this.capabilities = null; } return this; }
Source:
protected X509Certificate loadCACertificate(String path) { try ( InputStream inStream = new FileInputStream(path); ) { X509Certificate cert = (X509Certificate) this.certFactory.generateCertificate(inStream); START inStream.close(); END return cert; } catch (Exception e) { throw new RuntimeException(e); } } This line unnecessary since we're using try-with-resources syntax...

Target:
protected X509Certificate loadCACertificate(String path) { try ( InputStream inStream = new FileInputStream(path); ) { return (X509Certificate) this.certFactory.generateCertificate(inStream); } catch (Exception e) { throw new RuntimeException(e); } }
Source:
START public void initModelTranslator(ModelTranslator modelTranslator) { END modelTranslator.registerTranslator(this.capabilityTranslator, ConsumerCapability.class, CapabilityDTO.class); } What's driving the change to increase visibility here? These are intended to be used only by subclasses.

Target:
protected void initModelTranslator(ModelTranslator modelTranslator) { modelTranslator.registerTranslator(this.capabilityTranslator, ConsumerCapability.class, CapabilityDTO.class); }
Source:
public EventDTO clone() { EventDTO copy = super.clone(); START copy.timestamp = timestamp != null ? new Date(timestamp.getTime()) : null; END return copy; } Use the clone method here rather than new date.

Target:
public EventDTO clone() { EventDTO copy = super.clone(); copy.timestamp = this.timestamp != null ? (Date) this.timestamp.clone() : null; return copy; }
Source:
START public java.util.Collection<Consumer> getConsumers() { END return this.virtUuidToConsumerMap.values(); } A bit more PoC code that's left over. We should do a proper import and not fully qualify this on the fly.

Target:
public Collection<Consumer> getConsumers() { return this.virtUuidToConsumerMap.values(); }
Source:
private void clearContentAccessCerts(Environment env) { ownerEnvContentAccessCurator.removeAllForEnvironment(env.getId()); START ownerEnvContentAccessCurator.refresh(); END } How does this work? I don't see a specific `refresh()` method in OwnerEnvContentAccessCurator, so I'm supposing it goes to `refresh(E... entities)` in the superclass. But since you're not passing in any entities, that looks like it would just be a no-op.

Target:
private void clearContentAccessCerts(Environment env) { ownerEnvContentAccessCurator.removeAllForEnvironment(env.getId()); }
Source:
public GuestIdDTO clone() { GuestIdDTO copy = super.clone(); Map<String, String> attributes = this.getAttributes(); if (attributes != null) { START copy.setAttributes(new HashMap<String, String>(attributes)); END } return copy; } This is unnecessary once the encapsulation issue is resolved

Target:
public GuestIdDTO clone() { GuestIdDTO copy = super.clone(); copy.setAttributes(this.getAttributes()); return copy; }
Source:
public boolean equals(Object other) { if (!(other instanceof GuestId)) { return false; } GuestId that = (GuestId) other; if (this.getGuestId().equalsIgnoreCase(that.getGuestId())) { START EqualsBuilder builder = new EqualsBuilder() END .append(this.getAttributes(), that.getAttributes()); return builder.isEquals(); } return false; } This is just a map of strings, and the EqualsBuilder is just calling into .equals as the replaced code was doing. We're not gaining anything with this change.

Target:
public boolean equals(Object other) { if (!(other instanceof GuestId)) { return false; } GuestId that = (GuestId) other; if (this.getGuestId().equalsIgnoreCase(that.getGuestId()) && this.getAttributes().equals(that.getAttributes())) { return true; } return false; }
Source:
public String getHref() { START return this.id != null ? String.format("/pools/%s", this.id) : null; END } For methods like this which pull from other bits of data, since we're making it extensible, try to use the methods instead: ``` return this.getId() != null ? String.format(...) : null;``` That way subclasses need not override both methods should the source of the ID change.

Target:
public String getHref() { return this.getId() != null ? String.format("/pools/%s", this.getId()) : null; }
Source:
private boolean changedProductsInSet(Set<Product> products, Map<String, Product> changedProducts) { if (products != null && changedProducts != null) { START for (Product product: products) { END if (product != null && product.getId() != null && changedProducts.get(product.getId()) != null) { return true; } } } return false; } Checkstyle failure here: need a space between product and the colon. Should also pull the method declaration into one line as well.

Target:
private boolean changedProductsInSet(Set<Product> products, Map<String, Product> changedProducts) { if (products != null && changedProducts != null) { for (Product product : products) { if (product != null && changedProducts.get(product.getId()) != null) { return true; } } } return false; }
Source:
public int hashCode() { HashCodeBuilder hcBuilder = new HashCodeBuilder(); hcBuilder.append(releaseVer); return hcBuilder.toHashCode(); START } END Nice, but unnecessary -- HashCodeBuilder in this case is just doing exactly what the original code you replaced does (especially since you're not seeing the builder with a prime value). Just leave this as-is for now.

Target:
public int hashCode() { return this.releaseVer != null ? this.releaseVer.hashCode() : 0; }
Source:
public void deleteSubscription(@PathParam("subscription_id") String subscriptionId) { // Look up master pool by subscription Id Pool master = this.poolManager.getMasterPoolBySubscriptionId(subscriptionId); if (master == null) { throw new NotFoundException( i18n.tr("A subscription with the ID \"{0}\" could not be found.", subscriptionId)); } START this.poolManager.deletePools(Collections.singletonList(master), null); END } This is very minor, but would you mind switching this to ``` this.poolManager.deletePools(Collections.singletonList(master)) ``` so we don't have that superfluous `null` hanging around. I think the functionality should be the same since the one parameter method just delegates to the two parameter method but provides the `null` as the second parameter.

Target:
public void deleteSubscription(@PathParam("subscription_id") String subscriptionId) { // Look up master pool by subscription Id Pool master = this.poolManager.getMasterPoolBySubscriptionId(subscriptionId); if (master == null) { throw new NotFoundException( i18n.tr("A subscription with the ID \"{0}\" could not be found.", subscriptionId)); } this.poolManager.deletePools(Collections.singletonList(master)); }
Source:
START public boolean preProcess(BindContext context) { END for (BindOperation operation : operations) { log.debug("Starting preprocess of {}", operation.getClass().getSimpleName()); if (operation.preProcess(context)) { log.debug("Finished preprocess of {}", operation.getClass().getSimpleName()); } else { log.error("Skipped chain in preprocess of operation {}", operation.getClass().getSimpleName()); return false; } } return true; } method can be protected now (private if not isolated in tests).

Target:
private boolean preProcess(BindContext context) { for (BindOperation operation : operations) { log.debug("Starting preprocess of {}", operation.getClass().getSimpleName()); if (operation.preProcess(context)) { log.debug("Finished preprocess of {}", operation.getClass().getSimpleName()); } else { log.error("Skipped chain in preprocess of operation {}", operation.getClass().getSimpleName()); return false; } } return true; }
Source:
START public boolean execute(BindContext context) { END for (BindOperation operation : operations) { log.debug("Starting execute of {}", operation.getClass().getSimpleName()); if (operation.execute(context)) { log.debug("Finished execute of {}", operation.getClass().getSimpleName()); } else { log.error("Skipped chain execute in operation {}", operation.getClass().getSimpleName()); return false; } } return true; } method can be protected now (private if not isolated in tests).

Target:
private boolean execute(BindContext context) { for (BindOperation operation : operations) { log.debug("Starting execute of {}", operation.getClass().getSimpleName()); if (operation.execute(context)) { log.debug("Finished execute of {}", operation.getClass().getSimpleName()); } else { log.error("Skipped chain execute in operation {}", operation.getClass().getSimpleName()); return false; } } return true; }
Source:
START public void lock(BindContext context) { END log.debug("Requesting locks"); context.lockPools(); log.debug("Successfully achieved locks"); } method can be protected now (private if not isolated in tests).

Target:
private void lock(BindContext context) { log.debug("Requesting locks"); context.lockPools(); log.debug("Successfully achieved locks"); }
Source:
public void regenerateCertificatesOf(String productId, boolean lazy) { if (lazy) { poolCurator.markCertificatesDirtyForProductId(productId); } else { List<Pool> poolsForProduct = this.listAvailableEntitlementPools(null, null, null, productId, new Date(), false, false, new PoolFilterBuilder(), null, false, false) .getPageData(); for (Pool pool : poolsForProduct) { START regenerateCertificatesOf(pool.getEntitlements(), lazy); END } } } We don't need to pass lazy through here, since we already know it's false at this point.

Target:
public void regenerateCertificatesOf(String productId, boolean lazy) { if (lazy) { poolCurator.markCertificatesDirtyForProductId(productId); } else { List<Pool> poolsForProduct = this.listAvailableEntitlementPools(null, null, null, productId, new Date(), false, false, new PoolFilterBuilder(), null, false, false) .getPageData(); for (Pool pool : poolsForProduct) { regenerateCertificatesOf(pool.getEntitlements(), false); } } }
Source:
public boolean deleteForOwner(Owner owner) { String deleteForOwner = "delete from UeberCertificate uc where uc.owner = :owner"; Query query = getEntityManager().createQuery(deleteForOwner); query.setParameter("owner", owner); START return query.executeUpdate() > 0 ? true : false; END } You can just return ```query.executeUpdate() > 0``` here.

Target:
public boolean deleteForOwner(Owner owner) { String deleteForOwner = "delete from UeberCertificate uc where uc.owner = :owner"; Query query = getEntityManager().createQuery(deleteForOwner); query.setParameter("owner", owner); return query.executeUpdate() > 0; }
Source:
public boolean isUeberPool() { START return product.getName().equals(Product.ueberProductNameForOwner(owner)); END } It's unlikely, but product could be null here.

Target:
public boolean isUeberPool() { return product != null && Product.ueberProductNameForOwner(owner).equals(product.getName()); }
Source:
public Map<String, Object> getQueueInfo(String queueName) throws JMSException { log.debug("Getting info about queue {}", queueName); List<Map<String, Object>> mm = runQuery("_object_id", singularMap("_object_name", queueName)); if (mm.size() == 0) { throw new RuntimeException("Couldn't find a queue in Qpid: " + queueName); } if (mm.size() > 1) { throw new RuntimeException("Found unexpected amount of information about queue: " + queueName); } return mm.get(0); START } END This should be private unless there are plans to use it outside the class.

Target:
private Map<String, Object> getQueueInfo(String queueName) throws JMSException { log.debug("Getting info about queue {}", queueName); List<Map<String, Object>> mm = runQuery("_object_id", singularMap("_object_name", queueName)); if (mm.size() == 0) { throw new RuntimeException("Couldn't find a queue in Qpid: " + queueName); } if (mm.size() > 1) { throw new RuntimeException("Found unexpected amount of information about queue: " + queueName); } return mm.get(0); }
Source:
START public static Map<Object, Object> singularMap(Object key, Object value) { END Map<Object, Object> query = new HashMap<Object, Object>(); query.put(key, value); return query; } This should be private unless there are plans to use it outside the class.

Target:
private static Map<Object, Object> singularMap(Object key, Object value) { Map<Object, Object> query = new HashMap<Object, Object>(); query.put(key, value); return query; }
Source:
public void remove(@PathParam("owner_key") String ownerKey, @PathParam("content_id") String contentId) { Owner owner = this.getOwnerByKey(ownerKey); Content content = this.getContent(ownerKey, contentId); if (content.isLocked()) { throw new ForbiddenException(i18n.tr("content \"{1}\" is locked", content.getId())); } START List<Product> affectedProducts = this.contentManager.removeContent(content, owner, true); END } unused collection affectedProducts

Target:
public void remove(@PathParam("owner_key") String ownerKey, @PathParam("content_id") String contentId) { Owner owner = this.getOwnerByKey(ownerKey); Content content = this.getContent(ownerKey, contentId); if (content.isLocked()) { throw new ForbiddenException(i18n.tr("content \"{1}\" is locked", content.getId())); } this.contentManager.removeContent(content, owner, true); }
Source:
public Content setOwners(Collection<Owner> owners) { this.owners.clear(); START if (owners != null) { END this.owners.addAll(owners); } return this; } Shouldn't we perform the null check before trying to call `clear()`?

Target:
public Content setOwners(Collection<Owner> owners) { if (this.owners == null) { this.owners = new HashSet<Owner>(); } this.owners.clear(); if (owners != null) { this.owners.addAll(owners); } return this; }
Source:
public int revokeAllEntitlements(Consumer consumer) { List<Entitlement> entsToDelete = entitlementCurator.listByConsumer(consumer); revokeEntitlements(entsToDelete); START return entsToDelete.size(); END } Why is it not needed to not compute consumer compliance here any more? Unless there is a valid reason, perhaps we could kick off an asynchronous consumer compliance job from #1073 ? Looks like there were two APIs to remove all entitlements of a consumer, one with compliance check and other without, so this was an explicit decision at some point, hence the question

Target:
public int revokeAllEntitlements(Consumer consumer) { return revokeAllEntitlements(consumer, true); }
Source:
public void queueEvent(Event event) { START if (log.isDebugEnabled()) { END log.debug("Queuing event: " + event); } getEventQueue().add(event); } With Logback, we don't need these types of guards. ``` java log.debug("Queing event: {}", event) ``` should do the trick with no penalty in performance.

Target:
public void queueEvent(Event event) { log.debug("Queuing event: " + event); getEventQueue().add(event); }
Source:
public HornetqEventDispatcher(ObjectMapper mapper, Config config) { this.mapper = mapper; try { largeMsgSize = config.getInt(ConfigProperties.HORNETQ_LARGE_MSG_SIZE); factory = createClientSessionFactory(); } catch (HornetQException e) { throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); START } END } Could we consolidate these catch clauses? Or is HornetQException a RuntimeException?

Target:
public HornetqEventDispatcher(ObjectMapper mapper, Config config) { this.mapper = mapper; try { largeMsgSize = config.getInt(ConfigProperties.HORNETQ_LARGE_MSG_SIZE); factory = createClientSessionFactory(); } catch (Exception e) { throw new RuntimeException(e); } }
Source:
public void sendEvent(Event event) { if (log.isDebugEnabled()) { START log.debug("Sending event: " + event); END } try { ClientMessage message = getClientSession().createMessage(true); String eventString = mapper.writeValueAsString(event); message.getBodyBuffer().writeString(eventString); getClientProducer().send(message); } catch (Exception e) { log.error("Error while trying to send event: " + event, e); } } No `if` block required here either.

Target:
public void sendEvent(Event event) { log.debug("Sending event: " + event); try { ClientMessage message = getClientSession().createMessage(true); String eventString = mapper.writeValueAsString(event); message.getBodyBuffer().writeString(eventString); getClientProducer().send(message); } catch (Exception e) { log.error("Error while trying to send event: " + event, e); } }
Source:
public void handleCreated(Event event) { START curator.insert(new BasicDBObject(event.getNewEntity().toMap())); END } This seems a bit hairy, we're deconstructing and reconstructing a hashmap.

Target:
public void handleCreated(Event event) { curator.insert((BasicDBObject) event.getNewEntity()); }
Source:
public List<Report> getReports() { START return new ArrayList<Report>(this.reports.values()); END } Any reason not to use return type Collection<Report> here, then return reports.values()?

Target:
public Collection<Report> getReports() { return this.reports.values(); }
Source:
public String toString() { START return "Pool[id: " + getId() + ", owner: " + ((owner == null) ? "null" : owner.getId()) + END ", product: " + productId + ", quantity: " + getQuantity() + ", expires: " + getEndDate() + "]"; } I think owner has a solid toString, it might be more useful to do something more like this: ``` java return "Pool[id: " + getId() + ", owner: " + owner + ``` May not even need "owner: ", because owner.toString returns ``` java return "Owner [id: " + getId() + ", key: " + getKey() + "]"; ``` but null will be all alone. (that shouldn't happen unless something else is wrong, so we're probably safe allowing it)

Target:
public String toString() { return "Pool[id: " + getId() + ", owner: " + owner + ", product: " + productId + ", quantity: " + getQuantity() + ", expires: " + getEndDate() + "]"; }
Source:
public Consumer(String name, String userName, Owner owner, ConsumerType type) { this(); this.name = name; this.username = userName; this.owner = owner; this.type = type; this.facts = new HashMap<String, String>(); this.installedProducts = new HashSet<ConsumerInstalledProduct>(); this.guestIds = new ArrayList<GuestId>(); this.autoheal = true; START this.serviceLevel = null; END } I wouldn't change this line, by initializing as empty string, we don't have to worry about whether we've just created a Consumer with no serviceLevel in java(null string), vs loaded one with no serviceLevel from the database (empty string). Logically it probably shouldn't make a difference, just scary.

Target:
public Consumer(String name, String userName, Owner owner, ConsumerType type) { this(); this.name = name; this.username = userName; this.owner = owner; this.type = type; this.facts = new HashMap<String, String>(); this.installedProducts = new HashSet<ConsumerInstalledProduct>(); this.guestIds = new ArrayList<GuestId>(); this.autoheal = true; this.serviceLevel = ""; }
Source:
public ToolInstallation installVersion(String version) { autoInstall.check(); START sleep(1000); END control("properties/hudson-tools-InstallSourceProperty/installers/id").select(version); return this; } Is this intended for `master`, or just "temporary" code?

Target:
public ToolInstallation installVersion(String version) { autoInstall.check(); control("properties/hudson-tools-InstallSourceProperty/installers/id").select(version); return this; }
Source:
public void tearDown(Run<?, ?> build, FilePath workspace, Launcher launcher, TaskListener listener) throws IOException, InterruptedException { // null result means success so far. If no logs are found, it's probably because it was simply skipped if (build.getResult() == null) { SonarUtils.addBuildInfoTo(build, installation.getName(), true); } else { SonarUtils.addBuildInfoTo(build, installation.getName(), false); START } END } How about putting the condition in the 3rd param to avoid duplication?

Target:
public void tearDown(Run<?, ?> build, FilePath workspace, Launcher launcher, TaskListener listener) throws IOException, InterruptedException { // null result means success so far. If no logs are found, it's probably because it was simply skipped SonarUtils.addBuildInfoTo(build, installation.getName(), build.getResult() == null); }
Source:
public LauncherSettingsValidator() { START validationRules = new ArrayList<>(); END setupRules(); } Why not do ... ```java validationRules = setupRules(); ```

Target:
private LauncherSettingsValidator() { }
Source:
public void resetTheApp() { resetApp(); appWasReset(); try { START Thread.sleep(10000); END } catch (Throwable t) } Why do we need this sleep?

Target:
public void resetTheApp() { resetApp(); appWasReset(); }
Source:
void retrievePolicyForService(UUID serviceId) throws Throwable { ServicePolicy policy = getDirectoryClient().getServicePolicy(serviceId); START currentServicePolicyEntity = policy == null ? null : ServicePolicyEntity.fromServicePolicy(policy); END } getServicePolicy shouldn't ever return null. Based on how the Python SDK functions we return a policy object every time. In the case that it is in fact empty ({"factors": [], "minimum_requirements": []}), we return a policy with all the minimum_factors set to false or 0.

Target:
void retrievePolicyForService(UUID serviceId) throws Throwable { ServicePolicy policy = getDirectoryClient().getServicePolicy(serviceId); currentServicePolicyEntity = ServicePolicyEntity.fromServicePolicy(policy); }
Source:
void retrievePolicyForService(UUID serviceId) throws Throwable { ServicePolicy policy = client.getServicePolicy(serviceId); START currentServicePolicyEntity = policy == null ? null : ServicePolicyEntity.fromServicePolicy(policy); END } getServicePolicy shouldn't ever return null. Based on how the Python SDK functions we return a policy object every time. In the case that it is in fact empty ({"factors": [], "minimum_requirements": []}), we return a policy with all the minimum_factors set to false or 0.

Target:
void retrievePolicyForService(UUID serviceId) throws Throwable { ServicePolicy policy = client.getServicePolicy(serviceId); currentServicePolicyEntity = ServicePolicyEntity.fromServicePolicy(policy); }
Source:
public static McMMOPlayerProfileLoadEvent callPlayerProfileLoadEvent(Player player, PlayerProfile profile){ START McMMOPlayerProfileLoadEvent e = new McMMOPlayerProfileLoadEvent(player, profile); END mcMMO.p.getServer().getPluginManager().callEvent(e); return e; } not a fan of shorthand one letter variable names, would prefer a descriptive var name instead of a single character

Target:
public static McMMOPlayerProfileLoadEvent callPlayerProfileLoadEvent(Player player, PlayerProfile profile){ McMMOPlayerProfileLoadEvent event = new McMMOPlayerProfileLoadEvent(player, profile); mcMMO.p.getServer().getPluginManager().callEvent(event); return event; }
Source:
public McMMOPlayerBrewEvent(Player player, Block brewingStand) { super(player, SkillType.ALCHEMY); START this.setBrewingStandBlock(brewingStand); END cancelled = false; } For sake of consistency (and my OCD), use <code>this.brewingStand = brewingStand</code> rather than the setter here.

Target:
public McMMOPlayerBrewEvent(Player player, Block brewingStand) { super(player, SkillType.ALCHEMY); this.brewingStand = brewingStand; cancelled = false; }
Source:
public McMMOPlayerCatalysisEvent(Player player, double speed) { super(player, SkillType.ALCHEMY); START this.setSpeed(speed); END cancelled = false; } For sake of consistency (and my OCD), use <code>this.speed = speed</code> rather than the setter here.

Target:
public McMMOPlayerCatalysisEvent(Player player, double speed) { super(player, SkillType.ALCHEMY); this.speed = speed; cancelled = false; }
Source:
public static boolean makeMossy(Block block) { switch (block.getType()) { case COBBLESTONE: case DIRT: START case COBBLE_WALL END return true; case SMOOTH_BRICK: if (block.getData() == 0) { return true; } default: return false; } } This line needs a colon, to make it "case COBBLE_WALL:" I would also like to note that it should have been down lower, with the smooth brick check.

Target:
public static boolean makeMossy(Block block) { switch (block.getType()) { case COBBLESTONE: case DIRT: return true; case SMOOTH_BRICK: case COBBLE_WALL: if (block.getData() == 0) { return true; } default: return false; } }
Source:
public void writeToFile(final File destination) { InputStream input = null; final OutputStream output; try { input = getDataSource().getInputStream(); output = new FileOutputStream(destination); StreamUtil.copy(input, output); } catch (final IOException ioex) { throw new MailException(ioex); } finally { StreamUtil.close(input); START StreamUtil.close(output); END } } Hi, your change will produce a compiler error - see [travis](https://travis-ci.org/oblac/jodd/jobs/632646285). this should work: ``` public void writeToFile(final File destination) { InputStream input = null; OutputStream output = null; try { input = getDataSource().getInputStream(); output = new FileOutputStream(destination); StreamUtil.copy(input, output); } catch (final IOException ioex) { throw new MailException(ioex); } finally { StreamUtil.close(input); StreamUtil.close(output); } } ```

Target:
public void writeToFile(final File destination) { InputStream input = null; OutputStream output = null; try { input = getDataSource().getInputStream(); output = new FileOutputStream(destination); StreamUtil.copy(input, output); } catch (final IOException ioex) { throw new MailException(ioex); } finally { StreamUtil.close(input); StreamUtil.close(output); } }
Source:
private static int zzUnpackAction() { int result = new int[184]; START int offset = 0; END zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result); return result; } You could kill offset and pass 0

Target:
private static int zzUnpackAction() { int result = new int[184]; int offset = 0; offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result); return result; }
Source:
public String toHtmlString() { StringBuilder str = new StringBuilder("<html>"); str.append("&nbsp;name: ").append("<b>") .append(component.getName()).append("</b><br>") .append("&nbsp;class: ").append("<b>") START .append(component.getClass().getName()).append("</b><br>"); END return str.toString(); } return new StringBuilder().append()....toString();

Target:
public String toHtmlString() { return new StringBuilder("<html>").append("&nbsp;name: ") .append("<b>").append(component.getName()) .append("</b><br>").append("&nbsp;class: ").append("<b>") .append(component.getClass().getName()).append("</b><br>") .toString(); }
Source:
public String toString() { StringBuilder sb = new StringBuilder(); START sb.append("jtx{").append(propagationBehavior.toString()).append(',') END .append(readOnlyMode ? "readonly" : "readwrite").append(',') .append(isolationLevel.toString()).append(',').append(timeout) .append('}'); return sb.toString(); } Useless `toString()`, that's what StringBuilder.append(Object) does (just that i's protected against NPE and will print "null").

Target:
public String toString() { return new StringBuilder().append("jtx{").append(propagationBehavior) .append(',').append(readOnlyMode ? "readonly" : "readwrite") .append(',').append(isolationLevel.toString()).append(',') .append(timeout).append('}').toString(); }
Source:
public Family createFamily(User creator) { START return create(creator.getProfileDocument()); END } `creator` may be `null`, this needs a check.

Target:
public Family createFamily(User creator) { return create(creator != null ? creator.getProfileDocument() : null); }
Source:
protected List<String> getCodeFields() { ParameterizedType p = (ParameterizedType) this.getClass().getGenericSuperclass(); START System.out.println(p.getActualTypeArguments()[0]); END return getProperties(); } Why is this printing to stdout?

Target:
protected List<String> getCodeFields() { return getProperties(); }