auphong2707/dl4se-code-review-dataset huggingface dataset:
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); START } catch (Exception e) { END Log.e(TAG, e.getMessage()); } return mIcon11; } Could this be more specific (IOException maybe?)

Target:
protected Bitmap doInBackground(String... strings) { Bitmap mIcon11 = null; String url = strings[0]; try { InputStream in = new URL(url).openStream(); mIcon11 = BitmapFactory.decodeStream(in); } catch (IOException e) { Log.e(TAG, e.getMessage()); } return mIcon11; }
Source:
private void displayAppStateMetadata(int stateKey) { TextView metaDataView = (TextView) findViewById(R.id.text_metadata); START metaDataView.setText(""); END String metadataStr = "Source: Cloud Save" + '\n' + "State Key: " + stateKey; metaDataView.setText(metadataStr); } Do you need to call setText here? it looks like it is being set a couple lines later?

Target:
private void displayAppStateMetadata(int stateKey) { TextView metaDataView = (TextView) findViewById(R.id.text_metadata); String metadataStr = "Source: Cloud Save" + '\n' + "State Key: " + stateKey; metaDataView.setText(metadataStr); }
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); START intent.putExtra(SNAPSHOT_METADATA, ( selected).freeze()); END if (mConflictId != null) { intent.putExtra(CONFLICT_ID, mConflictId); intent.putExtra(RETRY_COUNT, mRetryCount); } setResult(RESULT_OK, intent); finish(); } Strange parentheses here ( selected), maybe this was a cast before?

Target:
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(); }
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); } START } END } need to call super.onActivityResult()?

Target:
protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, 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); } } }
Source:
START public void afterEach(ExtensionContext context) throws Exception { END BrokerRunningSupport brokerRunning = BROKER_RUNNING_HOLDER.get(); if (brokerRunning != null && brokerRunning.isPurgeAfterEach()) { brokerRunning.purgeTestQueues(); } } `Exception` is redundant

Target:
public void afterEach(ExtensionContext context) { BrokerRunningSupport brokerRunning = BROKER_RUNNING_HOLDER.get(); if (brokerRunning != null && brokerRunning.isPurgeAfterEach()) { brokerRunning.purgeTestQueues(); } }
Source:
public SimpleRabbitListenerContainerFactory consumerBatchContainerFactory() { SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory(); factory.setConnectionFactory(rabbitConnectionFactory()); factory.setConsumerTagStrategy(consumerTagStrategy()); factory.setBatchListener(true); factory.setContainerConfigurer(container -> { container.setConsumerBatchEnabled(true); START container.setDeBatchingEnabled(true); END container.setBatchSize(2); }); return factory; } Why these two options can't be populated directly by the `SimpleRabbitListenerContainerFactory` when that `etBatchListener(true)` is used?

Target:
public SimpleRabbitListenerContainerFactory consumerBatchContainerFactory() { SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory(); factory.setConnectionFactory(rabbitConnectionFactory()); factory.setConsumerTagStrategy(consumerTagStrategy()); factory.setBatchListener(true); factory.setBatchSize(2); factory.setConsumerBatchEnabled(true); return factory; }
Source:
protected void doInvokeListener(MessageListener listener, Object data) { Message message = null; try { START if (listener instanceof BatchMessageListener) { END listener.onMessageBatch((List<Message>) data); } else { message = (Message) data; listener.onMessage(message); } } catch (Exception e) { throw wrapToListenerExecutionFailedExceptionIfNeeded(e, message); } } 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.

Target:
protected void doInvokeListener(MessageListener listener, Object data) { Message message = null; try { if (data instanceof List) { listener.onMessageBatch((List<Message>) data); } else { message = (Message) data; listener.onMessage(message); } } catch (Exception e) { throw wrapToListenerExecutionFailedExceptionIfNeeded(e, message); } }
Source:
public void removeBeforePublishPostProcessor(MessagePostProcessor beforePublishPostProcessor) { Assert.notNull(beforePublishPostProcessor, "'beforePublishPostProcessor' cannot be null"); START if (this.beforePublishPostProcessors != null) { END this.beforePublishPostProcessors.remove(beforePublishPostProcessor); } } There is no reason to have this `if`, since we are covered with the previous `Assert.notNull()`. You can return `boolean` removal result though.

