auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Object getPayload() { InputStream inputStream; try { inputStream = inputStream(); } catch (IOException e1) { START throw new UncheckedIOException(new SoftEndOfStreamException("Socket closed when getting input stream", e1)); END } try { return getDeserializer() .deserialize(inputStream); } catch (IOException e) { throw new UncheckedIOException(e); } } Can we make a `SoftEndOfStreamException` as an `UncheckedIOException` to avoid this wrapping? i don't mind for other branches, but at least for the `master`. Thanks

Target:
public Object getPayload() { InputStream inputStream; try { inputStream = inputStream(); } catch (IOException e1) { throw new SoftEndOfStreamException("Socket closed when getting input stream", e1); } try { return getDeserializer() .deserialize(inputStream); } catch (IOException e) { throw new UncheckedIOException(e); } }
Source:
public String toString() { return "RSocketConnectedEvent{" + "destination='" + this.destination + '\'' + START ", data=" + Arrays.toString(this.data.asByteBuffer().array()) + END ", requester=" + this.requester + '}'; } I don't think rendering a `byte[]` as a bunch of ints is useful, maybe omit this (or just include the length, perhaps).

Target:
public String toString() { return "RSocketConnectedEvent{" + "destination='" + this.destination + '\'' + ", requester=" + this.requester + '}'; }
Source:
public String toString() { return "RSocketConnectedEvent{" + "destination='" + this.destination + '\'' + START ", data length=" + this.data.asByteBuffer().array().length + END ", requester=" + this.requester + '}'; } This still seems to be a lot of overhead in a `toString()`. Why do we need this `DataBuffer` in the event?

Target:
public String toString() { return "RSocketConnectedEvent{" + "destination='" + this.destination + '\'' + ", requester=" + this.requester + '}'; }
Source:
public <P> HeaderEnricherSpec expirationDateFunction(Function<Message<P>, Object> expirationDateFunction) { START return priorityFunction(expirationDateFunction, null); END } copy/paste

Target:
public <P> HeaderEnricherSpec expirationDateFunction(Function<Message<P>, Object> expirationDateFunction) { return expirationDateFunction(expirationDateFunction, null); }
Source:
private void setupStatsEnabledNamePatterns(IntegrationManagementConfigurer configurer) { START List<String> patterns = new ArrayList<String>(); END String[] statsEnabled = this.attributes.getStringArray("statsEnabled"); for (String managedComponent : statsEnabled) { String pattern = this.environment.resolvePlaceholders(managedComponent); patterns.addAll(Arrays.asList(StringUtils.commaDelimitedListToStringArray(pattern))); } configurer.setEnabledStatsPatterns(patterns.toArray(new String[patterns.size()])); } Please, make this as diamond and there are a couple `patterns.toArray(new String[patterns.size()])` in this class. I guess they are smells on Sonar, so would be great to fix them as well since we are already in this class. Thanks

Target:
private void setupStatsEnabledNamePatterns(IntegrationManagementConfigurer configurer) { List<String> patterns = new ArrayList<>(); String[] statsEnabled = this.attributes.getStringArray("statsEnabled"); for (String managedComponent : statsEnabled) { String pattern = this.environment.resolvePlaceholders(managedComponent); patterns.addAll(Arrays.asList(StringUtils.commaDelimitedListToStringArray(pattern))); } configurer.setEnabledStatsPatterns(patterns.toArray(new String[0])); }
Source:
public String[] getSourceNames() { START return this.sourcesByName.keySet().toArray(new String[this.sourcesByName.size()]); END } Please, fix these kind of smells with an explicit array size. Thanks

Target:
public String[] getSourceNames() { return this.sourcesByName.keySet().toArray(new String[0]); }
Source:
public MessageChannel getDiscardChannel() { START String channelName = this.discardChannelName; END if (channelName != null) { this.discardChannel = getChannelResolver().resolveDestination(channelName); this.discardChannelName = null; } return this.discardChannel; } We should exit early if `this.discardChannel` is not null, no need to store this local variable in that case.

Target:
public MessageChannel getDiscardChannel() { if (this.discardChannel == null) { String channelName = this.discardChannelName; if (channelName != null) { this.discardChannel = getChannelResolver().resolveDestination(channelName); this.discardChannelName = null; } } return this.discardChannel; }
Source:
START public void destroy() { END if (this.roleController != null) { this.roleController.removeLifecycle(this); } } We can't do this - breaking change for anyone that has subclassed and implemented `destroy()`. I suggest we use `// NOSONAR TODO: remove throws in 5.2`, which removing it from our subclasses.

