auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Optional<List<SingularityMesosArtifact>> getExtraArtifacts() { return extraArtifacts; }

Target:
Instead of passing Optional lists around, let’s just default it to an empty list if the constructor arg is null. Same for the other objects that use this. Will save a lot of isPresent being throw around
Source:
public void testOneOffsDontMoveDuringDecomission() { SingularityRequestBuilder bldr = new SingularityRequestBuilder(requestId, RequestType.ON_DEMAND); requestResource.postRequest(bldr.build()); deploy("d2"); requestResource.scheduleImmediately(requestId, Optional.absent()); validateTaskDoesntMoveDuringDecommission(); }

Target:
would it have made sense to create a method here that didn't take the second parameter?
Source:
private void checkOut() { LOG.trace("Checking out offer {}", offerId); Preconditions.checkState(offerState == OfferState.AVAILABLE, "Offer %s was in state %s", offerId, offerState); this.offerState = OfferState.CHECKED_OUT; }

Target:
Saw a sentry come through for this the other day. This exception will bubble all the way back up to the LeaderOnlyPoller and cause us to abort. Should we maybe catch this and just skip the offer in the case that something else has it checked out?
Source:
public Long getS3ChunkDownloadTimeoutMillis() { return s3ChunkDownloadTimeoutMillis; }

Target:
why `Long` here?
Source:
public SingularityDeployProgress withCompletedStep() { return new SingularityDeployProgress(targetActiveInstances, currentActiveInstances + 1, deployInstanceCountPerStep, deployStepWaitTimeMs, true, autoAdvanceDeploySteps, failedDeployTasks, System.currentTimeMillis()); }

Target:
is `currentActiveInstances + 1` correct here? wouldn't it be `currentActiveInstances + deployInstanceCountPerStep`?
Source:
private static Boolean hasRole(Resource r) { return r.hasRole() && !r.getRole().equals("*"); }

Target:
can you switch to primitive `boolean`s instead? removes the potential for NullPointerExceptions
Source:
public void downloadFile(String uri, File target) { Matcher m = parseURI(uri); if (m.matches()) { try { InputStream s = minioClient.getObject(m.group("bucket"), m.group("path")); FileUtils.copyInputStreamToFile(s, target); } catch (Exception ex) { Exceptions.printStackTrace(ex); } } }

Target:
Is this stream getting closed? Add it to try block just in case: `try(InputStream s = minioClient.getObject(m.group("bucket"), m.group("path"))) {`
Source:
public void setSingleBlockMode(boolean singleBlockMode) { logger.log(Level.INFO, "Setting singleBlockMode to ".concat((singleBlockMode)?"true":"false")); this.singleBlockMode = singleBlockMode; changed(); }

Target:
It's a matter of taste of course, but I'd prefer to use `Boolean.toString(singleBlockMode)` here.
Source:
private void checkForLanguageChangeAndAskForRestart(UGSEvent ugsEvent) { if (ugsEvent.isSettingChangeEvent()) { if (!StringUtils.equalsIgnoreCase(lastSelectedLanguage, backend.getSettings().getLanguage())) { lastSelectedLanguage = backend.getSettings().getLanguage(); Localization.initialize(backend.getSettings().getLanguage()); notifyRestartRequired(); } else if (!StringUtils.equalsIgnoreCase(lastSelectedConnectionClass, backend.getSettings().getConnectionClass())) { notifyRestartRequired(); } } }

Target:
Gotcha, because the settings are reloaded in the `ConnectionFactory` the app needs to flush the file first. You could also call `SettingsFactory.saveSettings(backend.getSettings())` instead of making the user restart the app. Or if it isn't too much work the connection-string idea.
Source:
protected void onCreate(Bundle savedInstanceState) { getDelegate().installViewFactory(); getDelegate().onCreate(savedInstanceState); super.onCreate(savedInstanceState); AnkiDroidApp.updateContextWithLanguage(this); }

Target:
Are both of these lines required? I'd have expected we'd only need the `attachBaseContext`
Source:
private void setCustomServerWithNoUrl() { SharedPreferences userPreferences = AnkiDroidApp.getSharedPrefs(AnkiDroidApp.getInstance()); userPreferences.edit().putBoolean("useCustomSyncServer", true).commit(); }

Target:
Just out of curiosity since you just up on SharedPreferences, why `commit` here vs `apply`? I scanned back and saw you used apply (correctly, I believe) in PreferenceBackedHostNum, and I think apply would be fine here as well. For the same reasons commit is typically unnecessary and may slow things down, I think it may be unnecessary and just slow testing down here, but perhaps I'm about to learn something about SharedPreferences, or I read it wrong
Source:
public boolean newDue() { return mCol.getDb().queryScalar("SELECT 1 FROM cards WHERE did IN " + _deckLimit() + " AND queue = " + Consts.QUEUE_TYPE_NEW + " LIMIT 1", new Object[] {_deckLimit()}) != 0; }