Target:
public boolean removeBeforePublishPostProcessor(MessagePostProcessor beforePublishPostProcessor) { Assert.notNull(beforePublishPostProcessor, "'beforePublishPostProcessor' cannot be null"); if (this.beforePublishPostProcessors != null) { return this.beforePublishPostProcessors.remove(beforePublishPostProcessor); } return false; }
Source:
public synchronized int getPendingConfirmsCount() { return this.pendingConfirms.values().stream() START .map(Map::size) END .mapToInt(Integer::valueOf) .sum(); } mapToInt() directly here?

Target:
public synchronized int getPendingConfirmsCount() { return this.pendingConfirms.values().stream() .mapToInt(Map::size) .sum(); }
Source:
public int purgeQueue(final String queueName) { return this.rabbitTemplate.execute(channel -> { PurgeOk queuePurged = channel.queuePurge(queueName); if (this.logger.isDebugEnabled()) { START logger.debug("Purged queue: " + queueName + ", " + queuePurged); END } return queuePurged.getMessageCount(); }); } 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

Target:
public int purgeQueue(final String queueName) { return this.rabbitTemplate.execute(channel -> { PurgeOk queuePurged = channel.queuePurge(queueName); if (this.logger.isDebugEnabled()) { this.logger.debug("Purged queue: " + queueName + ", " + queuePurged); } return queuePurged.getMessageCount(); }); }
Source:
public void handleRecoveryStarted(Recoverable recoverable) { if (logger.isDebugEnabled()) { logger.debug("Closing an autorecovered channel: " + recoverable); } try { ((Channel) recoverable).close(); } catch (IOException | TimeoutException e) { START logger.debug("Error closing an autorecovered channel"); END } finally { hasListener.remove(recoverable); } } "Error closing" with `debug`? 🤷‍♂️

Target:
public void handleRecoveryStarted(Recoverable recoverable) { if (logger.isDebugEnabled()) { logger.debug("Closing an autorecovered channel: " + recoverable); } try { ((Channel) recoverable).close(); } catch (IOException | TimeoutException e) { logger.error("Error closing an autorecovered channel", e); } finally { hasListener.remove(recoverable); } }
Source:
public void setEnvironment(Environment environment) { START this.propertyValue = environment.getProperty(this.propertyName); END Assert.notNull(this.propertyValue, () -> "No property exists with name '" + this.propertyName + "'"); } Is it really safe to try to obtain a property from this container callback, which is really call earlier in the application lifecycle?

Target:
public void setEnvironment(Environment environment) { this.environment = environment; }
Source:
public synchronized void setAfterAckCallback(java.util.function.Consumer<Channel> callback) { START if (getPendingConfirmsCount() == 0) { END callback.accept(this); } else { this.afterAckCallback = callback; } } `Assert.notNull()` for the `callback` ?

Target:
public synchronized void setAfterAckCallback(java.util.function.Consumer<Channel> callback) { if (getPendingConfirmsCount() == 0 && callback != null) { callback.accept(this); } else { this.afterAckCallback = 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)) { START queue.setDeclaredName(declaredName); END } return declaredName; }); } catch (AmqpException e) { logOrRethrowDeclarationException(queue, "queue", e); return null; } } Looks like this logic is already done in the delegating `declareQueues()`. Isn't it?

Target:
public String declareQueue(final Queue queue) { try { return this.rabbitTemplate.execute(channel -> { DeclareOk[] declared = declareQueues(channel, queue); return declared.length > 0 ? declared[0].getQueue() : null; }); } catch (AmqpException e) { logOrRethrowDeclarationException(queue, "queue", e); return null; } }
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) { START Assert.isTrue(StringUtils.hasText(queue.getName()), "Cannot add broker-named queues dynamically"); END } } this.queues.addAll(Arrays.asList(queues)); } Why `Asesrt.hasText()` doesn't work here?