Target:
public void destroy() throws Exception { // NOSONAR TODO: remove throws in 5.2 if (this.roleController != null) { this.roleController.removeLifecycle(this); } }
Source:
public boolean supports(HandlerResult result) { START Assert.notNull(result, "'result' must not be null"); END Object handler = result.getHandler(); return handler instanceof HandlerMethod && WebFluxInboundEndpoint.class.isAssignableFrom(((HandlerMethod) handler).getBeanType()); } I don't think we need this assert; Spring will never call this with a null result.

Target:
public boolean supports(HandlerResult result) { Object handler = result.getHandler(); return handler instanceof HandlerMethod && WebFluxInboundEndpoint.class.isAssignableFrom(((HandlerMethod) handler).getBeanType()); }
Source:
START Message<?> doPoll() { END Message<?> message = this.messageGroupStore.pollMessageFromGroup(this.groupId); this.messageStoreNotFull.signal(); return message; } What happened to this method? Why isn't it a `private` anymore?

Target:
protected Message<?> doPoll() { Message<?> message = this.messageGroupStore.pollMessageFromGroup(this.groupId); this.messageStoreNotFull.signal(); return message; }
Source:
public Set<String> keySet() { Set<String> keys = new HashSet<>(); START keys.addAll(this.jdbcTemplate.queryForList(this.getAllKeysQuery, new Object[]{this.region}, String.class)); END return Collections.unmodifiableSet(keys); } There is this variant to simplify the code here: `queryForList(String sql, Class<T> elementType, @Nullable Object... args)`

Target:
public Set<String> keySet() { Set<String> keys = new HashSet<>(); keys.addAll(this.jdbcTemplate.queryForList(this.getAllKeysQuery, String.class, this.region)); return Collections.unmodifiableSet(keys); }
Source:
protected IntegrationFlowDefinition<?> buildFlow() { START return from((MessageSource<?>) () -> new GenericMessage<>("flowAdapterMessage"), END e -> e.poller(p -> p .trigger(ctx -> this.nextExecutionTime.getAndSet(null)))) .channel(MessageChannels.queue("flowAdapterOutput")); } I wonder if that would better to rename to `fromSupplier()`. And yeah... remove that `from(Supplier)` altogether. Breaking change, agreed, but no choice. I will find this explicit casting style more annoying than removed method. WDYT?

Target:
protected IntegrationFlowDefinition<?> buildFlow() { return from(() -> new GenericMessage<>("flowAdapterMessage"), e -> e.poller(p -> p .trigger(ctx -> this.nextExecutionTime.getAndSet(null)))) .channel(MessageChannels.queue("flowAdapterOutput")); }
Source:
public void shouldShutdownInternalExecutorService() throws Exception { this.initiator.start(); START this.initiator.destroy(); END ExecutorService executorService = (ExecutorService) TestUtils.getPropertyValue(this.initiator, "executorService"); assertTrue(executorService.isShutdown()); } OK. I see what you mean. Good to know 😄

Target:
public void shouldShutdownInternalExecutorService() throws Exception { this.initiator.start(); this.initiator.destroy(); ExecutorService executorService = TestUtils.getPropertyValue(this.initiator, "executorService", ExecutorService.class); assertTrue(executorService.isShutdown()); }
Source:
public UdpServerListeningEvent(UnicastReceivingChannelAdapter adapter, int port) { super(adapter); START Assert.notNull(adapter, "'adapter' cannot be null"); END this.port = port; } We don't need this. See super-super-super class: ``` public EventObject(Object source) { if (source == null) throw new IllegalArgumentException("null source"); this.source = source; } ```

Target:
public UdpServerListeningEvent(UnicastReceivingChannelAdapter adapter, int port) { super(adapter); this.port = port; }
Source:
public void sendAndReceive() { this.input.send(new GenericMessage<String>("foo")); Message<?> message = this.output.receive(100); assertNotNull(message); assertEquals("foo: 1", message.getPayload()); assertEquals(1, count); assertTrue(this.applicationContext.containsBean("annotatedEndpoint.process.serviceActivator")); assertTrue(this.applicationContext.containsBean("annotatedEndpoint2.process.serviceActivator")); START assertTrue(this.applicationContext.containsBean("annotatedEndpoint3.process.serviceActivator")); END } The test isn't full. It doesn't prove that `async` is applied. I'm sure the test will pass even without that `async = "true"`. Please, develop the test-case to reflect the expectations.

Target:
public void sendAndReceive() { this.input.send(new GenericMessage<String>("foo")); Message<?> message = this.output.receive(100); assertNotNull(message); assertEquals("foo: 1", message.getPayload()); assertEquals(1, count); assertTrue(this.applicationContext.containsBean("annotatedEndpoint.process.serviceActivator")); assertTrue(this.applicationContext.containsBean("annotatedEndpoint2.process.serviceActivator")); }
Source:
START public boolean isTransacted() { END return this.transacted; } Do we really need to have all the getters as `public`? When such a component is declared through Java config, we have all the bunch of method to choose. I would agree to have them as `protected`, but `public` reason should be explained at least. Also I assume all the setters must be supplied with JavaDocs.

Target:
protected boolean isTransacted() { return this.transacted; }
Source:
public void in(String in) { START this.latch.countDown(); END if ("nackIt".equals(in)) { throw new RuntimeException("testing auto nack"); } else { this.received = in; } } I think this has to go to the `finally` block, already after `this.received = in;`. Otherwise race condition.

Target:
public void in(String in) { try { if ("nackIt".equals(in)) { throw new RuntimeException("testing auto nack"); } else { this.received = in; } } finally { this.latch.countDown(); } }
Source:
protected MessageGroupPreparedStatementSetter() { this.serializer = new SerializingConverter(); START this.lobHandler = new DefaultLobHandler(); END } Thanks, @meherzad , for update. Well, that's not what I want. I really would like to see them both as `null` here and add null checks to the `setValues()` method around them. This way an implementor may decide to get some other logic for the message to store, e.g. convert to simple string representation. This way (s)he is able to override `setValues()` and don't count with serializer/lobHandler. I think the way with nul checks we somehow minimize the time for the actions under `preparedStatement`.

Target:
protected MessageGroupPreparedStatementSetter() { this.serializer = null; this.lobHandler = null; }
Source:
public void setScanner(DirectoryScanner scanner) { Assert.notNull(scanner, "scanner must not be null"); START this.fileSource.setScanner(scanner); END this.scannerExplicitlySet = true; } The `this.fileSource.setScanner(scanner);` takes care about assert. We don't need this extra.

Target:
public void setScanner(DirectoryScanner scanner) { this.fileSource.setScanner(scanner); this.scannerExplicitlySet = true; }
Source:
public boolean equals(Object o) { if (this == o) return true; START if (o == null || getClass() != o.getClass()) return false; END Foo foo1 = (Foo) o; return Objects.equals(this.foo, foo1.foo); } checkstyle

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Foo foo1 = (Foo) o; return this.foo != null ? this.foo.equals(foo1.foo) : foo1.foo == null; }
Source:
START MessagingTemplate getMessagingTemplate() { END return this.messagingTemplate; } Just curious: what made you to add this method? And if it is here already any way how about to make it `protected` ?