Target:
⚠️ The parameter seems wrong
Source:
public void load() { if (mFutureTask != null) { return; } mFutureTask = new FutureTask<Models> (() -> new Models(mCol).load(loadColumn("models"))); new Thread(mFutureTask).start(); }

Target:
This function could potentially be called simultaneously from multiple threads which would lead to a race condition, so better make it `synchronized`
Source:
public void addSharedDeck() { if(AdaptionUtil.hasWebBrowser(DeckPicker.this)) { openUrl(Uri.parse(getResources().getString(R.string.shared_decks_url))); }else { UIUtils.showThemedToast(DeckPicker.this, getResources().getString(R.string.no_browser_notification)+ getResources().getString(R.string.shared_decks_url), false); } }

Target:
```suggestion if (AdaptionUtil.hasWebBrowser(DeckPicker.this)) { openUrl(Uri.parse(getResources().getString(R.string.shared_decks_url))); } else { UIUtils.showThemedToast(DeckPicker.this, getResources().getString(R.string.no_browser_notification) + getResources().getString(R.string.shared_decks_url), false); ```
Source:
public Long[] cardIds() { Long[] cids; if (mDid < 0) { cids = Utils.list2ObjectArray(mCol.getDb().queryColumn(Long.class, "select id from cards", 0)); } else { cids = mCol.getDecks().cids(mDid, true); } mCount = cids.length; return cids; }

Target:
Before we were checking if `mDid == null`, whereas now we're invoking the comparison operator without checking for null, which will presumably crash with NPE when it is indeed null...? This is a place we have to be extra careful when translating from Python. Could you please double check that it's correct for both branches?
Source:
public Exporter(Collection col) { mCol = col; mDid = null; mCids = null; }

Target:
Seems to be unused... What's going on here?
Source:
public static @Nullable JSONObject getTempModel(@NonNull String tempModelFileName) { Timber.d("getTempModel() fetching tempModel %s", tempModelFileName); try (ByteArrayOutputStream target = new ByteArrayOutputStream()) { CompatHelper.getCompat().copyFile(tempModelFileName, target); return new JSONObject(target.toString()); } catch (IOException | JSONException e) { Timber.e(e, "Unable to read+parse tempModel from file %s", tempModelFileName); return null; } }

