auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
START public IContextInformation getContextInformation() { return new IContextInformation() { @Override public String getContextDisplayString() { return "Added " + bundle + " to build path"; } @Override public Image getImage() { return Icons.image("bundle"); } @Override public String getInformationDisplayString() { return "Added " + bundle + " to build path - info"; } }; } END For the quick fix processor, I could never figure out when this was used. It is possible they are not used for quick fixes, but for completion proposals (which are different to quick fixes). However they are used, the strings should probably use `displayString` (eg, with these new changes, sometimes we're adding to the test path and not the build path).

Target:
public IContextInformation getContextInformation() { return null; }
Source:
public boolean select(Viewer viewer, Object parentElement, Object element) { if (element instanceof IJavaProject) { element = ((IJavaProject) element).getProject(); } return !Optional.ofNullable(element) .filter(IProject.class::isInstance) .map(IProject.class::cast) START .filter(Objects::nonNull) END .filter(p -> TemporaryProject.PROJECT_NAME.equals(p.getName())) .isPresent(); } Why do you need the non-null filter? The `Class.isInstance` will already filter out null values.

Target:
public boolean select(Viewer viewer, Object parentElement, Object element) { if (element instanceof IJavaProject) { element = ((IJavaProject) element).getProject(); } return !Optional.ofNullable(element) .filter(IProject.class::isInstance) .map(IProject.class::cast) .filter(p -> TemporaryProject.PROJECT_NAME.equals(p.getName())) .isPresent(); }
Source:
START public Container(Project project, String message) { END this.project = project; this.bsn = "<unknown>"; this.version = "<unknown>"; this.warning = message; this.type = TYPE.ERROR; this.path = "unknown"; } Can we make this private and just have people use the static method?

Target:
private Container(Project project, String message) { this.project = project; this.bsn = "<unknown>"; this.version = "<unknown>"; this.warning = message; this.type = TYPE.ERROR; this.path = "unknown"; }
Source:
public BundleDTO install(String location, byte[] data) throws Exception { START if (data == null) { END return null; } Bundle installedBundle = null; try (InputStream stream = new ByteArrayInputStream(data)) { installedBundle = context.getBundle(location); if (installedBundle == null) { installedBundle = context.installBundle(location, stream); } else { installedBundle.update(stream); refresh(true); } } return toDTO(installedBundle); } the data cannot be null

Target:
public BundleDTO install(String location, byte[] data) throws Exception { Bundle installedBundle = null; try (InputStream stream = new ByteArrayInputStream(data)) { installedBundle = context.getBundle(location); if (installedBundle == null) { installedBundle = context.installBundle(location, stream); } else { installedBundle.update(stream); refresh(true); } } return toDTO(installedBundle); }
Source:
public static boolean isNotResolved(Bundle bundle) { START return bundle.getState() == Bundle.INSTALLED || bundle.getState() == Bundle.UNINSTALLED; END } ```java return (bundle.getState() & (Bundle.INSTALLED | Bundle.UNINSTALLED)) != 0; ```

Target:
public static boolean isNotResolved(Bundle bundle) { return (bundle.getState() & (Bundle.INSTALLED | Bundle.UNINSTALLED)) != 0; }
Source:
default BundleSpecBuilder addResourceWithCopy(Class<?> class1) { String className = class1.getName(); String path = className.replace('.', '/') + ".class"; START URL url = BundleSpecBuilder.class.getClassLoader() END .getResource(path); if (url == null) { throw new IllegalArgumentException( "Couldn't find class file for " + class1.getName() + ", possibly a synthetic class"); } addResource(path, url); return this; } Shouldn't this use the specified class' class loader to load the resource? For example, `URL url = class1.getClassLoader().getResource(path);`? Or even `URL url = class1.getResource(class1.getSimpleName()+".class");` since the class file resource is in the package of the class.

Target:
default BundleSpecBuilder addResourceWithCopy(Class<?> class1) { String className = class1.getName(); String path = className.replace('.', '/') + ".class"; URL url = class1.getClassLoader() .getResource(path); if (url == null) { throw new IllegalArgumentException( "Couldn't find class file for " + className + ", possibly a synthetic class"); } addResource(path, url); return this; }
Source:
static Discover parse(String s) { START if (s == null || s.isEmpty()) END return Discover.none; return Discover.valueOf(s); } You may want to do: https://github.com/bndtools/bnd/blob/57a70d6a05d77289e2f4702246ece22984b89070/aQute.libg/src/aQute/lib/strings/Strings.java#L147 since it also trims the string in case the input value has leading or trailing whitespace.

Target:
static Discover parse(String s) { if (s == null || (s = s.trim()).isEmpty()) return Discover.none; return Discover.valueOf(s); }
Source:
public void testGetWithSource() throws Exception { config(null); File jar = repo.get("org.osgi.dto", new Version("1.0.0.201505202023"), null); START assertThat(jar.isFile()).isTrue(); END File sources = repo.get("org.osgi.dto.source", new Version("1.0.0.201505202023"), null); assertThat(sources.isFile()).isTrue(); } This should be better written as `assertThat(jar).isFile();`

Target:
public void testGetWithSource() throws Exception { config(null); File jar = repo.get("org.osgi.dto", new Version("1.0.0.201505202023"), null); assertThat(jar).isFile(); File sources = repo.get("org.osgi.dto.source", new Version("1.0.0.201505202023"), null); assertThat(sources).isFile(); }
Source:
boolean isInnerClass() { String binary = type.getBinary(); return attributes(InnerClassesAttribute.class).flatMap(a -> Arrays.stream(a.classes)) START .filter(inner -> Objects.nonNull(inner.inner_name)) END .anyMatch(inner -> !Modifier.isStatic(inner.inner_access) && inner.inner_class.equals(binary)); } Instead of adding a filter operation, could we just AND the non-null check into the anyMatch test? ```java .anyMatch(inner -> (inner.inner_name != null) && !Modifier.isStatic(inner.inner_access) && inner.inner_class.equals(binary)); ```

Target:
boolean isInnerClass() { String binary = type.getBinary(); return attributes(InnerClassesAttribute.class).flatMap(a -> Arrays.stream(a.classes)) .anyMatch(inner -> (inner.inner_name != null) && !Modifier.isStatic(inner.inner_access) && inner.inner_class.equals(binary)); }
Source:
public void testFinalFieldReference() throws Exception { START Builder b = new Builder(); END b.setProperty(Constants.DSANNOTATIONS, "test.component.*FinalClassNonFinalField*"); b.setProperty("Private-Package", "test.component"); b.addClasspath(new File("bin_test")); b.build(); assertOk(b); } To clean up properly, please place the Builder in a try-with-resource block ```java try (Builder b = new Builder()) { // test } ```

Target:
public void testFinalFieldReference() throws Exception { try (Builder b = new Builder()) { b.setProperty(Constants.DSANNOTATIONS, "test.component.*FinalClassNonFinalField*"); b.setProperty("Private-Package", "test.component"); b.addClasspath(new File("bin_test")); b.build(); assertOk(b); } }
Source:
default BundleSpecBuilder extension(Extension extension) { requireNonNull(extension, "Extension cannot be null"); START directive("extension", extension.value); END return this; } extension.toString()

Target:
default BundleSpecBuilder extension(Extension extension) { requireNonNull(extension, "Extension cannot be null"); directive("extension", extension.toString()); return this; }
Source:
private void verifyDirectives(String header, String directives, Pattern namePattern, String type) throws Exception { START verifyDirectives(header, directives, namePattern, type, (namespace, pattern) -> pattern); END } ```java private void verifyDirectives(String header, String directives, Pattern namePattern, String type) throws Exception { verifyDirectives(header, namespace -> directives, namePattern, type); } private void verifyDirectives(String header, Function<String, String> directives, Pattern namePattern, String type) throws Exception { ```

Target:
private void verifyDirectives(String header, String directives, Pattern namePattern, String type) throws Exception { verifyDirectives(header, namespace -> directives, namePattern, type); }
Source:
protected void refreshServiceTaskList(ServiceTaskSummary serviceTaskSummary) { serviceTaskService.call((String serviceTaskName) -> { START notificationEvent.fire(new NotificationEvent(getRemoveTaskSuccess() + serviceTaskName)); END refreshData(); }).removeServiceTask(serviceTaskSummary); } ```suggestion notificationEvent.fire(new NotificationEvent(constants.RemoveTaskSuccess(serviceTaskName))); ```

Target:
protected void refreshServiceTaskList(ServiceTaskSummary serviceTaskSummary) { serviceTaskService.call((String serviceTaskName) -> { notificationEvent.fire(new NotificationEvent(getRemoveTaskSuccess(serviceTaskName))); refreshData(); }).removeServiceTask(serviceTaskSummary); }
Source:
public String removeServiceTask(ServiceTaskSummary serviceTaskSummary) { START repoService.removeServiceTask(serviceTaskSummary.getId(), serviceTaskSummary.getInstalledOn().size() > 0 ? false : true); END return serviceTaskSummary.getName(); } @mswiderski is the logic correct here? Should we disable the ST only when it is used by no project? ....

Target:
public String removeServiceTask(ServiceTaskSummary serviceTaskSummary) { repoService.removeServiceTask(serviceTaskSummary.getId()); return serviceTaskSummary.getName(); }
Source:
public void onDeselectAllItemsEvent(@Observes DeselectAllItemsEvent event) { if (getListView().getListGrid() != null) { getListView().getListGrid().deselectAllItems(); } START refreshGrid(); END } just not sure if we always want to refresh the grid when deselectall is executed.

Target:
public void onDeselectAllItemsEvent(@Observes DeselectAllItemsEvent event) { deselectAllItems(); }
Source:
public void bulkClaim(List<TaskSummary> taskSummaries) { if (taskSummaries == null || taskSummaries.isEmpty()) { return; } START taskSummaries.parallelStream().forEach(taskSummary -> { END if (getClaimActionCondition().test(taskSummary)) { claimTask(taskSummary); } else { view.displayNotification( constants.ClaimNotAllowedOn(String.valueOf(taskSummary.getId()), taskSummary.getName())); } }); } Although using parallelStream could be more efficient, I would suggest using a plain _forEach_ to keep the behaviour more consistent.

Target:
public void bulkClaim(List<TaskSummary> taskSummaries) { if (taskSummaries == null || taskSummaries.isEmpty()) { return; } taskSummaries.forEach(taskSummary -> { if (getClaimActionCondition().test(taskSummary)) { claimTask(taskSummary); } else { view.displayNotification( constants.ClaimNotAllowedOn(String.valueOf(taskSummary.getId()), taskSummary.getName())); } }); }
Source:
public void init() { START filterSettingsManager.getDefaultActiveFilterKey(defaultFilter -> loadSavedFilters(defaultFilter)); END } in here I think default filter is an attribute of the filter itself. You should continue using just _loadSavedFilters_ and that would set the default filter automatically.

Target:
public void init() { loadSavedFilters(); }
Source:
public String toString() { return "TaskSelectionEvent{" + "forAdmin=" + forAdmin + ", forLog=" + forLog + ", description='" + description + '\'' + ", expirationTime=" + expirationTime + ", actualOwner='" + actualOwner + '\'' + ", status='" + status + '\'' + ", slaCompliance='" + slaCompliance + '\'' + ", priority=" + priority + ", processInstanceId=" + processInstanceId + ", processId='" + processId + '\'' + ", workItemId=" + workItemId + START ", slaCompliance=" + slaCompliance + END "} " + super.toString(); } slaCompliance is twice here

Target:
public String toString() { return "TaskSelectionEvent{" + "forAdmin=" + forAdmin + ", forLog=" + forLog + ", description='" + description + '\'' + ", expirationTime=" + expirationTime + ", actualOwner='" + actualOwner + '\'' + ", status='" + status + '\'' + ", slaCompliance='" + slaCompliance + '\'' + ", priority=" + priority + ", processInstanceId=" + processInstanceId + ", processId='" + processId + '\'' + "} " + super.toString(); }
Source:
public void testControlBulkOperationsEnabled() { boolean enabled = false; START List a = Collections.singletonList(mockButton); END when(rightActionsToolbar.spliterator()) .thenReturn(Spliterators.spliteratorUnknownSize(a.iterator(), 0)); when(extendedPagedTable.hasSelectedItems()).thenReturn(enabled); getView().controlBulkOperations(extendedPagedTable); verify(mockButton).setEnabled(enabled); } @nmirasch one more thing, I would change the List from raw type to `List<Button>`, and move all these three lines into setupMocks methods.

Target:
public void testControlBulkOperationsEnabled() { when(extendedPagedTable.hasSelectedItems()).thenReturn(true); getView().controlBulkOperations(extendedPagedTable); verify(mockButton).setEnabled(true); }
Source:
public void refreshLogs() { currentPage = 1; loadTaskLogs(); START displayVisibleLogs(); END } shouldn't this be executed in the callback from _getTaskEvents_ ?

Target:
public void refreshLogs() { currentPage = 0; loadTaskLogs(); }
Source:
private List<ColumnMeta<T>> renameDomainSpecifColumns(ExtendedPagedTable<T> extendedPagedTable, Set<String> columns) { return (List<ColumnMeta<T>>) extendedPagedTable.getColumnMetaList().stream() .filter(cm -> !cm.isExtraColumn() && columns.contains(cm.getCaption())) START .map(colMet -> { END return newColumnMeta(colMet.getCaption(), true); }).collect(Collectors.toList()); } ```suggestion .map(colMet -> newColumnMeta(colMet.getCaption(), true)) ```

Target:
private List<ColumnMeta<T>> renameDomainSpecifColumns(ExtendedPagedTable<T> extendedPagedTable, Set<String> columns) { return (List<ColumnMeta<T>>) extendedPagedTable.getColumnMetaList().stream() .filter(cm -> !cm.isExtraColumn() && columns.contains(cm.getCaption())) .map(colMet -> newColumnMeta(colMet.getCaption(), true, false) ).collect(Collectors.toList()); }
Source:
public Predicate<String> getFilterEventPredicate() { return dataSetId -> getDataSetQueryHelper() != null && START getDataSetQueryHelper() != null && END getDataSetQueryHelper().getCurrentTableSettings() != null && dataSetId != null && dataSetId.equals(getDataSetQueryHelper().getCurrentTableSettings().getUUID()); } I guess _getDataSetQueryHelper_ is duplicated here?

Target:
public Predicate<String> getFilterEventPredicate() { return dataSetId -> getDataSetQueryHelper() != null && getDataSetQueryHelper().getCurrentTableSettings() != null && dataSetId != null && dataSetId.equals(getDataSetQueryHelper().getCurrentTableSettings().getUUID()); }
Source:
public void onEditButtonClicked(final ClickEvent ignore) { START presenter.openEditModal(name.textContent, value.textContent);; END } No need to pass values back to the presenter.

Target:
public void onEditButtonClicked(final ClickEvent ignore) { presenter.openEditModal();; }
Source:
public void testFilterInitiator(){ String variableNameWithInitiator = "initiator"; String variableValueWithInitiator = "initiator people"; String variableNameWithoutInitiator = "noinitiator"; String variableValueWithoutInitiator = "other people"; START assertEquals(presenter.filterInitiator(variableNameWithInitiator,variableValueWithInitiator,variableValueWithInitiator),true); END assertEquals(presenter.filterInitiator(variableNameWithoutInitiator,variableValueWithoutInitiator,variableValueWithoutInitiator),false); assertEquals(presenter.filterInitiator(variableNameWithInitiator,variableValueWithInitiator,variableValueWithoutInitiator),false); assertEquals(presenter.filterInitiator(variableNameWithoutInitiator,variableValueWithoutInitiator,variableValueWithInitiator),false); } expected value should be the first parameter in _assertEquals_

Target:
public void testFilterInitiator(){ String variableNameWithInitiator = "initiator"; String variableValueWithInitiator = "initiator people"; String variableNameWithoutInitiator = "noinitiator"; String variableValueWithoutInitiator = "other people"; assertEquals(true, presenter.filterInitiator(variableNameWithInitiator, variableValueWithInitiator, variableValueWithInitiator)); assertEquals(false, presenter.filterInitiator(variableNameWithoutInitiator, variableValueWithoutInitiator, variableValueWithoutInitiator)); assertEquals(false, presenter.filterInitiator(variableNameWithInitiator, variableValueWithInitiator, variableValueWithoutInitiator)); assertEquals(false, presenter.filterInitiator(variableNameWithoutInitiator, variableValueWithoutInitiator, variableValueWithInitiator)); }
Source:
public void onProcessSelectionEvent(@Observes final ProcessDefSelectionEvent event) { String containerId = event.getDeploymentId(); String serverTemplateId = event.getServerTemplateId(); String processId = event.getProcessId(); processImageService.call((String svgContent) -> displayImage(svgContent), START (String message, Throwable throwable) -> { END displayImage(""); return false; }).getProcessDiagram(serverTemplateId, containerId, processId); } I think in general we should avoid using the remote callback error like this because we might suppress other errors. Best would be handle it with the spec management call, testing if the container is started or not.

Target:
public void onProcessSelectionEvent(@Observes final ProcessDefSelectionEvent event) { String containerId = event.getDeploymentId(); String serverTemplateId = event.getServerTemplateId(); String processId = event.getProcessId(); processImageService.call((String svgContent) -> displayImage(svgContent)).getProcessDiagram(serverTemplateId, containerId, processId); }
Source:
public void init() { caseService = new CallerMock<>(caseManagementService); when(caseManagementService.getCaseInstances(any(CaseInstanceSearchRequest.class))).thenReturn(caseInstanceSummaryList); presenter.setCaseService(caseService); when(view.getCaseInstanceSearchRequest()).thenReturn(new CaseInstanceSearchRequest()); doAnswer((i) ->{ START presenter.refreshData(); END return null; }).when(actions).onRefreshCaseClick(any(MouseEvent.class)); } I gave a second thought on this test class and I think in here you're actually mocking the bit that needs to be tested. It would be better if you create a new test class for `CaseInstanceListSearchViewImpl` and then mock the presenter to verify it was actually called.

Target:
public void init() { caseService = new CallerMock<>(caseManagementService); when(caseManagementService.getCaseInstances(any(CaseInstanceSearchRequest.class))).thenReturn(caseInstanceSummaryList); presenter.setCaseService(caseService); when(view.getCaseInstanceSearchRequest()).thenReturn(new CaseInstanceSearchRequest()); }
Source:
public AdvancedFilterEditor(DataSetClientServices dataSetClientServices) { initWidget(uiBinder.createAndBindUi(this)); this.dataSetClientServices = dataSetClientServices; okButton.setType(ButtonType.PRIMARY); START okButton.addClickHandler(new ClickHandler() { END @Override public void onClick(ClickEvent event) { ok(); } }); } perhaps use lambda style in here :)