Target:
protected MessagingTemplate getMessagingTemplate() { return this.messagingTemplate; }
Source:
public Session<F> getSession() { if (this.activeTemplateCallbacks.get() > 0) { START return this.contextSessions.get(); END } else { return this.sessionFactory.getSession(); } } Need to check for null.

Target:
public Session<F> getSession() { if (this.activeTemplateCallbacks.get() > 0) { Session<F> session = this.contextSessions.get(); // If no session in the ThreadLocal, no {@code invoke()} in this call stack if (session != null) { return session; } } return this.sessionFactory.getSession(); }
Source:
public TransactionSynchronization create(Object key) { Assert.notNull(key, "'key' must not be null"); START if (!TransactionSynchronizationManager.hasResource(key)) { END DefaultTransactionalResourceSynchronization synchronization = new DefaultTransactionalResourceSynchronization(key); TransactionSynchronizationManager.bindResource(key, synchronization.getResourceHolder()); return synchronization; } return null; } I think it would be cleaner to move this test to the callers rather than this strange return `null` if something's already bound with the key.

Target:
public TransactionSynchronization create(Object key) { Assert.notNull(key, "'key' must not be null"); return new DefaultTransactionalResourceSynchronization(key); }
Source:
public ExpressionEvaluatingRouter(String expressionString) { super(new ExpressionEvaluatingMessageProcessor<Object>(EXPRESSION_PARSER.parseExpression(expressionString))); START setPrimaryExpression(getExpression()); END } Why `this(EXPRESSION_PARSER.parseExpression(expressionString))` doesn't work? And JavaDocs, please

Target:
public ExpressionEvaluatingRouter(String expressionString) { this(EXPRESSION_PARSER.parseExpression(expressionString)); }
Source:
protected AbstractRemoteFileStreamingMessageSource(RemoteFileTemplate<F> template, Comparator<AbstractFileInfo<F>> comparator) { this.remoteFileTemplate = template; this.comparator = comparator; if (JacksonJsonUtils.isJackson2Present()) { START this.objectMapper = JsonObjectMapperProvider.newInstanceBuilder(false).build(); END } else { this.objectMapper = null; } } So, if there is no `jackson`, but is `boon` we fail with the: > Neither jackson-databind.jar, nor boon.jar Because of: ``` else if (boonPresent) { return new BoonJsonObjectMapperBuilder(); } else { throw new IllegalStateException("Neither jackson-databind.jar, nor boon.jar is present in the classpath."); } ``` Why an approach from the `FileSplitter` doesn't work here? ``` JsonObjectMapperProvider.jsonAvailable() ? JsonObjectMapperProvider.newInstance() : null; ``` In other words fallback to `boon` if present and no `jackson`.

Target:
protected AbstractRemoteFileStreamingMessageSource(RemoteFileTemplate<F> template, Comparator<AbstractFileInfo<F>> comparator) { this.remoteFileTemplate = template; this.comparator = comparator; }
Source:
START public void doSetFilter(FileListFilter<F> filter) { END this.filter = filter; } Did you intend to make this `final` ?

Target:
protected final void doSetFilter(FileListFilter<F> filter) { this.filter = filter; }
Source:
AsyncHttpMessageHandlerSpec(Expression uriExpression, AsyncRestTemplate asyncRestTemplate) { this.target = new AsyncHttpRequestExecutingMessageHandler(uriExpression, asyncRestTemplate); this.target.setUriVariableExpressions(this.uriVariableExpressions); START this.target.setHeaderMapper(this.headerMapper); END this.asyncRestTemplate = asyncRestTemplate; } M-m-m. I think we have to move these to assignments to the ctor of super class. And in that case we won't need to make those variables as `protected` to make Sonar Qube angry

Target:
AsyncHttpMessageHandlerSpec(Expression uriExpression, AsyncRestTemplate asyncRestTemplate) { super(new AsyncHttpRequestExecutingMessageHandler(uriExpression, asyncRestTemplate)); this.asyncRestTemplate = asyncRestTemplate; }
Source:
FileState(BufferedWriter writer) { this.writer = writer; this.stream = null; START this.lastFlush = System.currentTimeMillis(); END } `lastFlush` is never updated. Am I missing something? Also I wonder if we should update `MessageFlushPredicate.shouldFlush()` for this new `lastFlush` argument as well.

Target:
FileState(BufferedWriter writer) { this.writer = writer; this.stream = null; }
Source:
public HttpRequestExecutingMessageHandler(String uri) { START this(uri, (RestTemplate) null); END } My IDEA says me that this cast is redundant: ![redundantcast](https://cloud.githubusercontent.com/assets/1071590/22128295/d3cc88a2-de6d-11e6-8104-2aae7c3888ea.png)

Target:
public HttpRequestExecutingMessageHandler(String uri) { this(uri, null); }
Source:
public void setRequestFactory(ClientHttpRequestFactory requestFactory) { if (this.isAsync()) { START throw new IllegalArgumentException("ClientHttpRequestFactory cannot be set in async mode"); END } this.restTemplate.setRequestFactory(requestFactory); } I think we shouldn't be so strict. The `async` mode will be ignored anyway, because this component doesn't return `ListenableFuture`. See `AbstractMessageProducingHandler`: ``` if (this.async && reply instanceof ListenableFuture<?>) { ListenableFuture<?> future = (ListenableFuture<?>) reply; ``` So, we should just silently close our eyes for what user has configured for the `HttpRequestExecutingMessageHandler.async`

Target:
public void setRequestFactory(ClientHttpRequestFactory requestFactory) { this.restTemplate.setRequestFactory(requestFactory); }
Source:
private void publishIdleEvent(long idleTime) { if (this.eventPublisher != null && getFile().exists()) { FileTailingIdleEvent event = new FileTailingIdleEvent(this, this.file, idleTime); this.eventPublisher.publishEvent(event); } else { START logger.info("No publisher for idle event"); END } } This logger doesn't reflect reality any more. We come here even when file doesn't exist. So, we should move `exists` condition inside

Target:
private void publishIdleEvent(long idleTime) { if (this.eventPublisher != null) { if (getFile().exists()) { FileTailingIdleEvent event = new FileTailingIdleEvent(this, this.file, idleTime); this.eventPublisher.publishEvent(event); } } else { logger.info("No publisher for idle event"); } }
Source:
public ConversionService getObject() { ConversionService service = super.getObject(); if (service instanceof GenericConversionService) { ((GenericConversionService) service).removeConvertible(Object.class, Object.class); if (isMongodbIntegrationPresent) { try { Class<?> stringToBasicQueryConverterCls = Class.forName(MONGO_BASIC_QUERY_CONVERTER_CLASS_NAME); START ((GenericConversionService) service).addConverter((GenericConverter) stringToBasicQueryConverterCls.newInstance()); END } catch (Exception ignore) { } } } return service; } No, that's not a solution for us. This is some kind of package tangle just for particular case, when we can just evaluate expression to the `Object` and check its type to `String` or `BasicQuery`. This customization just for the `BasicQuery` use-case in the common `ConversionService` doesn't provide much value and even gives some extra noise. That is much simpler to create `BasicQuery` manually from String SpEL result.

Target:
public ConversionService getObject() { ConversionService service = super.getObject(); if (service instanceof GenericConversionService) { ((GenericConversionService) service).removeConvertible(Object.class, Object.class); } return service; }
Source:
public int getSubscriberCount() { MessageDispatcher dispatcher = getRequiredDispatcher(); if (dispatcher instanceof AbstractDispatcher) { return ((AbstractDispatcher) dispatcher).getHandlerCount(); } START return this.handlerCounter.get(); END } Looks like this counter is always there and since our contract requires the value from the `AbstractSubscribableChannel`, how about to pull `getHandlerCount()` contract to the `MessageDispatcher` directly? Yeah, only for `master`, of course, but still it is my point about this persistent but odd logic. WDYT? Otherwise, yes, there is nothing to complain about and I will merge and cherry-pick

Target:
public int getSubscriberCount() { return getRequiredDispatcher().getHandlerCount(); }
Source:
START public ImapIdleChannelAdapterSpec adviceChain(Advice... adviceChain) { END this.target.setAdviceChain(Arrays.asList(adviceChain)); return this; } Looks like we have missed here `transactional()` option for convenience.

Target:
public ImapIdleChannelAdapterSpec adviceChain(Advice... adviceChain) { this.adviceChain.addAll(Arrays.asList(adviceChain)); return this; }
Source:
START public AbstractConnectionFactorySpec(C connectionFactory) { END this.target = connectionFactory; } Typically I do all the Spec only visible for the factory methods to instantiate. Is there any purpose to let this be created directly from end-user level?

Target:
AbstractConnectionFactorySpec(C connectionFactory) { this.target = connectionFactory; }
Source:
public static UdpOutboundChannelAdapterSpec outboundMulticastAdapter(String destinationExpression) { START return new UdpMulticastOutboundChannelAdapterSpec(destinationExpression); END } I think the return type of the method must be `UdpMulticastOutboundChannelAdapterSpec` as well. Otherwise we don't have access to the `timeToLive()` method from the target code.

Target:
public static UdpMulticastOutboundChannelAdapterSpec outboundMulticastAdapter(String destinationExpression) { return new UdpMulticastOutboundChannelAdapterSpec(destinationExpression); }
Source:
private static boolean rename(File source, File target) throws IOException { Files.move(source.toPath(), target.toPath(), StandardCopyOption.REPLACE_EXISTING); START return true; END } This can return void. We can now remove the `if` from `if(rename...` and the log about falling back to copy/delete in `handleFileMessage()`. Also, the logic in `renameTo()` that deletes an existing file can be removed and the if tests and associated `throw` s can be removed also, since `Files.move` will throw an exception.

Target:
private static void rename(File source, File target) throws IOException { Files.move(source.toPath(), target.toPath(), StandardCopyOption.REPLACE_EXISTING); }
Source:
private void receiveAndSend(JmsTemplate template) { javax.jms.Message request = template.receive(requestQueue7); final javax.jms.Message jmsReply = request; try { template.send(request.getJMSReplyTo(), (MessageCreator) session -> jmsReply); } catch (JmsException e) { } START catch (JMSException e) { END } } We can use `multi-catch` here if we already pursuit modern style :smile: : http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html ![multi-catch](https://cloud.githubusercontent.com/assets/1071590/19704537/f85a84ac-9ad5-11e6-91a6-61c7ed0a9e18.png) Also pay attention how `MessageCreator` cast is redundant. Plus with lambdas we don't need `final` for passed variables. So, this block can be simplified until this: ``` private void receiveAndSend(JmsTemplate template) { javax.jms.Message request = template.receive(requestQueue7); try { template.send(request.getJMSReplyTo(), session -> request); } catch (JmsException | JMSException e) { } } ```

Target:
private void receiveAndSend(JmsTemplate template) { javax.jms.Message request = template.receive(requestQueue7); final javax.jms.Message jmsReply = request; try { template.send(request.getJMSReplyTo(), (MessageCreator) session -> jmsReply); } catch (JmsException | JMSException e) { } }
Source:
public void afterTest() { new TransactionTemplate(this.transactionManager).execute(status -> { final int deletedGroupToMessageRows = jdbcTemplate.update("delete from INT_GROUP_TO_MESSAGE"); final int deletedMessages = jdbcTemplate.update("delete from INT_MESSAGE"); final int deletedMessageGroups = jdbcTemplate.update("delete from INT_MESSAGE_GROUP"); START LOG.info(String.format("Cleaning Database - Deleted Messages: %s, " + END "Deleted GroupToMessage Rows: %s, Deleted Message Groups: %s", deletedMessages, deletedGroupToMessageRows, deletedMessageGroups)); return null; }); } I'm against unconditional logs in tests. Would you mind removing it in the next polishing? Thanks

Target:
public void afterTest() { new TransactionTemplate(this.transactionManager).execute(status -> { this.jdbcTemplate.update("delete from INT_GROUP_TO_MESSAGE"); this.jdbcTemplate.update("delete from INT_MESSAGE"); this.jdbcTemplate.update("delete from INT_MESSAGE_GROUP"); return null; }); }
Source:
START public IntegrationGraphCorsConfigurer(String path, String[] allowedOrigins) { END this.path = path; this.allowedOrigins = allowedOrigins; } Redundant modifier. See Travis report And seems for me the whole class can be `private`.

Target:
private IntegrationGraphCorsConfigurer(String path, String[] allowedOrigins) { this.path = path; this.allowedOrigins = allowedOrigins; }
Source:
public void setReleasePartialSequences(boolean releasePartialSequences) { START if (!this.releaseStrategySet) { END setReleaseStrategy(new SequenceSizeReleaseStrategy()); } this.releasePartialSequences = releasePartialSequences; } `if (!this.releaseStrategySet && releasePartialSequences) {` I don't see reason to override `SimpleSequenceSizeReleaseStrategy` if we are not going to use `releasePartialSequences` feature. At least that is your assertion in the commit message: > Change the aggregator to use a `SimpleSequenceSizeReleaseStrategy` by default, unless > `setReleasePartialSequences(true)`.

Target:
public void setReleasePartialSequences(boolean releasePartialSequences) { if (!this.releaseStrategySet && releasePartialSequences) { setReleaseStrategy(new SequenceSizeReleaseStrategy()); } this.releasePartialSequences = releasePartialSequences; }
Source:
protected Message<?> receiveMessage() { if (this.limitingSource != null) { return this.limitingSource.receive(this.maxFetchSize); } else { START return this.source.receive(); END } } Ha! True. "decouple". That's correct word. It isn't poller responsibility to "fetch" the target system. Although I agree that it would be great to consult "maxFetchSize" from poll to poll. Backpressure ? 😄

Target:
protected Message<?> receiveMessage() { return this.source.receive(); }
Source:
public void testEarlySubscribe() { PublishSubscribeChannel channel = new PublishSubscribeChannel(mock(Executor.class)); try { START channel.subscribe(mock(MessageHandler.class)); END fail("expected Exception"); } catch (IllegalStateException e) { assertThat(e.getMessage(), equalTo("When providing an Executor, you cannot subscribe() until the channel " + "bean is fully initialized by the framework. Do not subscribe in a @Bean definition")); } channel.setBeanFactory(mock(BeanFactory.class)); channel.afterPropertiesSet(); channel.subscribe(mock(MessageHandler.class)); } Mock? You can use pretty simple Lambda: ``` channel.subscribe(m -> {}); ``` :smile:

Target:
public void testEarlySubscribe() { PublishSubscribeChannel channel = new PublishSubscribeChannel(mock(Executor.class)); try { channel.subscribe(m -> { }); channel.setBeanFactory(mock(BeanFactory.class)); channel.afterPropertiesSet(); fail("expected Exception"); } catch (IllegalStateException e) { assertThat(e.getMessage(), equalTo("When providing an Executor, you cannot subscribe() until the channel " + "bean is fully initialized by the framework. Do not subscribe in a @Bean definition")); } }
Source:
public static <T> MessageBuilder<T> fromMessage(Message<T> message) { Assert.notNull(message, "message must not be null"); if (message instanceof CloneableMessage) { return ((CloneableMessage<T>) message).cloneMessage(); } else { return new MessageBuilder<T>(message.getPayload(), message); START } END } Perhaps this logic should be in `DefaultMessageBuilderFactory` instead?

Target:
public static <T> MessageBuilder<T> fromMessage(Message<T> message) { Assert.notNull(message, "message must not be null"); return new MessageBuilder<T>(message.getPayload(), message); }
Source:
public Map<String, Object> getProperties() { START return this.properties; END } M-m-m. Can't we simplify the life for Jackson and for client afterward and return `null` here if `properties` is empty? I'm sure that we will add eventually more and more here, but there may be some cases when it is still empty.

Target:
public Map<String, Object> getProperties() { return this.properties.size() == 0 ? null : this.properties; }
Source:
public Map<String, Object> getProperties() { START return this.properties == null ? null : this.properties; END } ??? ``` private final Map<String, Object> properties = new HashMap<String, Object>(); ``` So, it can't be `null`. My idea was like: ``` return this.properties.isEmpty() ? null : this.properties; ```

Target:
public Map<String, Object> getProperties() { return this.properties.size() == 0 ? null : this.properties; }
Source:
START public static SessionFactory<FTPFile> ftpSessionFactory() { END return FtpStreamingMessageSourceTests.sessionFactory(); } Why these two beans are `static`? Looks like is just overhead. Although it isn't critical. Never mind

Target:
public SessionFactory<FTPFile> ftpSessionFactory() { return FtpStreamingMessageSourceTests.sessionFactory(); }
Source:
public MessageChannel getInputChannel() { START return this.inputChannel == null ? null : this.inputChannel; END } Overdid: if `null`, return `null` :smile: From other side it can't be `null`. See ctor: ``` Assert.notNull(inputChannel, "inputChannel must not be null"); ```

Target:
public MessageChannel getInputChannel() { return this.inputChannel; }
Source:
private MessageProducerNode producerNode(String name, MessageProducerSupport producer) { MessageChannel outputChannel = producer.getOutputChannel(); START String outputChannelName = outputChannel == null ? "__unknown__" : outputChannel.toString(); END return new MessageProducerNode(this.nodeId.incrementAndGet(), name, producer, outputChannelName); } Is it still good that we have here this weird placeholder? I thought we agreed that `MessageProducerSupport.afterSingletonsInstantiated()` fixes the problem and we don't have `null` here anymore.

Target:
private MessageProducerNode producerNode(String name, MessageProducerSupport producer) { MessageChannel outputChannel = producer.getOutputChannel(); return new MessageProducerNode(this.nodeId.incrementAndGet(), name, producer, outputChannel.toString()); }
Source:
public void setExtractPayload(boolean extractPayload) { if (this.payloadExpression == null) { setPayloadExpression(extractPayload ? EXPRESSION_PARSER.parseExpression("payload") : EXPRESSION_PARSER.parseExpression("#this")); START } END } Perhaps it's time to port `FunctionExpression` from the DSL ?

Target:
public void setExtractPayload(boolean extractPayload) { if (this.payloadExpression == null) { setPayloadExpression(extractPayload ? null : EXPRESSION_PARSER.parseExpression("#this")); } }
Source:
START public void setTaskScheduler(TaskScheduler taskScheduler) { END Assert.notNull(taskScheduler, "taskScheduler must not be null"); this.taskScheduler = taskScheduler; } Maybe it would be better to override this method to `public` like it is in the `AbstractCorrelatingMessageHandler`, for example? It really smells a bit to publish such kind of options in the `IntegrationObjectSupport`...

Target:
protected void setTaskScheduler(TaskScheduler taskScheduler) { Assert.notNull(taskScheduler, "taskScheduler must not be null"); this.taskScheduler = taskScheduler; }
Source:
protected void doStart() { Assert.state(this.outputChannel != null || StringUtils.hasText(this.outputChannelName), "'outputChannel' or 'outputChannelName' is required"); if (this.outputChannelName != null) { START synchronized (this) { END if (this.outputChannelName != null) { this.outputChannel = getChannelResolver().resolveDestination(this.outputChannelName); this.outputChannelName = null; } } } } This is redundant. We are protected with the `lifecycleLock` in the `AbstractEndpoint.start()`

Target:
protected void doStart() { Assert.state(this.outputChannel != null || StringUtils.hasText(this.outputChannelName), "'outputChannel' or 'outputChannelName' is required"); if (this.outputChannelName != null) { this.outputChannel = getChannelResolver().resolveDestination(this.outputChannelName); } }
Source:
protected void doStop() { try { this.active = false; START this.lifecycleCondition.await(Math.min(this.stopTimeout, this.receiveTimeout), TimeUnit.MILLISECONDS); END } catch (InterruptedException e) { logger.debug("Thread interrupted while stopping the endpoint"); Thread.currentThread().interrupt(); } finally { this.listening = false; } } I think you might have misunderstood me; my point is that we really shouldn't block in `stop()` at all; we should be overriding `doStop(Runnable callback)` return, and invoke the callback after the listener has stopped. Also, I noticed that the gateway is not invoking `super.doStop()` so the `replyMessageCorrelator` is not stopped. Same problem with `doStart()`.

Target:
protected void doStop() { super.doStop(); this.active = this.listening = false; }
Source:
public void handleTransportError(StompSession session, Throwable exception) { if (exception instanceof ConnectionLostException) { this.session = null; AbstractStompSessionManager.this.connected = false; START scheduleReconnect(); END } synchronized (this.delegates) { for (StompSessionHandler delegate : this.delegates) { delegate.handleTransportError(session, exception); } } } `ApplicationEvent` here too?

Target:
public void handleTransportError(StompSession session, Throwable exception) { if (exception instanceof ConnectionLostException) { this.session = null; scheduleReconnect(exception); } synchronized (this.delegates) { for (StompSessionHandler delegate : this.delegates) { delegate.handleTransportError(session, exception); } } }
Source:
public Object fromMessage(Message<?> message, Class<?> targetClass) { try { Message<?> mm = MutableMessageBuilder.fromMessage(message).build(); START return this.codec.encode(mm); END } catch (IOException e) { throw new MessagingException(message, e); } } I'd like to understand the reason of this extra `MutableMessage` creation object before encoding...

Target:
public Object fromMessage(Message<?> message, Class<?> targetClass) { try { return this.codec.encode(message); } catch (IOException e) { throw new MessagingException(message, e); } }
Source:
private void register(Kryo kryo, Registration registration) { int id = registration.getId(); Registration existing = kryo.getRegistration(id); if (existing != null) { START throw new SerializationFailedException((String.format("registration already exists %s", existing))); END } if (log.isInfoEnabled()) { log.info(String.format("registering %s with serializer %s", registration, registration.getSerializer().getClass() .getName())); } kryo.register(registration); } ??? Do we really do the `registerType()` during serialization operation ?

Target:
private void register(Kryo kryo, Registration registration) { int id = registration.getId(); Registration existing = kryo.getRegistration(id); if (existing != null) { throw new RuntimeException((String.format("registration already exists %s", existing))); } if (log.isInfoEnabled()) { log.info(String.format("registering %s with serializer %s", registration, registration.getSerializer().getClass() .getName())); } kryo.register(registration); }
Source:
public FileKryoRegistrar() { START super(); END this.registrationId = DEFAULT_REGISTRATION_ID; } Unnecessary

Target:
public FileKryoRegistrar() { this.registrationId = DEFAULT_REGISTRATION_ID; }
Source:
public StoredProcExecutor(DataSource dataSource) { Assert.notNull(dataSource, "dataSource must not be null."); this.dataSource = dataSource; if (!guavaPresent) { START this.jdbcCallOperationsMap = new LinkedHashMap<String, SimpleJdbcCallOperations>() { END @Override protected boolean removeEldestEntry(Entry<String, SimpleJdbcCallOperations> eldest) { return size() > jdbcCallOperationsCacheSize; } }; } else { this.jdbcCallOperationsMap = null; } } `SuppressWarnings("serial")` Also, you need to use ``` new LinkedHashMap<String, SimpleJdbcCallOperations>(this.jdbcCallOperationsCacheSize + 1, 0.75f, true) {...} ``` to enable LRU processing.

Target:
public StoredProcExecutor(DataSource dataSource) { Assert.notNull(dataSource, "dataSource must not be null."); this.dataSource = dataSource; }
Source:
public boolean removeInterceptor(ChannelInterceptor interceptor) { boolean removed = super.removeInterceptor(interceptor) && interceptor instanceof ExecutorChannelInterceptor && this.executorInterceptors.remove(interceptor); if (removed) { this.executorInterceptorsSize--; return true; } else { START return false; END } } Should be true if not an exec. inter. and super.remove() was successful

Target:
public boolean removeInterceptor(ChannelInterceptor interceptor) { boolean removed = super.removeInterceptor(interceptor); if (removed && interceptor instanceof ExecutorChannelInterceptor) { this.executorInterceptorsSize--; } return removed; }
Source:
public void setLoggingEnabled(boolean enabled) { START delegate.setLoggingEnabled(enabled); END } Minor: should be with `this.`, but anyway...

Target:
public void setLoggingEnabled(boolean enabled) { this.delegate.setLoggingEnabled(enabled); }
Source:
public boolean remove(ChannelInterceptor interceptor) { this.size--; START return this.interceptors.remove(interceptor); END } This is a bug! The requested `interceptor` might not be in the list, so we should decrement only if `true` from `remove()`.

Target:
public boolean remove(ChannelInterceptor interceptor) { if (this.interceptors.remove(interceptor)) { this.size--; return true; } else { return false; } }
Source:
public void configure() throws Exception { MongoDbFactory mongoDbFactory = this.prepareMongoFactory(DEFAULT_COLLECTION_NAME); START MongoTemplate template = new MongoTemplate(mongoDbFactory); END store = new MongoDbMetadataStore(template); } Since we have already `MongoDbFactory` ctor this extra `MongoTemplate` variable is redundant

Target:
public void configure() throws Exception { final MongoDbFactory mongoDbFactory = this.prepareMongoFactory(DEFAULT_COLLECTION_NAME); store = new MongoDbMetadataStore(mongoDbFactory); }
Source:
public void testReplace() throws Exception{ boolean removedValue = store.replace(file1, file1Id, "4567"); assertFalse(removedValue); START END String fileID = store.putIfAbsent(file1, file1Id); assertNull(fileID); removedValue = store.replace(file1, file1Id, "4567"); assertTrue(removedValue); } I think here must be `store.get(file1)` to be sure that the `replace` hasn't affected the collection.

Target:
public void testReplace() throws Exception { boolean removedValue = store.replace(file1, file1Id, "4567"); assertFalse(removedValue); String fileID = store.get(file1); assertNull(fileID); fileID = store.putIfAbsent(file1, file1Id); assertNull(fileID); removedValue = store.replace(file1, file1Id, "4567"); assertTrue(removedValue); fileID = store.get(file1); assertNotNull(fileID); assertEquals("4567", fileID); }
Source:
public void testRemove() throws Exception{ String fileID = store.remove(file1); assertNull(fileID); fileID = store.putIfAbsent(file1, file1Id); assertNull(fileID); fileID = store.remove(file1); assertNotNull(fileID); START assertEquals(file1Id, fileID); END } And `get` in the end to check that there is nothing in the collection on the matter.

Target:
public void testRemove() throws Exception { String fileID = store.remove(file1); assertNull(fileID); fileID = store.putIfAbsent(file1, file1Id); assertNull(fileID); fileID = store.remove(file1); assertNotNull(fileID); assertEquals(file1Id, fileID); fileID = store.get(file1); assertNull(fileID); }
Source:
public MongoDbMetadataStore(MongoDbFactory factory, String collectionName) { Assert.notNull(factory, "'factory' must not be null."); Assert.hasText(collectionName, "'collectionName' must not be empty."); template = new MongoTemplate(factory); START this.collectionName = collectionName; END } `MongoTemplate` takes care about `factory` assert. Hence they are redundant here and this ctor must be like: ``` this(new MongoTemplate(factory), collectionName); ``` That's all!

Target:
public MongoDbMetadataStore(MongoDbFactory factory, String collectionName) { this(new MongoTemplate(factory), collectionName); }
Source:
public void enableStats(boolean statsEnabled) { if (statsEnabled) { this.countsEnabled = true; } this.statsEnabled = statsEnabled; START if (this.channelMetrics != null) { END this.channelMetrics.setFullStatsEnabled(statsEnabled); } } Redundant `null check`

Target:
public void enableStats(boolean statsEnabled) { if (statsEnabled) { this.countsEnabled = true; } this.statsEnabled = statsEnabled; this.channelMetrics.setFullStatsEnabled(statsEnabled); }
Source:
ContainerNode<?> asJson(Object target) throws AccessException { if (target instanceof String) { try { JsonNode json = this.objectMapper.readTree((String) target); return assertContainerNode(json); } catch (JsonProcessingException e) { throw new AccessException("Exception while trying to deserialize String", e); } catch (IOException e) { throw new AccessException("Exception while trying to deserialize String", e); } } else { START throw new IllegalStateException("Can't happen. Check SUPPORTED_CLASSES"); END } } Something wrong is here, because `getSpecificTargetClasses()` returns `null`

Target:
ContainerNode<?> asJson(Object target) throws AccessException { if (target instanceof String) { try { JsonNode json = this.objectMapper.readTree((String) target); return assertContainerNode(json); } catch (IOException e) { throw new AccessException("Exception while trying to deserialize String", e); } } else { throw new IllegalStateException("Can't happen. Check SUPPORTED_CLASSES"); } }
Source:
public RFC5424MessageConverter() { START this.parser = new RFC5424SyslogParser(); END } `this(new RFC5424SyslogParser());` However it is minor and we can live with this one as well

Target:
public RFC5424MessageConverter() { this(new RFC5424SyslogParser()); }
Source:
public void testGatewayScatterGather() { Message<?> bestQuoteMessage = this.gateway.exchange(new GenericMessage<String>("foo")); Object payload = bestQuoteMessage.getPayload(); assertThat(payload, instanceOf(List.class)); START assertThat(((List) payload).size(), greaterThanOrEqualTo(1)); END } `(List<?>)` (3 places)

Target:
public void testGatewayScatterGather() { Message<?> bestQuoteMessage = this.gateway.exchange(new GenericMessage<String>("foo")); Object payload = bestQuoteMessage.getPayload(); assertThat(payload, instanceOf(List.class)); assertThat(((List<?>) payload).size(), greaterThanOrEqualTo(1)); }
Source:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ToStringFriendlyJsonNode that = (ToStringFriendlyJsonNode) o; START return !(node != null ? !node.equals(that.node) : that.node != null); END } I think node can't be null

Target:
public boolean equals(Object o) { return this == o || !(o == null || getClass() != o.getClass()) && this.node.equals(((ToStringFriendlyJsonNode) o).node); }
Source:
START public Folder getFolder() { END return this.folder; } The purpose to publicate it ?

Target:
protected Folder getFolder() { return this.folder; }
Source:
public void setHeadersMap(Map<String, String> headers) { Assert.notNull(headers); HttpHeaders httpHeaders = new HttpHeaders(); START for (String key : headers.keySet()) { END String value = headers.get(key); String[] values = StringUtils.commaDelimitedListToStringArray(value); for (String v : values) { httpHeaders.add(key, v); } } setHeaders(httpHeaders); } Use `entrySet()`

Target:
public void setHeadersMap(Map<String, String> headers) { Assert.notNull(headers); HttpHeaders httpHeaders = new HttpHeaders(); for (Map.Entry<String, String> entry : headers.entrySet()) { String[] values = StringUtils.commaDelimitedListToStringArray(entry.getValue()); for (String v : values) { httpHeaders.add(entry.getKey(), v); } } setHeaders(httpHeaders); }
Source:
START public long getSendCount() { END return sendCount.get(); } We can't make breaking changes like this in a point release (cherry-picks). I think we have no choice but to add methods such as `getSendCountAsLong()`. And perhaps it makes sense to retain the int versions anyway for those users that don't need long precision.

Target:
public int getSendCount() { return (int) sendCount.get(); }
Source:
protected Collection<MessageChannel> determineTargetChannels(Message<?> message) { List<MessageChannel> channels = new ArrayList<MessageChannel>(); START ConcurrentLinkedQueue<Recipient> recipientList = this.recipients; END for (Recipient recipient : recipientList) { if (recipient.accept(message)) { channels.add(recipient.getChannel()); } } return channels; } Not sure, if this scope variable is needed anymore. `Concurrent...` does the stuff on `ConcurrentModificationException`

Target:
protected Collection<MessageChannel> determineTargetChannels(Message<?> message) { List<MessageChannel> channels = new ArrayList<MessageChannel>(); for (Recipient recipient : this.recipients) { if (recipient.accept(message)) { channels.add(recipient.getChannel()); } } return channels; }
Source:
public MessageSelector getSelector() { return selector; START } END What is a `public` goal of this getter? I'd prefer do not expose them at all to avoid undesired mutation. I understand the point for `expression` comparison, but it seems for me we have to encapsulte `equals` logic to the `Recipient` class. I think it doesn't hurt to have an extra GC from the `removeRecipient(String channelName, String selector)`. Or from other side we should check the type of `MessageSelector` to get access to its `expressionString`

Target:
private MessageSelector getSelector() { return selector; }
Source:
public void stop() { this.setActive(false); if (this.selector != null) { try { START this.selector.close(); END } catch (Exception e) { logger.error("Error closing selector", e); } } if (this.serverChannel == null) { return; } try { this.serverChannel.close(); } catch (IOException e) this.serverChannel = null; super.stop(); } I see another bug - probably unlikely and maybe not even possible, but `super.stop()` is not called if `serverChannel == null`.

Target:
public void stop() { this.setActive(false); if (this.selector != null) { try { this.selector.close(); } catch (Exception e) { logger.error("Error closing selector", e); } } if (this.serverChannel != null) { try { this.serverChannel.close(); } catch (IOException e) finally { this.serverChannel = null; } } super.stop(); }
Source:
protected void onInit() { START if (this.getSessionAcknowledgeMode()!= null) { END Integer acknowledgeMode = JmsAdapterUtils.parseAcknowledgeMode(this.getSessionAcknowledgeMode()); if (acknowledgeMode != null) { if (JmsAdapterUtils.SESSION_TRANSACTED == acknowledgeMode) { jmsTemplate.setSessionTransacted(true); } else { jmsTemplate.setSessionAcknowledgeMode(acknowledgeMode); } } } } whitespace before `!=`

Target:
protected void onInit() { if (this.getSessionAcknowledgeMode() != null) { Integer acknowledgeMode = JmsAdapterUtils.parseAcknowledgeMode(this.getSessionAcknowledgeMode()); if (acknowledgeMode != null) { if (JmsAdapterUtils.SESSION_TRANSACTED == acknowledgeMode) { this.jmsTemplate.setSessionTransacted(true); } else { this.jmsTemplate.setSessionAcknowledgeMode(acknowledgeMode); } } } }
Source:
public XmlValidatingMessageSelector(Resource schema, String schemaType) throws IOException { START this(schema, SchemaType.valueOf(schemaType)); END } That's not true: `schemaType` can be `null` and `empty string` as well. Yes, you have `if(schemaType == null) {` in the another ctor, but here `assert` logic has to be anyway

Target:
public XmlValidatingMessageSelector(Resource schema, String schemaType) throws IOException { this(schema, StringUtils.isEmpty(schemaType) ? (SchemaType) null : SchemaType.valueOf(schemaType)); }
Source:
public void stop(Runnable callback) { try { this.connectionManager.stop(callback); } finally { START this.connectionLatch = new CountDownLatch(1); END } } I suggest we do this in `start()` as well (or instead). This code relies on the fact that the connection manager invokes the callback before returning. While this is true now, it might not be in future.

Target:
public void stop(Runnable callback) { this.connectionManager.stop(callback); }