auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public boolean shouldRetryRequest(HttpCommand command, HttpResponse response) { boolean retry = false; try { byte[] data = closeClientButKeepContentStream(response); START String message = data != null ? new String(data) : null; END switch (response.getStatusCode()) { case 500: case 503: retry = super.shouldRetryRequest(command, response); break; default: break; } } finally { releasePayload(response); } return retry; } Message seems to be unused. Remove this line?

Target:
public boolean shouldRetryRequest(HttpCommand command, HttpResponse response) { boolean retry = false; try { byte[] data = closeClientButKeepContentStream(response); switch (response.getStatusCode()) { case 500: case 503: retry = super.shouldRetryRequest(command, response); break; default: break; } } finally { releasePayload(response); } return retry; }
Source:
public static void addRecoveryListenerIfNecessary(Channel channel) { if (channel instanceof ChannelProxy) { if (((ChannelProxy) channel).getTargetChannel() instanceof AutorecoveringChannel) { START AutorecoveringChannel autorecoveringChannel = (AutorecoveringChannel) ((ChannelProxy) channel) END .getTargetChannel(); if (hasListener.putIfAbsent(autorecoveringChannel, Boolean.TRUE) == null) { autorecoveringChannel.addRecoveryListener(INSTANCE); } } } } Don't we need to deal with an `else` variant as well? On the other hand why `ChannelProxy` can't implement `AutorecoveringChannel` and delegate respectively? Although I believe there is going to be some overhead since we may disable auto-recovery, but we still fill up this cache almost for nothing...

Target:
public static void addRecoveryListenerIfNecessary(Channel channel) { AutorecoveringChannel autorecoveringChannel = null; if (channel instanceof ChannelProxy) { if (((ChannelProxy) channel).getTargetChannel() instanceof AutorecoveringChannel) { autorecoveringChannel = (AutorecoveringChannel) ((ChannelProxy) channel) .getTargetChannel(); } } else if (channel instanceof AutorecoveringChannel) { autorecoveringChannel = (AutorecoveringChannel) channel; } if (autorecoveringChannel != null && hasListener.putIfAbsent(autorecoveringChannel, Boolean.TRUE) == null) { autorecoveringChannel.addRecoveryListener(INSTANCE); } }
Source:
public DelegatingTemplateEngine(final CompositeConfiguration config, final ContentStore db, final File destination, final File templatesPath) { super(config, db, destination, templatesPath); this.renderers = new TemplateEngines(config, db, destination, templatesPath); START this.registerExtractorsForCustomTypes(); END } Was thinking about this.... could this call happen when other types are registered by Oven in DocumentTypes or was there a specific reason this occurs here?