Target:
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.hasText(queue.getName(), "Cannot add broker-named queues dynamically"); } } this.queues.addAll(Arrays.asList(queues)); }
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()) START .toArray(new Queue[0])); END } These two guys, can be replaced with a single `toArray(Queue[]::new)` The `map()` above can be also a method reference: `map(Queue::new)`

Target:
public void setQueueNames(String... queueName) { Assert.noNullElements(queueName, "Queue name(s) cannot be null"); setQueues(Arrays.stream(queueName) .map(n -> new Queue(n)) .toArray(Queue[]::new)); }
Source:
public Advice[] getAdviceChain() { START return adviceChain; END } Must be with `this.` Also how about `addAdvices(Advice... advices)` ?

Target:
public Advice[] getAdviceChain() { return this.adviceChain; }
Source:
START private Object next() { END if (this.iterator == null || !this.iterator.hasNext()) { this.iterator = this.listeners.iterator(); } return this.iterator.next(); } I would suggest making this method synchronized

Target:
private synchronized Object next() { if (this.iterator == null || !this.iterator.hasNext()) { this.iterator = this.listeners.iterator(); } return this.iterator.next(); }
Source:
public String getAdminUri() { if (StringUtils.hasText(this.adminUri)) { return this.adminUri; } else if (!StringUtils.hasText(this.hostName)) { return "http://localhost:15672/api/"; } else { START return "http://" + this.hostName + ":15672/api/"; END } } Can't we cache the result of calculations of this method into the `adminUri`?

Target:
public String getAdminUri() { if (!StringUtils.hasText(this.adminUri)) { if (!StringUtils.hasText(this.hostName)) { this.adminUri = "http://localhost:15672/api/"; } else { this.adminUri = "http://" + this.hostName + ":15672/api/"; } } return this.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()); START assertNotNull(binding); END } 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.

Target:
public void fanoutBinding() { FanoutExchange fanoutExchange = new FanoutExchange("f"); Binding binding = BindingBuilder.bind(queue).to(fanoutExchange); assertNotNull(binding); assertEquals(fanoutExchange.getName(), binding.getExchange()); assertEquals("", binding.getRoutingKey()); assertEquals(Binding.DestinationType.QUEUE, binding.getDestinationType()); assertEquals(queue.getName(), binding.getDestination()); }
Source:
public void addQueues(Queue... queues) { START this.addQueueNames(collectQueueNames(queues)); END } We don't use `this.` on method calls; previous code was bad; we generally clean these up when modifying code.

Target:
public final void addQueues(Queue... queues) { addQueueNames(collectQueueNames(queues)); }
Source:
public void destroy() throws Exception { for (ConnectionFactory connectionFactory : this.nodeFactories.values()) { START ((DisposableBean) connectionFactory).destroy(); END } if (this.defaultConnectionFactory instanceof DisposableBean) { ((DisposableBean) this.defaultConnectionFactory).destroy(); } } I think for safety and clear code we have to use ` instanceof DisposableBean` here as well

Target:
public void destroy() throws Exception { for (ConnectionFactory connectionFactory : this.nodeFactories.values()) { if (connectionFactory instanceof DisposableBean) { ((DisposableBean) connectionFactory).destroy(); } } if (this.defaultConnectionFactory instanceof DisposableBean) { ((DisposableBean) this.defaultConnectionFactory).destroy(); } }
Source:
public Queue replies() { START return new AnonymousQueue(new AnonymousQueue.Base64UrlNamingStrategy()); END } I think we can revert this change already since `AnonymousQueue` is now Base64 by default.

Target:
public Queue replies() { return new AnonymousQueue(); }
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()); START this.directReplyToContainer.setQueueNames(Address.AMQ_RABBITMQ_REPLY_TO); END this.directReplyToContainer.setChannelAwareMessageListener(this); } DITO

