auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public GenericEdge(GenericEdge copyMe) { this(new GenericVertex(copyMe.source), new GenericVertex(copyMe.target), new HashMap<>(copyMe.getProperties())); }

Target:
Either access the properties via name or method, but don't mix.
Source:
public NodeInfo getNodeInfo() { return this.getProperty(GenericProperties.NODE_INFO); // final Optional<Object> first = graphProperties.getProperties().values().stream().filter(v -> v instanceof NodeInfo).findFirst(); // if (first.isPresent()) { // return (NodeInfo) first.get(); // } // return (NodeInfo) graphProperties.getComputedProperties().values().stream().filter(v -> v instanceof NodeInfo).findFirst().orElse(null); }

Target:
We need to distinguish between computed/enriched and static properties. Either return `null` or `enrichedProperties.getProperty(ComputedProperties.NODE_INFO)`
Source:
public static OnmsTopologyVertex create(String id, String label, String address, String iconKey) { return new OnmsTopologyVertex(Objects.requireNonNull(id, "id is null, cannot create vertex"), label, address, iconKey); }

Target:
Can we put the `Objects.requireNonNull(...)` at the beginning of the method? This makes it easier to read.
Source:
private static Integer sysPropToIntOrNull(String sysProp) { final String val = System.getProperty(sysProp, null); if (val == null) { return null; } try { return Integer.parseInt(val); } catch (NumberFormatException e) { LOG.error("Failed to parse value of system property {}='{}' to an integer. Using default value."); return null; } }

Target:
Missing the substitutions for the `{}`'s. ```suggestion LOG.error("Failed to parse value of system property {}='{}' to an integer. Using default value.", sysProp, val); ```
Source:
public DhcpdImpl() { Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { DhcpdImpl.this.shutdown = true; DhcpdImpl.this.port67Listener.stop(); DhcpdImpl.this.port68Listener.stop(); LOG.debug("Dhcpd terminated successfully."); } })); }

Target:
We should cleanup when the bundle is destroyed rather than using a shutdown hook.
Source:
public DhcpClient(final String macAddress, final boolean relayMode, final String myIpAddress, final boolean extendedMode, final String requestIpAddress, final int timeout, final int retries, final Dhcpd dhcpd) { this.m_macAddress = macAddress; this.m_relayMode = relayMode; this.m_myIpAddress = myIpAddress; this.m_extendedMode = extendedMode; this.m_requestIpAddress = requestIpAddress; this.m_timeout = timeout; this.m_retries = retries; this.m_dhcpd = dhcpd; }

Target:
`this` and `m_` is redundant
Source:
public boolean parseUpdates() { synchronized (m_updates) { if (m_updates.booleanValue()) { m_updates = false; return true; } } return false; }

Target:
No need to call `booleanValue()` here.
Source:
public boolean hasUpdates() { synchronized (m_updates) { if (m_updates.booleanValue()) { return true; } } return false; }

Target:
Can be simplified to `return m_updates`.
Source:
public void onAlarmDeleted(OnmsAlarm alarm) { final Integer alarmId = alarm.getId(); final String reductionKey = alarm.getReductionKey(); forEachListener(l -> l.handleDeletedAlarm(alarmId, reductionKey)); }