Target:
Would make sense to me to catch `Exception` here and return null on any failure, rather than on specific failures.
Source:
public static void setLanguage(String localeCode) { Configuration config = getInstance().getResources().getConfiguration(); Locale newLocale = LanguageUtil.getLocale(localeCode); config.locale = newLocale; getInstance().getResources().updateConfiguration(config, getInstance().getResources().getDisplayMetrics()); // The notification channels have persistent user-visible text so we need language set first AnkiDroidApp.getInstance().setupNotificationChannels(); }

Target:
A function called `setLanguage()` should set the language, nothing more nothing less... You can call `setupNotificationChannels()` immediately after the function is called without actually putting it inside the function, right?
Source:
public static String getName(Channel channel, Resources res) { switch (channel) { case SYNC: return res.getString(R.string.sync_title); case GLOBAL_REMINDERS: return res.getString(R.string.widget_minimum_cards_due_notification_ticker_title); case DECK_REMINDERS: return res.getString(R.string.deck_conf_reminders); case GENERAL: default: return res.getString(R.string.app_name); } }

Target:
Is it a lot of work to make this private?
Source:
public void setDebugACRAConfig(SharedPreferences prefs) { // Disable crash reporting setAcraReportingMode(FEEDBACK_REPORT_NEVER); prefs.edit().putString(FEEDBACK_REPORT_KEY, FEEDBACK_REPORT_NEVER).apply(); // Use a wider logcat filter in case crash reporting manually re-enabled String logcatArgs = { "-t", "300", "-v", "long", "ACRA:S"}; setAcraConfigBuilder(getAcraCoreConfigBuilder().setLogcatArguments(logcatArgs)); }

Target:
Can you make these methods private? I know you're using them in the unit test, but I think you can use the deencapsulation feature of the testing framework, right? The interface of a class should not be changed to accommodate a unit test.
Source:
public void setAcraConfigBuilder(CoreConfigurationBuilder acraCoreConfigBuilder) { this.acraCoreConfigBuilder = acraCoreConfigBuilder; ACRA.init(this, acraCoreConfigBuilder); }

Target:
This should be private
Source:
private void onCheckAll() { boolean all = mCheckedCardPositions.size() < getCards().size(); if (all) { for (int i = 0; i < mCards.size(); i++) mCheckedCardPositions.add(i); } else { mCheckedCardPositions.clear(); } updateMultiselectMenu(); mActionBarTitle.setText(Integer.toString(mCheckedCardPositions.size())); mCardsAdapter.notifyDataSetChanged(); }

Target:
braces
Source:
private static String _imgLink(Collection col, String latex, JSONObject model) { String txt = _latexFromHtml(col, latex); String ext = "png"; if (model.optBoolean("latexsvg", false)) ext = "svg"; String fname = "latex-" + Utils.checksum(txt) + "." + ext; return "<img class=latex src=\"" + fname + "\">"; }

Target:
Please use braces here
Source:
protected void onHandleIntent(Intent intent) { if (sWasRun) return; scheduleDeckReminder(); scheduleNotification(this); sWasRun = true; }

Target:
Please use braces with your one-line `if` statements
Source:
public long abort() throws UnknownHttpResponseException { return parseLong(_run("abort", new JSONObject())); }

Target:
abort doesn't modify the mod time, so there's no value to return. it's probably returning None encoded as json (null), but as long as you get a 200 reply the command succeeded
Source:
public void applyChunk(JSONObject sech) throws UnknownHttpResponseException { parseDict(_run("applyChunk", sech)); }

Target:
The return value can be ignored https://github.com/dae/anki/blob/master/anki/sync.py#L177
Source:
private String getLogMessage(String methodName, Uri uri) { String format = "%s.%s %s"; String path = uri == null ? null : uri.getPath(); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { return String.format(format, CardContentProvider.class.getSimpleName(), methodName, path); } else { return String.format(format + " (%s)", CardContentProvider.class.getSimpleName(), methodName, path, getCallingPackage()); } }

Target:
Use getClass() in these two places.
Source:
public int getProviderSpecVersionCode() { try { // the Android documentation for PackageManager#resolveContentProvider suggests flags should be 0, but GET_META_DATA seems to work anyway ProviderInfo info = mContext.getPackageManager().resolveContentProvider(FlashCardsContract.AUTHORITY, PackageManager.GET_META_DATA); if (info == null) { return -1; } Bundle metaData = info.metaData; if (metaData == null) { // this happens for one of two reasons: // 1. There are no metadata keys specified for the provider // 2. if we use the flag 0 instead of PackageManager.GET_META_DATA in PackageManager#resolveContentProvider() // we should presume the first one (and so return the default), since the second one is a programming error return DEFAULT_PROVIDER_SPEC_VALUE; } if (info.metaData.containsKey(PROVIDER_SPEC_META_DATA_KEY)) { return info.metaData.getInt(PROVIDER_SPEC_META_DATA_KEY); } else { return DEFAULT_PROVIDER_SPEC_VALUE; } } catch (Throwable t) { //Timber.w("metaDataKeyError: " + key, t); return -2; } }

Target:
It looks like you missed my edits to `getProviderSpecVersionCode()`... 9 lines vs. 24 lines in yours
Source:
public NexusUnexpectedResponseException( final int statusCode, final String statusMessage ) { this( statusCode, statusMessage, String.format( "Unexpected response: %s %s", String.valueOf( statusCode ), String.valueOf( statusMessage ) ) ); }

Target:
Uneeded String.valueOf() in arguments to String.format()
Source:
public void onAdjustment( final FixedRateWalkerThrottleController controller ) { logger.info( "Current speed upgrades/sec, with average upgrade/sec (is limited to upgrades/sec), currently sleeping {}ms per upgrade.", new Object[] { controller.getLastSliceTps(), controller.getGlobalAverageTps(), controller.getLimiterTps(), controller.getCurrentSleepTime() } ); }

Target:
Probably better to have this at DEBUG level for final release.
Source:
public List<LauncherActivityInfo> getActivityList(String packageName, UserHandle user) { final Predicate<LauncherActivityInfo> predicatePackage = info -> info.getComponentName() != null && packageName != null && packageName.equals(info.getComponentName().getPackageName()); return activityList.get(user).stream().filter(predicatePackage).collect(Collectors.toList()); }

Target:
nit: @Implementation should be protected to avoid introducing extra shadow APIs
Source:
public MqttConnectOptions getConnectionInfo() { MqttConnectOptions options = this.clientFactory.getConnectionOptions(); if (options.getServerURIs() == null && getUrl() != null) { options = MqttUtils.cloneConnectOptions(options); options.setServerURIs(new String[] { getUrl() }); } return options; }

Target:
Better to extract local variable for `URL` to avoid noise from Sonar that we defer NPE calling the method several times.
Source:
public MqttConnectOptions getConnectionInfo() { MqttConnectOptions options = this.clientFactory.getConnectionOptions(); if (options.getServerURIs() == null && getUrl() != null) { if (options.getServerURIs() == null && getUrl() != null) { options = MqttUtils.cloneConnectOptions(options); options.setServerURIs(new String[] { getUrl() }); } options.setServerURIs(new String[] { getUrl() }); } return options; }

Target:
Looks like duplication for this `if`s
Source:
public final void setSendTimeoutExpression(Expression sendTimeoutExpression) { Assert.notNull(sendTimeoutExpression, "'sendTimeoutExpression' must not be null"); this.sendTimeoutExpression = sendTimeoutExpression; }

Target:
Looks like you have changed your mind and decided to not use this setter in the ctor. I mean doesn't look like there is still a justification for a `final`...
Source:
public void destroy() throws Exception { this.pool.close(); this.pool.removeAllIdleItems(); }

Target:
Why that new `close()` can't do this for us, too?
Source:
public void setReplyChannel(MessageChannel replyChannel) { this.setOutputChannel(replyChannel); }

Target:
`this.` on method calls? I guess you have just moved those existing setter over here for better class structure. Nevertheless can we fix `this.` as well since we are already here in a change?
Source:
public Integer getId() { return id; }

Target:
`this.` prefix should be used for class properties.
Source:
public void acknowledge() { if (this.ackClient != null || !this.ackClient.equals(MqttPahoMessageDrivenChannelAdapter.this.client)) { try { this.ackClient.messageArrivedComplete(this.id, this.qos); } catch (MqttException e) { throw new IllegalStateException(e); } } else { throw new IllegalStateException("Client has changed"); } }

Target:
I wonder why do we care about this. We are just have her self-containing `AcknowledgmentImpl` with the client it has been created. If that client becomes invalid at the moment of `acknowledge()` we have nothing to do anyway. What am I missing?
Source:
public void addSessionFactory(String key, SessionFactory<F> factory) { this.factories.put(key, factory); }

Target:
I have an opinion that deprecated API should call a new one for better coverage. This way when we need to make a change in the target logic, a deprecated API won't be affected because it is meant to be for removal eventually anyway. 😄
Source:
AmqpOutboundChannelAdapterSpec(AmqpTemplate amqpTemplate) { super(amqpTemplate, false); }

Target:
Gary, can you make all the ctors and `final` props in these AMQP specs as `protected` for possible extension? So, I won't include them into my extensions PR #3167 to avoid conflicts between our two fixes. Thanks
Source:
public AbstractHttpRequestExecutingMessageHandler(Expression uriExpression) { Assert.notNull(uriExpression, "URI Expression is required"); this.uriExpression = uriExpression; this.uriFactory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.TEMPLATE_AND_VALUES); }

Target:
Why is this needed? This is the default.
Source:
public void subscribe(Subscriber<? super Message<?>> subscriber) { this.processor .doFinally((s) -> this.subscribedSignal.onNext(this.processor.hasDownstreams())) .subscribe(subscriber); if (this.processor.hasDownstreams()) { this.subscribedSignal.onNext(true); } }

Target:
probably `this.subscribedSignal.onNext(this.processor.hasDownstreams())` would be better
Source:
public void processBeforeCommit(IntegrationResourceHolder holder) { if (this.beforeCommitChannel != null) { doProcess(holder, this.beforeCommitExpression, this.beforeCommitChannel, "beforeCommit"); } }

Target:
I don't this this is right solution. We don't need to to build and send a message only when there is no particular channel.
Source:
private Channels() { }

Target:
Best to leave super() to avoid empty block complaint from Sonar.
Source:
protected Duration getConfirmTimeout() { if (this.confirmTimeout == null) { return DEFAULT_CONFIRM_TIMEOUT; } return this.confirmTimeout; }

Target:
Can't we have a `confirmTimeout` initialized with `DEFAULT_CONFIRM_TIMEOUT` by default? I see there is a logic where `if (this.confirmTimeout != null)` though, but why then just don't return that `null` with an appropriate `@Nullable` on this method instead? I think that way we would have a consistency with the current logic and what is possible with this `getConfirmTimeout()` in the inheritors.
Source:
public String toString() { return "FileWrittenEvent [remoteHandle=" + this.remoteHandle + ", file=" + this.file + ", dataLen=" + this.dataLen + ", cause=" + this.cause + ", clientAddress=" + getSession().getClientAddress() + "]"; }

Target:
I think `cause` should be conditional because it can be `null`. Therefore an explicit `StringBuilder` instead.
Source:
public Object getPayload() { InputStream inputStream; try { inputStream = inputStream(); } catch (IOException e1) { throw new UncheckedIOException(new SoftEndOfStreamException("Socket closed when getting input stream", e1)); } try { return getDeserializer() .deserialize(inputStream); } catch (IOException e) { throw new UncheckedIOException(e); } }

Target:
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
Source:
public String toString() { return "RSocketConnectedEvent{" + "destination='" + this.destination + '\'' + ", data=" + Arrays.toString(this.data.asByteBuffer().array()) + ", requester=" + this.requester + '}'; }

Target:
I don't think rendering a `byte[]` as a bunch of ints is useful, maybe omit this (or just include the length, perhaps).
Source:
public String toString() { return "RSocketConnectedEvent{" + "destination='" + this.destination + '\'' + ", data length=" + this.data.asByteBuffer().array().length + ", requester=" + this.requester + '}'; }

Target:
This still seems to be a lot of overhead in a `toString()`. Why do we need this `DataBuffer` in the event?
Source:
public <P> HeaderEnricherSpec expirationDateFunction(Function<Message<P>, Object> expirationDateFunction) { return priorityFunction(expirationDateFunction, null); }

Target:
copy/paste
Source:
private void setupStatsEnabledNamePatterns(IntegrationManagementConfigurer configurer) { List<String> patterns = new ArrayList<String>(); 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()])); }