Target:
public AdvancedFilterEditor(DataSetClientServices dataSetClientServices) { initWidget(uiBinder.createAndBindUi(this)); this.dataSetClientServices = dataSetClientServices; okButton.setType(ButtonType.PRIMARY); okButton.addClickHandler(event -> ok()); }
Source:
START public void displayNotification(String text) { END notification.fire(new NotificationEvent(text)); } private?

Target:
private void displayNotification(String text) { notification.fire(new NotificationEvent(text)); }
Source:
private boolean isInvalidCommandTypeError(Throwable throwable) { String message = ""; if (throwable.getMessage() != null) { message = throwable.getMessage(); START } else if (throwable.getCause() != null) { END message = throwable.getCause().getMessage(); } return message.contains("Invalid command type"); } As I mentioned, here we have a potential _NullPointerException_ gap. The _else if_ expression should be expanded to: ```else if (throwable.getCause() != null && throwable.getCause().getMessage() != null)```

Target:
private boolean isInvalidCommandTypeError(Throwable throwable) { String message = ""; if (throwable.getMessage() != null) { message = throwable.getMessage(); } else if (throwable.getCause() != null && throwable.getCause().getMessage() != null) { message = throwable.getCause().getMessage(); } return message.contains("Invalid command type"); }
Source:
public void openErrorView(final String id){ final PlaceRequest request = new DefaultPlaceRequest(EXECUTION_ERRORS); if(TASK_TYPE.equals(type)) { request.addParameter(SEARCH_PARAMETER_TASK_ID, id); } else { request.addParameter(SEARCH_PARAMETER_PROCESS_INSTANCE_ID, START id); END } request.addParameter(SEARCH_PARAMETER_IS_ERROR_ACK, Boolean.toString(false)); viewPresenter.openView(request); } @mcivantos-tribalyte in here, I believe this class should not dependend on the domain ( task or process ), you could simply delegate back to the presenter that would know which paramters to add into the place request. Same goes for the _TASK_INSTANCE_ATTRIBUTE_ and _PROCESS_INSTANCE_ATTRIBUTE_ that could be generic as _data-jbpm-id_.