Target:
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.setChannelAwareMessageListener(this); }
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) { START AsyncRabbitTemplate.this.directReplyToContainer.releaseConsumerFor(RabbitFuture.this.channel, false, END null); } return super.cancel(mayInterruptIfRunning); } `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`

Target:
public boolean cancel(boolean mayInterruptIfRunning) { if (this.timeoutTask != null) { this.timeoutTask.cancel(true); } AsyncRabbitTemplate.this.pending.remove(this.correlationId); if (this.channel != null && AsyncRabbitTemplate.this.directReplyToContainer != null) { AsyncRabbitTemplate.this.directReplyToContainer.releaseConsumerFor(this.channel, false, null); } return super.cancel(mayInterruptIfRunning); }
Source:
public void addQueues(Queue... queues) { try { addQueues(Arrays.stream(queues) .map(Queue::getName)); } catch (AmqpIOException e) { START throw new AmqpIOException("Failed to add " + queues, e.getCause()); END } super.addQueues(queues); } DITO for `Arrays.asList()`

Target:
public void addQueues(Queue... queues) { try { addQueues(Arrays.stream(queues) .map(Queue::getName)); } catch (AmqpIOException e) { throw new AmqpIOException("Failed to add " + Arrays.asList(queues), e.getCause()); } super.addQueues(queues); }
Source:
private List<Queue> converteQueueList(List<QueueInfo> queues) { return queues.stream() START .map(qi -> convert(qi)) END .collect(Collectors.toList()); } I'm fairly certain that you could replace all of these with method references. e.g.: `.map(this::convert))`.

Target:
private List<Queue> converteQueueList(List<QueueInfo> queues) { return queues.stream() .map(this::convert) .collect(Collectors.toList()); }
Source:
protected ConnectionFactory createRabbitConnectionFactory() { RabbitConnectionFactoryBean factoryBean = new RabbitConnectionFactoryBean(); configureRabbitConnectionFactory(factoryBean); try { factoryBean.afterPropertiesSet(); return factoryBean.getObject(); } catch (Exception e) { START LogFactory.getLog("log4j2AppenderErrors").error("Failed to create customized Rabbit ConnectionFactory.", END e); return null; } } 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?

Target:
protected ConnectionFactory createRabbitConnectionFactory() { RabbitConnectionFactoryBean factoryBean = new RabbitConnectionFactoryBean(); configureRabbitConnectionFactory(factoryBean); try { factoryBean.afterPropertiesSet(); return factoryBean.getObject(); } catch (Exception e) { LOGGER.error("Failed to create customized Rabbit ConnectionFactory.", e); return null; } }
Source:
public void sampleConfiguration() { String property = System.getProperty("java.version"); START System.out.println(property); END ConfigurableApplicationContext context = new AnnotationConfigApplicationContext( EnableRabbitSampleConfig.class, SampleBean.class); testSampleConfiguration(context); } 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.