Target:
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
Source:
public String[] getSourceNames() { return this.sourcesByName.keySet().toArray(new String[this.sourcesByName.size()]); }

Target:
Please, fix these kind of smells with an explicit array size. Thanks
Source:
public MessageChannel getDiscardChannel() { String channelName = this.discardChannelName; if (channelName != null) { this.discardChannel = getChannelResolver().resolveDestination(channelName); this.discardChannelName = null; } return this.discardChannel; }

Target:
We should exit early if `this.discardChannel` is not null, no need to store this local variable in that case.
Source:
public void destroy() { if (this.roleController != null) { this.roleController.removeLifecycle(this); } }

Target:
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.
Source:
public boolean supports(HandlerResult result) { Assert.notNull(result, "'result' must not be null"); Object handler = result.getHandler(); return handler instanceof HandlerMethod && WebFluxInboundEndpoint.class.isAssignableFrom(((HandlerMethod) handler).getBeanType()); }

Target:
I don't think we need this assert; Spring will never call this with a null result.
Source:
Message<?> doPoll() { Message<?> message = this.messageGroupStore.pollMessageFromGroup(this.groupId); this.messageStoreNotFull.signal(); return message; }

Target:
What happened to this method? Why isn't it a `private` anymore?
Source:
public Set<String> keySet() { Set<String> keys = new HashSet<>(); keys.addAll(this.jdbcTemplate.queryForList(this.getAllKeysQuery, new Object[]{this.region}, String.class)); return Collections.unmodifiableSet(keys); }