Target:
public void openErrorView(final String id){ viewPresenter.openErrorView(id); }
Source:
public void openErrorView(final String id){ final PlaceRequest request = new DefaultPlaceRequest(EXECUTION_ERRORS); request.addParameter(SEARCH_PARAMETER_IS_ERROR_ACK, Boolean.toString(false)); START viewPresenter.openView(request,id); END } @mcivantos-tribalyte I still think that all of these should be moved to the presenter, in here you should only call the _openErrorView_ in the presenter.

Target:
public void openErrorView(final String id){ viewPresenter.openErrorView(id); }
Source:
public boolean isSupportedArrayComponentType(Class<?> componentType) { START return byte.class == componentType || END boolean.class == componentType || short.class == componentType || int.class == componentType || long.class == componentType || double.class == componentType; } Swap the order so all the numbers are together

Target:
public boolean isSupportedArrayComponentType(Class<?> componentType) { return boolean.class == componentType || byte.class == componentType || short.class == componentType || int.class == componentType || long.class == componentType || double.class == componentType; }
Source:
public boolean[] readBoolArray() throws TException { START TList tList = protocol.readListBegin(); END boolean[] array = new boolean[tList.size]; for (int i = 0; i < tList.size; i++) { array[i] = readBool(); } protocol.readListEnd(); return array; } Just name this `list`?