Target:
public void sampleConfiguration() { ConfigurableApplicationContext context = new AnnotationConfigApplicationContext( EnableRabbitSampleConfig.class, SampleBean.class); testSampleConfiguration(context); }
Source:
protected Address getReplyToAddress(Message request) throws Exception { Address replyTo = request.getMessageProperties().getReplyToAddress(); START Address defaultReplyTo = delegatingHandler.getDefaultReplyTo(); END 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; } 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`

Target:
protected Address getReplyToAddress(Message request) throws Exception { Address replyTo = request.getMessageProperties().getReplyToAddress(); Address defaultReplyTo = null; if (delegatingHandler != null) { 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; }
Source:
protected Address getReplyToAddress(Message request) throws Exception { Address replyTo; START replyTo = AddressUtils.decodeReplyToAddress(request); END 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; } Why declaration and initialization are splitted ?

Target:
protected Address getReplyToAddress(Message request) throws Exception { Address 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; }
Source:
protected Message doSendAndReceive(final String exchange, final String routingKey, final Message message) { if (!this.evaluatedFastReplyTo) { START evaluateFastReplyTo(); END } if (this.replyQueue == null || this.usingFastReplyTo) { return doSendAndReceiveWithTemporary(exchange, routingKey, message); } else { return doSendAndReceiveWithFixed(exchange, routingKey, message); } } I think we need here `synchronized double check`

Target:
protected Message doSendAndReceive(final String exchange, final String routingKey, final Message message) { if (!this.evaluatedFastReplyTo) { synchronized(this) { if (!this.evaluatedFastReplyTo) { evaluateFastReplyTo(); } } } if (this.replyQueue == null || this.usingFastReplyTo) { return doSendAndReceiveWithTemporary(exchange, routingKey, message); } else { return doSendAndReceiveWithFixed(exchange, routingKey, message); } }
Source:
private void physicalClose() throws Exception { if (logger.isDebugEnabled()) { logger.debug("Closing cached Channel: " + this.target); } if (this.target == null) { return; } try { START this.target.close(); END } catch (AlreadyClosedException e) { if (logger.isTraceEnabled()) { logger.trace(this.target + " is already closed"); } } } I understand the `isOpen` issue, but why you removed `this.target = null;` ?

Target:
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"); } } finally { 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(); START while (this.consumers.size() < this.concurrentConsumers) { END BlockingQueueConsumer consumer = createBlockingQueueConsumer(); this.consumers.put(consumer, true); count++; } } } return count; } Why isn't it enough to iterate as it was before? `initializeConsumers()` is called only once - from `doStart()`

Target:
protected int initializeConsumers() { int count = 0; synchronized (this.consumersMonitor) { if (this.consumers == null) { cancellationLock.reset(); this.consumers = new HashMap<BlockingQueueConsumer, Boolean>(this.concurrentConsumers); for (int i = 0; i < this.concurrentConsumers; i++) { BlockingQueueConsumer consumer = createBlockingQueueConsumer(); this.consumers.put(consumer, true); count++; } } } return count; }
Source:
public void setAdminsThatShouldDeclare(AmqpAdmin... admins) { START Assert.notNull(admins, "'admins' cannot be null"); END 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; } 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?

Target:
public void setAdminsThatShouldDeclare(AmqpAdmin... admins) { Collection<AmqpAdmin> declaringAdmins = new ArrayList<AmqpAdmin>(); if (admins != null) { if (admins.length > 1) { Assert.noNullElements(admins, "'admins' cannot contain null elements"); } if (admins.length > 0 && !(admins.length == 1 && admins[0] == null)) { declaringAdmins.addAll(Arrays.asList(admins)); } } this.declaringAdmins = declaringAdmins; }
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()); START } END } Great! You should remove this last else if{...} stanza; it will never be executed because the one above it will run. Thanks.

Target:
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); } }
Source:
public void onClose(int closeCode, String message) { LOGGER.info("onClose( closeCode={}, message={})", connection, message); if (null != closeListener) { closeListener.onClose(closeCode, message, this.session); } START if (this.session != null) { END this.session.close(); this.session = null; } syncEventBus.unregister(this); asyncEventBus.unregister(this); } put this in a finally

Target:
public void onClose(int closeCode, String message) { LOGGER.info("onClose( closeCode={}, message={})", connection, message); try { if (null != closeListener) { closeListener.onClose(closeCode, message, this.session); } } finally { if (this.session != null) { this.session.close(); this.session = null; } syncEventBus.unregister(this); asyncEventBus.unregister(this); } }
Source:
public String treatRequest(String helpRequesterInformations) { START System.out.println("police called!"); END EmergencyServer.policeWasCalled = true; return RESPONSE_TO_POST_REQUEST; } Il reste un sysou de trop!

Target:
public String treatRequest(String helpRequesterInformations) { EmergencyServer.policeWasCalled = true; return RESPONSE_TO_POST_REQUEST; }
Source:
public String treatRequest(@PathParam("path") String path) { String emergencyAnswer = null; try { emergencyAnswer = sendingPostResquest(EMERGENCY_URL, A_POST_REQUEST); START } catch (Exception e) { END // TODO the emergency server is probably no started e.printStackTrace(); } return RESPONSE_TO_POST_REQUEST + emergencyAnswer; } C'est vraiment général comme catch. Est-ce que y'a moins de le rendre plus spécifique ?

Target:
public String treatRequest(@PathParam("path") String path) { String emergencyAnswer = null; try { emergencyAnswer = sendingPostResquest(EMERGENCY_URL, A_POST_REQUEST); } catch (IOException e) { e.printStackTrace(); } return RESPONSE_TO_POST_REQUEST + emergencyAnswer; }
Source:
public boolean equals(Object o) { return o == this; START } END EqualsVerifierTest for this?

Target:
public boolean equals(Object o) { return o != null && o.getClass() == this.getClass(); }
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) { START LOG.error(e, ""); END 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()); } } } 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.

Target:
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(); } 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()); } } }
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(), START entry -> entry != null && !matchedKeys.contains(entry.getKey()) END ); } nextMatch(); } When can `entry` be null?

Target:
public void matchRemainder() { matchingRemainder = true; if (condition.isAlwaysFalse()) { currentIterator = extractor.iterable().iterator(); } else if (condition.isAlwaysTrue()) { currentIterator = Collections.emptyIterator(); } else { //noinspection ConstantConditions - entry can not be null because extractor.iterable() prevents this currentIterator = Iterators.filter( extractor.iterable().iterator(), entry -> !matchedKeys.contains(entry.getKey()) ); } nextMatch(); }
Source:
public long size() throws IOException { START flushIfNeeded(0); // To avoid check the declared IOException never thrown error END return writeOutBytes; } I think this is cleaner ``` public long size() { return writeOutBytes; } ```

Target:
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); START return result; END } Unnecessary change?

Target:
public Sequence<T> run(QueryPlus<T> queryPlus, ResponseContext responseContext) { //noinspection ObjectEquality if (queryPlus.getQuery() != query) { throw new ISE("Unexpected query received"); } return baseRunner.run(queryPlus.withQuery(newQuery), responseContext); }
Source:
private <T> Query<T> prioritizeAndLaneQuery(Query<T> query, Iterable<Segment> segments) { Set<SegmentServerSelector> segmentServerSelectors = new HashSet<>(); for (Segment s : segments) { START segmentServerSelectors.add(new SegmentServerSelector(null, s.getId().toDescriptor())); END } return scheduler.prioritizeAndLaneQuery(QueryPlus.wrap(query), segmentServerSelectors); } Would you add `@Nullable` to the constructor parameter of `SegmentServerSelector` and `getServer()`?

Target:
private <T> Query<T> prioritizeAndLaneQuery(Query<T> query, Iterable<Segment> segments) { Set<SegmentServerSelector> segmentServerSelectors = new HashSet<>(); for (Segment s : segments) { segmentServerSelectors.add(new SegmentServerSelector(s.getId().toDescriptor())); } return scheduler.prioritizeAndLaneQuery(QueryPlus.wrap(query), segmentServerSelectors); }
Source:
public Object get(Object obj) { START return super.get(StringUtils.toLowerCase((String) obj)); END } This breaks the contract of HashMap which allows the key to be null. StringUtils.toLowerCase(null) will throw an NPE

Target:
public Object get(Object obj) { return super.get(obj == null ? null : StringUtils.toLowerCase((String) obj)); }
Source:
START public void handlesLastPartitionCorrectly() END { List<PartialHashSegmentMergeIOConfig> assignedPartitionLocation = ParallelIndexSupervisorTask.createMergeIOConfigs( 10, createPartitionToLocations(count), CREATE_PARTIAL_SEGMENT_MERGE_IO_CONFIG ); assertNoMissingPartitions(count, assignedPartitionLocation); } 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.

Target:
public void handlesLastPartitionCorrectly() { List<PartialHashSegmentMergeIOConfig> assignedPartitionLocation = createMergeIOConfigs(); assertNoMissingPartitions(count, assignedPartitionLocation); }
Source:
START public static void checkPreJoinableClausesForDuplicatesAndShadowing( END final List<PreJoinableClause> preJoinableClauses ) { List<String> prefixes = new ArrayList<>(); for (PreJoinableClause clause : preJoinableClauses) { prefixes.add(clause.getPrefix()); } checkPrefixesForDuplicatesAndShadowing(prefixes); } ```suggestion private static void checkPreJoinableClausesForDuplicatesAndShadowing( ```

Target:
private static void checkPreJoinableClausesForDuplicatesAndShadowing( final List<PreJoinableClause> preJoinableClauses ) { List<String> prefixes = new ArrayList<>(); for (PreJoinableClause clause : preJoinableClauses) { prefixes.add(clause.getPrefix()); } checkPrefixesForDuplicatesAndShadowing(prefixes); }
Source:
private String buildMetric(String metric) { final String sanitized = sanitize(metric); START if (Strings.isNullOrEmpty(namespacePrefix)) { END return sanitized; } else { return StringUtils.format("%s.%s", sanitize(namespacePrefix), sanitized); } } I think this can just check `namespacePrefix == null` now

Target:
private String buildMetric(String metric) { final String sanitized = sanitize(metric); if (namespacePrefix == null) { return sanitized; } else { return StringUtils.format("%s.%s", sanitize(namespacePrefix), sanitized); } }
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); } START log.warn("Exception when opening stream to azure resource, containerName: %s, blobPath: %s, Error: %s", END containerName, blobPath, e.getMessage() ); throw new RuntimeException(e); } } Should the log level be error instead of warn?

Target:
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.error("Exception when opening stream to azure resource, containerName: %s, blobPath: %s, Error: %s", containerName, blobPath, e.getMessage() ); throw new RuntimeException(e); } }
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()) { START log.warn( END "Probably autoscalers with duplicated categories were defined. The first instance of each duplicate category will be used."); } return result; } 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.

Target:
public static Map<String, AutoScaler> mapAutoscalerByCategory(List<AutoScaler> autoScalers) { return autoScalers.stream().collect(Collectors.groupingBy( ProvisioningUtil::getAutoscalerCategory, Collectors.collectingAndThen(Collectors.toList(), values -> values.get(0)) )); }
Source:
START public ResultSegment<ListBlobItem> listBlobsWithPrefixInContainerSegmented( END 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 ); } package private `@VisibleForTesting`

Target:
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 ); }
Source:
Int2IntListLookupTable(int maxSize, IntFunction<IntList> loader) { this.loader = loader; this.lookup = new IntList[maxSize]; START Arrays.fill(lookup, null); END } I thought Java guaranteed that object arrays will start with all `null`s.

Target:
Int2IntListLookupTable(int maxSize, IntFunction<IntList> loader) { this.loader = loader; this.lookup = new IntList[maxSize]; }
Source:
START public void forEach(BiConsumer<Interval, PartitionBoundaries> consumer) END { intervalToPartitionBoundaries.forEach(consumer); } Can this be private?

Target:
private void forEach(BiConsumer<Interval, PartitionBoundaries> consumer) { intervalToPartitionBoundaries.forEach(consumer); }
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, START NoopJoinableFactory.INSTANCE, END cache, cacheConfig, cachePopulatorStats ); return realtimeAppenderator; } I think you want to use the `joinableFactory` here?

Target:
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, joinableFactory, cache, cacheConfig, cachePopulatorStats ); return realtimeAppenderator; }
Source:
public float getFloat() { START return foundValue.floatValue(); END } 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

Target:
public float getFloat() { return (float) foundValue; }
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 ); START queryHelper.testQueriesFromString(queryResponseTemplate, 5); END } 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.

Target:
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, 2); }
Source:
public int hashCode() { return Objects.hash(listDelimiter, columns, findColumnsFromHeader, skipHeaderRows); START } END Looks like format is missing in equalsAndHashCode

Target:
public int hashCode() { return Objects.hash(listDelimiter, columns, findColumnsFromHeader, skipHeaderRows, format); }
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); START return CompressionUtils.decompress(byteSource.openStream(), uri.toString()); END } 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.

Target:
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.getPath()); }
Source:
START protected InputSourceReader formattableReader( END InputRowSchema inputRowSchema, InputFormat inputFormat, @Nullable File temporaryDirectory ) throws IOException { return new InputEntityIteratingReader( inputRowSchema, inputFormat, // formattableReader() is supposed to be called in each task that actually creates segments. // The task should already have only one split in parallel indexing, // while there's no need to make splits using splitHintSpec in sequential indexing. createSplits(inputFormat, null).map(split -> new S3Entity(s3Client, split.get())), temporaryDirectory ); } Unit test coverage is missing for this method

Target:
protected InputSourceReader formattableReader( InputRowSchema inputRowSchema, InputFormat inputFormat, @Nullable File temporaryDirectory ) { return new InputEntityIteratingReader( inputRowSchema, inputFormat, // formattableReader() is supposed to be called in each task that actually creates segments. // The task should already have only one split in parallel indexing, // while there's no need to make splits using splitHintSpec in sequential indexing. createSplits(inputFormat, null).map(split -> new S3Entity(s3Client, split.get())), temporaryDirectory ); }
Source:
public Stream<InputSplit> createSplits(InputFormat inputFormat, @Nullable SplitHintSpec splitHintSpec) throws IOException { if (firehoseFactory.isSplittable()) { return ((FiniteFirehoseFactory) firehoseFactory).getSplits(splitHintSpec); } else { START throw new UnsupportedOperationException(); END } } Is supporting unsplittable `Firehose`s future work?

Target:
public Stream<InputSplit> createSplits(InputFormat inputFormat, @Nullable SplitHintSpec splitHintSpec) throws IOException { if (firehoseFactory.isSplittable()) { return firehoseFactory.getSplits(splitHintSpec); } else { throw new UnsupportedOperationException(); } }
Source:
public List<InputRow> parseInputRows(String line) throws IOException, ParseException { final Map<String, Object> zipped = parseLine(line); return Collections.singletonList( START MapInputRowParser.parse( END getInputRowSchema().getTimestampSpec(), getInputRowSchema().getDimensionsSpec(), zipped ) ); } Can you add a version of `MapInputRowParser.parse` that takes an `InputRowSchema` since providing timestamp and dimension specs from it seems like it will be common

Target:
public List<InputRow> parseInputRows(String line) throws IOException, ParseException { final Map<String, Object> zipped = parseLine(line); return Collections.singletonList(MapInputRowParser.parse(getInputRowSchema(), zipped)); }
Source:
default PeekableIntIterator peekableIterator() { START return new PeekableIteratorAdapter(iterator()); END } nit: IntelliJ is complaining about raw types here `return new PeekableIteratorAdapter<>(iterator());`

Target:
default PeekableIntIterator peekableIterator() { return new PeekableIteratorAdapter<>(iterator()); }
Source:
public KafkaRecordSupplier( Map<String, Object> consumerProperties, ObjectMapper sortingMapper ) { this.consumerProperties = consumerProperties; this.sortingMapper = sortingMapper; this.consumer = getKafkaConsumer(); START } END The original constructor can delegate to your new one, i.e.: ```java public KafkaRecordSupplier( Map<String, Object> consumerProperties, ObjectMapper sortingMapper ) { this(consumerProperties, sortingMapper, getKafkaConsumer()); } ```

Target:
public KafkaRecordSupplier( Map<String, Object> consumerProperties, ObjectMapper sortingMapper ) { this(consumerProperties, sortingMapper, getKafkaConsumer(sortingMapper, consumerProperties)); }