Target:
There is this variant to simplify the code here: `queryForList(String sql, Class<T> elementType, @Nullable Object... args)`
Source:
protected IntegrationFlowDefinition<?> buildFlow() { return from((MessageSource<?>) () -> new GenericMessage<>("flowAdapterMessage"), e -> e.poller(p -> p .trigger(ctx -> this.nextExecutionTime.getAndSet(null)))) .channel(MessageChannels.queue("flowAdapterOutput")); }

Target:
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?
Source:
public void shouldShutdownInternalExecutorService() throws Exception { this.initiator.start(); this.initiator.destroy(); ExecutorService executorService = (ExecutorService) TestUtils.getPropertyValue(this.initiator, "executorService"); assertTrue(executorService.isShutdown()); }

Target:
OK. I see what you mean. Good to know 😄
Source:
public UdpServerListeningEvent(UnicastReceivingChannelAdapter adapter, int port) { super(adapter); Assert.notNull(adapter, "'adapter' cannot be null"); this.port = port; }

Target:
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; } ```
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")); assertTrue(this.applicationContext.containsBean("annotatedEndpoint3.process.serviceActivator")); }

Target:
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.
Source:
public boolean isTransacted() { return this.transacted; }

Target:
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.
Source:
public void in(String in) { this.latch.countDown(); if ("nackIt".equals(in)) { throw new RuntimeException("testing auto nack"); } else { this.received = in; } }

Target:
I think this has to go to the `finally` block, already after `this.received = in;`. Otherwise race condition.
Source:
protected MessageGroupPreparedStatementSetter() { this.serializer = new SerializingConverter(); this.lobHandler = new DefaultLobHandler(); }

Target:
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`.
Source:
public void setScanner(DirectoryScanner scanner) { Assert.notNull(scanner, "scanner must not be null"); this.fileSource.setScanner(scanner); this.scannerExplicitlySet = true; }