Target:
public boolean[] readBoolArray() throws TException { TList list = protocol.readListBegin(); boolean[] array = new boolean[list.size]; for (int i = 0; i < list.size; i++) { array[i] = readBool(); } protocol.readListEnd(); return array; }
Source:
public boolean[] read(TProtocol protocol) throws Exception { START Preconditions.checkNotNull(protocol, "protocol is null"); END return new TProtocolReader(protocol).readBoolArray(); } Static import

Target:
public boolean[] read(TProtocol protocol) throws Exception { checkNotNull(protocol, "protocol is null"); return new TProtocolReader(protocol).readBoolArray(); }
Source:
public boolean isSupportedArrayComponentType(Class<?> componentType) { START if (boolean.class == componentType) { END return true; } if (short.class == componentType) { return true; } if (int.class == componentType) { return true; } if (long.class == componentType) { return true; } if (double.class == componentType) { return true; } return false; } This would be easier to read if collapsed

Target:
public boolean isSupportedArrayComponentType(Class<?> componentType) { return boolean.class == componentType || short.class == componentType || int.class == componentType || long.class == componentType || double.class == componentType; }
Source:
public ThriftClient(ThriftClientManager clientManager, Class<T> clientType, ThriftClientConfig clientConfig, String clientName) { START this(clientManager, clientType, defaultChannelFactory, clientConfig, clientName); END } a default value in the middle of the arguments (one c'tor being A, B, C, D, E, the other A, B, D, E) looks strange.

Target:
public ThriftClient( ThriftClientManager clientManager, Class<T> clientType, ThriftClientConfig clientConfig, String clientName) { this(clientManager, clientType, clientConfig, clientName, defaultChannelFactory); }
Source:
private void createScheduler() throws SchedulerException { // backwards compatibility - only use this when something is provided in // the config START if (!configuration.getQuartzConfiguration().isEmpty()) { END StdSchedulerFactory factory = new StdSchedulerFactory(); factory.initialize(createProperties()); scheduler = factory.getScheduler(); return; } scheduler = StdSchedulerFactory.getDefaultScheduler(); } if you put it the other way around ```java if (configuration.getQuartzConfiguration().isEmpty()){ scheduler = StdSchedulerFactory.getDefaultScheduler(); } ``` you avoid the double negation - I find that a lot easier to read.

Target:
private void createScheduler() throws SchedulerException { if (configuration.getQuartzConfiguration().isEmpty()) { scheduler = StdSchedulerFactory.getDefaultScheduler(); return; } StdSchedulerFactory factory = new StdSchedulerFactory(); factory.initialize(createProperties()); scheduler = factory.getScheduler(); }
Source:
public String getEndpointHost() { if(endpointHost.startsWith("https://")){ START return endpointHost.substring(8); END } return endpointHost; } ```suggestion return endpointHost.substring("https://".length()); ``` Just a but more clear than the magic numbe `8`

Target:
public String getEndpointHost() { if(endpointHost.startsWith("https://")){ return endpointHost.substring("https://".length()); } return endpointHost; }
Source:
private Resource getComponentResource(String resourceType, ResourceResolver resourceResolver) { String[] resolverSearchPaths = resourceResolver.getSearchPath(); for (String searchPath : resolverSearchPaths) { START String tempResourceType = searchPath + resourceType; if (resourceResolver.getResource(tempResourceType) != null) { resourceType = searchPath + resourceType; return resourceResolver.getResource(resourceType); END } } return null; } ```suggestion Resource resource = resourceResolver.getResource(searchPath + resourceType); if (resource != null) { return resource; ```

Target:
private Resource getComponentResource(String resourceType, ResourceResolver resourceResolver) { String[] resolverSearchPaths = resourceResolver.getSearchPath(); for (String searchPath : resolverSearchPaths) { Resource resource = resourceResolver.getResource(searchPath + resourceType); if (resource != null) { return resource; } } return null; }
Source:
private String applyUrlRewrites(String url) { START String path = URI.create(url).getPath(); END for (Map.Entry<String, String> rewrite : urlRewrites.entrySet()) { if (path.startsWith(rewrite.getKey())) { return url.replaceFirst(rewrite.getKey(), rewrite.getValue()); } } return url; } @leonbe02 LGTM - just want to double check that url will always be a valid param for `URI.create(..)`? I'd think if it isnt, and an IllegalArgumentException is thrown, it would be best just to use the param's original value?

Target:
private String applyUrlRewrites(String url) { try { String path = URI.create(url).getPath(); for (Map.Entry<String, String> rewrite : urlRewrites.entrySet()) { if (path.startsWith(rewrite.getKey())) { return url.replaceFirst(rewrite.getKey(), rewrite.getValue()); } } return url; } catch (IllegalArgumentException e) { return url; } }
Source:
public String getValue(Object obj) { Resource result = (Resource) obj; PageManager pageMgr = result.getResourceResolver().adaptTo(PageManager.class); START Page page = Optional.ofNullable(pageMgr).map(p -> p.getContainingPage(result)).orElse(null); END return page != null ? page.getPath() : ""; } Instead of using orElse on line 42 you could combine the next line as another map call and then to orElse(null) in the return statement

Target:
public String getValue(Object obj) { Resource result = (Resource) obj; PageManager pageMgr = result.getResourceResolver().adaptTo(PageManager.class); return Optional.ofNullable(pageMgr).map(p -> p.getContainingPage(result)).map(Page::getPath).orElse(""); }
Source:
public void addClientLibraries(ClientLibraryType type, Collection<String> categories) { START Set<String> categoriesSet = clientLibraries.getOrDefault(type, new LinkedHashSet<>()); END for (String category : categories) { categoriesSet.add(category); } clientLibraries.put(type, categoriesSet); } Shouldn't this method simply call `public void addClientLibraries(ClientLibraryType type, String... categories)` after converting the collection to an array (or vice versa)? Codeclimate is gonna complain.

Target:
public void addClientLibraries(ClientLibraryType type, Collection<String> categories) { Set<String> categoriesSet = clientLibraries.getOrDefault(type, new LinkedHashSet<>()); categoriesSet.addAll(categories); clientLibraries.put(type, categoriesSet); }
Source:
START public String[] getAuthorizedGroups() { END return new String[]{"administrators"}; } this method should probably be final. Also it is missing the @Override annotation AFAICT

Target:
protected final String[] getAuthorizedGroups() { return new String[]{"administrators"}; }
Source:
public void activate(ComponentContext context) throws LoginException { START log.info("activate"); END bctx = context.getBundleContext(); refreshCache(); log.info("Activation successful!"); } trace?

Target:
public void activate(ComponentContext context) throws LoginException { log.trace("activate"); bctx = context.getBundleContext(); refreshCache(); log.trace("Activation successful!"); }
Source:
public void deactivate(ComponentContext context) throws LoginException { START log.info("deactivate"); END for (String id : registeredServices.keySet()) { unregisterService(id); } log.info("Deactivation successful!"); } trace?

Target:
public void deactivate(ComponentContext context) throws LoginException { log.trace("deactivate"); for (String id : registeredServices.keySet()) { unregisterService(id); } log.trace("Deactivation successful!"); }
Source:
public void start(Context c) { mContext = c; LocationManager lm = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE); if (mLastLocation == null) { mLastLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); } if (mLastLocation != null) { START lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, mNetworkLocationListener); END } } Why is this null checking before requesting locations? I would think it's ok to request new locations even if we didn't have a last known location in the GPS provider.

