auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void doStop() { try { this.active = false; this.lifecycleCondition.await(Math.min(this.stopTimeout, this.receiveTimeout), TimeUnit.MICROSECONDS); START this.listening = false; END } catch (InterruptedException e) { logger.debug("Thread interrupted while stopping the endpoint"); Thread.currentThread().interrupt(); } } Needs to be in finally - we might get interrupted.

Target:
protected void doStop() { try { this.active = false; this.lifecycleCondition.await(Math.min(this.stopTimeout, this.receiveTimeout), TimeUnit.MICROSECONDS); } catch (InterruptedException e) { logger.debug("Thread interrupted while stopping the endpoint"); Thread.currentThread().interrupt(); } finally { this.listening = false; } }
Source:
public static void main(String[] args) throws Exception { AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("SyslogdTests-context.xml", SyslogdTests.class); System.out.println("Hit enter to terminate"); System.in.read(); START ctx.close(); END ctx.destroy(); } One more time: why invoke `close()` directly, if `destroy()` does the same? What does 'd' letter mean in the name of this (and similar for tcp) test class? And don't you invoke `close()` in similar test for tcp? :smile:

Target:
public static void main(String[] args) throws Exception { AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("SyslogdTests-context.xml", SyslogdTests.class); System.out.println("Hit enter to terminate"); System.in.read(); ctx.close(); }
Source:
public String toString() { StringBuilder builder = new StringBuilder(); builder.append("JpaParameter [name=").append(this.name) .append(", value=").append(this.value) .append(", expression=").append(this.expression) START .append(", projectionExpression=").append(this.projectionExpression) END .append("]"); return builder.toString(); } These two need `.getExpressionString()`.

Target:
public String toString() { StringBuilder builder = new StringBuilder(); builder.append("JpaParameter [name=").append(this.name) .append(", value=").append(this.value) .append(", expression=").append(this.expression) .append("]"); return builder.toString(); }
Source:
START public Message getMessage() { END return message; } `Message<?>`

Target:
public Message<?> getMessage() { return message; }
Source:
protected Properties getIntegrationProperties() { if (this.beanFactory != null) { return IntegrationContextUtils.getIntegrationProperties(this.beanFactory); } else { START return null; END } } Maybe we can return an empty Properties here (perhaps a static constant empty props so we don't create a new one for each instance). It would save a null check everywhere that uses it.

Target:
protected Properties getIntegrationProperties() { return IntegrationContextUtils.getIntegrationProperties(this.beanFactory); }
Source:
public boolean isModified() { if (this.refreshDelay < 0) { return false; } long time = System.currentTimeMillis(); START if (this.refreshDelay == 0 || (time - this.lastModifiedChecked.get()) > this.refreshDelay) { END this.lastModifiedChecked.set(time); boolean modified = this.source.isModified(); if (modified) { this.script = null; } return modified; } return false; } can this be just (time - this.lastModifiedChecked.get()) > this.refreshDelay) should always be > 0

Target:
public boolean isModified() { return this.refreshDelay >= 0 && (System.currentTimeMillis() - this.lastModifiedChecked.get()) > this.refreshDelay && this.source.isModified(); }
Source:
public void put(String key, String value) { Assert.notNull(key, "'key' must not be null."); Assert.notNull(value, "'value' must not be null."); START BoundValueOperations<String, String> ops = redisTemplate.boundValueOps(key); END ops.set(value); } `this.redisTemplate`

Target:
public void put(String key, String value) { Assert.notNull(key, "'key' must not be null."); Assert.notNull(value, "'value' must not be null."); BoundValueOperations<String, String> ops = this.redisTemplate.boundValueOps(key); ops.set(value); }
Source:
public String get(String key) { Assert.notNull(key, "'key' must not be null."); START BoundValueOperations<String, String> ops = redisTemplate.boundValueOps(key); END return ops.get(); } `this.redisTemplate`

Target:
public String get(String key) { Assert.notNull(key, "'key' must not be null."); BoundValueOperations<String, String> ops = this.redisTemplate.boundValueOps(key); return ops.get(); }
Source:
protected void onInit() { super.onInit(); this.jpaExecutor.setBeanFactory(this.getBeanFactory()); if(this.evaluationContext == null) { this.evaluationContext = ExpressionUtils.createStandardEvaluationContext(getBeanFactory()); START } END } use instead, please, `implements IntegrationEvaluationContextAware`

Target:
protected void onInit() { super.onInit(); this.jpaExecutor.setBeanFactory(this.getBeanFactory()); }
Source:
private void configureMappingRouter(AbstractMappingMessageRouter router) { if (this.channelMappings != null) { router.setChannelMappings(this.channelMappings); } if (this.resolutionRequired != null) { router.setResolutionRequired(this.resolutionRequired); } else { START router.setResolutionRequired(true); END } if (this.channelResolver != null) { logger.warn("'channel-resolver' attribute has been deprecated in favor of using SpEL via 'expression' attribute"); router.setChannelResolver(this.channelResolver); } } I'm curious why this call needed to be added since AbstractMappingMessageRouter has: ``` private volatile boolean resolutionRequired = true; ```

Target:
private void configureMappingRouter(AbstractMappingMessageRouter router) { if (this.channelMappings != null) { router.setChannelMappings(this.channelMappings); } if (this.resolutionRequired != null) { router.setResolutionRequired(this.resolutionRequired); } if (this.channelResolver != null) { logger.warn("'channel-resolver' attribute has been deprecated in favor of using SpEL via 'expression' attribute"); router.setChannelResolver(this.channelResolver); } }
Source:
MessageHandler createMethodInvokingHandler(Object targetObject, String targetMethodName) { MessageHandler directHandler = null; directHandler = createDirectHandlerIfPossible(targetObject, targetMethodName); if (directHandler != null) { return directHandler; } START else { END ServiceActivatingHandler handler = (StringUtils.hasText(targetMethodName)) ? new ServiceActivatingHandler(targetObject, targetMethodName) : new ServiceActivatingHandler(targetObject); return this.configureHandler(handler); } } I guess 'else' is not required here since the if block has a return... personally, I'd find this easier to read: ``` MessageHandler handler = createDirectHandlerIfPossible(targetObject, targetMethodName); if (handler == null) { ServiceActivatingHandler handler = (StringUtils.hasText(targetMethodName)) ? new ServiceActivatingHandler(targetObject, targetMethodName) : new ServiceActivatingHandler(targetObject); handler = this.configureHandler(handler); } return handler; ``` ...but feel free to ignore that :)