Target:
The `this.fileSource.setScanner(scanner);` takes care about assert. We don't need this extra.
Source:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Foo foo1 = (Foo) o; return Objects.equals(this.foo, foo1.foo); }

Target:
checkstyle
Source:
MessagingTemplate getMessagingTemplate() { return this.messagingTemplate; }

Target:
Just curious: what made you to add this method? And if it is here already any way how about to make it `protected` ?
Source:
public Session<F> getSession() { if (this.activeTemplateCallbacks.get() > 0) { return this.contextSessions.get(); } else { return this.sessionFactory.getSession(); } }

Target:
Need to check for null.
Source:
public TransactionSynchronization create(Object key) { Assert.notNull(key, "'key' must not be null"); if (!TransactionSynchronizationManager.hasResource(key)) { DefaultTransactionalResourceSynchronization synchronization = new DefaultTransactionalResourceSynchronization(key); TransactionSynchronizationManager.bindResource(key, synchronization.getResourceHolder()); return synchronization; } return null; }

Target:
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.
Source:
public ExpressionEvaluatingRouter(String expressionString) { super(new ExpressionEvaluatingMessageProcessor<Object>(EXPRESSION_PARSER.parseExpression(expressionString))); setPrimaryExpression(getExpression()); }

Target:
Why `this(EXPRESSION_PARSER.parseExpression(expressionString))` doesn't work? And JavaDocs, please
Source:
protected AbstractRemoteFileStreamingMessageSource(RemoteFileTemplate<F> template, Comparator<AbstractFileInfo<F>> comparator) { this.remoteFileTemplate = template; this.comparator = comparator; if (JacksonJsonUtils.isJackson2Present()) { this.objectMapper = JsonObjectMapperProvider.newInstanceBuilder(false).build(); } else { this.objectMapper = null; } }

Target:
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`.
Source:
public void doSetFilter(FileListFilter<F> filter) { this.filter = filter; }

Target:
Did you intend to make this `final` ?
Source:
AsyncHttpMessageHandlerSpec(Expression uriExpression, AsyncRestTemplate asyncRestTemplate) { this.target = new AsyncHttpRequestExecutingMessageHandler(uriExpression, asyncRestTemplate); this.target.setUriVariableExpressions(this.uriVariableExpressions); this.target.setHeaderMapper(this.headerMapper); this.asyncRestTemplate = asyncRestTemplate; }

Target:
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
Source:
FileState(BufferedWriter writer) { this.writer = writer; this.stream = null; this.lastFlush = System.currentTimeMillis(); }

Target:
`lastFlush` is never updated. Am I missing something? Also I wonder if we should update `MessageFlushPredicate.shouldFlush()` for this new `lastFlush` argument as well.
Source:
public HttpRequestExecutingMessageHandler(String uri) { this(uri, (RestTemplate) null); }

Target:
My IDEA says me that this cast is redundant: ![redundantcast](https://cloud.githubusercontent.com/assets/1071590/22128295/d3cc88a2-de6d-11e6-8104-2aae7c3888ea.png)
Source:
public void setRequestFactory(ClientHttpRequestFactory requestFactory) { if (this.isAsync()) { throw new IllegalArgumentException("ClientHttpRequestFactory cannot be set in async mode"); } this.restTemplate.setRequestFactory(requestFactory); }

Target:
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`
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 { logger.info("No publisher for idle event"); } }

Target:
This logger doesn't reflect reality any more. We come here even when file doesn't exist. So, we should move `exists` condition inside
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); ((GenericConversionService) service).addConverter((GenericConverter) stringToBasicQueryConverterCls.newInstance()); } catch (Exception ignore) { } } } return service; }

Target:
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.
Source:
public int getSubscriberCount() { MessageDispatcher dispatcher = getRequiredDispatcher(); if (dispatcher instanceof AbstractDispatcher) { return ((AbstractDispatcher) dispatcher).getHandlerCount(); } return this.handlerCounter.get(); }

Target:
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
Source:
public ImapIdleChannelAdapterSpec adviceChain(Advice... adviceChain) { this.target.setAdviceChain(Arrays.asList(adviceChain)); return this; }

Target:
Looks like we have missed here `transactional()` option for convenience.
Source:
public AbstractConnectionFactorySpec(C connectionFactory) { this.target = connectionFactory; }