Target:
public void start(Context c) { mContext = c; LocationManager lm = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE); if (mLastLocation == null) { mLastLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (mLastLocation == null) { mLastLocation = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); } } lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, mNetworkLocationListener); }
Source:
public static boolean shouldLog(ScanResult scanResult) { if (SSIDBlockList.isOptOut(scanResult)) { START Log.w(LOG_TAG, "Blocked opt-out SSID"); END return false; } if (BSSIDBlockList.contains(scanResult)) { Log.w(LOG_TAG, "Blocked BSSID: " + scanResult); return false; } if (SSIDBlockList.contains(scanResult)) { Log.w(LOG_TAG, "Blocked SSID: " + scanResult); return false; } return true; } I don't think we need the warning level log here. Let's change that to a Log.d for debugging.

Target:
public static boolean shouldLog(ScanResult scanResult) { if (SSIDBlockList.isOptOut(scanResult)) { Log.d(LOG_TAG, "Blocked opt-out SSID"); return false; } if (BSSIDBlockList.contains(scanResult)) { Log.w(LOG_TAG, "Blocked BSSID: " + scanResult); return false; } if (SSIDBlockList.contains(scanResult)) { Log.w(LOG_TAG, "Blocked SSID: " + scanResult); return false; } return true; }
Source:
public void removeListener() { if (mLocationManager == null) { return; } mLocationManager.removeGpsStatusListener(mSatelliteListener); enableLocationListener(false, mGpsLocationListener); enableLocationListener(false, mNetworkLocationListener); START mLocationManager = null; END } In my branch I have mLocationManager as final in this class, so I was planning to merge that. I don't understand setting the location manager to null, is there a reason? @cascheberg I apologize for being to be so slow with reviews, @crankycoder and I haven't been available much this week. Stumbler does need an update with this fix, and also we need to figure out why certain users are reporting stumbler pausing and not starting.

