auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public final RedirectAction getLogoutRedirectAction(final WebContext context) { // it's an AJAX request -> unauthorized (instead of a redirection) START if (ajaxRequestResolver.isAjax(context)) { END logger.info("AJAX request detected -> returning 401"); cleanRequestedUrl(context); return null; } // authentication has already been tried -> unauthorized final String attemptedAuth = (String) context.getSessionAttribute(getName() + ATTEMPTED_AUTHENTICATION_SUFFIX); if (CommonHelper.isNotBlank(attemptedAuth)) { return null; } init(context); return retrieveLogoutRedirectAction(context); } These checks are not necessary for logout.

Target:
public final RedirectAction getLogoutRedirectAction(final WebContext context) { init(context); return retrieveLogoutRedirectAction(context); }
Source:
public void setMainTabSelectedItem(Erratum selectedItem) { START logger.info("setMainTabSelectedItem"); //$NON-NLS-1$ END updateErrataDetailFormPanel(selectedItem); } debug/trace/remove?

Target:
public void setMainTabSelectedItem(Erratum selectedItem) { updateErrataDetailFormPanel(selectedItem); }
Source:
public EurekaArchaius2InstanceConfig(Config config, String namespace, DataCenterInfo dcInfo) { this.defaultAppGroup = config.getString(FALLBACK_APP_GROUP_KEY, Values.UNKNOWN_APPLICATION); this.namespace = namespace; this.config = config.getPrefixedView(namespace); this.dcInfo = dcInfo; // TODO: Remove this when DiscoveryManager is finally no longer used START DiscoveryManager.getInstance().setEurekaInstanceConfig(this); END } If we need to do this, I feel like we can at least do this somewhere else. A binding for something like DiscoveryManagerInitializer with dependencies on these Config classes might work.

Target:
public EurekaArchaius2InstanceConfig(Config config, String namespace, DataCenterInfo dcInfo) { this.defaultAppGroup = config.getString(FALLBACK_APP_GROUP_KEY, Values.UNKNOWN_APPLICATION); this.namespace = namespace; this.config = config.getPrefixedView(namespace); this.dcInfo = dcInfo; }
Source:
public AdhocQueryResponse respondingGatewayCrossGatewayQuery(AdhocQueryRequest body, WebServiceContext context) { AssertionType assertion = getAssertion(context, null); if (assertion != null) { assertion.setImplementsSpecVersion(UDDI_SPEC_VERSION.SPEC_2_0.toString()); } START return inboundDocQuery.respondingGatewayCrossGatewayQuery(body, assertion, this.getWebContextProperties(context)); END } Right here (and in the equivalent 3.0 class) is the only place you're using "this" where a field isn't shadowed, is this intentional?

Target:
public AdhocQueryResponse respondingGatewayCrossGatewayQuery(AdhocQueryRequest body, WebServiceContext context) { AssertionType assertion = getAssertion(context, null); if (assertion != null) { assertion.setImplementsSpecVersion(UDDI_SPEC_VERSION.SPEC_2_0.toString()); } return inboundDocQuery.respondingGatewayCrossGatewayQuery(body, assertion, getWebContextProperties(context)); }
Source:
public void allBindingsChanged(BindingProvider provider) { logger.trace("allBindingsChanged() called."); START if (provider instanceof VeluxBindingProvider) { END } super.allBindingsChanged(provider); } Drop this empty block.

Target:
public void allBindingsChanged(BindingProvider provider) { logger.trace("allBindingsChanged() called."); super.allBindingsChanged(provider); }
Source:
private Map<String, String> makeParserFields() { final Map<String, String> fieldMapping = Maps.newHashMap(); for (final SchemaPath sp : getColumns()) { final String drillField = sp.getRootSegment().getPath(); try { START final String parserField = HttpdParser.parserFormattedFieldName(drillField); END fieldMapping.put(drillField, parserField); } catch (Exception e) { LOG.info("Putting field: " + drillField + " into map", e); } } return fieldMapping; } Please, remove `final` modifiers as they seem to be redundant.

Target:
private Map<String, String> makeParserFields() { Map<String, String> fieldMapping = new HashMap<>(); for (final SchemaPath sp : getColumns()) { String drillField = sp.getRootSegment().getPath(); try { String parserField = HttpdParser.parserFormattedFieldName(drillField); fieldMapping.put(drillField, parserField); } catch (Exception e) { LOG.info("Putting field: " + drillField + " into map", e); } } return fieldMapping; }
Source:
public Builder client(@NonNull OkHttpClient client) { if (client == null) { throw new NullPointerException("client == null"); } if (downloader != null) { throw new IllegalArgumentException("Downloader already set."); } downloader = new OkHttp3Downloader(client, client.cache(), true); return this; START } END Message needs changed. What does Retrofit do? Do we care if people overwrite this? I don't, and it breaks your `newBuilder()` desire.

Target:
public Builder client(@NonNull OkHttpClient client) { if (client == null) { throw new NullPointerException("client == null"); } downloader = new OkHttp3Downloader(client, client.cache(), true); return this; }
Source:
protected Optional<CoverageReportView> getCoverageReportView(PlaceRequest placeRequest) { final Activity activity = placeManager.getActivity(placeRequest); START if (activity != null) { END final AbstractWorkbenchActivity coverageActivity = (AbstractWorkbenchActivity) activity; return Optional.of((CoverageReportView) coverageActivity.getWidget()); } else { return Optional.empty(); } } Just a small remark feel free to skip it. It would have a nicer look if you keep if else logic direct like if (activity == null) { return Optional.empty(); } else { final AbstractWorkbenchActivity coverageActivity = (AbstractWorkbenchActivity) activity; return Optional.of((CoverageReportView) coverageActivity.getWidget()); }

Target:
protected Optional<CoverageReportView> getCoverageReportView(PlaceRequest placeRequest) { final Activity activity = placeManager.getActivity(placeRequest); if (activity == null) { return Optional.empty(); } else { final AbstractWorkbenchActivity coverageActivity = (AbstractWorkbenchActivity) activity; return Optional.of((CoverageReportView) coverageActivity.getWidget()); } }
Source:
private void edit() { if (getWindow() != null) { return; } AffinityGroup affinityGroup = getSelectedItem(); if (affinityGroup == null) { return; } START sortVms(affinityGroup); END AffinityGroupModel model = new EditAffinityGroupModel(affinityGroup, this, getClusterResolver()); model.init(); setWindow(model); } Generally you don't sort the VMs, and in the one case where you do - you don't really sort them either, but just move one to the top of the list. So firstly, consider dropping this method, making edit() protected and add the logic only in VmAffinityGroupListModel. Secondly, you could drop the comparator there and just iterate over the items to find the specific ID and move it to the top of the list, the comparator thing isn't necessary.

Target:
private void edit() { if (getWindow() != null) { return; } AffinityGroup affinityGroup = getSelectedItem(); if (affinityGroup == null) { return; } AffinityGroupModel model = new EditAffinityGroupModel(affinityGroup, this, getClusterResolver()); model.init(); setWindow(model); }
Source:
public void testIteratorCloses() throws Exception { Kabob bob = db.getJdbi().onDemand(Kabob.class); Iterator<Something> itty = bob.iterateAll(); START assertThat(itty.hasNext()).isFalse(); END } Considering the expected exception for this test, it seems like the `assertThat` is superfluous, and all we really want is `itty.hasNext();`

Target:
public void testIteratorCloses() throws Exception { Kabob bob = db.getJdbi().onDemand(Kabob.class); Iterator<Something> itty = bob.iterateAll(); itty.hasNext(); }
Source:
public static void assertSwappedIngredientsMatch(ObjectInstance ing, State s, List<String> ings) { Set<String> swappedIngredients = IngredientFactory.getRecursiveContentsAndSwapped(s, ing); Boolean match = true; START assertEquals(swappedIngredients.size(), ings.size()); END for (String i : ings) { if (!swappedIngredients.contains(i)) { match = false; break; } } assertTrue(match); } Cant the class name be included here so we know where this method is being called from.

Target:
public static void assertSwappedIngredientsMatch(ObjectInstance ing, State s, List<String> ings) { Set<String> swappedIngredients = IngredientFactory.getRecursiveContentsAndSwapped(s, ing); Boolean match = true; Assert.assertEquals(swappedIngredients.size(), ings.size()); for (String i : ings) { if (!swappedIngredients.contains(i)) { match = false; break; } } Assert.assertTrue(match); }
Source:
public List<Document> getClientDocuments(String clientId) throws MambuApiException { START if (clientId == null || clientId.trim().isEmpty()) { END throw new IllegalArgumentException("ClientId ID must not be null or empty"); } return DocumentsService.getDocuments(mambuAPIService, CLIENTS, clientId); } Edge case of duplicate code ;) It could be extracted to a common private method with two params for id and type. Up to you if you want to change it or not ;)

Target:
public List<Document> getClientDocuments(String clientId) throws MambuApiException { if (clientId == null || clientId.trim().isEmpty()) { throw new IllegalArgumentException("ClientId ID must not be null or empty"); } return new DocumentsService(mambuAPIService).getDocuments(CLIENTS, clientId); }
Source:
public void testFailForCheckDisksNotInBackupStorage() { final VM vm = new VM(); command.setVm(vm); when(vmDao.get(command.getParameters().getVmId())).thenReturn(vm); command.setCluster(new Cluster()); Guid storageDomainId = initDiskImage(vm); when(storageDomainStaticDao.get(storageDomainId)).thenReturn(backupStorageDomain(true)); START assertFalse("checkDisksNotInBackupStorage() fails to run because one or more disk is in backup domain", END command.checkDisksInBackupStorage()); } Now this should return true, since there are disks on the storage domain (Remember that you don't check the validate only the method checkDisksInBackupStorage) Change to assertTrue

Target:
public void testFailForCheckDisksNotInBackupStorage() { final VM vm = new VM(); command.setVm(vm); when(vmDao.get(command.getParameters().getVmId())).thenReturn(vm); command.setCluster(new Cluster()); Guid storageDomainId = initDiskImage(vm); when(storageDomainStaticDao.get(storageDomainId)).thenReturn(backupStorageDomain(true)); assertTrue("checkDisksNotInBackupStorage() fails to run because one or more disk is in backup domain", command.checkDisksInBackupStorage()); }
Source:
public long skip(long n) { if (n > 0) { long skip = bytes.length - pos; if (skip > n) skip = n; pos += skip; return skip; } else { int idx = Math.min(bytes.length, pos); long skip = idx + n; START pos = (int) skip; END return skip; } } shouldn't be the ```max()``` between ```offset``` and ```skip``` to avoid the ```pos``` to be previous than ```offset```?

Target:
public long skip(long n) { if (n > 0) { long skip = bytes.length - pos; if (skip > n) skip = n; pos += skip; return skip; } else { int idx = Math.min(bytes.length, pos); long skip = idx + n; // Calculate max to avoid skipping before offset pos = (int) Math.max(skip, offset); return skip; } }
Source:
public void actionPerformed(AnActionEvent e) { BaseAction.State s = setupAction(e); List<String> lastTask = Collections.singletonList(s.getLastRanTask()); s.performTasks(lastTask); START s.cleanup(); END } You may want to put this into a try/finally block.

Target:
public void actionPerformed(AnActionEvent e) { BaseAction.State s = setupAction(e); try { List<String> lastTask = Collections.singletonList(s.getLastRanTask()); s.performTasks(lastTask); } finally { s.cleanup(); } }
Source:
public void addAll(SerializableStatus status) { Assert.isLegal(status != null); SerializableStatus[] statuses = (SerializableStatus[]) status.getChildren(); for (SerializableStatus START statuse : END statuses) { add(statuse); } } rename to s

Target:
public void addAll(SerializableStatus status) { Assert.isLegal(status != null); SerializableStatus[] statuses = (SerializableStatus[]) status.getChildren(); for (SerializableStatus s : statuses) { add(s); } }
Source:
protected boolean canDoAction() { START return super.canDoAction() && VdsGroupExists() && logicalNetworkExists() && changesAreClusterCompatible(); END } how about moving logicalNetworkExists() after changesAreClusterCompatible() ? in case changesAreClusterCompatible() returns false, it will save one DB call :)

Target:
protected boolean canDoAction() { return super.canDoAction() && VdsGroupExists() && changesAreClusterCompatible() && logicalNetworkExists(); }
Source:
protected void reloadCache() { schemaMappingCache.invalidateAll(); // this preloads the list of schema names Set<String> schemas = getSchemaNames(); // invalidate and remove from the schema table mapping all records, start from scratch for (String key : schemaTableMapping.keySet()) { schemaTableMapping.get(key).invalidateAll(); schemaTableMapping.remove(key); START } END for (final String schema : schemas) { // this preloads the list of table names for each schema getTableNames(schema); } } any reason you can't just iterate through the values? schemaTableMapping.values().foreach(v -> v.invalidateAll()); schemaTableMapping.clear();

Target:
protected void reloadCache() { schemaMappingCache.invalidateAll(); // this preloads the list of schema names Set<String> schemas = getSchemaNames(); // invalidate and remove from the schema table mapping all records, start from scratch schemaTableMapping.keySet().forEach(key -> { schemaTableMapping.get(key).invalidateAll(); }); schemaTableMapping.clear(); for (final String schema : schemas) { // this preloads the list of table names for each schema getTableNames(schema); } }
Source:
public void testSetUser() { Configuration configuration = generateConfiguration(); configuration.setUser("24601", "m@rp.fr", "MM"); START assertEquals(User.class, configuration.getUser().getClass()); END assertEquals("24601", configuration.getUser().getId()); assertEquals("m@rp.fr", configuration.getUser().getEmail()); assertEquals("MM", configuration.getUser().getName()); } This assertion could be removed as it seems to test the Java type system rather than our code

Target:
public void testSetUser() { Configuration configuration = generateConfiguration(); configuration.setUser("24601", "m@rp.fr", "MM"); assertEquals("24601", configuration.getUser().getId()); assertEquals("m@rp.fr", configuration.getUser().getEmail()); assertEquals("MM", configuration.getUser().getName()); }
Source:
private void writeStringToFile(File file, String str) throws IOException { START try (BufferedWriter bw = new BufferedWriter(new FileWriter(file.toString()))) { END bw.write(str); } } No need to call `file.toString()` -> `FileWriter` can take `File` in the constructor as well.

Target:
private void writeStringToFile(File file, String str) throws IOException { try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) { bw.write(str); } }
Source:
private RelNode possiblyWrapRootWithOuterLimitFromContext( RelRoot root ) { Object outerLimitObj = plannerContext.getQueryContext().get(PlannerContext.CTX_SQL_OUTER_LIMIT); if (outerLimitObj == null) { return root.rel; } START Long outerLimit = DimensionHandlerUtils.convertObjectToLong(outerLimitObj, true); END if (outerLimit == null) { return root.rel; } return LogicalSort.create( root.rel, root.collation, makeBigIntLiteral(0), makeBigIntLiteral(outerLimit) ); } Minor: the two calls could be collapsed, since `DimensionHandlerUtils.convertObjectToLong` handles nulls just fine.

Target:
private RelNode possiblyWrapRootWithOuterLimitFromContext( RelRoot root ) { Object outerLimitObj = plannerContext.getQueryContext().get(PlannerContext.CTX_SQL_OUTER_LIMIT); Long outerLimit = DimensionHandlerUtils.convertObjectToLong(outerLimitObj, true); if (outerLimit == null) { return root.rel; } return LogicalSort.create( root.rel, root.collation, makeBigIntLiteral(0), makeBigIntLiteral(outerLimit) ); }
Source:
START public void testSamePortConfiguredForClientAndElection() throws IOException, ConfigException { END QuorumPeerConfig quorumPeerConfig = new QuorumPeerConfig(); try { Properties zkProp = getDefaultZKProperties(); zkProp.setProperty("server.1", "localhost:2888:2888"); quorumPeerConfig.parseProperties(zkProp); fail("ConfigException is expected"); } catch (ConfigException ce) { String expectedMessage = "Client and election port must be different! Please update the configuration file on server.1"; assertEquals(expectedMessage, ce.getMessage()); } } nit - ConfigException is unused

Target:
public void testSamePortConfiguredForClientAndElection() throws IOException, ConfigException { QuorumPeerConfig quorumPeerConfig = new QuorumPeerConfig(); Properties zkProp = getDefaultZKProperties(); zkProp.setProperty("server.1", "localhost:2888:2888"); quorumPeerConfig.parseProperties(zkProp); }
Source:
public static URLConnection openURLConnection(URL url) START throws IOException, ConnectException { END return openURLConnection(url,DEFAULT_CONNECTION_TIMEOUT); } ConnectException is not actually thrown by anything... it shouldn't be declared in the `throws`

Target:
public static URLConnection openURLConnection(URL url) throws IOException { return openURLConnection(url,DEFAULT_CONNECTION_TIMEOUT); }
Source:
public void updateParentCommandId(ArrayList<VdcActionParametersBase> parameters, CommandBase command) { START for (VdcActionParametersBase param : parameters) { END param.setParentCommand(command.getActionType()); param.setParentParameters(command.getParameters()); } } 1. let's replace with params.forEach 2. it makes more sense that this method will reside in HostSetupNetworksParametersBuilder - I don't see how its related to "ReportFailedChildHostOperationsUtil"

Target:
public void updateParentCommandId(ArrayList<VdcActionParametersBase> parameters, CommandBase command) { parameters.forEach(param -> { param.setParentCommand(command.getActionType()); param.setParentParameters(command.getParameters()); }); }
Source:
public MetricData getDatapointsForRange(Locator locator, Range range, Granularity gran) { RollupType rollupType = null; String rollupTypeStr = metaCache.safeGet(locator, rollupTypeCacheKey); if ( rollupTypeStr != null ) { rollupType = RollupType.fromString(rollupTypeStr); } if ( rollupType == null ) { rollupType = RollupType.BF_BASIC; } START return getNumericMetricDataForRange(locator, range, gran, rollupType); END } nm. I misread the diff. I thought ```getDatapointsForRange()``` only called ```getNumericMetricDataForRange()```

Target:
public MetricData getDatapointsForRange(Locator locator, Range range, Granularity gran) { RollupType rollupType = RollupType.BF_BASIC; String rollupTypeStr = metaCache.safeGet(locator, rollupTypeCacheKey); if ( rollupTypeStr != null ) { rollupType = RollupType.fromString(rollupTypeStr); } return getNumericMetricDataForRange(locator, range, gran, rollupType); }
Source:
public boolean shouldProcessRequestedCashAdvancesFromSaeData() { START return (getConcurParameterValue(ConcurParameterConstants.CONCUR_PROCESS_CASH_ADVANCES_FROM_SAE_DATA_IND).equalsIgnoreCase(KFSConstants.ParameterValues.YES)); END } to be null safe on here, I would suggest using stringutils.equalsignorecase or start the expression with the constant

Target:
public boolean shouldProcessRequestedCashAdvancesFromSaeData() { return (StringUtils.equalsIgnoreCase(getConcurParameterValue(ConcurParameterConstants.CONCUR_PROCESS_CASH_ADVANCES_FROM_SAE_DATA_IND), KFSConstants.ParameterValues.YES)); }
Source:
static Path resolvePath(Path file, String workingDirectory) { START return file == null ? null : (file.isAbsolute() ? file : (file.getFileName().startsWith(File.separator) ? file.toAbsolutePath() : (Paths.get(workingDirectory, END file.getFileName().toString())))); } Looks that works OK, but for me it's hard to read. I would rather see better readable return.

Target:
static Path resolvePath(Path file, String workingDirectory) { if(file == null){ return null; }else if(file.isAbsolute()){ return file; }else if(file.getFileName().startsWith(File.separator)){ return file.toAbsolutePath(); }else{ return Paths.get(workingDirectory, file.getFileName().toString()); } }
Source:
public void removeServiceEventListener(Object listener) { assert getExecutor().isInExecutorThread(); ListenerEntry entry = new ListenerEntry(listener, null); START if (DsfDebugOptions.DEBUG && DsfDebugOptions.DEBUG_SESSION && DsfDebugOptions.DEBUG_SESSION_LISTENERS) { END String msg = new Formatter().format( "%s %s removed as a service listener to %s (id=%s)", //$NON-NLS-1$ DsfPlugin.getDebugTime(), LoggingUtils.toString(listener), LoggingUtils.toString(this), getId() ).toString(); DsfDebugOptions.trace(msg); } fListeners.remove(entry); } Let's only use DsfDebugOptions.DEBUG_SESSION_LISTENERS here but have it include the others directly in DsfDebugOptions.

Target:
public void removeServiceEventListener(Object listener) { assert getExecutor().isInExecutorThread(); ListenerEntry entry = new ListenerEntry(listener, null); if (DsfDebugOptions.DEBUG_SESSION_LISTENERS) { String msg = new Formatter().format( "%s %s removed as a service listener to %s (id=%s)", //$NON-NLS-1$ DsfPlugin.getDebugTime(), LoggingUtils.toString(listener), LoggingUtils.toString(this), getId() ).toString(); DsfDebugOptions.trace(msg); } fListeners.remove(entry); }
Source:
private static void validateEntityLabel(EntityType entityType) { String label = entityType.getLabel(); START if (label.isEmpty()) END { throw new MolgenisValidationException( new ConstraintViolation(format("Label of EntityType [%s] is empty", entityType.getId()))); } else if (label.trim().equals("")) { throw new MolgenisValidationException(new ConstraintViolation( format("Label of EntityType [%s] contains only white space", entityType.getId()))); } } I smell an incoming NPE here...

Target:
private static void validateEntityLabel(EntityType entityType) { String label = entityType.getLabel(); if (label != null) { if (label.isEmpty()) { throw new MolgenisValidationException( new ConstraintViolation(format("Label of EntityType [%s] is empty", entityType.getId()))); } else if (label.trim().equals("")) { throw new MolgenisValidationException(new ConstraintViolation( format("Label of EntityType [%s] contains only white space", entityType.getId()))); } } }
Source:
public void deleteIfExists(File path, String user, String logPrefix) throws IOException { START LOG.info("Deleting path {}", path); END Path p = path.toPath(); if (Files.exists(p)) { try { FileUtils.forceDelete(path); } catch (FileNotFoundException ignored) } } We could just call deleteIfExists(path) since it's same.

Target:
public void deleteIfExists(File path, String user, String logPrefix) throws IOException { //by default no need to do this as a different user deleteIfExists(path); }
Source:
protected void releaseTransport(Transport transport) { START if (dedicatedTransport == null) { END //we aren't using this transport. we can release it super.releaseTransport(transport); } } This could be even `if (dedicatedTransport != transport)`

Target:
protected void releaseTransport(Transport transport) { if (dedicatedTransport != transport) { //we aren't using this transport. we can release it super.releaseTransport(transport); } }
Source:
String prepare(String name, Map<String, Map<String, String>> domain) { StringBuilder builder = new StringBuilder(name); while (domain.containsKey(name)) { START builder.append("~"); END } domain.put(builder.toString(), new LinkedHashMap<>()); return builder.toString(); } You probably made it a couple of thousand times slower :-) Keys rarely overlap in this domain creating a StringBuilder has an initialization cost that is not amortized.

Target:
String prepare(String name, Map<String, Map<String, String>> domain) { StringBuilder builder = new StringBuilder(name); while (domain.containsKey(name)) { builder.append("~"); } String val = builder.toString(); domain.put(val, new LinkedHashMap<>()); return val; }
Source:
public synchronized void deleteFile() { closeFile(); File historyTreeFile = fConfig.getStateFile(); try { if (!historyTreeFile.delete()) { /* We didn't succeed in deleting the file */ Activator.getDefault().logError("Failed to delete" + historyTreeFile.getName()); //$NON-NLS-1$ } START } catch (SecurityException e) { END Activator.getDefault().logError(e.getMessage(), e); } } is this a RuntimeException? In which case you probably don't want to catch it.

Target:
public synchronized void deleteFile() { closeFile(); File historyTreeFile = fConfig.getStateFile(); if (!historyTreeFile.delete()) { /* We didn't succeed in deleting the file */ Activator.getDefault().logError("Failed to delete" + historyTreeFile.getName()); //$NON-NLS-1$ } }
Source:
public void delete(UserEntityFile userEntityFile) { START getEntityManager().remove(userEntityFile); END } Replace method content with... super.delete(userEntityFile); ...as the underlying code will not only delete the entity but also fire an event about it.

Target:
public void delete(UserEntityFile userEntityFile) { super.delete(userEntityFile); }
Source:
START public void init() { END if (dubboConfigBinder == null) { try { dubboConfigBinder = applicationContext.getBean(DubboConfigBinder.class); } catch (BeansException ignored) { if (log.isDebugEnabled()) { log.debug("DubboConfigBinder Bean can't be found in ApplicationContext."); } // Use Default implementation dubboConfigBinder = createDubboConfigBinder(applicationContext.getEnvironment()); } } dubboConfigBinder.setIgnoreUnknownFields(ignoreUnknownFields); dubboConfigBinder.setIgnoreInvalidFields(ignoreInvalidFields); } If we allow to create sub class of this **DubboConfigBindingBeanPostProcessor ** and some **init method** get override then it might cause issue. So better to make init final or provide. What do you say?

Target:
private void init() { if (dubboConfigBinder == null) { try { dubboConfigBinder = applicationContext.getBean(DubboConfigBinder.class); } catch (BeansException ignored) { if (log.isDebugEnabled()) { log.debug("DubboConfigBinder Bean can't be found in ApplicationContext."); } // Use Default implementation dubboConfigBinder = createDubboConfigBinder(applicationContext.getEnvironment()); } } dubboConfigBinder.setIgnoreUnknownFields(ignoreUnknownFields); dubboConfigBinder.setIgnoreInvalidFields(ignoreInvalidFields); }
Source:
public static void removeDuplicateImages(Feed feed) { Set<String> known = new HashSet<String>(); for (FeedItem item : feed.getItems()) { START String url = (item.hasItemImage()) ? item.getImage().getDownload_url() : null; END if (url != null) { if (known.contains(url)) { item.setImage(null); } else { known.add(url); } } } } I find it even easier to read without the `(...)`

Target:
public static void removeDuplicateImages(Feed feed) { Set<String> known = new HashSet<String>(); for (FeedItem item : feed.getItems()) { String url = item.hasItemImage() ? item.getImage().getDownload_url() : null; if (url != null) { if (known.contains(url)) { item.setImage(null); } else { known.add(url); } } } }
Source:
protected void selectedItemsChanged() { START super.onSelectedItemChanged(); END updateActionAvailability(); } Shouldn't this also be changed to super.selectedItemsChanged()?

Target:
protected void selectedItemsChanged() { super.selectedItemsChanged(); updateActionAvailability(); }
Source:
public int[] borrowIntArray(int positionCount) { int[] array; START while (intArraysTop >= 0 && intArrays[intArraysTop].length < positionCount) { END estimatedSizeInBytes -= sizeOfIntArray(intArrays[intArraysTop].length); --intArraysTop; } if (intArraysTop < 0) { array = new int[positionCount]; estimatedSizeInBytes += sizeOfIntArray(positionCount); } else { array = intArrays[intArraysTop]; --intArraysTop; } ++borrowedIntArrays; return array; } Shouldn't this loop release memory of "discarded" arrays? E.g. intArrays[intArraysTop] = null?

Target:
public int[] borrowIntArray(int positionCount) { int[] array; while (intArraysTop >= 0 && intArrays[intArraysTop].length < positionCount) { estimatedSizeInBytes -= sizeOfIntArray(intArrays[intArraysTop].length); intArrays[intArraysTop] = null; --intArraysTop; } if (intArraysTop < 0) { array = new int[positionCount]; estimatedSizeInBytes += sizeOfIntArray(positionCount); } else { array = intArrays[intArraysTop]; --intArraysTop; } ++borrowedIntArrays; return array; }
Source:
START public Collection<MergeStrategySection> getAllMergeStrategySections() { END List<MergeStrategySection> all = new ArrayList<MergeStrategySection>(); all.addAll(getLocalMergeStrategySections()); all.addAll(getInheritedMergeStrategySections()); return all; } I suspect that you want to preserve order here and return a List?

Target:
public List<MergeStrategySection> getAllMergeStrategySections() { List<MergeStrategySection> all = new ArrayList<MergeStrategySection>(); all.addAll(getLocalMergeStrategySections()); all.addAll(getInheritedMergeStrategySections()); return all; }
Source:
public String getDeleteDescription() { START return getName() + (getAlias() == null ? "" : " (" + getAlias() + ")"); END } Alias should never be null.

Target:
public String getDeleteDescription() { return getName() + " (" + getAlias() + ")"; }
Source:
boolean selectCommonAncestor(ReadOnlyDocument doc1, ReadOnlyDocument doc2) START throws CouchbaseLiteException { END if (!c4doc.getRawDoc().selectCommonAncestorRevision(doc1.getRevID(), doc2.getRevID())) return false; setC4Doc(c4doc); // self.c4Doc = _c4Doc; // This will update to the selected revision return true; } Is CouchbaseLiteException thrown from anything in this method? Or it should return void but throw CouchbaseLiteException instead?

Target:
boolean selectCommonAncestor(ReadOnlyDocument doc1, ReadOnlyDocument doc2) { if (!c4doc.getRawDoc().selectCommonAncestorRevision(doc1.getRevID(), doc2.getRevID())) return false; setC4Doc(c4doc); // self.c4Doc = _c4Doc; // This will update to the selected revision return true; }
Source:
START public void setHazelcastRegisteredEventListenerId(String hazelcastRegisteredEventListenerId) { END this.hazelcastRegisteredEventListenerId = hazelcastRegisteredEventListenerId; } `protected`. It would be bad to allow end-user to mutate on this local property.

Target:
protected void setHazelcastRegisteredEventListenerId(String hazelcastRegisteredEventListenerId) { this.hazelcastRegisteredEventListenerId = hazelcastRegisteredEventListenerId; }
Source:
protected String getFileName(ITask task, Predicate<String> fileExists) { String encodedFileName = CoreUtil.asFileName(task.getTaskId()); // for backwards-compatibility with versions that always encoded file names, // we will use an encoded name if the file with an encoded name already exists START if (encodedFileName.length() <= FILENAME_MAX_LEN && fileExists.test(encodedFileName)) { END return encodedFileName; } // if file with encoded name does not exist, we will only encode file name if it is required String fileName; if (requiresEncoding(task.getTaskId())) { fileName = encodedFileName; } else { fileName = task.getTaskId(); } // trim the file name if it is too long return trimFilenameIfRequired(fileName); } In what case can the file exist but be too long? If we are on a system with a longer filename limit, we should just use the existing file and not worry about the length, I think.

Target:
protected String getFileName(ITask task, Predicate<String> fileExists) { String encodedFileName = CoreUtil.asFileName(task.getTaskId()); // for backwards-compatibility with versions that always encoded file names, // we will use an encoded name if the file with an encoded name already exists if (fileExists.test(encodedFileName)) { return encodedFileName; } // if file with encoded name does not exist, we will only encode file name if it is required String fileName; if (requiresEncoding(task.getTaskId())) { fileName = encodedFileName; } else { fileName = task.getTaskId(); } // trim the file name if it is too long return trimFilenameIfRequired(fileName); }
Source:
public boolean createIndex(String indexName) { Assert.notNull(indexName, "No index defined for Query"); try { CreateIndexRequest indexRequest = createIndexRequest(indexName); START return client.indices().create(indexRequest, RequestOptions.DEFAULT).isAcknowledged(); END } catch (Exception e) { throw new ElasticsearchException("Failed to create index " + indexName, e); } } why the extraction to a variable? I would keep it inlined: ``` return client.indices().create(createIndexRequest(indexName), RequestOptions.DEFAULT).isAcknowledged(); ```

Target:
public boolean createIndex(String indexName) { Assert.notNull(indexName, "No index defined for Query"); try { return client.indices().create(createIndexRequest(indexName), RequestOptions.DEFAULT).isAcknowledged(); } catch (Exception e) { throw new ElasticsearchException("Failed to create index " + indexName, e); } }
Source:
public static Properties defaultProperties() { Properties properties = BaseHttpApiMetadata.defaultProperties(); START properties.setProperty(ShipyardProperties.SHIPYARD_CREDENTIAL, "<remote-service-key-given-by-shipyard-cli>"); END return properties; } What is this property used for?

Target:
public static Properties defaultProperties() { return BaseHttpApiMetadata.defaultProperties(); }
Source:
protected boolean writeNeedsRemoteValue(InvocationContext ctx, WriteCommand command, Object key) { if (command.hasFlag(Flag.CACHE_MODE_LOCAL)) { return false; } if (ctx.isOriginLocal()) { // The return value only matters on the originator. // Conditional commands also check the previous value only on the originator. if (!command.readsExistingValues()) { return false; } // TODO Could make DELTA_WRITE/ApplyDeltaCommand override SKIP_REMOTE_LOOKUP by changing next line to // return !command.hasFlag(Flag.SKIP_REMOTE_LOOKUP) || command.alwaysReadsExistingValues(); START if (command.hasFlag(Flag.SKIP_REMOTE_LOOKUP)) { END return false; } } else { // Ignore SKIP_REMOTE_LOOKUP on remote nodes // TODO Can we ignore the CACHE_MODE_LOCAL flag as well? if (!command.alwaysReadsExistingValues()) { return false; } } return true; } It seems this could be changed to `return !command.hasFlag(Flag.SKIP_REMOTE_LOOKUP))`

Target:
protected boolean writeNeedsRemoteValue(InvocationContext ctx, WriteCommand command, Object key) { if (command.hasFlag(Flag.CACHE_MODE_LOCAL)) { return false; } if (ctx.isOriginLocal()) { // The return value only matters on the originator. // Conditional commands also check the previous value only on the originator. if (!command.readsExistingValues()) { return false; } // TODO Could make DELTA_WRITE/ApplyDeltaCommand override SKIP_REMOTE_LOOKUP by changing next line to // return !command.hasFlag(Flag.SKIP_REMOTE_LOOKUP) || command.alwaysReadsExistingValues(); return !command.hasFlag(Flag.SKIP_REMOTE_LOOKUP); } else { // Ignore SKIP_REMOTE_LOOKUP on remote nodes // TODO Can we ignore the CACHE_MODE_LOCAL flag as well? return command.alwaysReadsExistingValues(); } }
Source:
public BulkReceiveLibraryBackend(LibraryDto dto, Integer quantity, Project project, SampleClass aliquotClass, String defaultSciName, START LibraryTemplateService libraryTemplateService) throws IOException { END super("libraryReceipt", LibraryDto.class, "Libraries", dto, quantity); if (isDetailedSampleEnabled() && aliquotClass == null) throw new InvalidParameterException("Aliquot class cannot be null"); this.project = project; this.aliquotClass = aliquotClass; this.defaultSciName = defaultSciName; this.libraryTemplateService = libraryTemplateService; newBox = dto.getBox(); } ![MINOR](https://sonarsource.github.io/sonar-github/severity-minor.png 'Severity: MINOR') Remove the declaration of thrown exception 'java.io.IOException', as it cannot be thrown from constructor's body. [![rule](https://sonarsource.github.io/sonar-github/rule.png)](https://sonarcloud.io/coding_rules#rule_key=squid%3ARedundantThrowsDeclarationCheck)

Target:
public BulkReceiveLibraryBackend(LibraryDto dto, Integer quantity, Project project, SampleClass aliquotClass, String defaultSciName, LibraryTemplateService libraryTemplateService) { super("libraryReceipt", LibraryDto.class, "Libraries", dto, quantity); if (isDetailedSampleEnabled() && aliquotClass == null) throw new InvalidParameterException("Aliquot class cannot be null"); this.project = project; this.aliquotClass = aliquotClass; this.defaultSciName = defaultSciName; this.libraryTemplateService = libraryTemplateService; newBox = dto.getBox(); }
Source:
public void evict(AccountExternalId id) { byKey.remove(id.getKey()); byAccountId.remove(id.getAccountId()); START byEmail.remove(new EmailWrapper(id.getEmailAddress())); END } getEmailAddress can return null.

Target:
public void evict(AccountExternalId id) { byKey.remove(id.getKey()); byAccountId.remove(id.getAccountId()); if (id.getEmailAddress() != null) { byEmail.remove(new EmailWrapper(id.getEmailAddress())); } }
Source:
public void outjectRequestMap() { for (ValuedParameter vparameter : methodInfo.getValuedParameters()) { START result.include(vparameter.getParameter().getName(), vparameter.getValue()); END } } create a `vparameter.getName()` that delegates to `Parameter`

Target:
public void outjectRequestMap() { for (ValuedParameter vparameter : methodInfo.getValuedParameters()) { result.include(vparameter.getName(), vparameter.getValue()); } }
Source:
START public AbstractBlockFamily(BlockFamilyDefinition definition, BlockShape shape, BlockBuilderHelper blockBuilder) { END } seems like these constructors should set `protected` properties on the base class. They're called via `super` below.

Target:
protected AbstractBlockFamily(BlockFamilyDefinition definition, BlockShape shape, BlockBuilderHelper blockBuilder) { }
Source:
public void onStop() { super.onStop(); mGoogleApiClient.stopAutoManage(getActivity()); START if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) { END mGoogleApiClient.disconnect(); } } Maybe we can move the null check on `mGoogleApiClient` a level above so to protect also the access to `stopAutoManage`. wdyt?

Target:
public void onStop() { super.onStop(); if (mGoogleApiClient != null) { mGoogleApiClient.stopAutoManage(getActivity()); if (mGoogleApiClient.isConnected()) { mGoogleApiClient.disconnect(); } } }
Source:
protected Guid getQuotaId() { START if (getNewDisk() != null && (isInternalManagedDisk())) { END return ((DiskImage) getNewDisk()).getQuotaId(); } return null; } please remove redundant brackets (isInter...)

Target:
protected Guid getQuotaId() { if (getNewDisk() != null && isInternalManagedDisk()) { return ((DiskImage) getNewDisk()).getQuotaId(); } return null; }
Source:
public JClogin() { START logger.trace("JClogin(constructor) called."); END logger.trace("JClogin(this={}) called.",this); } One of these two trace lines should be removed.

Target:
public JClogin() { logger.trace("JClogin(constructor) called."); }
Source:
public ScriptingJobs(ScriptingAdaptor adaptor, XenonEngine xenonEngine, SchedulerConnectionFactory connectionFactory) { this.adaptor = adaptor; this.xenonEngine = xenonEngine; this.adaptorName = adaptor.getName(); this.connectionFactory = connectionFactory; START connections = Utils.emptyMap(1); END } I think using this util obfuscates the code

Target:
public ScriptingJobs(ScriptingAdaptor adaptor, XenonEngine xenonEngine, SchedulerConnectionFactory connectionFactory) { this.adaptor = adaptor; this.xenonEngine = xenonEngine; this.adaptorName = adaptor.getName(); this.connectionFactory = connectionFactory; connections = new HashMap<>(); }
Source:
public TMSKeyBuilder(final String prefix, TileLayerDispatcher layers) { START this.prefix = Strings.isNullOrEmpty(prefix) ? "" : prefix + "/"; END this.layers = layers; } I really dislike how this confuses things. Most of the `/`s are in the templates, but then this one special slash is being added here. This is a really good opportunity for future mistakes. Maybe this is a case for changing from using `String.format()` with templates that all do essentially the same thing for varying numbers of parameters to say just using `String.join()`.

Target:
public TMSKeyBuilder(final String prefix, TileLayerDispatcher layers) { this.prefix = prefix; this.layers = layers; }
Source:
public void testLeftJoinMissingStats() { PlanNodeStatsEstimate leftStats = planNodeStats( 0, START new SymbolStatistics(LEFT_JOIN_COLUMN, SymbolStatsEstimate.unknown()), END new SymbolStatistics(LEFT_OTHER_COLUMN, SymbolStatsEstimate.unknown())); PlanNodeStatsEstimate rightStats = planNodeStats( 0, new SymbolStatistics(RIGHT_JOIN_COLUMN, SymbolStatsEstimate.unknown()), new SymbolStatistics(RIGHT_OTHER_COLUMN, SymbolStatsEstimate.unknown())); assertJoinStats(LEFT, leftStats, rightStats, leftStats); } nit: I somehow liked the old, more concise `UNKNOWN_STATS`

Target:
public void testLeftJoinMissingStats() { PlanNodeStatsEstimate leftStats = planNodeStats( 0, new SymbolStatistics(LEFT_JOIN_COLUMN, SymbolStatsEstimate.unknown()), new SymbolStatistics(LEFT_OTHER_COLUMN, SymbolStatsEstimate.unknown())); PlanNodeStatsEstimate rightStats = planNodeStats( 0, new SymbolStatistics(RIGHT_JOIN_COLUMN, SymbolStatsEstimate.unknown()), new SymbolStatistics(RIGHT_OTHER_COLUMN, SymbolStatsEstimate.unknown())); assertJoinStats(LEFT, leftStats, rightStats, PlanNodeStatsEstimate.unknown()); }
Source:
public Collection<ClassDefinition> generate(ExtensionContext input) throws UnableToCompleteException { PrintWriter printWriter = tryCreate(); if (printWriter != null) { mergeTemplate(printWriter); commit(printWriter); registerGinBinding(); } else { getLogger().debug("Jackson Mapper Provider already generated. Returning."); } START return Lists.newArrayList(getClassDefinition()); END } Didn't you remove guava from GWTP?

Target:
public Collection<ClassDefinition> generate(ExtensionContext input) throws UnableToCompleteException { PrintWriter printWriter = tryCreate(); if (printWriter != null) { mergeTemplate(printWriter); commit(printWriter); registerGinBinding(); } else { getLogger().debug("Jackson Mapper Provider already generated. Returning."); } return Arrays.asList(getClassDefinition()); }
Source:
@Test public void shouldHandleSchemeInsensitiveCase() { String[] schemes = { "http", "https", "HTTP", "HTTPS", "HTtP", }; for (String scheme : schemes) { final Uri uri = URI_1.buildUpon().scheme(scheme).build(); final Boolean shouldHandle = networkHandler.canHandleRequest( START TestUtils.mockRequest(uri) END ); assertThat(shouldHandle).isTrue(); } } 👍 ah. a good reason to make `picasso3` the package name, so long as it has common names like `Request` in the API.

Target:
@Test public void shouldHandleSchemeInsensitiveCase() { String[] schemes = { "http", "https", "HTTP", "HTTPS", "HTtP", }; for (String scheme : schemes) { Uri uri = URI_1.buildUpon().scheme(scheme).build(); assertThat(networkHandler.canHandleRequest(TestUtils.mockRequest(uri))).isTrue(); } }
Source:
public void populate(CoreSession session) throws ClientException { UserManager um = Framework.getLocalService(UserManager.class); Framework.doPrivileged(() -> { // Create some users if (um != null) { createUsersAndGroups(um); } START }); END } if (um != null) { Framework.doPrivileged(() -> createUsersAndGroups(um)); }

Target:
public void populate(CoreSession session) throws ClientException { UserManager um = Framework.getLocalService(UserManager.class); // Create some users if (um != null) { Framework.doPrivileged(() -> createUsersAndGroups(um)); } }
Source:
public void stop(BundleContext context) throws Exception { try { Job.getJobManager().join(LUCENE_JOB_FAMILY, null); START plugin = null; END } finally { super.stop(context); } } Might be also in finally?

Target:
public void stop(BundleContext context) throws Exception { try { Job.getJobManager().join(LUCENE_JOB_FAMILY, null); } finally { plugin = null; super.stop(context); } }
Source:
public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) { ObjectUtil.checkNotNull(unit, "unit"); if (delay < 0) { delay = 0; } validateScheduled0(delay, unit); return schedule(new ScheduledFutureTask<Void>( this, START ObjectUtil.checkNotNull(command, "command"), END deadlineNanos(unit.toNanos(delay)))); } move null check back as first action to not change behaviour.

Target:
public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) { ObjectUtil.checkNotNull(command, "command"); ObjectUtil.checkNotNull(unit, "unit"); if (delay < 0) { delay = 0; } validateScheduled0(delay, unit); return schedule(new ScheduledFutureTask<Void>( this, command, deadlineNanos(unit.toNanos(delay)))); }
Source:
public Integer invoke() { Integer result = 0; try (InputStream in = cache.getViaStream(key)) { int read = 0; while ((read = in.read(buffer)) != -1) result = result + read; return value = result; } catch (IOException e) { throw new RuntimeException(e); START } catch (NullPointerException e) { END return null; } } I think that `if (in == null) return null` is a slightly better way to deal with this...

Target:
public Integer invoke() { Integer result = 0; try (InputStream in = cache.getViaStream(key)) { if (in == null) return null; int read = 0; while ((read = in.read(buffer)) != -1) result = result + read; return value = result; } catch (IOException e) { throw new RuntimeException(e); } }
Source:
public CoreEvent process(CoreEvent event) throws MuleException { try { return processToApply(event, this); } catch (Exception error) { Throwable cause = error.getCause(); START if (cause instanceof RetryContextInitializationException && END cause.getCause() instanceof ExpressionRuntimeException) { // Runtime exception caused by Retry Ctx initialization, propagating throw ((ExpressionRuntimeException) cause.getCause()); } else { // Not caused by context initialization. Throwing as raised. throw error; } } } check for `cause != null`

Target:
public CoreEvent process(CoreEvent event) throws MuleException { try { return processToApply(event, this); } catch (Exception error) { Throwable cause = error.getCause(); if (cause != null && cause instanceof RetryContextInitializationException && cause.getCause() instanceof ExpressionRuntimeException) { // Runtime exception caused by Retry Ctx initialization, propagating throw ((ExpressionRuntimeException) cause.getCause()); } else { // Not caused by context initialization. Throwing as raised. throw error; } } }
Source:
private static void addChildren(Map<String, List<PatchLineComment>> parentMap, List<PatchLineComment> children, List<PatchLineComment> outResult) { if (children != null) { for (PatchLineComment c : children) { outResult.add(c); START addChildren(parentMap, parentMap.get(c.getKey()), outResult); END } } } Missing a .get() here after .getKey() as the UUID is the key in the map, not the PatchLineComment.Key object instance.

Target:
private static void addChildren(Map<String, List<PatchLineComment>> parentMap, List<PatchLineComment> children, List<PatchLineComment> outResult) { if (children != null) { for (PatchLineComment c : children) { outResult.add(c); addChildren(parentMap, parentMap.get(c.getKey().get()), outResult); } } }
Source:
public void dispose() { START LogManager.logInfo("Disposing", this); //$NON-NLS-1$ END fWindow= null; } What is this logging buying us ? Do we really need so much of it?

Target:
public void dispose() { fWindow= null; }
Source:
public boolean equals(byte[] obj, Object otherObj) { if (obj == otherObj) return true; START if (obj == null || byte[].class != obj.getClass()) return false; END if (otherObj == null || byte[].class != otherObj.getClass()) return false; byte[] byteArray = obj; byte[] otherByteArray = (byte[]) otherObj; return Arrays.equals(byteArray, otherByteArray); } the second part of the OR is redundant: byte[].class != obj.getClass()

Target:
public boolean equals(byte[] obj, Object otherObj) { if (obj == otherObj) return true; if (obj == null) return false; if (otherObj == null || byte[].class != otherObj.getClass()) return false; byte[] otherByteArray = (byte[]) otherObj; return Arrays.equals(obj, otherByteArray); }
Source:
START public EngineSearcherTotalHitsMatcher(Query query, int totalHits) { END this.query = query; this.totalHits = totalHits; } can be private

Target:
private EngineSearcherTotalHitsMatcher(Query query, int totalHits) { this.query = query; this.totalHits = totalHits; }
Source:
protected boolean processEntryForContext(final ILogData data) { if (data != null) { try { START final Object payload = data.getPayload(runtime); END } catch (Throwable e) { log.error("Exception caught at address {}, {}, {}", data.getGlobalAddress(), data.getStreams(), data.getType()); throw e; } } return false; } Why don't you push this down to `LogData::getPayload` ? (since that's when deserialize is actually invoked)

Target:
protected boolean processEntryForContext(final ILogData data) { if (data != null) { final Object payload = data.getPayload(runtime); } return false; }