Target:
public DelegatingTemplateEngine(final CompositeConfiguration config, final ContentStore db, final File destination, final File templatesPath) { super(config, db, destination, templatesPath); this.renderers = new TemplateEngines(config, db, destination, templatesPath); }
Source:
START NavigableSet<Clustering> makeClusterings(boolean reversed) END { int pos = 0; NavigableSet<Clustering> clusterings = new TreeSet<>(reversed ? metadata.comparator.reversed() : metadata.comparator); while (pos <= KEY_RANGE) { int skip = rand.nextInt(KEY_RANGE / 10) * (rand.nextInt(3) + 2 / 3); // increased chance of getting 0 pos += skip; clusterings.add(clustering(pos)); } return clusterings; } Nit: can be private

Target:
private NavigableSet<Clustering> makeClusterings(boolean reversed) { int pos = 0; NavigableSet<Clustering> clusterings = new TreeSet<>(reversed ? metadata.comparator.reversed() : metadata.comparator); while (pos <= KEY_RANGE) { int skip = rand.nextInt(KEY_RANGE / 10) * (rand.nextInt(3) + 2 / 3); // increased chance of getting 0 pos += skip; clusterings.add(clustering(pos)); } return clusterings; }
Source:
START public Optional<String> getExtension() { END return Optional.fromNullable(extension); } Each of the getters in a POJO like this should have the same return type as the private member variables they expose. In this case, I'd recommend having `extension`, `dateformat`, and `frequencyOverride` be `Optional<>`s (in both their member variable types and their getter types). Our Jackson YAML deserialization should automatically take care of setting a missing field to an empty `Optional<>` in the resulting Java object.

Target:
public Optional<String> getExtension() { return extension; }
Source:
@Test START public void END constructor_nullDelegate() { try { new ForwardingOs(null) { }; fail(); } catch (NullPointerException expected) { } } Newline between @Test and public. There's only 4 instances like this in the libcore source, hundreds with it on its own line.

Target:
public void constructor_nullDelegate() { try { new ForwardingOs(null) {}; fail(); } catch (NullPointerException expected) { } }
Source:
public boolean visitEnter(FunctionParseNode node) throws SQLException { // TODO: Oracle supports nested aggregate function while other DBs don't. Should we? if (node.isAggregate()) { if (aggregateFunction != null) { throw new SQLFeatureNotSupportedException("Nested aggregate functions are not supported"); } this.aggregateFunction = node; this.isAggregate = true; START } else if(node.getClass().isAssignableFrom(ArrayIndexFunction.class)) { END this.isAggregate = true; } return true; } Remove this change please

Target:
public boolean visitEnter(FunctionParseNode node) throws SQLException { // TODO: Oracle supports nested aggregate function while other DBs don't. Should we? if (node.isAggregate()) { if (aggregateFunction != null) { throw new SQLFeatureNotSupportedException("Nested aggregate functions are not supported"); } this.aggregateFunction = node; this.isAggregate = true; } return true; }
Source:
public int hashCode() { START return Objects.hash(baseDataSource + dimensions + metrics); END } Probably `Objects.hash(baseDataSource, dimensions, metrics);`?

Target:
public int hashCode() { return Objects.hash(baseDataSource, dimensions, metrics); }
Source:
public boolean registerIfNew(String name, AsyncHttpClient ahc) { AsyncHttpClient value = asyncHttpClientMap.putIfAbsent(name, ahc); if (value == null) return true; else return false; START } END `return asyncHttpClientMap.putIfAbsent(name, ahc) == null;

Target:
public boolean registerIfNew(String name, AsyncHttpClient ahc) { return asyncHttpClientMap.putIfAbsent(name, ahc)==null; }
Source:
public Node getContextNode() { START return getLibraryNode() != null || getParent() == null ? this : org.raml.yagi.framework.util.NodeUtils.getContextNode(getParent()); END } You can replace the qualified name with import

Target:
public Node getContextNode() { return getLibraryNode() != null || getParent() == null ? this : NodeUtils.getContextNode(getParent()); }
Source:
private void getLazyRoutingConfig() { START ImportHelper.loadRoutingFiles(app, new ImportHelper.LoadRoutingFilesCallback() { END @Override public void onRoutingFilesLoaded() { notifyEvent(InitEvents.ROUTING_CONFIG_INITIALIZED); } }); } Do not move it to ImportHelper

Target:
private void getLazyRoutingConfig() { loadRoutingFiles(app, new LoadRoutingFilesCallback() { @Override public void onRoutingFilesLoaded() { notifyEvent(InitEvents.ROUTING_CONFIG_INITIALIZED); } }); }
Source:
public <T> T toObject(ParameterizedTypeReference<T> type) { Assert.notNull(type, "Target type must not be null!"); START final String url = traverseToFinalUrl(true); END return operations.exchange(url, GET, prepareRequest(headers), type).getBody(); } Doesn't need to be final.

Target:
public <T> T toObject(ParameterizedTypeReference<T> type) { Assert.notNull(type, "Target type must not be null!"); return operations.exchange(traverseToFinalUrl(true), GET, prepareRequest(headers), type).getBody(); }
Source:
public ValidationResult validateMacAddress(List<? extends VmNic> vmNics) { for (VmNic iface : vmNics) { String START str = END iface.getMacAddress(); if (str != null) { if (!VALIDATE_MAC_ADDRESS.matcher(iface.getMacAddress()).matches()) { return new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_NETWORK_INTERFACE_MAC_INVALID, String.format("$IfaceName %1$s", iface.getName()), String.format("$MacAddress %1$s", iface.getMacAddress())); } } } return ValidationResult.VALID; } please inline this variable

Target:
public ValidationResult validateMacAddress(List<? extends VmNic> vmNics) { for (VmNic iface : vmNics) { if (iface.getMacAddress() != null) { if (!VALIDATE_MAC_ADDRESS.matcher(iface.getMacAddress()).matches()) { return new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_NETWORK_INTERFACE_MAC_INVALID, String.format("$IfaceName %1$s", iface.getName()), String.format("$MacAddress %1$s", iface.getMacAddress())); } } } return ValidationResult.VALID; }
Source:
public List<AuditLogWithHistory> getAuditLogsWithHistoryForId(final UUID accountId, final AuditLevel auditLevel, final InternalTenantContext context) throws AccountApiException { START return transactionalSqlDao.execute(false, AccountApiException.class, new EntitySqlDaoTransactionWrapper<List<AuditLogWithHistory>>() { END @Override public List<AuditLogWithHistory> inTransaction(final EntitySqlDaoWrapperFactory entitySqlDaoWrapperFactory) throws EntityPersistenceException, EventBusException { final AccountSqlDao transactional = entitySqlDaoWrapperFactory.become(AccountSqlDao.class); return auditDao.getAuditLogsWithHistoryForId(transactional, TableName.ACCOUNT, accountId, auditLevel, context); } }); } `true` instead (it's a read-only operation).

Target:
public List<AuditLogWithHistory> getAuditLogsWithHistoryForId(final UUID accountId, final AuditLevel auditLevel, final InternalTenantContext context) throws AccountApiException { return transactionalSqlDao.execute(true, AccountApiException.class, new EntitySqlDaoTransactionWrapper<List<AuditLogWithHistory>>() { @Override public List<AuditLogWithHistory> inTransaction(final EntitySqlDaoWrapperFactory entitySqlDaoWrapperFactory) { final AccountSqlDao transactional = entitySqlDaoWrapperFactory.become(AccountSqlDao.class); return auditDao.getAuditLogsWithHistoryForId(transactional, TableName.ACCOUNT, accountId, auditLevel, context); } }); }
Source:
public void run() { while (true) { updateTraceEntry(fTimeAnalysisEntry, Long.MAX_VALUE, fRange.getStartTime().toNanos(), fRange.getEndTime().toNanos()); synchronized (fProcessTraceThreads) { if (fRestart) { fRestart = false; } else { fProcessTraceThreads.remove(fTimeAnalysisEntry.getTrace()); START break; END } } } } should this be return?

Target:
public void run() { while (true) { updateTraceEntry(fTimeAnalysisEntry, Long.MAX_VALUE, fRange.getStartTime().toNanos(), fRange.getEndTime().toNanos()); synchronized (fProcessTraceThreads) { if (fRestart) { fRestart = false; } else { fProcessTraceThreads.remove(fTimeAnalysisEntry.getTrace()); return; } } } }
Source:
public final Object visitInvalidateCommand(InvocationContext ctx, InvalidateCommand command) throws Throwable { try { if (hasSkipLocking(command)) { return invokeNextInterceptor(ctx, command); } START lockAllAndRecord(ctx, Arrays.stream(command.getKeys()), getLockTimeoutMillis(command)); END return invokeNextInterceptor(ctx, command); } finally { if (!ctx.isInTxScope()) { lockManager.unlockAll(ctx); } } } Wouldn't `Arrays.asList()` be enough here? `Arrays.stream` seems to have a lot of memory overhead.

Target:
public final Object visitInvalidateCommand(InvocationContext ctx, InvalidateCommand command) throws Throwable { try { if (hasSkipLocking(command)) { return invokeNextInterceptor(ctx, command); } lockAllAndRecord(ctx, Arrays.asList(command.getKeys()), getLockTimeoutMillis(command)); return invokeNextInterceptor(ctx, command); } finally { if (!ctx.isInTxScope()) { lockManager.unlockAll(ctx); } } }
Source:
public GeographyPointValue(double longitude, double latitude) { // Add 0.0 to avoid -0.0. START m_latitude = latitude + 0.0; END m_longitude = longitude + 0.0; if (m_latitude < -90.0 || m_latitude > 90.0) { throw new IllegalArgumentException("Latitude out of range in GeographyPointValue constructor"); } if (m_longitude < -180.0 || m_longitude > 180.0) { throw new IllegalArgumentException("Longitude out of range in GeographyPointValue constructor"); } } This seems esoteric. What's wrong with -0.0 here?

Target:
public GeographyPointValue(double longitude, double latitude) { m_latitude = latitude; m_longitude = longitude; if (m_latitude < -90.0 || m_latitude > 90.0) { throw new IllegalArgumentException("Latitude out of range in GeographyPointValue constructor"); } if (m_longitude < -180.0 || m_longitude > 180.0) { throw new IllegalArgumentException("Longitude out of range in GeographyPointValue constructor"); } }
Source:
public final static AttachmentSizeFormatter getInstance() { try { START return new AttachmentSizeFormatter(); END } catch (ClassCastException e) { return new AttachmentSizeFormatter(Locale.ENGLISH); } } should we not just always use Locale.English? Based on the formats we give it I'm not sure what effect other locales would actually ever have.

Target:
public final static AttachmentSizeFormatter getInstance() { return new AttachmentSizeFormatter(); }
Source:
private static void initOculus() { switch (LWJGLUtil.getPlatform()) { START case LWJGLUtil.PLATFORM_WINDOWS: END OculusVrHelper.loadNatives(); break; } } You can just do an if statement here. :)

Target:
private static void initOculus() { if (LWJGLUtil.getPlatform() == LWJGLUtil.PLATFORM_WINDOWS) { OculusVrHelper.loadNatives(); } }
Source:
private void copyTimestampsFromChangelog(Library library) { Date earliest = getEarliestChangeDate(library); START Date latest = getLatestChangeDate(library); END library.setCreationDate(earliest); } Unused

Target:
private void copyTimestampsFromChangelog(Library library) { Date earliest = getEarliestChangeDate(library); library.setCreationDate(earliest); }
Source:
protected ProjectUploadController createProjectUploadController() { if (projectUploadController == null) { START projectUploadController = mock(ProjectUploadController.class); END } return projectUploadController; } since this happens in every test as the first thing, this probably should be in setUp(). at least the SharedPreferences call should be moved there. and i rather have the code duplication of having the two espresso clicks in each test, than this. before looking up what the method really does i suspected anything, but two clicks on "next" in it when reading the tests above.

Target:
protected ProjectUploadController createProjectUploadController() { projectUploadController = mock(ProjectUploadController.class); return projectUploadController; }
Source:
START public long getFilterBlobLimit() { END return filterSpec.getBlobLimit(); } I think we can keep this "final".

Target:
public final long getFilterBlobLimit() { return filterSpec.getBlobLimit(); }
Source:
public static IRemoteConnection createConnection(URI hostUri, String hostName) throws RemoteConnectionException { IRemoteConnection connection = null; IRemoteConnectionType connectionType = getConnectionType(hostUri); IConnectionFactory connectionFactory = CONNECTION_FACTORIES.get(connectionType.getId()); // Create a new connection if (connectionFactory != null) { connection = connectionFactory.createConnection(hostUri, hostName); } else { START connection = DEFAULT_CONNECTION_FACTORY.createConnection(hostUri, hostName); END } return connection; } You could set connectionFactory to default, and then create the connection in the return statement.

Target:
public static IRemoteConnection createConnection(URI hostUri, String hostName) throws RemoteConnectionException { IRemoteConnectionType connectionType = getConnectionType(hostUri); IConnectionFactory connectionFactory = CONNECTION_FACTORIES.get(connectionType.getId()); if (connectionFactory == null) { connectionFactory = DEFAULT_CONNECTION_FACTORY; } // Create and return a new connection return connectionFactory.createConnection(hostUri, hostName); }
Source:
protected boolean canDoAction() { StorageServerConnectionExtension conn = getParameters().getStorageServerConnectionExtension(); return validate(getConnectionExtensionValidator().isConnectionExtensionExists(conn.getId())) && START validate(getConnectionExtensionValidator().isConnectionDoesNotExistForHostAndTarget(conn.getHostId(), END conn.getIqn())); } I'd do this in the previous patch already.

Target:
protected boolean canDoAction() { StorageServerConnectionExtension conn = getParameters().getStorageServerConnectionExtension(); return validate(getConnectionExtensionValidator().isConnectionExtensionExists(conn.getId())) && validate(getConnectionExtensionValidator().isConnectionDoesNotExistForHostAndTarget(conn)); }
Source:
public void setObservationLevel(final String observationLevel) { final Integer datasetTypeId = DatasetTypeEnum.getIdByName(observationLevel); START if(datasetTypeId > 0) { END this.observationLevel = Integer.toString(datasetTypeId); } else { this.observationLevel = observationLevel; } } I think this logic should reside elsewhere, a service or controller class. A DTO usually only has properties with getters and setters. Make sure as well to have a unit test for this logic.

Target:
public void setObservationLevel(final String observationLevel) { this.observationLevel = observationLevel; }
Source:
protected IStatus run(IProgressMonitor monitor) { while (!monitor.isCanceled()) { try { Thread.sleep(INDEXING_THREAD_SLEEP_VALUE); } catch (InterruptedException e) { START Thread.currentThread().interrupt(); END } } monitor.done(); return Status.OK_STATUS; } won't exit the loop. You need to return here

Target:
protected IStatus run(IProgressMonitor monitor) { while (!monitor.isCanceled()) { try { Thread.sleep(INDEXING_THREAD_SLEEP_VALUE); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return Status.OK_STATUS; } } monitor.done(); return Status.OK_STATUS; }
Source:
public void handleClose(CloseEvent event, List<DashboardPanel> panels) { String id = event.getComponent().getId(); for (DashboardPanel panel : panels) { START if (panel.getType().replace(" ", "_").toLowerCase(Locale.ENGLISH).equals(id)) { END panel.close(); break; } } } Why can't we use id.equalIgnoreCase check instead of the other way around? This option is more flexible than hard code English locale

Target:
public void handleClose(CloseEvent event, List<DashboardPanel> panels) { String id = event.getComponent().getId(); for (DashboardPanel panel : panels) { if (id.equalsIgnoreCase(panel.getType().replace(" ", "_"))) { panel.close(); break; } } }
Source:
public LoggerServiceImpl() { actions.put( "log-record", new Runnable() { @Override public void run() { logrecord(); } } ); START } END so you do not need default constructor now, night?

Target:
public LoggerServiceImpl() { }
Source:
public void setMaxRowSize(int rowSize) { START if (maxRowSize == -1) { END maxRowSize = rowSize; } else { if (maxRowSize < rowSize) { maxRowSize = rowSize; } } } if rowsize is always positive the check for -1 is not necessary

Target:
public void setMaxRowSize(int rowSize) { if (rowSize > maxRowSize) { maxRowSize = rowSize; } }
Source:
START public InodeLockList() { END mInodes = new ArrayList<>(); mLockModes = new ArrayList<>(); } is this change no longer necessary?

Target:
InodeLockList() { mInodes = new ArrayList<>(); mLockModes = new ArrayList<>(); }
Source:
public void testBuildBlobId() throws Exception { START for (Short version : versions) { END buildBlobIdAndAssert(version, referenceFlag, referenceDatacenterId, referenceAccountId, referenceContainerId, referencePartitionId); } } if most of you test cases runs for both version, why not go our usual route of parametrized args.

Target:
public void testBuildBlobId() throws Exception { buildBlobIdAndAssert(version, referenceFlag, referenceDatacenterId, referenceAccountId, referenceContainerId, referencePartitionId); }
Source:
private String resolveRelativeModulePath(String url) { File f = new File(url); if (!f.isAbsolute()) START if (repo.isBare()) { END url = new File(repo.getDirectory(), url).getAbsolutePath(); } else { url = new File(repo.getWorkTree(), url).getAbsolutePath(); } return url; } curlies not needed

Target:
private String resolveRelativeModulePath(String url) { File f = new File(url); if (!f.isAbsolute()) if (repo.isBare()) url = new File(repo.getDirectory(), url).getAbsolutePath(); else url = new File(repo.getWorkTree(), url).getAbsolutePath(); return url; }
Source:
START public void incSize(int by) { END size += by; } These are vary dangerous methods because they are public. This can lead to procedural programming where it is difficult to determine if the object is in a valid state. Can these be made private?

Target:
private void incSize(int by) { size += by; }
Source:
public CompletionStage<Void> rollback(LocalTransaction localTransaction) { try { return CompletionStages.handleAndCompose(rollbackInternal(icf.running().createTxInvocationContext(localTransaction)), (ignore, t) -> { if (t != null) { return handleRollbackFailure(t, localTransaction); START } END return CompletableFutures.completedNull(); }); } catch (Throwable e) { return handleRollbackFailure(e, localTransaction); } } AFAICT `handleRollbackFailure` and `handleCommitFailure` don't need to return a `CompletionStage`

Target:
public CompletionStage<Void> rollback(LocalTransaction localTransaction) { return CompletionStages.handleAndCompose(rollbackInternal(icf.running().createTxInvocationContext(localTransaction)), (ignore, t) -> { if (t != null) { return handleRollbackFailure(t, localTransaction); } return CompletableFutures.completedNull(); }); }
Source:
public void link(Attributes attributes, String hrefOrHashName, String text) { START if (hrefOrHashName != null) { END assertOpenBlock(); try { currentBlock.write('"'); writeAttributes(attributes); currentBlock.write(text); currentBlock.write('"'); currentBlock.write(':'); currentBlock.write(hrefOrHashName); } catch (IOException e) { throw new RuntimeException(e); } } } This seems "lossy" in that the attributes and text of the link are lost if there is no link target. I'd prefer to see this emit as much as possible, and simply omit the href value if needed, e.g. if (hrefOrHashName == null) { hrefOrHashName = ""; } same with the other builders

Target:
public void link(Attributes attributes, String hrefOrHashName, String text) { assertOpenBlock(); try { currentBlock.write('"'); writeAttributes(attributes); currentBlock.write(text); currentBlock.write('"'); currentBlock.write(':'); if (hrefOrHashName != null) { currentBlock.write(hrefOrHashName); } } catch (IOException e) { throw new RuntimeException(e); } }
Source:
protected IProblemLocation createProblemLocation(ProblemMarkerInfo info) { IProblemLocationFactory factory = CodanRuntime.getInstance().getProblemLocationFactory(); START IFile file = (IFile) info.file; END return factory.createProblemLocation(file, info.startChar, info.endChar, info.lineNumber); } Redundant variable - inline.

Target:
protected IProblemLocation createProblemLocation(ProblemMarkerInfo info) { IProblemLocationFactory factory = CodanRuntime.getInstance().getProblemLocationFactory(); return factory.createProblemLocation( (IFile) info.file, info.startChar, info.endChar, info.lineNumber); }
Source:
protected void unregisterSender() { START if (sender != null) END sender.unregister(context, parent.getPriorityClass()); } Why have this check here? I don't see a code path that can result in `sender` being null, which the check implies could happen. If this check is necessary it needs locking to avoid a race condition.

Target:
protected void unregisterSender() { sender.unregister(context, parent.getPriorityClass()); }
Source:
public void addInput(Page page) { requireNonNull(page, "page is null"); checkState(!isFinished(), "Operator is already finished"); index.addPage(page); if (!localUserMemoryContext.trySetBytes((index.getEstimatedSize().toBytes()))) { index.compact(); } START localUserMemoryContext.setBytes(index.getEstimatedSize().toBytes()); END operatorContext.recordGeneratedOutput(page.getSizeInBytes(), page.getPositionCount()); } Do we need to call this if the above `trySetBytes` call worked? If not, move this inside of the `if`.

Target:
public void addInput(Page page) { requireNonNull(page, "page is null"); checkState(!isFinished(), "Operator is already finished"); index.addPage(page); if (!localUserMemoryContext.trySetBytes((index.getEstimatedSize().toBytes()))) { index.compact(); localUserMemoryContext.setBytes(index.getEstimatedSize().toBytes()); } operatorContext.recordGeneratedOutput(page.getSizeInBytes(), page.getPositionCount()); }
Source:
public Comparable getSortKey() { String sourceProviderName = mySourceProvider == null ? "" : mySourceProvider.getName(); START final String s = getQualifiedNameSortKey() + "-" + (SdkConstants.FD_MAIN.equals(sourceProviderName) ? "" : sourceProviderName); END return s; } inline s?

Target:
public Comparable getSortKey() { String sourceProviderName = mySourceProvider == null ? "" : mySourceProvider.getName(); return getQualifiedNameSortKey() + "-" + (SdkConstants.FD_MAIN.equals(sourceProviderName) ? "" : sourceProviderName); }
Source:
protected String getLaunchDebugCommand(JBossServer jbossServer) throws CoreException { String programArguments = getLaunchProgramArgs(); String vmArguments = getLaunchVMArgs(); String jar = getJar(jbossServer.getServer()); String debugPort = getDebugPort(); String debugArgs = "-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=" + debugPort + " -Xdebug "; START String command = "java " + debugArgs + vmArguments + " -jar " + jar + " " + IJBossRuntimeConstants.SPACE + programArguments + "&"; END return command; } `" " + IJBossRuntimeConstants.SPACE`

Target:
protected String getLaunchDebugCommand(JBossServer jbossServer) throws CoreException { String programArguments = getLaunchProgramArgs(); String vmArguments = getLaunchVMArgs(); String jar = getJar(jbossServer.getServer()); String debugPort = getDebugPort(); String debugArgs = "-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=" + debugPort + " -Xdebug "; String command = "java " + debugArgs + vmArguments + " -jar " + jar + IJBossRuntimeConstants.SPACE + programArguments + "&"; return command; }
Source:
private void initFirewallType() { START ListModel<FirewallType> firewallType = getFirewallType(); END firewallType.setItems(Arrays.asList(FirewallType.values())); firewallType.setIsChangeable(false); firewallType.setSelectedItem(FirewallType.FIREWALLD); } you need to make sure that in case of edit you select the firewall type as it was configured on the cluster and not always select the default.

Target:
private void initFirewallType() { ListModel<FirewallType> firewallType = getFirewallType(); firewallType.setItems(Arrays.asList(FirewallType.values())); firewallType.setIsChangeable(true); firewallType.setSelectedItem(FirewallType.FIREWALLD); }
Source:
public void copyValues() { if (batchSize == 0) { return; } verify(decodedBlock != null); int[] positions = getPositions(); START verify(positionsOffset + batchSize - 1 < positions.length && positions[positionsOffset] >= 0 && END positions[positionsOffset + batchSize - 1] < decodedBlock.getPositionCount()); appendValuesToBuffer(); appendNulls(); bufferedPositionCount += batchSize; } I'd remove this check. If you decide to keep it, consider separating conjuncts into separate calls and moving these into `appendValuesToBuffer`. ``` verify(positionsOffset + batchSize - 1 < positions.length); verify(positions[positionsOffset] >= 0); verify(positions[positionsOffset + batchSize - 1] < decodedBlock.getPositionCount()); ```

Target:
public void copyValues() { if (batchSize == 0) { return; } appendValuesToBuffer(); appendNulls(); bufferedPositionCount += batchSize; }
Source:
public StepContext getObject() throws Exception { org.springframework.batch.core.scope.context.StepContext stepContext = StepSynchronizationManager.getContext(); String stepName = stepContext.getStepName(); String jobName = stepContext.getStepExecution().getJobExecution().getJobInstance().getJobName(); START Properties properties = batchPropertyContext.getStepLevelProperties(jobName + "." + stepName + "." + stepName); END return new StepContext(stepContext.getStepExecution(), properties); } Why the extra stepName here?

Target:
public StepContext getObject() throws Exception { org.springframework.batch.core.scope.context.StepContext stepContext = StepSynchronizationManager.getContext(); String stepName = stepContext.getStepName(); String jobName = stepContext.getStepExecution().getJobExecution().getJobInstance().getJobName(); Properties properties = batchPropertyContext.getStepLevelProperties(jobName + "." + stepName); return new StepContext(stepContext.getStepExecution(), properties); }
Source:
protected boolean hasInferredTypeHeader(MessageProperties properties) { boolean hasInferredTypeHeader = properties.getInferredArgumentType() != null; START return hasInferredTypeHeader; END } No reason to extract the variable. The compilator is good here with optimization, but the source code is still this and maybe simplified.

Target:
protected boolean hasInferredTypeHeader(MessageProperties properties) { return properties.getInferredArgumentType() != null; }
Source:
private void invokeClassLoadTestingHookIfNeeded() throws InterruptedException { // Testing support only. if (TESTING_CLASS_LOAD != null) { TESTING_CLASS_LOAD.run(); START if (Thread.currentThread().isInterrupted()) { // Otherwise the interrupt isn't recognized and the test doesn't work. throw new InterruptedException("loading was interrupted."); } END } } nit: maybe use a different runnable hook, which would directly throw the exception you need for your test, instead of "hardcoding" the exception here? We can imagine test cases which would involve setting the interrupted flag here, but without expecting this `InterruptedException` (for instance something which would try to get a `RemotingException` from the `proxy.fetch` call in `loadRemoteClass`).

Target:
private void invokeClassLoadTestingHookIfNeeded() throws InterruptedException { // Testing support only. if (TESTING_CLASS_LOAD != null) { TESTING_CLASS_LOAD.run(); } }
Source:
public IEventDeclaration getEventDeclaration(int eventIndex) { if (eventIndex == EventDeclaration.UNSET_EVENT_ID) { START return fEventUnsetId; END } return fEvents.get(eventIndex); } Could be get(0) if using a SingletonList (see below) or even better if UNSET_EVENT_ID was 0...

Target:
public IEventDeclaration getEventDeclaration(int eventIndex) { if (eventIndex == EventDeclaration.UNSET_EVENT_ID) { return fEvents.get(0); } return fEvents.get(eventIndex); }
Source:
protected void loadProperties(Properties props) throws IOException { try { super.loadProperties(props); } catch(FileNotFoundException e) { //location was not found, create if (configFile != null && copyOutTemplate) { OutputStream fout = configFile.out(); props.store(fout, comments); fout.flush(); START fout.close(); END } } } @NielsCharlier fix resource leak with a try-with-resources block?

Target:
protected void loadProperties(Properties props) throws IOException { try { super.loadProperties(props); } catch(FileNotFoundException e) { //location was not found, create if (configFile != null && copyOutTemplate) { try (OutputStream fout = configFile.out()) { props.store(fout, comments); fout.flush(); } } } }
Source:
public Builder addRequestHandler(RequestHandler requestHandler) { if (requestHandler == null) { throw new IllegalArgumentException("RequestHandler must not be null."); } if (requestHandlers == null) { START requestHandlers = new ArrayList(); END } if (requestHandlers.contains(requestHandler)) { throw new IllegalStateException("RequestHandler already registered."); } requestHandlers.add(requestHandler); return this; } Missing generics

Target:
public Builder addRequestHandler(RequestHandler requestHandler) { if (requestHandler == null) { throw new IllegalArgumentException("RequestHandler must not be null."); } if (requestHandlers == null) { requestHandlers = new ArrayList<RequestHandler>(); } if (requestHandlers.contains(requestHandler)) { throw new IllegalStateException("RequestHandler already registered."); } requestHandlers.add(requestHandler); return this; }
Source:
private Object eval(Bindings bindings, String expression) { try { return jsScriptEngine.eval(bindings, expression); } catch (javax.script.ScriptException t) { START return new ScriptException(t.getCause()); END } catch (Throwable t) { return new ScriptException(t); } } ![MINOR](https://sonarsource.github.io/sonar-github/severity-minor.png 'Severity: MINOR') Remove this use of "ScriptException"; it is deprecated. [![rule](https://sonarsource.github.io/sonar-github/rule.png)](https://sonarcloud.io/coding_rules#rule_key=squid%3ACallToDeprecatedMethod)

Target:
private Object eval(Bindings bindings, String expression) { try { return jsScriptEngine.eval(bindings, expression); } catch (javax.script.ScriptException t) { return new ScriptException(t.getCause()); } catch (Exception t) { return new ScriptException(t); } }
Source:
public void testWithParameters() throws IOException { try (Analyzer ws = newHomoglyphFilter()) { TokenStream ts = ws.tokenStream("", input); START BaseTokenStreamTestCase.assertTokenStreamContents(ts, END expected); } } static import?

Target:
public void testWithParameters() throws IOException { try (Analyzer ws = newHomoglyphFilter()) { TokenStream ts = ws.tokenStream("", input); assertTokenStreamContents(ts, expected); } }
Source:
private static void editTree(TreeOperation op, Repository repo, RevWalk rw, RevCommit base, DirCacheEditor dce, ObjectInserter ins, String path, byte[] content) throws IOException, InvalidChangeOperationException { switch (op) { case DELETE_ENTRY: dce.add(new DeletePath(path)); break; case CHANGE_ENTRY: case RESTORE_ENTRY: START dce.add(getPathEdit(op, repo, rw, base, path, ins, content)); END } dce.finish(); } Break after this line.

Target:
private static void editTree(TreeOperation op, Repository repo, RevWalk rw, RevCommit base, DirCacheEditor dce, ObjectInserter ins, String path, byte[] content) throws IOException, InvalidChangeOperationException { switch (op) { case DELETE_ENTRY: dce.add(new DeletePath(path)); break; case CHANGE_ENTRY: case RESTORE_ENTRY: dce.add(getPathEdit(op, repo, rw, base, path, ins, content)); break; } dce.finish(); }
Source:
public RegisteredService findServiceBy(final long id) { START var result = this.services.get(id, k -> this.serviceRegistry.findServiceById(id)); END return validateRegisteredService(result); } Are you switching to var in order to correctly determine the final type?

Target:
public RegisteredService findServiceBy(final long id) { val result = this.services.get(id, k -> this.serviceRegistry.findServiceById(id)); return validateRegisteredService(result); }
Source:
public Map<String, Object> getMetaData(String iconName) throws IconException { START return this.getMetaData(iconName, getIconSet(iconName).getName()); END } This means ``getIconSet`` will be called twice for the most common use case. I would add a private ``getMetaData(String iconName, IconSet iconSet)`` and call it from the rest of the ``getMetaData()`` methods.

Target:
public Map<String, Object> getMetaData(String iconName) throws IconException { return this.getMetaData(iconName, getIconSet(iconName)); }
Source:
START public QualityProfileDto selectByNameAndLanguage(String name, String language, DbSession session) { END return mapper(session).selectByNameAndLanguage(name, language); } ![INFO](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/severity-info.png 'Severity: INFO') Do not forget to remove this deprecated code someday. [![rule](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/rule.png)](https://next.sonarqube.com/sonarqube/coding_rules#rule_key=squid%3AS1133)

Target:
public QualityProfileDto selectByNameAndLanguage(String name, String language, DbSession session) { return mapper(session).selectByNameAndLanguage(null, name, language); }
Source:
private int addFieldToDescriptionMap(Map<String, Object> descriptionMap, String diskAlias, String fieldName, String fieldValue, int descriptionAvailableLength) { if ((descriptionAvailableLength -= getJsonFieldPotentialOverhead(fieldName, descriptionMap)) > 0) { // There's enough space for the field's overhead in the metadata + at least one character from its value. if (fieldValue.length() > descriptionAvailableLength) { fieldValue = fieldValue.substring(0, descriptionAvailableLength); auditLogNoSpaceToStoreEntireDiskField(diskAlias, fieldName, fieldValue); } descriptionMap.put(fieldName, fieldValue); return descriptionAvailableLength - fieldValue.length(); } START return 0; END } This is unintuitive - why not return the number of characters you need and allow the calling function to decide what to do with it?

Target:
private int addFieldToDescriptionMap(Map<String, Object> descriptionMap, String diskAlias, String fieldName, String fieldValue, int descriptionAvailableLength) { if ((descriptionAvailableLength -= getJsonFieldPotentialOverhead(fieldName, descriptionMap)) > 0) { // There's enough space for the field's overhead in the metadata + at least one character from its value. if (fieldValue.length() > descriptionAvailableLength) { fieldValue = fieldValue.substring(0, descriptionAvailableLength); } descriptionMap.put(fieldName, fieldValue); return descriptionAvailableLength - fieldValue.length(); } return descriptionAvailableLength; }
Source:
public static CompletableFuture<Void> runLaterChecked(CheckedRunnable workToEnqueue) { return runLater(() -> { try { workToEnqueue.run(); } catch (Exception e) { START throw new CompletionException(e); END } }); } I would probably catch throwables, because ClassDefNotFoundError..

Target:
public static CompletableFuture<Void> runLaterChecked(CheckedRunnable workToEnqueue) { return runLater(() -> { try { workToEnqueue.run(); } catch (Throwable t) { throw new CompletionException(t); } }); }
Source:
public void add(String str, StatsSnapshot statsSnapshot) { START this.subMap = this.subMap == null ? new HashMap<>() : this.subMap; END this.subMap.put(str, statsSnapshot); } minor: don't need `this.` in both lines

Target:
public void add(String str, StatsSnapshot statsSnapshot) { subMap = subMap == null ? new HashMap<>() : subMap; subMap.put(str, statsSnapshot); }
Source:
public Context currentContext() { START return context; END } Our standard convention is to prefix with `this` for instance members - `return this.context`

Target:
public Context currentContext() { return this.context; }
Source:
private void startDiscovery() { discoveryService.scheduleWithFixedDelay(() -> { try { // jitter to avoid overloading database and overloading the backup store START SECONDS.sleep(ThreadLocalRandom.current().nextLong(1, organizationDiscoveryIntervalMillis / 1000)); END log.info("Running shard organizer..."); submitJobs(discoverAndInitializeTablesToOrganize()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (Throwable t) { log.error(t, "Error running shard organizer"); } }, 0, organizationDiscoveryIntervalMillis, TimeUnit.MILLISECONDS); } What if `organizationDiscoveryIntervalMillis` is less than 1000? Use `MILLISECONDS` instead

Target:
private void startDiscovery() { discoveryService.scheduleWithFixedDelay(() -> { try { // jitter to avoid overloading database and overloading the backup store MILLISECONDS.sleep(ThreadLocalRandom.current().nextLong(1, organizationDiscoveryIntervalMillis)); log.info("Running shard organizer..."); submitJobs(discoverAndInitializeTablesToOrganize()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (Throwable t) { log.error(t, "Error running shard organizer"); } }, 0, organizationDiscoveryIntervalMillis, TimeUnit.MILLISECONDS); }
Source:
private CacheBuilder<CacheKey, TypeCodec<?>> defaultCacheBuilder() { CacheBuilder<CacheKey, TypeCodec<?>> builder = CacheBuilder.newBuilder() // 19 primitive codecs + collections thereof = 19*3 + 19*19 = 418 codecs, // so let's start with roughly 1/4 of that .initialCapacity(100) .weigher(new TypeCodecWeigher()) .maximumWeight(1000); if (logger.isTraceEnabled()) // do not bother adding a listener if it will be ineffective START builder = builder.removalListener(new TypeCodecRemovalListener()); END return builder; } It's possible that log levels can be manipulated dynamically, but that seems like such a thin use case that we don't need to worry about it.

Target:
private CacheBuilder<CacheKey, TypeCodec<?>> defaultCacheBuilder() { CacheBuilder<CacheKey, TypeCodec<?>> builder = CacheBuilder.newBuilder() // 19 primitive codecs + collections thereof = 19*3 + 19*19 = 418 codecs, // so let's start with roughly 1/4 of that .initialCapacity(100) .maximumWeight(1000) .weigher(new TypeCodecWeigher()); if (logger.isTraceEnabled()) // do not bother adding a listener if it will be ineffective builder = builder.removalListener(new TypeCodecRemovalListener()); return builder; }
Source:
public void scanFile(JavaFileScannerContext context) { expectedLevel = 0; isBlockAlreadyReported = false; lastCheckedLine = 0; START isInAnonymousClass.clear(); END this.context = context; scan(context.getTree()); isInAnonymousClass.clear(); } If you clear the list at the end of the scan, no need to clear it before.

Target:
public void scanFile(JavaFileScannerContext context) { expectedLevel = 0; isBlockAlreadyReported = false; lastCheckedLine = 0; this.context = context; scan(context.getTree()); isInAnonymousClass.clear(); }
Source:
public static Project getByName(String name) { RuntimeEnvironment env = RuntimeEnvironment.getInstance(); if (env.hasProjects()) { START Project search = new Project(name); END Project proj; if ((proj = env.getProjects().get(name)) != null) { return (proj); } } return null; } unused variable?

Target:
public static Project getByName(String name) { RuntimeEnvironment env = RuntimeEnvironment.getInstance(); if (env.hasProjects()) { Project proj; if ((proj = env.getProjects().get(name)) != null) { return (proj); } } return null; }
Source:
START public ImportNetworksModel(final com.google.inject.Provider<CommonModel> commonModelProvider, END NetworkListModel sourceListModel) { this(sourceListModel, commonModelProvider); } Instead of adding this injected ctor here, I would add a new class that extends ImportNetworksModel and has this ctor. So the base class will have the general ctor and the children will have the injected ones with the explicit model type. The way it is implemented now is a bit confusing.

Target:
public ImportNetworksModel(final com.google.inject.Provider<CommonModel> commonModelProvider, NetworkListModel sourceListModel) { super(sourceListModel, commonModelProvider); }
Source:
void onNext(ClickEvent event) { START GQuery.console.info("next"); END next(); } debug

Target:
void onNext(ClickEvent event) { next(); }
Source:
START public void testDestroy() throws Exception { END final ManagedInstance managedInstance = mock(ManagedInstance.class); final Object control = mock(Object.class); final Consumer<Object> consumer = mock(Consumer.class); InstanceUtils.destroy(managedInstance, control, consumer); verify(consumer, times(1)).accept(eq(control)); verify(managedInstance, times(1)).destroy(eq(control)); } The Exception is never thrown.

Target:
public void testDestroy() { final ManagedInstance managedInstance = mock(ManagedInstance.class); final Object control = mock(Object.class); final Consumer<Object> consumer = mock(Consumer.class); InstanceUtils.destroy(managedInstance, control, consumer); verify(consumer, times(1)).accept(eq(control)); verify(managedInstance, times(1)).destroy(eq(control)); }
Source:
START static GlyphPair END gp(String original, String mirror) { return new GlyphPair(original, mirror); } nit: Should be `public`. We're only using this inside of the package, but there is no reason to restrict it, and it should have the same visibility as the constructor, since it is just a shortcut for the ctor.

Target:
public static GlyphPair gp(String original, String mirror) { return new GlyphPair(original, mirror); }
Source:
public void testSimpleAnnounce() throws IOException { IndexerSQLMetadataStorageCoordinator coordinator = new IndexerSQLMetadataStorageCoordinator( mapper, tablesConfig, derbyConnector ); START coordinator.announceHistoricalSegments(segments); END Assert.assertArrayEquals( mapper.writeValueAsString(defaultSegment).getBytes("UTF-8"), derbyConnector.lookup( tablesConfig.getSegmentsTable(), "id", "payload", defaultSegment.getIdentifier() ) ); } i think, it is done in every test and can possibly be moved to setUp()

Target:
public void testSimpleAnnounce() throws IOException { coordinator.announceHistoricalSegments(segments); Assert.assertArrayEquals( mapper.writeValueAsString(defaultSegment).getBytes("UTF-8"), derbyConnector.lookup( tablesConfig.getSegmentsTable(), "id", "payload", defaultSegment.getIdentifier() ) ); }
Source:
public static IDomain getFirstDomainOrCreate(IUser user) throws OpenShiftException { START IDomain domain; END domain = getFirstDomain(user); if (domain == null) { domain = user.createDomain(createRandomName()); } return domain; } please dont remove explicit initialization

Target:
public static IDomain getFirstDomainOrCreate(IUser user) throws OpenShiftException { IDomain domain = null; domain = getFirstDomain(user); if (domain == null) { domain = user.createDomain(createRandomName()); } return domain; }
Source:
public void testSetDependencies() { Assert.assertNotNull(this.c.getDependencies()); START final Set<String> dependencies = Sets.newHashSet(); END dependencies.add("s3://netflix/jars/myJar.jar"); this.c.setDependencies(dependencies); Assert.assertEquals(dependencies, this.c.getDependencies()); this.c.setDependencies(null); Assert.assertThat(this.c.getDependencies(), Matchers.empty()); } why not use `Sets.newHashSet({value})` here like you are everywhere else?

Target:
public void testSetDependencies() { Assert.assertNotNull(this.c.getDependencies()); final Set<String> dependencies = Sets.newHashSet("s3://netflix/jars/myJar.jar"); this.c.setDependencies(dependencies); Assert.assertEquals(dependencies, this.c.getDependencies()); this.c.setDependencies(null); Assert.assertThat(this.c.getDependencies(), Matchers.empty()); }
Source:
START public static <T> PredicateOperation predicate(Operator operator, ImmutableList<Expression<?>> args) { END return new PredicateOperation(operator, args); } These `<T>`s don't occur anywhere in the method signature.

Target:
public static PredicateOperation predicate(Operator operator, ImmutableList<Expression<?>> args) { return new PredicateOperation(operator, args); }
Source:
private void usingIsEmpty() { START Optional<Object> op = Optional.emtpy(); END if (!op.isEmpty()) { op.get(); // Compliant - dead code } } typo in the name of the invoked method, should be `Optional.empty()`

Target:
private void usingIsEmpty() { Optional<Object> op = Optional.empty(); if (!op.isEmpty()) { op.get(); // Compliant - dead code } }
Source:
public void addNotificationEvent(NotificationEvent entry) throws MetaException { if (addNotificationEventModifier != null) { Boolean success = addNotificationEventModifier.apply(entry); if ((success != null) && !success) { throw new MetaException("InjectableBehaviourObjectStore: Invalid addNotificationEvent operation on DB: " START + entry.getDbName() + " table: " + entry.getTableName() + " event : " + entry.getEventType()); END } } else { super.addNotificationEvent(entry); } } DB and table name need not be set always. shall use String.valueOf(entry.getDbName()) as it return "null" string if null.

Target:
public void addNotificationEvent(NotificationEvent entry) throws MetaException { if (addNotificationEventModifier != null) { Boolean success = addNotificationEventModifier.apply(entry); if ((success != null) && !success) { throw new MetaException("InjectableBehaviourObjectStore: Invalid addNotificationEvent operation on DB: " + entry.getDbName() + " table: " + entry.getTableName() + " event : " + entry.getEventType()); } } super.addNotificationEvent(entry); }
Source:
public List<PermissionSubject> getPermissionCheckSubjects() { START return Collections.singletonList(new PermissionSubject(getParameters().getProfile().getStorageDomainId(), END VdcObjectType.Storage, getActionType().getActionGroup())); } if the profile isn't set you'll have NPE here.

Target:
public List<PermissionSubject> getPermissionCheckSubjects() { return Collections.singletonList(new PermissionSubject(getParameters().getProfile() != null ? getParameters().getProfile() .getStorageDomainId() : null, VdcObjectType.Storage, getActionType().getActionGroup())); }