Target:
public void removeListener() { if (mLocationManager == null) { return; } mLocationManager.removeGpsStatusListener(mSatelliteListener); enableLocationListener(false, mGpsLocationListener); enableLocationListener(false, mNetworkLocationListener); }
Source:
START public static void createGlobalInstance(Context c) { END if (sInstance != null) { return; } sInstance = new ClientPrefs(c); } I generally like to have singletons to be synchronized. ClientPrefs is only instantiated in one place anyway, and that's single threaded, so this is more of a nit.

Target:
public static synchronized void createGlobalInstance(Context c) { if (sInstance != null) { return; } sInstance = new ClientPrefs(c); }
Source:
START public static ClientPrefs getInstance() { END assert(sInstance != null); assert(sInstance.getClass().isInstance(ClientPrefs.class)); return (ClientPrefs)sInstance; } Does it make sense to change this to `getInstance(Context c)` and merge this with `createGlobalInstance`?

Target:
public static synchronized ClientPrefs getInstance() { assert(sInstance != null); assert(sInstance.getClass().isInstance(ClientPrefs.class)); return (ClientPrefs)sInstance; }
Source:
public Lease_newBreakOption(Lease lease) { START super(Lease_newBreakOption.class); END this.lease = lease; } remove super(...) call

Target:
public Lease_newBreakOption(Lease lease) { this.lease = lease; }
Source:
public boolean equals(final Object obj) { START if (!(obj instanceof DueDateAmountMap)) { END return false; } return innerMap.equals(obj); } Why not just do this instead: `return obj instanceof DueDateAmountMap && innerMap.equals(obj);`

Target:
public boolean equals(final Object obj) { return obj instanceof DueDateAmountMap && innerMap.equals(obj); }
Source:
private Department getDepartment(HttpServletRequest request, List<Department> departments) { Department department = getDomainObject(request, "departmentID"); START return department != null ? department : departments.stream().findAny().orElse(null); END } Creating a Stream for the sole purpose of retrieving a single element from the a List is a bit excessive. I suggest something like this instead: `return department != null ? department : departments.isEmpty() ? null : departments.get(0);`

Target:
private Department getDepartment(HttpServletRequest request, List<Department> departments) { Department department = getDomainObject(request, "departmentID"); return department != null ? department : departments.isEmpty() ? null : departments.get(0); }
Source:
public PhoneNumber parsePhoneNumber(String numberText) { if (!StringUtils.isEmpty(numberText)) { if (numberText.startsWith("00")) { numberText = numberText.replaceFirst("00", "+"); } try { final PhoneNumber phoneNumber = PHONE_UTIL.parse(numberText, null); if (PHONE_UTIL.isValidNumber(phoneNumber)) { return phoneNumber; } } catch (NumberParseException e) { START System.out.println("O n�mero n�o � v�lido:" + e); END return null; } } return null; } Using System.out is strictly forbidden. This line should be deleted.

Target:
public PhoneNumber parsePhoneNumber(String numberText) { if (!StringUtils.isEmpty(numberText)) { if (numberText.startsWith("00")) { numberText = numberText.replaceFirst("00", "+"); } try { final PhoneNumber phoneNumber = PHONE_UTIL.parse(numberText, null); if (PHONE_UTIL.isValidNumber(phoneNumber)) { return phoneNumber; } } catch (NumberParseException e) { return null; } } return null; }
Source:
public String getInternationalFormatNumber(String numberText) { final PhoneNumber phoneNumber = parsePhoneNumber(numberText); START if (phoneNumber != null) { END return PHONE_UTIL.format(phoneNumber, PhoneNumberFormat.E164); } return null; } Using the ternary operator here will result in nicer code: `return phoneNumber != null ? PHONE_UTIL.format(phoneNumber, PhoneNumberFormat.E164) : null`