Target:
MessageHandler createMethodInvokingHandler(Object targetObject, String targetMethodName) { MessageHandler handler = null; handler = createDirectHandlerIfPossible(targetObject, targetMethodName); if (handler == null) { handler = configureHandler( StringUtils.hasText(targetMethodName) ? new ServiceActivatingHandler(targetObject, targetMethodName) : new ServiceActivatingHandler(targetObject)); } return handler; }
Source:
public Message<?> receive(long timeout) { try { if (this.receiveTimeout < 0) { this.latch.await(); } else { if (!this.latch.await(this.receiveTimeout, TimeUnit.MILLISECONDS)) { this.clientTimedOut = true; } } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } START this.clientHasReceived = true; END return this.message; } should this only be set if the latch.await above returned true? in the current impl I don't think it would make a difference since clientTimedOut is checked prior to clientHasReceived in the if/else below, but that order could be a fragile assumption

Target:
public Message<?> receive(long timeout) { try { if (this.receiveTimeout < 0) { this.latch.await(); this.clientHasReceived = true; } else { if (this.latch.await(this.receiveTimeout, TimeUnit.MILLISECONDS)) { this.clientHasReceived = true; } else { this.clientTimedOut = true; } } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return this.message; }
Source:
protected boolean isPostProcessWithinAdviceIfPresent() { START return this.hasAdviceChain() ? this.postProcessWithinAdvice : true; END } `return !this.hasAdviceChain() || this.postProcessWithinAdvice;`

Target:
protected boolean isPostProcessWithinAdviceIfPresent() { return !this.hasAdviceChain() || this.postProcessWithinAdvice; }
Source:
START protected Object handleRequestMessage(Message<?> requestMessage) { END Object result = this.doHandleRequestMessage(requestMessage); if (this.isPostProcessWithinAdviceIfPresent()) { this.postProcess(requestMessage, result); } return result; } Should be **final** as and `doInvokeAdvisedRequestHandler` too. In general postProcess implementation now looks not so clear and and very stiffly: `doInvokeAdvisedRequestHandler`, in the end, delegates to this `handleRequestMessage`. So check `isPostProcessWithinAdviceIfPresent()` twice looks like redundant. Unfortunately, I don't see more flexible solution yet :-(. Maybe through a `ThreadLocal` flag?

Target:
protected final Object handleRequestMessage(Message<?> requestMessage) { Object result = this.doHandleRequestMessage(requestMessage); if (this.isPostProcessWithinAdviceIfPresent()) { this.postProcess(requestMessage, result); } return result; }
Source:
public HDPath extend(List<ChildNumber> path2) { List<ChildNumber> mutable = new ArrayList<>(this.unmodifiableList); // Mutable copy mutable.addAll(path2); START return new HDPath(mutable); END } question: the `hasPrivateKey` field ends up being false in HDPaths produced by `extend()` operations, should it be preserved or should there be a way to introduce true values?

Target:
public HDPath extend(List<ChildNumber> path2) { return this.extend(HDPath.of(path2)); }
Source:
START public synchronized Sha256Hash hashForSignatureWitness( END int inputIndex, Script scriptCode, Coin prevValue, SigHash type, boolean anyoneCanPay) { byte[] connectedScript = scriptCode.getProgram(); return hashForSignatureWitness(inputIndex, connectedScript, prevValue, type, anyoneCanPay); } This parameter seems to be ignored, because it is overridden in line 1284. Is this perhaps a bug? Or am I wrong?

Target:
public synchronized Sha256Hash hashForSignatureWitness( int inputIndex, Script scriptCode, Coin prevValue, SigHash type, boolean anyoneCanPay) { return hashForSignatureWitness(inputIndex, scriptCode.getProgram(), prevValue, type, anyoneCanPay); }
Source:
public int hashCode() { int hashCode = (int)version ^ "getblocks".hashCode() ^ stopHash.hashCode(); START return locator.hashCode(hashCode); END } ...so don't pass the "intial hashcode" into location.hashCode(...) but instead mix the various hash codes yourself here. Guava Objects.hashCode() can help.

Target:
public int hashCode() { int hashCode = (int) version ^ "getblocks".hashCode() ^ stopHash.hashCode(); return hashCode ^= locator.hashCode(); }
Source:
public byte[] getProgram() { try { // Don't round-trip as Bitcoin Core doesn't and it would introduce a mismatch. if (program != null) return Arrays.copyOf(program, program.length); ByteArrayOutputStream bos = new ByteArrayOutputStream(); for (ScriptChunk chunk : chunks) { START bos.write(chunk.toByteArray()); END } program = bos.toByteArray(); return program; } catch (IOException e) { throw new RuntimeException(e); // Cannot happen. } } Here we will be making many allocations.

Target:
public byte[] getProgram() { try { // Don't round-trip as Bitcoin Core doesn't and it would introduce a mismatch. if (program != null) return Arrays.copyOf(program, program.length); ByteArrayOutputStream bos = new ByteArrayOutputStream(); for (ScriptChunk chunk : chunks) { chunk.write(bos); } program = bos.toByteArray(); return program; } catch (IOException e) { throw new RuntimeException(e); // Cannot happen. } }
Source:
public ECKey getKey() { START final ECKey key = ECKey.fromPrivate(Arrays.copyOf(bytes, 32)); END return isCompressed() ? key : key.decompress(); } Rather than creating a compressed key and then decompressing it, shall we use the `ECKey.fromPrivate(bytes, compressed)` constructor in the first place?

Target:
public ECKey getKey() { return ECKey.fromPrivate(Arrays.copyOf(bytes, 32), isCompressed()); }
Source:
public void writeWallet(Wallet wallet, OutputStream output) throws IOException { Protos.Wallet walletProto = walletToProto(wallet); START int serializedSize = walletProto.getSerializedSize(); END int bufferSize = serializedSize > this.walletWriteBufferSize ? this.walletWriteBufferSize : serializedSize; final CodedOutputStream codedOutput = CodedOutputStream.newInstance(output, bufferSize); walletProto.writeTo(codedOutput); codedOutput.flush(); } Wouldn't this forced call slow down saving considerably? Do we need the minimum calculation? It doesn't hurt to pick a larger buffer, no?

Target:
public void writeWallet(Wallet wallet, OutputStream output) throws IOException { Protos.Wallet walletProto = walletToProto(wallet); final CodedOutputStream codedOutput = CodedOutputStream.newInstance(output, this.walletWriteBufferSize); walletProto.writeTo(codedOutput); codedOutput.flush(); }
Source:
public static byte[] createHeightScriptData(final int height, final int numberOfBytes) { final int maxNumberOfBytes = 4; checkArgument(numberOfBytes <= maxNumberOfBytes); final byte[] int32Buffer = ByteBuffer.allocate(maxNumberOfBytes).order(ByteOrder.LITTLE_ENDIAN).putInt(height).array(); START if (numberOfBytes != maxNumberOfBytes) { END return Arrays.copyOf(int32Buffer, numberOfBytes); } else { return int32Buffer; } } I'd write '<' here, rather than '!='. It's a bit clearer imho.

Target:
public static byte[] createHeightScriptData(final int height, final int numberOfBytes) { final int maxNumberOfBytes = 4; checkArgument(numberOfBytes <= maxNumberOfBytes); final byte[] int32Buffer = ByteBuffer.allocate(maxNumberOfBytes).order(ByteOrder.LITTLE_ENDIAN).putInt(height).array(); if (numberOfBytes < maxNumberOfBytes) { return Arrays.copyOf(int32Buffer, numberOfBytes); } else { return int32Buffer; } }
Source:
START public final MessageSerializer getDefaultSerializer() { END // Construct a default serializer if we don't have one if (null == this.defaultSerializer) { this.defaultSerializer = getSerializer(false, false); } return defaultSerializer; } Shouldn't this be synchronized?

Target:
public final MessageSerializer getDefaultSerializer() { // Construct a default serializer if we don't have one if (null == this.defaultSerializer) { // Don't grab a lock unless we absolutely need it synchronized(this) { // Now we have a lock, double check there's still no serializer // and create one if so. if (null == this.defaultSerializer) { // As the serializers are intended to be immutable, creating // two due to a race condition should not be a problem, however // to be safe we ensure only one exists for each network. this.defaultSerializer = getSerializer(false, false); } } } return defaultSerializer; }
Source:
TransactionInput(NetworkParameters params, Transaction parentTransaction, TransactionOutput output) { super(params); long outputIndex = output.getIndex(); try { outpoint = new TransactionOutPoint(params, outputIndex, output.getParentTransaction()); START } catch (NullPointerException e) { END outpoint = new TransactionOutPoint(params, output); } scriptBytes = EMPTY_ARRAY; sequence = NO_SEQUENCE; setParent(parentTransaction); this.value = output.getValue(); length = 41; } It's usually a bad idea to catch NPE's or any other exception that can be generated by a common class of bugs. You're doing this because output.getParentTransaction() might return null? In that case use an if statement!

Target:
TransactionInput(NetworkParameters params, Transaction parentTransaction, TransactionOutput output) { super(params); long outputIndex = output.getIndex(); if(output.getParentTransaction() != null ) { outpoint = new TransactionOutPoint(params, outputIndex, output.getParentTransaction()); } else { outpoint = new TransactionOutPoint(params, output); } scriptBytes = EMPTY_ARRAY; sequence = NO_SEQUENCE; setParent(parentTransaction); this.value = output.getValue(); length = 41; }
Source:
public void deserializeAndAddExtension(WalletExtension extension, byte[] data) throws Exception { String id = checkNotNull(extension).getWalletExtensionID(); lock.lock(); try { START if (extensions.containsKey(id)) END return; else { extension.deserializeWalletExtension(this, data); addExtension(extension); } } finally { lock.unlock(); } } Missing { }

Target:
public void deserializeAndAddExtension(WalletExtension extension, byte[] data) throws Exception { String id = checkNotNull(extension).getWalletExtensionID(); lock.lock(); try { if (extensions.containsKey(id)) { return; } else { extension.deserializeWalletExtension(this, data); addExtension(extension); } } finally { lock.unlock(); } }
Source:
public boolean removeWatchedAddress(final Address address) { START return removeWatchedAddresses(Lists.newArrayList(address)); END } FYI ImmutableList.of(address) is more efficient, but it's no big deal, that's just a note for future reference.

Target:
public boolean removeWatchedAddress(final Address address) { return removeWatchedAddresses(ImmutableList.of(address)); }
Source:
public void notifyBuildEnded(GerritTriggeredEvent event) { if (event instanceof ChangeBasedEvent) { IGerritHudsonTriggerConfig serverConfig = getServerConfig(event); if ((serverConfig != null && serverConfig.isGerritBuildCurrentPatchesOnly()) START || this.getBuildCancellationPolicy().isEnabled()) { END getRunningJobs().remove((ChangeBasedEvent)event); } } } You check for `null` in `EventListener` so I guess you need to check for it here as well.

Target:
public void notifyBuildEnded(GerritTriggeredEvent event) { if (event instanceof ChangeBasedEvent) { IGerritHudsonTriggerConfig serverConfig = getServerConfig(event); if ((serverConfig != null && serverConfig.isGerritBuildCurrentPatchesOnly()) || (this.getBuildCancellationPolicy() != null && this.getBuildCancellationPolicy().isEnabled())) { getRunningJobs().remove((ChangeBasedEvent)event); } } }
Source:
public void run() { GerritTrigger trigger = getGerritTrigger(); if (trigger == null) { return; } if (StringUtils.isEmpty(trigger.getTriggerConfigURL())) { return; } START if (!trigger.getJob().isBuildable()) { END return; } trigger.updateTriggerConfigURL(); } To be safe, should check `gerritTrigger.getJob() != null` first.

Target:
public void run() { GerritTrigger trigger = getGerritTrigger(); if (trigger == null) { return; } if (StringUtils.isEmpty(trigger.getTriggerConfigURL())) { return; } if (trigger.getJob() != null && !trigger.getJob().isBuildable()) { return; } trigger.updateTriggerConfigURL(); }
Source:
START public long calculateAverageDynamicConfigRefreshInterval() { END long total = 0; for (GerritServer server : PluginImpl.getServers_()) { total += server.getConfig().getDynamicConfigRefreshInterval(); } long average = total / Math.max(1, PluginImpl.getServers_().size()); //Avoid division by 0 return Math.max(GerritDefaultValues.MINIMUM_DYNAMIC_CONFIG_REFRESH_INTERVAL, average); } `@Restricted(NoExternalUse.class)`

Target:
long calculateAverageDynamicConfigRefreshInterval() { long total = 0; for (GerritServer server : PluginImpl.getServers_()) { total += server.getConfig().getDynamicConfigRefreshInterval(); } long average = total / Math.max(1, PluginImpl.getServers_().size()); //Avoid division by 0 return Math.max(GerritDefaultValues.MINIMUM_DYNAMIC_CONFIG_REFRESH_INTERVAL, average); }
Source:
public void setTriggerConfigURL(String triggerConfigURL) { // If the trigger URL has changed from the previous value, then we can't use // the project list that we might already have loaded from the last time this trigger // was started. Just make a note of that here; we'll deal with it in "start()". if (triggerConfigURL == null) { if (this.triggerConfigURL != null) { // We need to start fresh when the URL has changed. this.dynamicConfigurationChangedFromLastStart = true; } } else { if (!triggerConfigURL.equals(this.triggerConfigURL)) { // We need to start fresh when the URL has changed. START this.dynamicConfigurationChangedFromLastStart = true; END } else { // We had this same configuration before. this.dynamicConfigurationChangedFromLastStart = false; } } this.triggerConfigURL = triggerConfigURL; } Have you tested that this actually works? IIRC when configuring the trigger a new instance is created, both via the UI and via pipeline script, so it's not the same instance that gets the `stop` and `start` calls.

Target:
public void setTriggerConfigURL(String triggerConfigURL) { this.triggerConfigURL = triggerConfigURL; }
Source:
public void run() { GerritTrigger trigger = getGerritTrigger(); if (trigger == null) { return; } START if (trigger.getTriggerConfigURL() == null || trigger.getTriggerConfigURL().isEmpty()) { END return; } trigger.updateTriggerConfigURL(); } use `StringUtils.isEmpty()`

Target:
public void run() { GerritTrigger trigger = getGerritTrigger(); if (trigger == null) { return; } if (StringUtils.isEmpty(trigger.getTriggerConfigURL())) { return; } trigger.updateTriggerConfigURL(); }
Source:
/*package*/ RunningJobs getRunningJobs() { if (runningJobs == null) { runningJobs = new RunningJobs(); START } END return runningJobs; } Removing the synchronized here means there is risk of dirty write.

Target:
/*package*/ synchronized RunningJobs getRunningJobs() { if (runningJobs == null) { runningJobs = new RunningJobs(); } return runningJobs; }
Source:
private List<Run> fromMemoryImprintToBuilds(MemoryImprint memoryImprint) { final List<Run> runs = new ArrayList<Run>(memoryImprint.getEntries().length); for (Entry entry : memoryImprint.getEntries()) { if (entry == null) { continue; } START runs.add(entry.getBuild()); END } return runs; } `getBuild()` can also be `null` if jobs have been triggered but not yet started. Even though you take care of potential `null` entries below it is safest if we can omit them all together in the source in case some other caller isn't that foreseeing.

Target:
private List<Run> fromMemoryImprintToBuilds(MemoryImprint memoryImprint) { final List<Run> runs = new ArrayList<Run>(memoryImprint.getEntries().length); for (Entry entry : memoryImprint.getEntries()) { if (entry == null || entry.getBuild() == null) { continue; } runs.add(entry.getBuild()); } return runs; }
Source:
public void setEntryCustomUrl(GerritTriggeredEvent event, Run r, String customUrl) { MemoryImprint pb = getMemoryImprint(event); if (pb != null) { Entry entry = pb.getEntry(r.getParent()); if (entry != null) { START logger.info("Recording custom URL for {}: {}", event, customUrl); END entry.setCustomUrl(customUrl); } } } lower this to `debug` or `trace` and you can fix around line 422 while you're at it ;)

Target:
public void setEntryCustomUrl(GerritTriggeredEvent event, Run r, String customUrl) { MemoryImprint pb = getMemoryImprint(event); if (pb != null) { Entry entry = pb.getEntry(r.getParent()); if (entry != null) { logger.trace("Recording custom URL for {}: {}", event, customUrl); entry.setCustomUrl(customUrl); } } }
Source:
public static DependencyQueueTaskDispatcher getInstance() { ExtensionList<DependencyQueueTaskDispatcher> dispatchers = Jenkins.getInstance().getExtensionList(DependencyQueueTaskDispatcher.class); START if (dispatchers == null) { END return null; } return dispatchers.get(0); } I guess the list could be empty as well causing an indexoutofbounds on line 110. so adding " || dispatchers.isEmpty()" would make it safer.

Target:
public static DependencyQueueTaskDispatcher getInstance() { ExtensionList<DependencyQueueTaskDispatcher> dispatchers = Jenkins.getInstance().getExtensionList(DependencyQueueTaskDispatcher.class); if (dispatchers == null || dispatchers.isEmpty()) { return null; } return dispatchers.get(0); }
Source:
public boolean initialize() { if (events == null) { try { events = CacheBuilder.newBuilder() START .expireAfterWrite(unit.toMillis(expiration), TimeUnit.MILLISECONDS) END .build(); logger.info("initialized replication cache with expiration in {}: {}", unit, expiration); } catch (Exception ex) { logger.warn("initialize failure in {}: {}", unit, expiration); return false; } } return true; } Why not use the unit as the second parameter?

Target:
public boolean initialize() { if (events == null) { try { events = CacheBuilder.newBuilder() .expireAfterWrite(expiration, unit) .build(); logger.info("initialized replication cache with expiration in {}: {}", unit, expiration); } catch (Exception ex) { logger.warn("initialize failure in {}: {}", unit, expiration); return false; } } return true; }
Source:
public List<PreparedRemark> prepareRemarkList(List<Remark> list) { if (list.isEmpty()) { return ImmutableList.of(); } List<PreparedRemark> remarksPrepared = new ArrayList<PreparedRemark>(list.size()); for (Remark remark : list) { try{ User refUser = userDao.getUserCached(remark.getRefUserId()); remarksPrepared.add(new PreparedRemark(remark,refUser)); START }catch(UserNotFoundException e){ END } } return remarksPrepared; } лучше этот Exception выбрасывать на верхний уровень или обернуть в RuntimeException если не хочется его везде прописывать. Т.к. его возникновение это признак нарушения целостности БД или программной ошибки.

Target:
public List<PreparedRemark> prepareRemarkList(List<Remark> list) throws Exception { if (list.isEmpty()) { return ImmutableList.of(); } List<PreparedRemark> remarksPrepared = new ArrayList<PreparedRemark>(list.size()); for (Remark remark : list) { User refUser = userDao.getUserCached(remark.getRefUserId()); remarksPrepared.add(new PreparedRemark(remark,refUser)); } return remarksPrepared; }
Source:
public void deleteTagFromTopic(int msgId, int tagId) { jdbcTemplate.update( "DELETE FROM tags WHERE msgid=? and tagid=?", START new Object[]{new Integer(msgId), new Integer(tagId)} END ); } Такая конструкция избыточна, там помоему можно просто писать ", msgid, tagid" - работает varargs + auto boxing

Target:
public void deleteTagFromTopic(int msgId, int tagId) { jdbcTemplate.update( "DELETE FROM tags WHERE msgid=? and tagid=?", new Object[]{ msgId, tagId } ); }
Source:
public String getOriginalFileName() { String idArray[] = this.id.split("/"); int idLen = idArray.length; String originalFileName = ""; START if(idArray != null && idArray.length>0) { END originalFileName = idArray[idLen-1]; } return originalFileName; } If you're pulling out `idLen` variable then you should use it consistently throughout the code. There's also no need for the `null` check here as the code would have already thrown a NPE on line 4483 if idArray was `null`.

Target:
public String getOriginalFileName() { String idArray[] = this.id.split("/"); String originalFileName = ""; if(idArray != null && idArray.length>0) { originalFileName = idArray[idArray.length-1]; } return originalFileName; }
Source:
public Set<String> availableRoleIds() { START String[] configStrings = ServerConfigurationService.getStrings("access.enabledRoles"); END LinkedHashSet<String> availableIds = new LinkedHashSet<String>(); availableIds.addAll(Arrays.asList(configStrings)); if(!this.isPubviewPossible) { availableIds.remove(PUBVIEW_ROLE); } return availableIds; } If this isn't defined then it will return a `null` and when doing the `Arrays.asList(null)` and NPE will get thrown.

Target:
public Set<String> availableRoleIds() { String[] configStrings = ServerConfigurationService.getStrings("access.enabledRoles"); LinkedHashSet<String> availableIds = new LinkedHashSet<String>(); if(configStrings != null) { availableIds.addAll(Arrays.asList(configStrings)); } if(!this.isPubviewPossible) { availableIds.remove(PUBVIEW_ROLE); } return availableIds; }
Source:
private int getKeySize() { START return _keySize; END } If the `_keySize` is an `Integer` then return that here so it doesn't get unboxed and reboxed. Use `int` everywhere or `Integer` everywhere.

Target:
private Integer getKeySize() { return _keySize; }
Source:
public void notifyBegin(List<Response.ResponseListener> listeners, Response response) { for (int i = 0; i < listeners.size(); i++) { START Response.ResponseListener listener = listeners.get(i); END if (listener instanceof Response.BeginListener) notifyBegin((Response.BeginListener)listener, response); } } I don't think we need to do this - the List iterator is supposed to be simple and in this case the JIT should eliminate its allocation.

Target:
public void notifyBegin(List<Response.ResponseListener> listeners, Response response) { for (Response.ResponseListener listener : listeners) { if (listener instanceof Response.BeginListener) notifyBegin((Response.BeginListener)listener, response); } }
Source:
START public HttpFields.Mutable getTrailers() END { return trailers; } Should not this be just `HttpFields` as return type?

Target:
public HttpFields getTrailers() { return trailers; }
Source:
public void test303(Scenario scenario) throws Exception { start(scenario, new RedirectHandler()); Response response = client.newRequest("localhost", connector.getLocalPort()) .scheme(scenario.getScheme()) .path("/303/localhost/done") .timeout(5, TimeUnit.SECONDS) .send(); assertNotNull(response); assertEquals(200, response.getStatus()); START assertFalse(response.getHeaders().contains(HttpHeader.LOCATION.asString())); END } Since you have replaced `containsKey()` with `contains()`, can you also remove all the `.asString()` in this class, now that `contains()` takes a `HttpHeader`?

Target:
public void test303(Scenario scenario) throws Exception { start(scenario, new RedirectHandler()); Response response = client.newRequest("localhost", connector.getLocalPort()) .scheme(scenario.getScheme()) .path("/303/localhost/done") .timeout(5, TimeUnit.SECONDS) .send(); assertNotNull(response); assertEquals(200, response.getStatus()); assertFalse(response.getHeaders().contains(HttpHeader.LOCATION)); }
Source:
public String getQueryEncoding() { START return _queryEncoding == null ? null : _queryEncoding.toString(); END } Should be `_queryEncoding.name()`, not `toString()`.

Target:
public String getQueryEncoding() { return _queryEncoding == null ? null : _queryEncoding.name(); }
Source:
public void setMaxInactiveInterval(int seconds) { _dftMaxIdleSecs = seconds; START System.err.println("SETMAXINACTIVE = " + seconds); END if (LOG.isDebugEnabled()) { if (_dftMaxIdleSecs <= 0) LOG.debug("Sessions created by this manager are immortal (default maxInactiveInterval={})", _dftMaxIdleSecs); else LOG.debug("SessionManager default maxInactiveInterval={}", _dftMaxIdleSecs); } } println left in

Target:
public void setMaxInactiveInterval(int seconds) { _dftMaxIdleSecs = seconds; if (LOG.isDebugEnabled()) { if (_dftMaxIdleSecs <= 0) LOG.debug("Sessions created by this manager are immortal (default maxInactiveInterval={})", _dftMaxIdleSecs); else LOG.debug("SessionManager default maxInactiveInterval={}", _dftMaxIdleSecs); } }
Source:
public int getSessionTimeout() { START System.err.println("CALLING GETSESSIONTIMEOUT"); END if (!isStarting()) throw new IllegalStateException(); if (!_enabled) throw new UnsupportedOperationException(); int timeout = -1; if (_sessionHandler != null) { timeout = _sessionHandler.getMaxInactiveInterval(); System.err.println("GETSESSIONTIMEOUT FROM SESSIONHANDLER = " + timeout); } return (int)TimeUnit.SECONDS.toMinutes(timeout); } ditto... and more below

Target:
public int getSessionTimeout() { if (!isStarting()) throw new IllegalStateException(); if (!_enabled) throw new UnsupportedOperationException(); int timeout = -1; if (_sessionHandler != null) { timeout = _sessionHandler.getMaxInactiveInterval(); } return (int)TimeUnit.SECONDS.toMinutes(timeout); }
Source:
protected void onError(HttpField field, Throwable t) { LOG.warn("Exception while processing {}", field, t); START throw new BadMessageException("Bad header value for " + field.getName()); END } add the Throwable t as the cause of this exception

Target:
protected void onError(HttpField field, Throwable t) { throw new BadMessageException("Bad header value for " + field.getName(), t); }
Source:
public AmplitudeClient(String instance) { this.instanceName = Utils.normalizeInstanceName(instance); START this.url = Constants.EVENT_LOG_URL; END logThread.start(); httpThread.start(); } I kinda like leaving this set when the variable is declared, but either way is fine.

Target:
public AmplitudeClient(String instance) { this.instanceName = Utils.normalizeInstanceName(instance); logThread.start(); httpThread.start(); }
Source:
protected void updateServer() { updateServer(false); START if (logDiagnosticEvents) { END Diagnostics.getLogger().flushEvents(); } } is this boolean necessary here? can we just delegate the check if diagnostics are enabled to the diagnostics logger?

Target:
protected void updateServer() { updateServer(false); Diagnostics.getLogger().flushEvents(); }
Source:
protected JSONObject getApiPropertiesTrackingOptions() { JSONObject apiPropertiesTrackingOptions = new JSONObject(); START if (disabledFields.size() == 0) { END return apiPropertiesTrackingOptions; } for (String key : SERVER_SIDE_PROPERTIES) { if (disabledFields.contains(key)) { try { apiPropertiesTrackingOptions.put(key, false); } catch (JSONException e) { AmplitudeLog.getLogger().e(TAG, e.toString()); } } } return apiPropertiesTrackingOptions; } Prefer `isEmpty()`.

Target:
protected JSONObject getApiPropertiesTrackingOptions() { JSONObject apiPropertiesTrackingOptions = new JSONObject(); if (disabledFields.isEmpty()) { return apiPropertiesTrackingOptions; } for (String key : SERVER_SIDE_PROPERTIES) { if (disabledFields.contains(key)) { try { apiPropertiesTrackingOptions.put(key, false); } catch (JSONException e) { AmplitudeLog.getLogger().e(TAG, e.toString()); } } } return apiPropertiesTrackingOptions; }
Source:
private String getCountryFromNetwork() { TelephonyManager manager = (TelephonyManager) context .getSystemService(Context.TELEPHONY_SERVICE); try { if (manager.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA) { String country = manager.getNetworkCountryIso(); if (country != null) { return country.toUpperCase(Locale.US); } } START } catch (NullPointerException e) { END // Failed to get phone type } catch (Resources.NotFoundException e) { // Failed to get phone type } return null; } I hesitate to say this, but I think catching all Exceptions would make sense here, as it's a system call and not much we can do about it. It should probably also include the getSystemService call on line 149.

Target:
private String getCountryFromNetwork() { try { TelephonyManager manager = (TelephonyManager) context .getSystemService(Context.TELEPHONY_SERVICE); if (manager.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA) { String country = manager.getNetworkCountryIso(); if (country != null) { return country.toUpperCase(Locale.US); } } } catch (Exception e) { // Failed to get country from network } return null; }
Source:
START public Iterable<DynamicTest> verifySquares() { END return Arrays.asList( testSquareAt(0, 0), testSquareAt(1, 2), testSquareAt(0, 1) ); } This could use the new parameterized support in m4

Target:
Iterable<DynamicTest> verifySquares() { return Arrays.asList( testSquareAt(0, 0), testSquareAt(1, 2), testSquareAt(0, 1) ); }
Source:
public void setText(final String text) { START if (this.text != null) { END this.text.setText(text); return; } this.text = new Text(text); add(this.text, (Element) getElement()); } Would it be better/easier to just have the `Text` be created/added in the constructor then just set/get from there? Could you try that?

Target:
public void setText(final String text) { this.text = new Text(text); add(this.text, (Element) getElement()); }
Source:
public Column(final ColumnSize firstSize, final ColumnSize... otherSizes) { setSize(firstSize, otherSizes); START setStyleName(firstSize.getCssName()); END } Why is this required? Shouldn't it be handled by `setSize()`?

Target:
public Column(final ColumnSize firstSize, final ColumnSize... otherSizes) { setSize(firstSize, otherSizes); }
Source:
public Point indexCenterPoint(int index){ START if(index < 0 || index > Constants.INVENTORY_SIZE){ END throw new IndexOutOfBoundsException(); } final Point base = component().screenPoint(); final int x = base.x - 3 + (index % 4) * WIDTH; final int y = base.y - 2 + (index / 4) * HEIGHT; return new Point(x + WIDTH / 2, y + HEIGHT / 2); } Should be `index > Constants.INVENTORY_SIZE - 1` since you're dealing with an index.

Target:
public Point indexCenterPoint(int index){ if(index < 0 || index > Constants.INVENTORY_SIZE - 1){ throw new IndexOutOfBoundsException(); } final Point base = component().screenPoint(); final int x = base.x - 3 + (index % 4) * WIDTH; final int y = base.y - 2 + (index / 4) * HEIGHT; return new Point(x + WIDTH / 2, y + HEIGHT / 2); }
Source:
public boolean isFull() { START return ctx.inventory.select().size() > Constants.INVENTORY_SIZE-1; END } I would suggest you to improve readability by changing it to `ctx.inventory.select().size() >= Constants.INVENTORY_SIZE`

Target:
public boolean isFull() { return ctx.inventory.select().size() >= Constants.INVENTORY_SIZE; }
Source:
public void poll() { if (getLogCount() > 0 && !inBank()) { burn(); } else if (!inBank()){ walkToBank(); } else if (inBank() && getLogCount() > 0) { leaveBank(); START } else { END bank(); } } Having an else statement in your poll() method means that your script will always be doing something, even when you don't want it to. What happens if the script gets stuck or none of your methods return the proper values?

Target:
public void poll() { if (getLogCount() > 0 && !inBank()) { burn(); } else if (!inBank() && getLogCount() == 0){ walkToBank(); } else if (inBank() && getLogCount() > 0) { leaveBank(); } else if (inBank() && getLogCount() == 0){ bank(); } }
Source:
public boolean inBank() { START Area bankArea = new Area(new Tile(3179, 3447), new Tile(3191,3433)); END return bankArea.contains(ctx.players.local()); } Make your bankArea a class-wide variable and have it populated once your script starts. Currently, your poll() method has the possibility of creating the same bankArea three times, which is a waste of resources and could potentially slow down the script.

Target:
public boolean inBank() { return bankArea.contains(ctx.players.local()); }
Source:
public void start() { // Checks if logged in START if (!ctx.game.loggedIn()){ END ctx.controller.stop(); return; } System.out.println("Script Started!"); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new Gui(); } }); } You don't need to worry about whether or not the player is logged in; the script's start() method will not be invoked until the player is in game.

Target:
public void start() { System.out.println("Script Started!"); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new Gui(); } }); }
Source:
public Book book() { for(Book b : Book.values()) { START if((ctx.varpbits.varpbit(Constants.SPELLBOOK_VARPBIT) & 0x3) == END b.varp) return b; } return Book.NIL; } Introduce a local variable for varp value so you don't have to grab it each iteration.

Target:
public Book book() { int varp = ctx.varpbits.varpbit(Constants.SPELLBOOK_VARPBIT) & 0x3; for(Book b : Book.values()) { if(varp == b.varp) return b; } return Book.NIL; }
Source:
public boolean clickContinue(final boolean key) { START final Component c = getContinue(); END if (c != null) { if (key) { ctx.input.send(" "); return true; } else { return c.click(); } } return false; } This can be simplified a ton. `return c != null && ((key && ctx.input.send("{VK_SPACE}")) || c.click())` The line note didn't turn out the way it should have; I meant the `clickContinue(boolean key)` method.

Target:
public boolean clickContinue(final boolean key) { final Component c = getContinue(); return c != null && (key && ctx.input.send(" ") || c.click()); }
Source:
public Doc() { meta = new Meta(); file = new File(); path = new Path(); START external = new HashMap<>(); END } I wonder if this should be `null` by default so it won't generate an empty property `external` when not needed?

Target:
public Doc() { meta = new Meta(); file = new File(); path = new Path(); external = null; }
Source:
public static String getFileExtension(File file) { String extension; try { extension = FilenameUtils.getExtension(file.getAbsolutePath()); START } catch (Exception e) { END extension = null; } return extension.toLowerCase(); } Might be better to throw the Exception instead of swallowing it. I'd write something like: ```java public static String getFileExtension(File file) throws Exception { return FilenameUtils.getExtension(file.getAbsolutePath()).toLowerCase(); } ``` This new method might deserve also some unit test in `FsCrawlerUtilTest`.

Target:
public static String getFileExtension(File file) { return FilenameUtils.getExtension(file.getAbsolutePath()).toLowerCase(); }
Source:
private SearchResponse runSearch(String filename, String content) throws IOException { logger.info(" -> Testing if file has been indexed correctly{}.", filename, content == null ? "" : " and contains [" + content + "]"); String fullQuery = "+file.filename:\"" + filename + "\""; if (content != null) { fullQuery += " +content:" + content; } START SearchResponse response = elasticsearchClient.search("fscrawler_test_all_documents", null, fullQuery, 10, "*"); END assertThat(response.getHits().getTotal(), is(1L)); return response; } Use here `ElasticsearchClient.defaultSearchSize` instead?

Target:
private SearchResponse runSearch(String filename, String content) throws IOException { logger.info(" -> Testing if file has been indexed correctly{}.", filename, content == null ? "" : " and contains [" + content + "]"); String fullQuery = "+file.filename:\"" + filename + "\""; if (content != null) { fullQuery += " +content:" + content; } SearchResponse response = elasticsearchClient.search("fscrawler_test_all_documents", null, fullQuery, 10, null); assertThat(response.getHits().getTotal(), is(1L)); return response; }
Source:
private void recycle() { START if(!options.isKeepAliveTTLEnabled()) END expirationTimestamp = keepAliveTimeout == 0 ? 0L : System.currentTimeMillis() + keepAliveTimeout * 1000; else { long now = System.currentTimeMillis(); long keepAliveTTL = options.getKeepAliveTTL() * 1000 - (now - initialTimestamp); expirationTimestamp = keepAliveTimeout == 0 || (keepAliveTTL <= 0) ? 0L : Math.min(now + keepAliveTimeout * 1000, now + keepAliveTTL); } listener.onRecycle(); } this should actually be moved to `isValid` and when initialTimestamp > keepAliveTTL then return false

Target:
private void recycle() { expirationTimestamp = keepAliveTimeout == 0 ? 0L : System.currentTimeMillis() + keepAliveTimeout * 1000; listener.onRecycle(); }
Source:
public boolean isValid() { long now = System.currentTimeMillis(); START return expirationTimestamp == 0 || now <= expirationTimestamp && (!options.isKeepAliveTTLEnabled() || options.getKeepAliveTTL() * 1000 > now - initialTimestamp); END } can you surround with parenthesis the two expressions right and left of `&&` to make it more clear ?

Target:
public boolean isValid() { long now = System.currentTimeMillis(); return (expirationTimestamp == 0 || now <= expirationTimestamp) && (!options.isKeepAliveTTLEnabled() || options.getKeepAliveTTL() * 1000 > now - initialTimestamp); }
Source:
public void testListenInvalidPort() { final int port = 9090; final HttpServer httpServer = vertx.createHttpServer() .requestHandler(ignore -> {}) .listen(port, onSuccess(s -> vertx.createNetServer() .connectHandler(ignore -> {}) .listen(port, onFailure(error -> { assertNotNull(error); testComplete(); })))); await(); START httpServer.close(); END } we need this close to be in a finally block

Target:
public void testListenInvalidPort() { final int port = 9090; final HttpServer httpServer = vertx.createHttpServer(); try { httpServer.requestHandler(ignore -> {}) .listen(port, onSuccess(s -> vertx.createNetServer() .connectHandler(ignore -> {}) .listen(port, onFailure(error -> { assertNotNull(error); testComplete(); })))); await(); } finally { httpServer.close(); } }
Source:
void register() { START register(repliedAddress, true, Promise.promise()); END } we should pass `null` and allow the downstream `EventBusImpl#addRegistration` to be passed `null`, to avoid creating a `Promise` when it is not needed.

Target:
void register() { register(repliedAddress, true, null); }
Source:
public <T> T convert(Class<T> type) { try { if (type == JsonObject.class || type == JsonArray.class) { return (T) Json.decodeValue(buffer.toString()); } else { return Json.decodeValue(buffer.toString(), type); } } catch (Exception e) { START e.printStackTrace(); END throw new DecodeException(e.getMessage()); } } no print stacktrace

Target:
public <T> T convert(Class<T> type) { try { if (type == JsonObject.class || type == JsonArray.class) { return (T) Json.decodeValue(buffer.toString()); } else { return Json.decodeValue(buffer.toString(), type); } } catch (Exception e) { throw new DecodeException(e.getMessage()); } }
Source:
public void example1Pointers() { // Build a pointer from a string JsonPointer pointer1 = JsonPointer.from("/hello/world"); // Build a pointer from an URI START JsonPointer pointer2 = JsonPointer.fromURI(URI.create("#/hello/world")); END // Build a pointer manually JsonPointer pointer3 = JsonPointer.create() .append("hello") .append("world"); } don't use URI here as it will not be translated to other languages.

Target:
public void example1Pointers() { // Build a pointer from a string JsonPointer pointer1 = JsonPointer.from("/hello/world"); // Build a pointer manually JsonPointer pointer2 = JsonPointer.create() .append("hello") .append("world"); }
Source:
void timeout() { if (status.compareAndSet(Status.WAITING, Status.TIMED_OUT)) { START handler.handle(Future.failedFuture(new VertxException("Timed out waiting to get lock"))); END } } use instead the string version in order to avoid creating a costly stack trace creation with the exception.

Target:
void timeout() { if (status.compareAndSet(Status.WAITING, Status.TIMED_OUT)) { handler.handle(Future.failedFuture("Timed out waiting to get lock")); } }
Source:
void handleClosed() { START Handler<Void> endHandler = this.endHandler; END synchronized (conn) { cleanupHandlers(); Handler<Void> closeHandler = this.closeHandler; if (closeHandler != null) { conn.getContext().runOnContext(closeHandler); } } if (endHandler != null) { endHandler.handle(null); } } endHandler must be read in the synchronized block

Target:
void handleClosed() { Handler<Void> endHandler; synchronized (conn) { cleanupHandlers(); endHandler = this.endHandler; Handler<Void> closeHandler = this.closeHandler; if (closeHandler != null) { conn.getContext().runOnContext(closeHandler); } } if (endHandler != null) { endHandler.handle(null); } }
Source:
public void setUp() throws Exception { super.setUp(); START if (USE_DOMAIN_SOCKETS) { END assertTrue("Native transport not enabled", USE_NATIVE_TRANSPORT); tmp = TestUtils.tmpFile("vertx", ".sock"); testAddress = SocketAddress.domainSocketAddress(tmp.getAbsolutePath()); } else { testAddress = SocketAddress.inetSocketAddress(1234, "localhost"); } testDir = testFolder.newFolder(); } actually we don't need this because it cannot work since we only have HTTP server with domain sockets and not HTTP client, that's why only a simple test is necessary

Target:
public void setUp() throws Exception { super.setUp(); testDir = testFolder.newFolder(); }