Target:
Line 147 and 148 are redundant.
Source:
public boolean equals(Object obj) { if (obj == null) { return false; } if (!(obj instanceof IpServiceEdgeRequestDTO)) { return false; } if (!super.equals(obj)) { return false; } // compare subclass fields return java.util.Objects.equals(applicationId, ((ApplicationEdgeRequestDTO) obj).applicationId); }

Target:
Looks like the class is wrong in this instanceof comparison. Here is the IntelliJ generated equals if you want to just use that ``` @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; ApplicationEdgeRequestDTO that = (ApplicationEdgeRequestDTO) o; return Objects.equals(applicationId, that.applicationId); } ``` ```suggestion if (!(obj instanceof ApplicationEdgeRequestDTO)) { return false; } ```
Source:
public static Set<String> getReductionKeys(final OnmsApplication application) { Objects.requireNonNull(application); Set<String> reductionKeys = new HashSet<>(); for(OnmsMonitoredService monitoredService : application.getMonitoredServices()) { reductionKeys.add(getNodeLostServiceReductionKey(monitoredService)); reductionKeys.add(getInterfaceDownReductionKey(monitoredService)); reductionKeys.add(getNodeDownReductionKey(monitoredService)); } return reductionKeys; }

Target:
Can we not duplicate the next 3 lines of code? Use the `getReductionKeys(OnmsMonitoredService)` method instead.
Source:
public void init() throws ConfigurationResourceException { final ServiceConfiguration config = serviceConfiguration.get(); for (Service service : config.getServices()) { final String name = service.getName().split("=")[1]; // OpenNMS:Name=Manager => Manager this.daemonList.add(new DaemonInfo(name, ignoreList.contains(name), service.isEnabled(), service.isReloadable() /* Internal daemons are not reloadable by default */)); } }

Target:
The member variables in this class are scoped to ```this``` unnecessarily. Not sure if that is a style preference, just pointing it out. Looks like the same is true for a couple other classes in this PR as well.
Source:
public void setRelatedAlarms(Set<OnmsAlarm> alarms) { m_associatedAlarms.clear(); alarms.stream().forEach(relatedAlarm -> m_associatedAlarms.add(new AlarmAssociation(this, relatedAlarm))); }

Target:
```suggestion alarms.forEach(relatedAlarm -> m_associatedAlarms.add(new AlarmAssociation(this, relatedAlarm))); ```
Source:
public void acknowledgeAlarm(OnmsAlarm alarm, Date now) { LOG.info("Acknowledging alarm with id: @ {}", alarm.getId(), now); final OnmsAlarm alarmInTrans = alarmDao.get(alarm.getId()); if (alarmInTrans == null) { LOG.warn("Alarm disappeared: {}. Skipping ack.", alarm); return; } OnmsAcknowledgment ack = new OnmsAcknowledgment(alarm, DEFAULT_USER, now); ack.setAckAction(AckAction.ACKNOWLEDGE); acknowledgmentDao.processAck(ack); }

Target:
We should use the alarm that was retrieved within the transaction i.e.: ```suggestion OnmsAcknowledgment ack = new OnmsAcknowledgment(alarmInTrans, DEFAULT_USER, now); ```
Source:
public void debug(String message, Object... objects) { LOG.warn(message, objects); }

Target:
debug vs warn
Source:
public void providerRegistered(Registration registration, ConfigurationProvider provider) { if (clazz.equals(registration.getProvider(ConfigurationProvider.class).getType())) { if (providers.add(new ConfigurationProviderState<>(provider))) { LOG.debug("Registered configuration provider for {}.", provider, clazz.getCanonicalName()); // Force a check on the next get forceReload = true; } } }

Target:
Eliminate this ```if``` on line 236 and move the condition to the ```if``` with ```&&``` on line 235.
Source:
public WsManAssetAdapterConfig getInstance() { m_config.getReadLock().lock(); try { return m_config; } finally { m_config.getReadLock().unlock(); } }

Target:
I suspect this locking code is not needed. The value of m_config can't change so it should be safe to unconditionally return it here. Delete 108 to 113 and replace with: ```return m_config;```
Source:
public void handleDaemonConfigChanged(final Event event) { DaemonTools.handleReloadEvent(event, "PollerBackEnd", (e)->{ m_pollerBackEnd.configurationUpdated(); }); }

Target:
Can you use the short version of the closure, as it is a one liner, the `{}` are not needed.
Source:
PropertiesHolder(final File file) { this.m_file = file; this.m_properties = null; }

Target:
Is there any reason to add the `this.` prefixes? Seems redundant when the member variables are already prefixed with `m_`.
Source:
public Collection<AlarmFeedback> getFeedback(String situationKey) throws FeedbackException { Gson gson = new Gson(); String query = "{\n" + " \"query\": { \"match\": { \"situation_key\": " + gson.toJson(situationKey) + " } }\n" + "}"; return search(query); }

Target:
The gson instance is thread-safe, so we can declare it as a member variable instead of recreating it everytime here.
Source:
private LinkdHopCriteria(String nodeId, String nodeLabel) { super(nodeLabel); setId(nodeId); m_nodeId = nodeId; }

Target:
why not using the super constructor? `super(nodeId, nodeLabel)`?
Source:
public void setRelatedAlarms(Set<OnmsAlarm> alarms) { this.m_relatedAlarms = alarms; }

Target:
Nit: `this.` is redundant when used with a variable prefixed with `m_`.
Source:
public void testKafkaRpcAtRemoteLocation() throws InterruptedException, ExecutionException { assertNotEquals(REMOTE_LOCATION_NAME, identity.getLocation()); Thread.sleep(5000); EchoRequest request = new EchoRequest("Kafka-RPC"); request.setLocation(REMOTE_LOCATION_NAME); request.setDelay(5000L); EchoResponse expectedResponse = new EchoResponse("Kafka-RPC"); EchoResponse actualResponse = echoClient.execute(request).get(); assertEquals(expectedResponse, actualResponse); }

Target:
Why do we need to sleep for 5 seconds here?
Source:
public DateTimeTag(){ String format = System.getProperty(SYSTEM_PROPERTY_DATE_FORMAT); if(format == null) { this.formatter = DEFAULT_FORMATTER; } else { try { this.formatter = DateTimeFormatter.ofPattern(format).withZone(ZoneId.systemDefault()); } catch (IllegalArgumentException e) { log.log(Level.WARNING, String.format("Can not use System Property %s=%s as dateformat, will fall back to default." + " Please see also java.time.format.DateTimeFormatter for the correct syntax", SYSTEM_PROPERTY_DATE_FORMAT, format) , e); this.formatter = DEFAULT_FORMATTER; } } }

Target:
Is there a particular reason, why we use the `java.util.Logging`instead of the `org.slf4j` logging? The usage of String.format in combination with logging looks odd to me.
Source:
public int getNumThreads() { getReadLock().lock(); try { if (m_config.getNumThreads() <= 0) { return m_config.getNumThreads(); } else { return Runtime.getRuntime().availableProcessors() * 2; } } finally { getReadLock().unlock(); } }

Target:
I think this condition should be opposite.
Source:
public static String getConvoKeyAsJsonString(FlowDocument document) { if (document.isInitiator() == null) { return null; } final ConversationKey convoKey = document.isInitiator() ? egressKeyFor(document) : ingressKeyFor(document); return toJsonString(convoKey); }

Target:
Can we just not call this, if `isInitiator() == null` returns `true`
Source:
public JexlEvaluateFunctions(JexlContext context, JexlEngine jexl){ Preconditions.checkNotNull(context, "JexlContext context"); Preconditions.checkNotNull(jexl, "JexlEngine jexl"); m_context= context; m_jexl = jexl; }

Target:
Just a note, you checkNotNull actually returns the value, so you could do `m_context = Preconditions.checkNotNull(context, ...)` instead of doing this on two lines.
Source:
public String[] marshal(final List<String> value) throws Exception { System.err.println("unmarshal: " + value); if (value == null) return null; return value.stream().map(String::trim).collect(Collectors.toList()).toArray(TYPE); }

Target:
`System.err` -> `LOG.trace`?
Source:
private void restartPoller(final long pollInterval) { LOG.debug("Restarting alarm poller (interval {}s).", pollInterval); if (m_alarmPoller != null) { stopPoller(); } startPoller(pollInterval); }

Target:
Stopping the poller also does check for the poller to be not null. I'd be consistent about this. Either check in stopPoller or before.
Source:
public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || this.getClass() != o.getClass()) { return false; } final GraphMLEdgeStatus that = (GraphMLEdgeStatus) o; return Objects.equal(this.getSeverity(), that.getSeverity()) && Objects.equal(this.getStyleProperties(), that.getStyleProperties()); }

Target:
Is there a particular reason why `getClass()` is used instead of `instanceof`. `instanceof` is less restrictive and may be the better choice.
Source:
public void expand() { try { ui.testCase.setImplicitWait(1, TimeUnit.SECONDS); getElement().findElement(By.xpath("//a[@class='gwt-Anchor icon-plus']")).click(); } catch (NoSuchElementException e) { } finally { ui.testCase.setImplicitWait(); } waitForTransition(); }

Target:
Why do the expand() and collapse() methods catch `NoSuchElementException`? In addition the `waitForTransition()` only makes sense if the element was clicked.
Source:
public DetectRequest buildRequest(String location, InetAddress address, Integer port, Map<String, String> attributes) { return new DetectRequestImpl(address, port); }

Target:
Should we not pass the attributes map here?
Source:
private void reload() throws IOException { final Reader r = new FileReader(ConfigFileConstants.getFile(ConfigFileConstants.EVENTD_CONFIG_FILE_NAME)); m_config = JaxbUtils.unmarshal(EventdConfiguration.class, r); }

Target:
Shouldn't we close the FileReader after the unmarshal? We could also pass the File directly to the JaxbUtils.
Source:
public boolean requiresTransaction() { return tokens.stream().filter(t -> t.requiresTransaction()).findAny().isPresent(); }

Target:
Can we pre-compute this value instead? The `tokens` are immutable and set in the constructor.
Source:
public void scan(ScanContext context) throws InterruptedException { InetAddress agentAddress = context.getAgentAddress("SNMP"); String location = context.getSysLocation(); if (agentAddress == null) { return; } SnmpAgentConfig agentConfig = m_snmpAgentConfigFactory.getAgentConfig(agentAddress, location); SnmpWalker walker = SnmpUtils.createWalker(agentConfig, getName(), createCollectionTracker(context)); walker.start(); walker.waitFor(); }

Target:
The sysLocation (http://www.alvestrand.no/objectid/1.3.6.1.2.1.1.6.html) is not necessarily the same as the node's location.
Source:
private static JAXBContext initOnmsEventParameterContext() { try { return JAXBContext.newInstance(EventParms.class); } catch (JAXBException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }

Target:
Lets re-throw this as a RuntimeException instead.
Source:
public Iterator<IPPollAddress> getExcludingInterator(final Iterator<IPPollAddress> it) { return StreamSupport.stream( Spliterators.spliteratorUnknownSize(it, ORDERED | IMMUTABLE), false ) // Filter out excluded addresses .filter(item -> { return !isExcluded(item.getAddress());}) .iterator(); }

Target:
This can even be shorter: `.filter(item -> !isExcluded(item.getAddress()))`
Source:
public void execute(List<VertexRef> targets, OperationContext operationContext) { if (operationContext != null && operationContext.getGraphContainer() != null) { operationContext.getGraphContainer().getBaseTopology().refresh(); operationContext.getGraphContainer().setDirty(true); operationContext.getGraphContainer().redoLayout(); TopologyUI.getCurrent().markAsDirtyRecursive(); } }

Target:
Can we then also change the TopologyUI auto refresher logic to use the "RedoLayoutOperation" instead? See https://github.com/OpenNMS/opennms/blob/develop/features/topology-map/org.opennms.features.topology.app/src/main/java/org/opennms/features/topology/app/internal/TopologyUI.java#L166
Source:
public void setIsTable(String table) { if ("true".equalsIgnoreCase(table)) { this.m_isTable = true; } else { this.m_isTable = false; } }

Target:
This can be refactored to `m_isTable = "true".equalsIgnoreCase(table)`
Source:
public BsmAdminPageEditWindow openNewDialog(String businessServiceName) throws InterruptedException { findElementById("createButton").click(); wait.until(pageContainsText("Business Service Edit")); // we wait until the edit dialog appears return new BsmAdminPageEditWindow(businessServiceName).name(businessServiceName); }

Target:
Let's remove the `BsmAdminPageEditWindow(String)` constructor.
Source:
public BsmAdminPageEditWindow addAttribute(String key, String value) throws InterruptedException { newAttributeWindow() .key(key) .value(value) .confirm(); wait.until(ExpectedConditions.elementToBeClickable(By.id("addAttributeButton"))); return this; }

Target:
This is kinda a duplicate, as we already wait in the confirm() method or is there a particular reason to wait again for another element?
Source:
public BsmAdminPageAttributeEditWindow value(String value) { findElementById("valueField").clear(); findElementById("valueField").sendKeys(String.valueOf(value)); return this; }

Target:
`value` already is a String, so we do not need `String.valueOf(value)` here.
Source:
public BsmAdminPageEditWindow editAttribute(String key, String value) throws InterruptedException { getSelectWebElement("attributeList").selectByVisibleText(key); editAttributeWindow() .value(value) .confirm(); wait.until(ExpectedConditions.elementToBeClickable(By.id("addAttributeButton"))); return this; }

Target:
This is kinda a duplicate, as we already wait in the confirm() method or is there a particular reason to wait again for another element?
Source:
public MeasurementsService(MeasurementFetchStrategy fetchStrategy, ExpressionEngine expressionEngine, FilterEngine filterEngine) { Preconditions.checkNotNull(fetchStrategy); Preconditions.checkNotNull(expressionEngine); Preconditions.checkNotNull(filterEngine); this.fetchStrategy = fetchStrategy; this.expressionEngine = expressionEngine; this.filterEngine = filterEngine; }

Target:
checkNotNull returns the object, so these lines can be rewritten in the form of: this.fetchStrategy = Preconditions.checkNotNull(fetchStrategy);
Source:
public static ByteSource serializeImage( final BufferedImage bufferedImage, final String mimeType, final int quality ) throws IOException { final byte[] serializedImage; final String format = getFormatByMimeType( mimeType ); if ( quality != 0 ) { serializedImage = writeImage( bufferedImage, format, quality ); } else { serializedImage = writeImage( bufferedImage, format ); } return ByteSource.wrap( serializedImage ); }

Target:
Avoid ByteSource in API. byte[] is ok here
Source:
public void modifyIcon( final ModifyProjectIconParams params ) { callWithUpdateContext( ( () -> { doModifyIcon( params ); LOG.info( "Icon for project updated: " + params.getName() ); return true; } ), params.getName() ); }

Target:
debug.
Source:
public String modifyLanguage( final ModifyLanguageParamsJson params ) { return Optional.ofNullable( doApplyLanguage( params.getName(), params.getLanguage() ) ). map( Locale::toLanguageTag ). orElse( null ); }

Target:
To improve readability return optional from doApplyLanguage
Source:
public ImmutableList<ProjectJson> getProjects() { return projects; }

Target:
Should be List
Source:
public static ProjectReadAccessType from( final String value ) { if ( value.equalsIgnoreCase( PUBLIC.toString() ) ) { return PUBLIC; } else if ( value.equalsIgnoreCase( PRIVATE.toString() ) ) { return PRIVATE; } else if ( value.equalsIgnoreCase( CUSTOM.toString() ) ) { return CUSTOM; } throw new IllegalArgumentException( "Cannot parse ProjectReadAccessType value: " + value ); }

Target:
@vbradnitski the `value` can be `NULL`, will be better to use `PRIVATE.name().equals(value)` or `Objects.equals(PRIVATE.name(), value)`. Also you can use `ProjectReadAccessType.valueOf(...)`
Source:
public ProjectJson create( final MultipartForm form ) throws Exception { final Project project = projectService.create( createParams( form ) ); final ProjectPermissions projectPermissions = getPermissionsFromForm( form ); projectService.modifyPermissions( project.getName(), getPermissionsFromForm( form ) ); return new ProjectJson( project, projectPermissions ); }

Target:
@vbradnitski you can use the `projectPermissions` variable instead of recall the `getPermissionsFromForm( form )` method.
Source:
public ContentAuditLogSupportImpl( final ContentConfig config, @Reference(service = ContentAuditLogExecutor.class) final Executor executor, @Reference AuditLogService auditLogService ) { this.executor = config.auditlog_enabled() ? executor : null; this.auditLogService = auditLogService; }

Target:
Instead of null use `c -> {}` And remove all null checks `if ( executor != null )`
Source:
private void register() { if ( this.clientReg != null ) { return; } this.clientReg = context.registerService( EsClient.class, client, new Hashtable<>() ); this.isRegistered = true; }

Target:
don't pass empty Hashtable. pass null. Then legacy class is not in use and it is a few nanoseconds faster :)
Source:
private Boolean doDelete( final ProjectName projectName ) { final DeleteRepositoryParams params = DeleteRepositoryParams.from( projectName.getRepoId() ); final RepositoryId deletedRepositoryId = this.repositoryService.deleteRepository( params ); return deletedRepositoryId != null; }

Target:
boolean instead of Boolean
Source:
public Certificate getCertificate(String alias) { try { return getUnderlyingKeyStore().getCertificate(alias); } catch (KeyStoreException e) { logger.info("could not retrieve certificate for alias " + alias, e); } return null; }

Target:
better use error/warn log level
Source:
private SSLContext buildSslContext() { SSLContext sslContext = null; try { SSLContextBuilder sslBuilder = sslContextBuilder; if (trustSelfSignCert) { if (sslBuilder != null) { throw new IllegalStateException("Cannot configure both SSLContextBuilder and TrustSelfSignCert"); } // trust any self signed certificate sslBuilder = SSLContexts.custom().loadTrustMaterial(TrustSelfSignedMultiChainStrategy.INSTANCE); } if (sslBuilder != null) { sslContext = sslBuilder.build(); } } catch (Exception e) { e.printStackTrace(); } return sslContext != null ? sslContext : SSLContexts.createDefault(); }

Target:
What is the reason for this validation?
Source:
private static String normAutoRangeValue(Object objectValue) { if (objectValue == null) return null; String value = objectValue.toString(); if ("auto".equals(value)) { return value; } return normRangeValue(objectValue); }

Target:
You don't really need a null check here, using `"auto".equals(objectValue)` is enough, if true return `objectValue.toString()`, otherwise continue on to `normRangeValue`. This can be important in case we decide to handle null values differently, and then we won't have to fix it in both places.
Source:
protected Bitmap doInBackground(String... strings) { Bitmap mIcon11 = null; String url = strings[0]; try { InputStream in = new java.net.URL(url).openStream(); mIcon11 = BitmapFactory.decodeStream(in); } catch (Exception e) { Log.e(TAG, e.getMessage()); } return mIcon11; }

Target:
Could this be more specific (IOException maybe?)
Source:
private void displayAppStateMetadata(int stateKey) { TextView metaDataView = (TextView) findViewById(R.id.text_metadata); metaDataView.setText(""); String metadataStr = "Source: Cloud Save" + '\n' + "State Key: " + stateKey; metaDataView.setText(metadataStr); }

Target:
Do you need to call setText here? it looks like it is being set a couple lines later?
Source:
public void onItemClick(AdapterView<?> adapterView, View view, int position, long listId) { SnapshotMetadata selected = (SnapshotMetadata) adapterView.getItemAtPosition(position); Intent intent = new Intent(Intent.ACTION_DEFAULT); intent.putExtra(SNAPSHOT_METADATA, ( selected).freeze()); if (mConflictId != null) { intent.putExtra(CONFLICT_ID, mConflictId); intent.putExtra(RETRY_COUNT, mRetryCount); } setResult(RESULT_OK, intent); finish(); }

Target:
Strange parentheses here ( selected), maybe this was a cast before?
Source:
protected void onActivityResult(int requestCode, int resultCode, Intent intent) { if (requestCode == RC_SIGN_IN) { mSignInClicked = false; mResolvingConnectionFailure = false; if (resultCode == RESULT_OK) { mGoogleApiClient.connect(); } else { BaseGameUtils.showActivityResultError(this, requestCode, resultCode, R.string.signin_failure, R.string.signin_other_error); } } }

Target:
need to call super.onActivityResult()?
Source:
public void afterEach(ExtensionContext context) throws Exception { BrokerRunningSupport brokerRunning = BROKER_RUNNING_HOLDER.get(); if (brokerRunning != null && brokerRunning.isPurgeAfterEach()) { brokerRunning.purgeTestQueues(); } }

Target:
`Exception` is redundant
Source:
public SimpleRabbitListenerContainerFactory consumerBatchContainerFactory() { SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory(); factory.setConnectionFactory(rabbitConnectionFactory()); factory.setConsumerTagStrategy(consumerTagStrategy()); factory.setBatchListener(true); factory.setContainerConfigurer(container -> { container.setConsumerBatchEnabled(true); container.setDeBatchingEnabled(true); container.setBatchSize(2); }); return factory; }

Target:
Why these two options can't be populated directly by the `SimpleRabbitListenerContainerFactory` when that `etBatchListener(true)` is used?
Source:
protected void doInvokeListener(MessageListener listener, Object data) { Message message = null; try { if (listener instanceof BatchMessageListener) { listener.onMessageBatch((List<Message>) data); } else { message = (Message) data; listener.onMessage(message); } } catch (Exception e) { throw wrapToListenerExecutionFailedExceptionIfNeeded(e, message); } }

Target:
Don't we need to do something slightly opposite? Check for `data instance of `List` and always call `onMessageBatch()` since it is there on the `MessageListener` anyway.
Source:
public void removeBeforePublishPostProcessor(MessagePostProcessor beforePublishPostProcessor) { Assert.notNull(beforePublishPostProcessor, "'beforePublishPostProcessor' cannot be null"); if (this.beforePublishPostProcessors != null) { this.beforePublishPostProcessors.remove(beforePublishPostProcessor); } }

Target:
There is no reason to have this `if`, since we are covered with the previous `Assert.notNull()`. You can return `boolean` removal result though.
Source:
public synchronized int getPendingConfirmsCount() { return this.pendingConfirms.values().stream() .map(Map::size) .mapToInt(Integer::valueOf) .sum(); }

Target:
mapToInt() directly here?
Source:
public int purgeQueue(final String queueName) { return this.rabbitTemplate.execute(channel -> { PurgeOk queuePurged = channel.queuePurge(queueName); if (this.logger.isDebugEnabled()) { logger.debug("Purged queue: " + queueName + ", " + queuePurged); } return queuePurged.getMessageCount(); }); }

Target:
Travis doesn't like this: ``` > Task :spring-rabbit:checkstyleMain [ant:checkstyle] [ERROR] /home/travis/build/spring-projects/spring-amqp/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/core/RabbitAdmin.java:340:33: Reference to instance variable 'logger' needs "this.". [RequireThis] ``` Any chances you can fix and we merge? Thanks
Source:
public void handleRecoveryStarted(Recoverable recoverable) { if (logger.isDebugEnabled()) { logger.debug("Closing an autorecovered channel: " + recoverable); } try { ((Channel) recoverable).close(); } catch (IOException | TimeoutException e) { logger.debug("Error closing an autorecovered channel"); } finally { hasListener.remove(recoverable); } }

Target:
"Error closing" with `debug`? 🤷‍♂️
Source:
public void setEnvironment(Environment environment) { this.propertyValue = environment.getProperty(this.propertyName); Assert.notNull(this.propertyValue, () -> "No property exists with name '" + this.propertyName + "'"); }

Target:
Is it really safe to try to obtain a property from this container callback, which is really call earlier in the application lifecycle?
Source:
public synchronized void setAfterAckCallback(java.util.function.Consumer<Channel> callback) { if (getPendingConfirmsCount() == 0) { callback.accept(this); } else { this.afterAckCallback = callback; } }

Target:
`Assert.notNull()` for the `callback` ?
Source:
public String declareQueue(final Queue queue) { try { return this.rabbitTemplate.execute(channel -> { DeclareOk[] declared = declareQueues(channel, queue); String declaredName = declared.length > 0 ? declared[0].getQueue() : null; if (StringUtils.hasText(declaredName)) { queue.setDeclaredName(declaredName); } return declaredName; }); } catch (AmqpException e) { logOrRethrowDeclarationException(queue, "queue", e); return null; } }

Target:
Looks like this logic is already done in the delegating `declareQueues()`. Isn't it?
Source:
public void addQueues(Queue... queues) { Assert.notNull(queues, "'queues' cannot be null"); Assert.noNullElements(queues, "'queues' cannot contain null elements"); if (isRunning()) { for (Queue queue : queues) { Assert.isTrue(StringUtils.hasText(queue.getName()), "Cannot add broker-named queues dynamically"); } } this.queues.addAll(Arrays.asList(queues)); }

Target:
Why `Asesrt.hasText()` doesn't work here?
Source:
public void setQueueNames(String... queueName) { Assert.noNullElements(queueName, "Queue name(s) cannot be null"); setQueues(Arrays.stream(queueName) .map(n -> new Queue(n)) .collect(Collectors.toList()) .toArray(new Queue[0])); }

Target:
These two guys, can be replaced with a single `toArray(Queue[]::new)` The `map()` above can be also a method reference: `map(Queue::new)`
Source:
public Advice[] getAdviceChain() { return adviceChain; }

Target:
Must be with `this.` Also how about `addAdvices(Advice... advices)` ?
Source:
private Object next() { if (this.iterator == null || !this.iterator.hasNext()) { this.iterator = this.listeners.iterator(); } return this.iterator.next(); }

Target:
I would suggest making this method synchronized
Source:
public String getAdminUri() { if (StringUtils.hasText(this.adminUri)) { return this.adminUri; } else if (!StringUtils.hasText(this.hostName)) { return "http://localhost:15672/api/"; } else { return "http://" + this.hostName + ":15672/api/"; } }

Target:
Can't we cache the result of calculations of this method into the `adminUri`?
Source:
public void fanoutBinding() { FanoutExchange fanoutExchange = new FanoutExchange("f"); Binding binding = BindingBuilder.bind(queue).to(fanoutExchange); assertEquals(fanoutExchange.getName(), binding.getExchange()); assertEquals("", binding.getRoutingKey()); assertEquals(Binding.DestinationType.QUEUE, binding.getDestinationType()); assertEquals(queue.getName(), binding.getDestination()); assertNotNull(binding); }

Target:
Thank you for so fast turnaround @neetkee ! Well, this `assertNotNull()` must be first any way. Otherwise we end up with ``NPE` already on a first `binding.getExchange()`. Please, fix that together with your name to the `@author` list and update for Copyright to the current year - `2002-2017`. After that we will merge it.
Source:
public void addQueues(Queue... queues) { this.addQueueNames(collectQueueNames(queues)); }

Target:
We don't use `this.` on method calls; previous code was bad; we generally clean these up when modifying code.
Source:
public void destroy() throws Exception { for (ConnectionFactory connectionFactory : this.nodeFactories.values()) { ((DisposableBean) connectionFactory).destroy(); } if (this.defaultConnectionFactory instanceof DisposableBean) { ((DisposableBean) this.defaultConnectionFactory).destroy(); } }

Target:
I think for safety and clear code we have to use ` instanceof DisposableBean` here as well
Source:
public Queue replies() { return new AnonymousQueue(new AnonymousQueue.Base64UrlNamingStrategy()); }

Target:
I think we can revert this change already since `AnonymousQueue` is now Base64 by default.
Source:
public AsyncRabbitTemplate(RabbitTemplate template) { Assert.notNull(template, "'template' cannot be null"); this.template = template; this.container = null; this.replyAddress = null; this.directReplyToContainer = new DirectReplyToMessageListenerContainer(this.template.getConnectionFactory()); this.directReplyToContainer.setQueueNames(Address.AMQ_RABBITMQ_REPLY_TO); this.directReplyToContainer.setChannelAwareMessageListener(this); }

Target:
DITO
Source:
public boolean cancel(boolean mayInterruptIfRunning) { if (this.timeoutTask != null) { this.timeoutTask.cancel(true); } AsyncRabbitTemplate.this.pending.remove(this.correlationId); if (RabbitFuture.this.channel != null) { AsyncRabbitTemplate.this.directReplyToContainer.releaseConsumerFor(RabbitFuture.this.channel, false, null); } return super.cancel(mayInterruptIfRunning); }

Target:
`directReplyToContainer` might be `null`. Although I agree that `this.channel` is fully depends of the `AsyncRabbitTemplate.this.directReplyToContainer`, but let's modify it to avoid such a noise: ![potential_npe](https://cloud.githubusercontent.com/assets/1071590/19314869/a6c95d82-9069-11e6-84bb-9f1d6d70714f.png) By the way it would be better to provide some `message` anyway. It is used in the event downstream: ``` consumer.cancelConsumer("Consumer " + this + " canceled due to " + message); ... publishConsumerFailedEvent(eventMessage, true, null); ``` And minor: no need in the `RabbitFuture.` prefix for the `this.channel`
Source:
public void addQueues(Queue... queues) { try { addQueues(Arrays.stream(queues) .map(Queue::getName)); } catch (AmqpIOException e) { throw new AmqpIOException("Failed to add " + queues, e.getCause()); } super.addQueues(queues); }

Target:
DITO for `Arrays.asList()`
Source:
private List<Queue> converteQueueList(List<QueueInfo> queues) { return queues.stream() .map(qi -> convert(qi)) .collect(Collectors.toList()); }

Target:
I'm fairly certain that you could replace all of these with method references. e.g.: `.map(this::convert))`.
Source:
protected ConnectionFactory createRabbitConnectionFactory() { RabbitConnectionFactoryBean factoryBean = new RabbitConnectionFactoryBean(); configureRabbitConnectionFactory(factoryBean); try { factoryBean.afterPropertiesSet(); return factoryBean.getObject(); } catch (Exception e) { LogFactory.getLog("log4j2AppenderErrors").error("Failed to create customized Rabbit ConnectionFactory.", e); return null; } }

Target:
Would you mind explaining this code a bit? I guess it is something global for appenders/loggers problems. Aren't there some public API or constant do not remember this String literal?
Source:
public void sampleConfiguration() { String property = System.getProperty("java.version"); System.out.println(property); ConfigurableApplicationContext context = new AnnotationConfigApplicationContext( EnableRabbitSampleConfig.class, SampleBean.class); testSampleConfiguration(context); }

Target:
I think it is an overhead. I believe you that you have had a good testing around there. Although I'll recheck test tasks with IO during merge.
Source:
protected Address getReplyToAddress(Message request) throws Exception { Address replyTo = request.getMessageProperties().getReplyToAddress(); Address defaultReplyTo = delegatingHandler.getDefaultReplyTo(); if (replyTo == null && defaultReplyTo == null) { throw new AmqpException( "Cannot determine ReplyTo message property value: " + "Request message does not contain reply-to property, " + "and no @SendTo annotation found."); } return replyTo == null ? defaultReplyTo : replyTo; }

Target:
The solution looks weak. I understand that all these classes are the part of the infrastructure and everything is called in the right order, but this filed can be `null`, if we don't call `configureListenerAdapter`
Source:
protected Address getReplyToAddress(Message request) throws Exception { Address replyTo; replyTo = AddressUtils.decodeReplyToAddress(request); if (replyTo == null) { if (this.responseExchange == null) { throw new AmqpException( "Cannot determine ReplyTo message property value: " + "Request message does not contain reply-to property, " + "and no default response Exchange was set."); } replyTo = new Address(this.responseExchange, this.responseRoutingKey); } return replyTo; }

Target:
Why declaration and initialization are splitted ?
Source:
protected Message doSendAndReceive(final String exchange, final String routingKey, final Message message) { if (!this.evaluatedFastReplyTo) { evaluateFastReplyTo(); } if (this.replyQueue == null || this.usingFastReplyTo) { return doSendAndReceiveWithTemporary(exchange, routingKey, message); } else { return doSendAndReceiveWithFixed(exchange, routingKey, message); } }

Target:
I think we need here `synchronized double check`
Source:
private void physicalClose() throws Exception { if (logger.isDebugEnabled()) { logger.debug("Closing cached Channel: " + this.target); } if (this.target == null) { return; } try { this.target.close(); } catch (AlreadyClosedException e) { if (logger.isTraceEnabled()) { logger.trace(this.target + " is already closed"); } } }

Target:
I understand the `isOpen` issue, but why you removed `this.target = null;` ?
Source:
protected int initializeConsumers() { int count = 0; synchronized (this.consumersMonitor) { if (this.consumers == null) { this.consumers = new HashMap<BlockingQueueConsumer, Boolean>(this.concurrentConsumers); cancellationLock.reset(); while (this.consumers.size() < this.concurrentConsumers) { BlockingQueueConsumer consumer = createBlockingQueueConsumer(); this.consumers.put(consumer, true); count++; } } } return count; }

Target:
Why isn't it enough to iterate as it was before? `initializeConsumers()` is called only once - from `doStart()`
Source:
public void setAdminsThatShouldDeclare(AmqpAdmin... admins) { Assert.notNull(admins, "'admins' cannot be null"); if (admins.length > 1) { Assert.noNullElements(admins, "'admins' cannot contain null elements"); } Collection<AmqpAdmin> declaringAdmins = new ArrayList<AmqpAdmin>(); if (admins.length > 0 && !(admins.length == 1 && admins[0] == null)) { declaringAdmins.addAll(Arrays.asList(admins)); } this.declaringAdmins = declaringAdmins; }

Target:
Above you state `A single null argument clears the collection`. It feels a bit weird that you can clear the list with passing `new AmqpAdmin[0]` or `(AmqpAdmin) null` but disallow passing in a straight `null`. It almost makes me look for a utility method _clearAdminsThatShouldDeclare()_. Also, due to the more complicated behavior of Varargs, should we at least add some JavaDoc examples, explaining how to reset the list?
Source:
protected void invokeErrorHandler(Throwable ex) { if (this.errorHandler != null) { this.errorHandler.handleError(ex); } else if (logger.isWarnEnabled()) { logger.warn("Execution of Rabbit message listener failed, and no ErrorHandler has been set.", ex); } else if (logger.isWarnEnabled()) { logger.warn("Execution of Rabbit message listener failed, and no ErrorHandler has been set: " + ex.getClass() + ": " + ex.getMessage()); } }

Target:
Great! You should remove this last else if{...} stanza; it will never be executed because the one above it will run. Thanks.
Source:
public void onClose(int closeCode, String message) { LOGGER.info("onClose( closeCode={}, message={})", connection, message); if (null != closeListener) { closeListener.onClose(closeCode, message, this.session); } if (this.session != null) { this.session.close(); this.session = null; } syncEventBus.unregister(this); asyncEventBus.unregister(this); }

Target:
put this in a finally
Source:
public String treatRequest(String helpRequesterInformations) { System.out.println("police called!"); EmergencyServer.policeWasCalled = true; return RESPONSE_TO_POST_REQUEST; }

Target:
Il reste un sysou de trop!
Source:
public String treatRequest(@PathParam("path") String path) { String emergencyAnswer = null; try { emergencyAnswer = sendingPostResquest(EMERGENCY_URL, A_POST_REQUEST); } catch (Exception e) { // TODO the emergency server is probably no started e.printStackTrace(); } return RESPONSE_TO_POST_REQUEST + emergencyAnswer; }

Target:
C'est vraiment général comme catch. Est-ce que y'a moins de le rendre plus spécifique ?
Source:
public boolean equals(Object o) { return o == this; }

Target:
EqualsVerifierTest for this?
Source:
public void run() { try { // IntegrationTestSuite is run when -Dit.test is not specify in maven command. // IntegrationTestSuite uses the configuration from integration-tests/src/test/resources/testng.xml // which already handle suite onStart and onFinish automatically if (!"IntegrationTestSuite".equals(getSuite().getName())) { SUITE_LISTENER.onStart(getSuite()); } runTests(); } catch (Exception e) { LOG.error(e, ""); throw new RuntimeException(e); } finally { // IntegrationTestSuite uses the configuration from integration-tests/src/test/resources/testng.xml // which already handle suite onStart and onFinish automatically if (!"IntegrationTestSuite".equals(getSuite().getName())) { SUITE_LISTENER.onFinish(getSuite()); } } }

Target:
Seems like neither `SuiteListener.onStart()` nor `runTests()` throw an `Exception`. Is this for logging? I changed `LoggerListener` to print stack trace properly [in my PR](https://github.com/apache/druid/pull/9783/files#diff-8e812fb64c6e87651c2a617561f88729R36) and this probably wouldn't be necessary.
Source:
public void matchRemainder() { matchingRemainder = true; if (condition.isAlwaysFalse()) { currentIterator = extractor.iterable().iterator(); } else if (condition.isAlwaysTrue()) { currentIterator = Collections.emptyIterator(); } else { currentIterator = Iterators.filter( extractor.iterable().iterator(), entry -> entry != null && !matchedKeys.contains(entry.getKey()) ); } nextMatch(); }

Target:
When can `entry` be null?
Source:
public long size() throws IOException { flushIfNeeded(0); // To avoid check the declared IOException never thrown error return writeOutBytes; }

Target:
I think this is cleaner ``` public long size() { return writeOutBytes; } ```
Source:
public Sequence<T> run(QueryPlus<T> queryPlus, ResponseContext responseContext) { //noinspection ObjectEquality if (queryPlus.getQuery() != query) { throw new ISE("Unexpected query received"); } Sequence<T> result = baseRunner.run(queryPlus.withQuery(newQuery), responseContext); return result; }

Target:
Unnecessary change?
Source:
private <T> Query<T> prioritizeAndLaneQuery(Query<T> query, Iterable<Segment> segments) { Set<SegmentServerSelector> segmentServerSelectors = new HashSet<>(); for (Segment s : segments) { segmentServerSelectors.add(new SegmentServerSelector(null, s.getId().toDescriptor())); } return scheduler.prioritizeAndLaneQuery(QueryPlus.wrap(query), segmentServerSelectors); }

Target:
Would you add `@Nullable` to the constructor parameter of `SegmentServerSelector` and `getServer()`?
Source:
public Object get(Object obj) { return super.get(StringUtils.toLowerCase((String) obj)); }

Target:
This breaks the contract of HashMap which allows the key to be null. StringUtils.toLowerCase(null) will throw an NPE
Source:
public void handlesLastPartitionCorrectly() { List<PartialHashSegmentMergeIOConfig> assignedPartitionLocation = ParallelIndexSupervisorTask.createMergeIOConfigs( 10, createPartitionToLocations(count), CREATE_PARTIAL_SEGMENT_MERGE_IO_CONFIG ); assertNoMissingPartitions(count, assignedPartitionLocation); }

Target:
Some ideas for other assertions. 1) Verify that the split is evenly distributed. i.e. we should have 10 tasks with 2 each (for 20), 4 tasks with 3 and 6 tasks with 2 (for 24), etc.
Source:
public static void checkPreJoinableClausesForDuplicatesAndShadowing( final List<PreJoinableClause> preJoinableClauses ) { List<String> prefixes = new ArrayList<>(); for (PreJoinableClause clause : preJoinableClauses) { prefixes.add(clause.getPrefix()); } checkPrefixesForDuplicatesAndShadowing(prefixes); }

Target:
```suggestion private static void checkPreJoinableClausesForDuplicatesAndShadowing( ```
Source:
private String buildMetric(String metric) { final String sanitized = sanitize(metric); if (Strings.isNullOrEmpty(namespacePrefix)) { return sanitized; } else { return StringUtils.format("%s.%s", sanitize(namespacePrefix), sanitized); } }

Target:
I think this can just check `namespacePrefix == null` now
Source:
public InputStream openStream(long offset) throws IOException { try { return azureStorage.getBlobInputStream(offset, containerName, blobPath); } catch (StorageException | URISyntaxException e) { if (AzureUtils.AZURE_RETRY.apply(e)) { throw new IOException("Recoverable exception", e); } log.warn("Exception when opening stream to azure resource, containerName: %s, blobPath: %s, Error: %s", containerName, blobPath, e.getMessage() ); throw new RuntimeException(e); } }

Target:
Should the log level be error instead of warn?
Source:
public static Map<String, AutoScaler> mapAutoscalerByCategory(List<AutoScaler> autoScalers) { Map<String, AutoScaler> result = autoScalers.stream().collect(Collectors.groupingBy( ProvisioningUtil::getAutoscalerCategory, Collectors.collectingAndThen(Collectors.toList(), values -> values.get(0)) )); if (result.size() != autoScalers.size()) { log.warn( "Probably autoscalers with duplicated categories were defined. The first instance of each duplicate category will be used."); } return result; }

Target:
Can we add the check in `DefaultWorkerBehaviorConfig` to ensure autoscalers with duplicate category aren't provided and fail? This is probably a case of user making an error in configuration.
Source:
public ResultSegment<ListBlobItem> listBlobsWithPrefixInContainerSegmented( final String containerName, final String prefix, ResultContinuation continuationToken, int maxResults ) throws StorageException, URISyntaxException { CloudBlobContainer cloudBlobContainer = cloudBlobClient.getContainerReference(containerName); return cloudBlobContainer .listBlobsSegmented( prefix, /* Use flat blob listing here so that we get only blob types and not directories.*/ USE_FLAT_BLOB_LISTING, EnumSet .noneOf(BlobListingDetails.class), maxResults, continuationToken, null, null ); }

Target:
package private `@VisibleForTesting`
Source:
Int2IntListLookupTable(int maxSize, IntFunction<IntList> loader) { this.loader = loader; this.lookup = new IntList[maxSize]; Arrays.fill(lookup, null); }

Target:
I thought Java guaranteed that object arrays will start with all `null`s.
Source:
public void forEach(BiConsumer<Interval, PartitionBoundaries> consumer) { intervalToPartitionBoundaries.forEach(consumer); }

Target:
Can this be private?
Source:
public Appenderator createRealtimeAppenderatorForTask( String taskId, DataSchema schema, AppenderatorConfig config, FireDepartmentMetrics metrics, DataSegmentPusher dataSegmentPusher, ObjectMapper objectMapper, IndexIO indexIO, IndexMerger indexMerger, QueryRunnerFactoryConglomerate conglomerate, DataSegmentAnnouncer segmentAnnouncer, ServiceEmitter emitter, ExecutorService queryExecutorService, JoinableFactory joinableFactory, Cache cache, CacheConfig cacheConfig, CachePopulatorStats cachePopulatorStats ) { realtimeAppenderator = Appenderators.createRealtime( taskId, schema, config, metrics, dataSegmentPusher, objectMapper, indexIO, indexMerger, conglomerate, segmentAnnouncer, emitter, queryExecutorService, NoopJoinableFactory.INSTANCE, cache, cacheConfig, cachePopulatorStats ); return realtimeAppenderator; }

Target:
I think you want to use the `joinableFactory` here?
Source:
public float getFloat() { return foundValue.floatValue(); }

Target:
This can throw an NPE if isNull is true. I can't tell if this is called from a hot loop or not. @clintropolis or @jon-wei might know how we should deal with this. I see this potential NPE in other aggregators as well. If you switch to using a primitive in the class, then all these getters can simply cast the local variable
Source:
private void verifyQuery(String queryResource) throws Exception { String queryResponseTemplate; try { InputStream is = AbstractITBatchIndexTest.class.getResourceAsStream(queryResource); queryResponseTemplate = IOUtils.toString(is, StandardCharsets.UTF_8); } catch (IOException e) { throw new ISE(e, "could not read query file: %s", queryResource); } queryResponseTemplate = StringUtils.replace( queryResponseTemplate, "%%DATASOURCE%%", fullDatasourceName ); queryHelper.testQueriesFromString(queryResponseTemplate, 5); }

Target:
I don't think this will help. The 'timesToRun' number requires ALL of the running to pass. If any one of the running failed then the test will fail. Increasing timesToRun will make the test slower but does not help with retrying intermittent failure. I have a PR to fix this issue at https://github.com/apache/druid/pull/9739 Sorry for the trouble from the intermittent failure.
Source:
public int hashCode() { return Objects.hash(listDelimiter, columns, findColumnsFromHeader, skipHeaderRows); }

Target:
Looks like format is missing in equalsAndHashCode
Source:
public InputStream open() throws IOException { // Get data of the given object and open an input stream final String bucket = uri.getAuthority(); final String key = GoogleUtils.extractGoogleCloudStorageObjectKey(uri); final GoogleByteSource byteSource = new GoogleByteSource(storage, bucket, key); return CompressionUtils.decompress(byteSource.openStream(), uri.toString()); }

Target:
minor: `uri.getPath()` is more appropriate here, since it will return the decoded version, whereas `uri.toString()` URI-encodes everything. It probably won't matter for this particular call site, but still seems like good form to me.