Target:
public String getInternationalFormatNumber(String numberText) { final PhoneNumber phoneNumber = parsePhoneNumber(numberText); return phoneNumber != null ? PHONE_UTIL.format(phoneNumber, PhoneNumberFormat.E164) : null; }
Source:
private List<PhdCandidacyPeriod> getCandidacyPeriods() { START List<PhdCandidacyPeriod> candidacyPeriodList = new ArrayList<>(); END CollectionUtils.select(Bennu.getInstance().getCandidacyPeriodsSet(), new Predicate() { @Override public boolean evaluate(Object arg0) { return arg0 instanceof PhdCandidacyPeriod; } }, candidacyPeriodList); return candidacyPeriodList; } this change is not in the scope of this issue.

Target:
private List<PhdCandidacyPeriod> getCandidacyPeriods() { List<PhdCandidacyPeriod> candidacyPeriodList = new ArrayList<PhdCandidacyPeriod>(); CollectionUtils.select(Bennu.getInstance().getCandidacyPeriodsSet(), new Predicate() { @Override public boolean evaluate(Object arg0) { return arg0 instanceof PhdCandidacyPeriod; } }, candidacyPeriodList); return candidacyPeriodList; }
Source:
static private String getDegreeCurricularPlansPresentationString(final Set<DegreeCurricularPlan> input) { String result = " [ "; for (Iterator<DegreeCurricularPlan> iterator = input.iterator(); iterator.hasNext();) { final DegreeCurricularPlan iter = iterator.next(); START result += iter.getName(); END if (iterator.hasNext()) { result += " , "; } } result += " ]"; return result; } This should use a `StringBuilder` (the same goes for all the other usages of `+=` on Strings for this PR).

Target:
static private String getDegreeCurricularPlansPresentationString(final Set<DegreeCurricularPlan> input) { StringBuilder result = new StringBuilder(" [ "); for (Iterator<DegreeCurricularPlan> iterator = input.iterator(); iterator.hasNext();) { final DegreeCurricularPlan iter = iterator.next(); result.append(iter.getName()); if (iterator.hasNext()) { result.append(" , "); } } result.append(" ]"); return result.toString(); }
Source:
START final public Double getWeight(ExecutionSemester semester) { END if (isBolonhaDegree()) { return getEctsCredits(semester); } if (getDegreeType().isMasterDegree()) { return getCredits(); } final Double weigth = super.getWeigth(); return (weigth == null || weigth == 0.0) ? WEIGHT_FOR_PRE_BOLONHA : weigth; } shouldn't the constants be removed from the source code?

Target:
final public Double getWeight(ExecutionSemester semester) { if (isBolonhaDegree()) { return getEctsCredits(semester); } if (getDegreeType().isMasterDegree()) { return getCredits(); } return super.getWeigth(); }
Source:
START public Degree getDegree() { END return ((DegreeUnit) getDelegateFunction().getFunction().getUnit()).getDegree(); } Why did you change the visibility of getDegree in this case?

Target:
protected Degree getDegree() { return ((DegreeUnit) getDelegateFunction().getFunction().getUnit()).getDegree(); }
Source:
private static void loadPokeZPowers() { if (zpowerloaded) { return; } START testLoad();; END zpowerloaded = true; String path = "db/moves/" + thisGen + "G/zpower.txt"; InfoFiller.fill(path, new FillerByte() { @Override void fillByte(int i, byte b) { moveNames.get(i).zpower = b; } }); } a semicolon too much

Target:
private static void loadPokeZPowers() { if (zpowerloaded) { return; } testLoad(); zpowerloaded = true; String path = "db/moves/" + thisGen + "G/zpower.txt"; InfoFiller.fill(path, new FillerByte() { @Override void fillByte(int i, byte b) { moveNames.get(i).zpower = b; } }); }
Source:
public boolean accept(Path path) { String name = path.getName(); if (name.startsWith("_") || name.startsWith(".")) { return false; } return true; START } END You can replace this with return !(name.startsWith("_") || name.startsWith(".")) Also can you add java docs for this class