Target:
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?
Source:
public static UdpOutboundChannelAdapterSpec outboundMulticastAdapter(String destinationExpression) { return new UdpMulticastOutboundChannelAdapterSpec(destinationExpression); }

Target:
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.
Source:
private static boolean rename(File source, File target) throws IOException { Files.move(source.toPath(), target.toPath(), StandardCopyOption.REPLACE_EXISTING); return true; }

Target:
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.
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) { } catch (JMSException e) { } }

Target:
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) { } } ```
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"); LOG.info(String.format("Cleaning Database - Deleted Messages: %s, " + "Deleted GroupToMessage Rows: %s, Deleted Message Groups: %s", deletedMessages, deletedGroupToMessageRows, deletedMessageGroups)); return null; }); }

Target:
I'm against unconditional logs in tests. Would you mind removing it in the next polishing? Thanks
Source:
public IntegrationGraphCorsConfigurer(String path, String[] allowedOrigins) { this.path = path; this.allowedOrigins = allowedOrigins; }

Target:
Redundant modifier. See Travis report And seems for me the whole class can be `private`.
Source:
public void setReleasePartialSequences(boolean releasePartialSequences) { if (!this.releaseStrategySet) { setReleaseStrategy(new SequenceSizeReleaseStrategy()); } this.releasePartialSequences = releasePartialSequences; }

Target:
`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)`.
Source:
protected Message<?> receiveMessage() { if (this.limitingSource != null) { return this.limitingSource.receive(this.maxFetchSize); } else { return this.source.receive(); } }

Target:
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 ? 😄
Source:
public void testEarlySubscribe() { PublishSubscribeChannel channel = new PublishSubscribeChannel(mock(Executor.class)); try { channel.subscribe(mock(MessageHandler.class)); 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)); }

Target:
Mock? You can use pretty simple Lambda: ``` channel.subscribe(m -> {}); ``` :smile:
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); } }

Target:
Perhaps this logic should be in `DefaultMessageBuilderFactory` instead?
Source:
public Map<String, Object> getProperties() { return this.properties; }

Target:
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.
Source:
public Map<String, Object> getProperties() { return this.properties == null ? null : this.properties; }

Target:
??? ``` 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; ```
Source:
public static SessionFactory<FTPFile> ftpSessionFactory() { return FtpStreamingMessageSourceTests.sessionFactory(); }

Target:
Why these two beans are `static`? Looks like is just overhead. Although it isn't critical. Never mind
Source:
public MessageChannel getInputChannel() { return this.inputChannel == null ? null : this.inputChannel; }

Target:
Overdid: if `null`, return `null` :smile: From other side it can't be `null`. See ctor: ``` Assert.notNull(inputChannel, "inputChannel must not be null"); ```
Source:
private MessageProducerNode producerNode(String name, MessageProducerSupport producer) { MessageChannel outputChannel = producer.getOutputChannel(); String outputChannelName = outputChannel == null ? "__unknown__" : outputChannel.toString(); return new MessageProducerNode(this.nodeId.incrementAndGet(), name, producer, outputChannelName); }

Target:
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.
Source:
public void setExtractPayload(boolean extractPayload) { if (this.payloadExpression == null) { setPayloadExpression(extractPayload ? EXPRESSION_PARSER.parseExpression("payload") : EXPRESSION_PARSER.parseExpression("#this")); } }

Target:
Perhaps it's time to port `FunctionExpression` from the DSL ?
Source:
public void setTaskScheduler(TaskScheduler taskScheduler) { Assert.notNull(taskScheduler, "taskScheduler must not be null"); this.taskScheduler = taskScheduler; }

Target:
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`...
Source:
protected void doStart() { Assert.state(this.outputChannel != null || StringUtils.hasText(this.outputChannelName), "'outputChannel' or 'outputChannelName' is required"); if (this.outputChannelName != null) { synchronized (this) { if (this.outputChannelName != null) { this.outputChannel = getChannelResolver().resolveDestination(this.outputChannelName); this.outputChannelName = null; } } } }

Target:
This is redundant. We are protected with the `lifecycleLock` in the `AbstractEndpoint.start()`
Source:
protected void doStop() { try { this.active = false; this.lifecycleCondition.await(Math.min(this.stopTimeout, this.receiveTimeout), TimeUnit.MILLISECONDS); } catch (InterruptedException e) { logger.debug("Thread interrupted while stopping the endpoint"); Thread.currentThread().interrupt(); } finally { this.listening = false; } }

Target:
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()`.
Source:
public void handleTransportError(StompSession session, Throwable exception) { if (exception instanceof ConnectionLostException) { this.session = null; AbstractStompSessionManager.this.connected = false; scheduleReconnect(); } synchronized (this.delegates) { for (StompSessionHandler delegate : this.delegates) { delegate.handleTransportError(session, exception); } } }

Target:
`ApplicationEvent` here too?
Source:
public Object fromMessage(Message<?> message, Class<?> targetClass) { try { Message<?> mm = MutableMessageBuilder.fromMessage(message).build(); return this.codec.encode(mm); } catch (IOException e) { throw new MessagingException(message, e); } }

Target:
I'd like to understand the reason of this extra `MutableMessage` creation object before encoding...
Source:
private void register(Kryo kryo, Registration registration) { int id = registration.getId(); Registration existing = kryo.getRegistration(id); if (existing != null) { throw new SerializationFailedException((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); }

Target:
??? Do we really do the `registerType()` during serialization operation ?
Source:
public FileKryoRegistrar() { super(); this.registrationId = DEFAULT_REGISTRATION_ID; }

Target:
Unnecessary
Source:
public StoredProcExecutor(DataSource dataSource) { Assert.notNull(dataSource, "dataSource must not be null."); this.dataSource = dataSource; if (!guavaPresent) { this.jdbcCallOperationsMap = new LinkedHashMap<String, SimpleJdbcCallOperations>() { @Override protected boolean removeEldestEntry(Entry<String, SimpleJdbcCallOperations> eldest) { return size() > jdbcCallOperationsCacheSize; } }; } else { this.jdbcCallOperationsMap = null; } }

Target:
`SuppressWarnings("serial")` Also, you need to use ``` new LinkedHashMap<String, SimpleJdbcCallOperations>(this.jdbcCallOperationsCacheSize + 1, 0.75f, true) {...} ``` to enable LRU processing.
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 { return false; } }

Target:
Should be true if not an exec. inter. and super.remove() was successful
Source:
public void setLoggingEnabled(boolean enabled) { delegate.setLoggingEnabled(enabled); }

Target:
Minor: should be with `this.`, but anyway...
Source:
public boolean remove(ChannelInterceptor interceptor) { this.size--; return this.interceptors.remove(interceptor); }

Target:
This is a bug! The requested `interceptor` might not be in the list, so we should decrement only if `true` from `remove()`.
Source:
public void configure() throws Exception { MongoDbFactory mongoDbFactory = this.prepareMongoFactory(DEFAULT_COLLECTION_NAME); MongoTemplate template = new MongoTemplate(mongoDbFactory); store = new MongoDbMetadataStore(template); }

Target:
Since we have already `MongoDbFactory` ctor this extra `MongoTemplate` variable is redundant
Source:
public void testReplace() throws Exception{ boolean removedValue = store.replace(file1, file1Id, "4567"); assertFalse(removedValue); String fileID = store.putIfAbsent(file1, file1Id); assertNull(fileID); removedValue = store.replace(file1, file1Id, "4567"); assertTrue(removedValue); }

Target:
I think here must be `store.get(file1)` to be sure that the `replace` hasn't affected the collection.
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); assertEquals(file1Id, fileID); }

Target:
And `get` in the end to check that there is nothing in the collection on the matter.
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); this.collectionName = collectionName; }

Target:
`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!
Source:
public void enableStats(boolean statsEnabled) { if (statsEnabled) { this.countsEnabled = true; } this.statsEnabled = statsEnabled; if (this.channelMetrics != null) { this.channelMetrics.setFullStatsEnabled(statsEnabled); } }

Target:
Redundant `null check`
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 { throw new IllegalStateException("Can't happen. Check SUPPORTED_CLASSES"); } }

Target:
Something wrong is here, because `getSpecificTargetClasses()` returns `null`
Source:
public RFC5424MessageConverter() { this.parser = new RFC5424SyslogParser(); }

Target:
`this(new RFC5424SyslogParser());` However it is minor and we can live with this one as well
Source:
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)); }

Target:
`(List<?>)` (3 places)
Source:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ToStringFriendlyJsonNode that = (ToStringFriendlyJsonNode) o; return !(node != null ? !node.equals(that.node) : that.node != null); }

Target:
I think node can't be null
Source:
public Folder getFolder() { return this.folder; }

Target:
The purpose to publicate it ?
Source:
public void setHeadersMap(Map<String, String> headers) { Assert.notNull(headers); HttpHeaders httpHeaders = new HttpHeaders(); for (String key : headers.keySet()) { String value = headers.get(key); String[] values = StringUtils.commaDelimitedListToStringArray(value); for (String v : values) { httpHeaders.add(key, v); } } setHeaders(httpHeaders); }

Target:
Use `entrySet()`
Source:
public long getSendCount() { return sendCount.get(); }

Target:
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.