Target:
public boolean accept(Path path) { String name = path.getName(); return !(name.startsWith("_") || name.startsWith(".")); }
Source:
public void after() throws IOException { START EasyMock.verify(_mocks.toArray()); END // Delete all camus data folder.delete(); } Is calling verify() in After method a good practice? What if there's a test that doesn't need to verify all these mocks?

Target:
public void after() throws IOException { // Delete all camus data folder.delete(); }
Source:
START private boolean shouldFetchFromSchemaRegistry(String id) { END if (!failedFetchHistories.containsKey(id)) { return true; } FailedFetchHistory failedFetchHistory = failedFetchHistories.get(id); boolean maxRetriesNotExceeded = failedFetchHistory.numOfAttempts < getByIdMaxRetries; boolean minRetryIntervalSatisfied = System.nanoTime() - failedFetchHistory.previousAttemptTime >= TimeUnit.SECONDS .toNanos(getByIdMinIntervalSeconds); return maxRetriesNotExceeded && minRetryIntervalSatisfied; } Do you want to synchronize on this method?

Target:
private synchronized boolean shouldFetchFromSchemaRegistry(String id) { if (!failedFetchHistories.containsKey(id)) { return true; } FailedFetchHistory failedFetchHistory = failedFetchHistories.get(id); boolean maxRetriesNotExceeded = failedFetchHistory.numOfAttempts < getByIdMaxRetries; boolean minRetryIntervalSatisfied = System.nanoTime() - failedFetchHistory.previousAttemptTime >= TimeUnit.SECONDS .toNanos(getByIdMinIntervalSeconds); return maxRetriesNotExceeded && minRetryIntervalSatisfied; }
Source:
START public static Map<String, Partitioner> getPartitioners() { END return partitionersByTopic; } Should this method return the map or the values collection or values set?

Target:
public static Set<Partitioner> getPartitioners() { return new HashSet<Partitioner>(partitionersByTopic.values()); }
Source:
START public List<HashMap<String,Object>> getLoggedEvents(@RequestParam String site, @RequestParam long since) { END return CircularQueueLogAppender.loggerQueue().getLoggedEvents(site, since); } Please return a `Map`, not a `HashMap`.

Target:
public List<Map<String,Object>> getLoggedEvents(@RequestParam String site, @RequestParam long since) { return CircularQueueLogAppender.loggerQueue().getLoggedEvents(site, since); }
Source:
protected boolean shouldNotFilter(final HttpServletRequest request) throws ServletException { SiteContext siteContext = SiteContext.getCurrent(); HierarchicalConfiguration config = siteContext.getConfig(); try { HierarchicalConfiguration corsConfig = config.configurationAt(CONFIG_KEY); if (corsConfig != null) { START boolean enable = corsConfig.getBoolean(ENABLE_KEY, false); END return !enable; } } catch (Exception e) { logger.debug("Site '{}' has no CORS configuration", siteContext.getSiteName()); } return true; } Just return the result of corsConfig.getBoolean, instead of using a variable and then immediately returning it. The variable is not necessary and I think even Codacy wil complain.

Target:
protected boolean shouldNotFilter(final HttpServletRequest request) throws ServletException { SiteContext siteContext = SiteContext.getCurrent(); HierarchicalConfiguration config = siteContext.getConfig(); try { HierarchicalConfiguration corsConfig = config.configurationAt(CONFIG_KEY); if (corsConfig != null) { return !corsConfig.getBoolean(ENABLE_KEY, false); } } catch (Exception e) { logger.debug("Site '{}' has no CORS configuration", siteContext.getSiteName()); } return true; }
Source:
START private Set<Location> getAllChildAndGrandLocations(Set<Location> visitLocations){ END Set<Location>allchildAndGrandVisitLocations=new HashSet<Location>(); for(Location visitLocation:visitLocations) { allchildAndGrandVisitLocations.addAll(visitLocation.getChildLocations()); if(visitLocation.getChildLocations() !=null) { getAllChildAndGrandLocations(allchildAndGrandVisitLocations); } else { break; } } return allchildAndGrandVisitLocations; } Can you write a quick test to make sure this worked properly? I may be wrong, but I'm not sure the accumulation of results will work correctly?

Target:
public static Set<Location> getAllChildAndGrandLocations(Set<Location> visitLocations) { Set<Location> allchildAndGrandVisitLocations = new HashSet<Location>(); for (Location visitLocation : visitLocations) { if (visitLocation.getChildLocations() != null) { allchildAndGrandVisitLocations.addAll(visitLocation.getChildLocations()); getAllChildAndGrandLocations(allchildAndGrandVisitLocations); } else { break; } } return allchildAndGrandVisitLocations; }
Source:
public void started() { START Context.getService(HtmlFormEntryService.class).addHandler("encounterProviderAndRole", new EncounterProviderAndRoleTagHandler()); END log.info("Started HTML Form Entry Module"); } Instead of adding this here, this should be added as an entry on the "handlers" bean in moduleApplicationContext, where the other ones were added. (Adding it via the activator in the 19ext module was a bit of a hack)

Target:
public void started() { log.info("Started HTML Form Entry Module"); }
Source:
public void stopped() { START HtmlFormEntryService hfes = Context.getService(HtmlFormEntryService.class); END if (hfes != null) hfes.getHandlers().remove("encounterProviderAndRole"); log.info("Stopped HTML Form Entry Module"); } This can be removed too, once we add the handler via moduleApplicationContext

Target:
public void stopped() { log.info("Stopped HTML Form Entry Module"); }
Source:
protected void writeEntityToNBT(NBTTagCompound tags) { if(type == null) setDead(); else { START tags.setString("Type", type.shortName); END if(player != null) tags.setString("Player", player.get().getName()); tags.setFloat("RotationYaw", axes.getYaw()); tags.setFloat("RotationPitch", axes.getPitch()); } } `player` won't be null since you set it to an Optional above.

Target:
protected void writeEntityToNBT(NBTTagCompound tags) { if(type == null) setDead(); else { tags.setString("Type", type.shortName); if(player.isPresent()) tags.setString("Player", player.get().getName()); tags.setFloat("RotationYaw", axes.getYaw()); tags.setFloat("RotationPitch", axes.getPitch()); } }
Source:
START public Team getTeam(EntityPlayer player) END { String username = player.getName(); for(Team team : teams) { for (String name : team.members) { if (username.equals(name)) { return team; } } } return null; } Would be worth returning an Optional in this method instead of returning null and having possible issues down the line.

Target:
public Optional<Team> getTeam(EntityPlayer player) { String username = player.getName(); for(Team team : teams) { for (String name : team.members) { if (username.equals(name)) { return Optional.of(team); } } } return Optional.empty(); }
Source:
public void launch(ISelection selection, String mode) { if (selection instanceof IStructuredSelection) { Object element = ((IStructuredSelection) selection).getFirstElement(); START if (element != null && element instanceof IResource) { END try { IResource selectedResource = (IResource) element; launchBower(selectedResource); } catch (CoreException e) { Activator.logError(e); } } } } Check for null is not required here, because (element instance of IResource) returns false for null element.

Target:
public void launch(ISelection selection, String mode) { if (selection instanceof IStructuredSelection) { Object element = ((IStructuredSelection) selection).getFirstElement(); if (element instanceof IResource) { try { IResource selectedResource = (IResource) element; launchBower(selectedResource); } catch (CoreException e) { Activator.logError(e); } } } }