auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void dispose() { if (ksession != null) { abortProcessInstances(ksession); ksession.dispose(); ksession = null; } START if (ksession2 != null) { ksession2.dispose(); ksession2 = null; } END } Same, it can be removed

Target:
public void dispose() { if (ksession != null) { abortProcessInstances(ksession); ksession.dispose(); ksession = null; } }
Source:
private int executeWithParameters(Map<String, Object> params, Query query) { applyMetaQueryParameters(params, query); query.getParameters() .stream() .filter(e -> params.containsKey(e.getName())) START .forEach(p -> query.setParameter(p.getName(), params.get(p.getName()))); END return query.executeUpdate(); } I believe `applyMetaQueryParameters` already handles this. Or is this because of something else?

Target:
private int executeWithParameters(Map<String, Object> params, Query query) { applyMetaQueryParameters(params, query); return query.executeUpdate(); }
Source:
public void setup() { // disable auto init of timers since ejb timer service supports persistence of timers System.setProperty("org.jbpm.rm.init.timer", "false"); START logger.info("Using local cache for EJB timers: {}", (USE_LOCAL_CACHE ? "true" : "false")); END } Why do we need to use conditional expression and the print true or false, isn’t it enough to directly priny USELOCALCACHE?

Target:
public void setup() { // disable auto init of timers since ejb timer service supports persistence of timers System.setProperty("org.jbpm.rm.init.timer", "false"); logger.info("Using local cache for EJB timers: {}", USE_LOCAL_CACHE); }
Source:
START static void cleanupSingletonSessionId() { END File tempDir = new File(System.getProperty("java.io.tmpdir")); if (tempDir.exists()) { String[] jbpmSerFiles = tempDir.list(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith("-jbpmSessionId.ser"); } }); for (String file : jbpmSerFiles) { new File(tempDir, file).delete(); } } } This should be on one line.

Target:
private static void cleanupSingletonSessionId() { File tempDir = new File(System.getProperty("java.io.tmpdir")); if (tempDir.exists()) { String[] jbpmSerFiles = tempDir.list(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith("-jbpmSessionId.ser"); } }); for (String file : jbpmSerFiles) { new File(tempDir, file).delete(); } } }}
Source:
public void cleanup() { cleanupSingletonSessionId(); if (units != null && !units.isEmpty()) { for (DeploymentUnit unit : units) { try { deploymentService.undeploy(unit); } catch (Exception e) { // do nothing in case of some failed tests to avoid next test to fail as well logger.error("---------------------------" + e.getLocalizedMessage()); START logger.error("--do nothing in case of some failed tests to avoid next test to fail as well-------------------------" + unit.getIdentifier()); END } } units.clear(); } close(); } Do we need this logging? Maybe we can at least decrease the logging level to debug so it doesn't pollute logs when tests are run.

Target:
public void cleanup() { cleanupSingletonSessionId(); if (units != null && !units.isEmpty()) { for (DeploymentUnit unit : units) { try { deploymentService.undeploy(unit); } catch (Exception e) { // do nothing in case of some failed tests to avoid next test to fail as well } } units.clear(); } close(); }
Source:
public Object getData(String name) { Object result = this.data.get(name); START if (result == null && name != null && name.equalsIgnoreCase("caseid")) { END result = getCaseId(); } return result; } I believe we can change ``` name != null && name.equalsIgnoreCase("caseid") ``` for ``` "caseid".equalsIgnoreCase(name) ```. Will be much easier to read.

Target:
public Object getData(String name) { Object result = this.data.get(name); if (result == null && "caseid".equalsIgnoreCase(name)) { result = getCaseId(); } return result; }
Source:
public void triggerAdHocFragment(String caseId, String stageId, String fragmentName, Object data) throws CaseNotFoundException { START authorizationManager.checkAuthorization(caseId); END ProcessInstanceDesc pi = verifyCaseIdExists(caseId); triggerAdHocFragment(pi.getId(), stageId, fragmentName, data); } This call is missing in the second method.

Target:
public void triggerAdHocFragment(String caseId, String stageId, String fragmentName, Object data) throws CaseNotFoundException { ProcessInstanceDesc pi = verifyCaseIdExists(caseId); triggerAdHocFragment(pi.getId(), stageId, fragmentName, data); }
Source:
public void executeWorkItem(WorkItem workItem, WorkItemManager manager) { try { manager.completeWorkItem(workItem.getId(), null); } catch(Throwable cause) { handleException(cause); START manager.abortWorkItem(workItem.getId()); END } } I don't think we should call abortWorkItem here as the work item most likely won't be there as it failed to execute.

Target:
public void executeWorkItem(WorkItem workItem, WorkItemManager manager) { try { // handler impl here manager.completeWorkItem(workItem.getId(), null); } catch(Throwable cause) { handleException(cause); } }
Source:
public static List<String> getAuthenticatedUserRoles(IdentityProvider identityProvider) { START List<String> roles = identityProvider != null ? identityProvider.getRoles() : new ArrayList<>(); END if (roles == null || roles.isEmpty()) { roles = new ArrayList<>(); roles.add(""); } return roles; } Seems to be a compilation issue here, new ArrayList<>() should be new ArrayList\<String\>()

Target:
public static List<String> getAuthenticatedUserRoles(IdentityProvider identityProvider) { List<String> roles = identityProvider != null ? identityProvider.getRoles() : new ArrayList<String>(); if (roles == null || roles.isEmpty()) { roles = new ArrayList<String>(); roles.add(""); } return roles; }
Source:
public Object getContentObject() { START throw new UnsupportedOperationException("Not implemented for JPA"); END } wha would it take to implement this for JPA? bit uncomfortable to have new methods only for particular type ...

Target:
public Object getContentObject() { return null; }
Source:
START public Collection<CaseInstance> getCaseInstances(QueryContext queryContext) { END Map<String, Object> params = new HashMap<String, Object>(); params.put("statuses", statuses); applyQueryContext(params, queryContext); applyDeploymentFilter(params); List<CaseInstance> processInstances = commandService.execute(new QueryNameCommand<List<CaseInstance>>("getCaseInstances", params)); return processInstances; } The method below could be reused passing the default statuses, avoiding code dup.

Target:
public Collection<CaseInstance> getCaseInstances(QueryContext queryContext) { return getCaseInstances(statuses, queryContext); }
Source:
public static NotificationListenerManager get() { if (INSTANCE == null) { START INSTANCE = new NotificationListenerManager(); END } return INSTANCE; } If you want to lazy-load the manager instance, would it be okay to use the [lazy holder idiom](https://en.wikipedia.org/wiki/Initialization-on-demand_holder_idiom)? I believe that the above code is a minor race condition.

Target:
public static NotificationListenerManager get() { return INSTANCE; }
Source:
public void afterCompletion(int status) { try { manager.disposeRuntimeEngine(runtime); } catch (Throwable e) { START logger.warn("Could not dispose runtime engine", e); END } } Please do -- in general, there are very few (if any) dispose or cleanup operations that should be warn. We only use warn for operations that directly prevent or impair normal operation. If you can push -f (force) a fix to the pull request, that would be great! Thanks.

Target:
public void afterCompletion(int status) { try { manager.disposeRuntimeEngine(runtime); } catch (Throwable e) { logger.debug("Could not dispose runtime engine", e); } }
Source:
private static void sendWithRest(MessageChannel channel) { IntStream.range(1, 10).forEach(i -> { channel.send(MessageBuilder.withPayload(createEvent()).build()); START }); END } Don't see reason to use `Streams` here. The simple `for (int i = 0; i < 10; i++)` should be enough.

Target:
private static void sendWithRest(MessageChannel channel) { for (int i = 0; i < 10; i++) { channel.send(MessageBuilder.withPayload(createEvent()).build()); } }
Source:
public String getVersionChanges(String versionStr) { START Map<String, String> depends = new HashMap<>(); END JSONObject version = versions.getJSONObject(versionStr); if (version.containsKey("changes")) { return version.getString("changes"); } return null; } What's this variable for?

Target:
public String getVersionChanges(String versionStr) { JSONObject version = versions.getJSONObject(versionStr); return version.containsKey("changes") ? version.getString("changes") : null; }
Source:
START public GHDiscussion wrapUp(GHTeam team) throws IOException { this.root = team.root; this.organization = team.getOrganization(); END this.team = team; return this; } ```suggestion public GHDiscussion wrapUp(GHTeam team) throws IOException { this.organization = team.getOrganization(); ```

Target:
GHDiscussion wrapUp(GHTeam team) { this.team = team; return this; }
Source:
START public void shouldPreferClientDestPortWhenInitialized() { END HttpRequestMessageImpl message = new HttpRequestMessageImpl(new SessionContext(), "HTTP/1.1", "POST", "/some/where", new HttpQueryParams(), new Headers(), "192.168.0.2", "https", 7002, "localhost", new InetSocketAddress("api.netflix.com", 443)); assertEquals(message.getClientDestinationPort(), 443); } Line wrapping is odd here. Either fill all the lines all the way, or put one arg per line. This is for consistency.

Target:
public void shouldPreferClientDestPortWhenInitialized() { HttpRequestMessageImpl message = new HttpRequestMessageImpl(new SessionContext(), "HTTP/1.1", "POST", "/some/where", new HttpQueryParams(), new Headers(), "192.168.0.2", "https", 7002, "localhost", new InetSocketAddress("api.netflix.com", 443)); assertEquals(message.getClientDestinationPort(), Optional.of(443)); }
Source:
public void stop() { START LOG.debug("Shutting down Zuul."); END serverGroup.stop(); // remove the shutdown hook that was added when the proxy was started, since it has now been stopped try { Runtime.getRuntime().removeShutdownHook(jvmShutdownHook); } catch (IllegalStateException e) { // This can happen if the VM is already shutting down LOG.debug("Failed to remove shutdown hook", e); } LOG.debug("Completed zuul shutdown."); } Why change these to debug?

Target:
public void stop() { LOG.info("Shutting down Zuul."); serverGroup.stop(); // remove the shutdown hook that was added when the proxy was started, since it has now been stopped try { Runtime.getRuntime().removeShutdownHook(jvmShutdownHook); } catch (IllegalStateException e) { // This can happen if the VM is already shutting down LOG.debug("Failed to remove shutdown hook", e); } LOG.info("Completed zuul shutdown."); }
Source:
private SslContext getClientSslContext() throws SSLException { return SslContextBuilder .forClient() .sslProvider(BaseSslContextFactory.chooseSslProvider()) .startTls(true) START .build(); END } Can you add `.protocols()` explicitly here. There's a `getProtocols()` method in `BaseSslContextFactory`. Should probably be `TLSv1.2`. I think maybe a cleaner solution is to subclass that class and create a `ClientSslContextFactory` that holds this logic. You can initialize it in the constructor of this class and just call this method in the init block.

Target:
private SslContext getClientSslContext() throws SSLException { return SslContextBuilder .forClient() .sslProvider(BaseSslContextFactory.chooseSslProvider()) .build(); }
Source:
public void setSerial(int port) { START this.localPort = port; END serial = EMULATOR_SERIAL_PREFIX + port; } I believe this line is incorrect and should be removed

Target:
public void setSerial(int port) { serial = EMULATOR_SERIAL_PREFIX + port; }
Source:
public void stop() { if (serverThread == null) { throw new IllegalStateException("Server is not running"); } serverThread.interrupt(); START TrafficCounter.shutdown(); END } Should this be called in `finally` above instead? The `TrafficCounter` is set up in the `ServerInitializer`.

Target:
public void stop() { if (serverThread == null) { throw new IllegalStateException("Server is not running"); } serverThread.interrupt(); }
Source:
protected static DefaultHardwareDevice anDevice(String name, DeviceTargetPlatform platform) throws AndroidDeviceException { DefaultHardwareDevice device = mock(DefaultHardwareDevice.class); when(device.getModel()).thenReturn(name); when(device.getTargetPlatform()).thenReturn(platform); START when(device.getModel()).thenReturn("Nexus 5"); END when(device.isDeviceReady()).thenReturn(true); when(device.screenSizeMatches("320x480")).thenReturn(true); return device; } The default value for this will be an empty string? If yes, can you change this to return an empty string instead and explicitly set the value to "Nexus 5" for the tests where you need that?

Target:
protected static DefaultHardwareDevice anDevice(String name, DeviceTargetPlatform platform) throws AndroidDeviceException { DefaultHardwareDevice device = mock(DefaultHardwareDevice.class); when(device.getModel()).thenReturn(name); when(device.getTargetPlatform()).thenReturn(platform); when(device.isDeviceReady()).thenReturn(true); when(device.screenSizeMatches("320x480")).thenReturn(true); return device; }
Source:
public String getDefaultApp(Set<String> supportedApps) { String defaultApp = getAut(); if (getLaunchActivity() == null) { if (!defaultApp.contains(":")) { // App version is not specified. Get the latest version from the apps store. defaultApp = getDefaultVersion(supportedApps, defaultApp); } else { defaultApp = supportedApps.contains(defaultApp) ? defaultApp : null; } } START return defaultApp; END } Can we shuffle the logic in this method around a bit. I think it's not clear from the code what it does. How about: ``` java public String getDefaultApp(Set<String> supportedApps) { String defaultApp = getAut(); // Always just return if the launch activity is specified if (getLaunchActivity() != null) { return defaultApp; } // App version is not specified. Get the latest version from the apps store. if (!defaultApp.contains(":")) { return getDefaultVersion(supportedApps, defaultApp); } return supportedApps.contains(defaultApp) ? defaultApp : null; } ```

Target:
public String getDefaultApp(Set<String> supportedApps) { String defaultApp = getAut(); // if the launch activity is specified, just return. if (getLaunchActivity() != null) { return defaultApp; } // App version is not specified. Get the latest version from the apps store. if (!defaultApp.contains(":")) { return getDefaultVersion(supportedApps, defaultApp); } return supportedApps.contains(defaultApp) ? defaultApp : null; }
Source:
START private boolean isApp(File file) { END if (file.getAbsolutePath().contains(".apk")) { String ext = file.getName(); return ext.endsWith(".apk"); } return false; } Cant this NOT be simplified to just check if the absolute path ends with `.apk` ?

Target:
private boolean isApp(File file) { if (file != null) { return file.getAbsolutePath().endsWith(".apk"); } return false; }
Source:
public void injectorCreated(Injector injector, InjectorConfig config) { START synchronized(this){ END injectorNames.add(config.getName()); } } Use `CopyOnWriteArrayList` for the `injectorNames` and remove `synchronized()` statements.

Target:
public void injectorCreated(Injector injector, InjectorConfig config) { injectorNames.add(config.getName()); }
Source:
public InjectorRunner(final BundleContext bundleContext, final String injectorName, final String bundleNameFilter, final String basePackage) { this.bundleContext = bundleContext; this.injectorName = injectorName; this.bundleNameFilter = bundleNameFilter; this.basePackage = basePackage; START this.injectorPath = injectorName; END } What's the purpose of this assignment?

Target:
public InjectorRunner(final BundleContext bundleContext, final String injectorName, final String bundleNameFilter, final String basePackage) { this.bundleContext = bundleContext; this.injectorName = injectorName; this.bundleNameFilter = bundleNameFilter; this.basePackage = basePackage; }
Source:
public int hashCode() { START HashCodeBuilder builder = new HashCodeBuilder(INITIAL, MULTIPLIER); END builder.append(path); builder.append(type); return builder.toHashCode(); } I think there is an default constructor for `HashCodeBuilder`, so you don't have to pass these constants.

Target:
public int hashCode() { HashCodeBuilder builder = new HashCodeBuilder(); builder.append(path); builder.append(type); return builder.toHashCode(); }
Source:
public static String getAttributeValueFromString(String string) { START String content = string; END if (content.length() > 0) { return content; } return null; } I'm not sure why this variable is needed here. Could be: ```java public static String getAttributeValueFromString(String string) { if (string.length() > 0) { return string; } return null; } ``` This functions also will fail if `string == null`. Should be something like this: ```java if (string == null || string.length() > 0) { return null; } ```

Target:
public static String getAttributeValueFromString(String string) { if (string != null && string.length() > 0) { return string; } return null; }
Source:
public JsonResponse add(@Valid @RequestBody SpamRuleDto ruleDto, BindingResult result) throws org.jtalks.common.service.exceptions.NotFoundException, InterruptedException { checkForAdminPermissions(); trimAndValidate(ruleDto, result); if (result.hasFieldErrors() || result.hasGlobalErrors()) { return new JsonResponse(JsonResponseStatus.FAIL, result.getAllErrors()); } START SpamRule spamRule = SpamRule.toEntity(ruleDto); END return saveOrUpdateSpamRule(result, spamRule); } Shouldn't this be `ruleDto.toEntity()`?

Target:
public JsonResponse add(@Valid @RequestBody SpamRuleDto ruleDto, BindingResult result) throws org.jtalks.common.service.exceptions.NotFoundException, InterruptedException { checkForAdminPermissions(); trimAndValidate(ruleDto, result); if (result.hasFieldErrors() || result.hasGlobalErrors()) { return new JsonResponse(JsonResponseStatus.FAIL, result.getAllErrors()); } SpamRule spamRule = ruleDto.toEntity(); return saveOrUpdateSpamRule(result, spamRule); }
Source:
public void regexValidationFailsIfLengthMoreThan255(){ SpamRuleDto spamRuleDto = randomSpamRuleDto().setRegex(alphanumeric(256)); Set<ConstraintViolation<SpamRuleDto>> constraintViolations = validator.validate(spamRuleDto); START Assert.assertEquals(constraintViolations.size(), 1); END } What about static import?

Target:
public void regexValidationFailsIfLengthMoreThan255(){ SpamRuleDto spamRuleDto = randomSpamRuleDto().setRegex(alphanumeric(256)); Set<ConstraintViolation<SpamRuleDto>> constraintViolations = validator.validate(spamRuleDto); assertEquals(constraintViolations.size(), 1); }
Source:
public GroupDto(Group group) { this.id = group.getId(); this.name = group.getName(); START this.users = UserDto.convertToUserDtoList(group.getUsers(), UserDto.BY_NAME_COMPARATOR, DISPLAY_USER_LIMIT); END } It's not good idea. Group 'Registered users' contain over 40k users which will be retrieved from DB. You could better write a hql query to retrieve a limited list of users from given group.

Target:
public GroupDto(Group group) { this.id = group.getId(); this.name = group.getName(); }
Source:
public GroupDto(Group group) { this.id = group.getId(); this.name = group.getName(); START this.users = UserDto.convertToUserDtoList(group.getUsers()); END } why do you need it?

Target:
public GroupDto(Group group) { this.id = group.getId(); this.name = group.getName(); }
Source:
START UserDto(User user) { END this.username = user.getUsername(); this.email = user.getEmail(); this.id = user.getId(); } Why do you use package-private access for this constructor?

Target:
public UserDto(User user) { this.username = user.getUsername(); this.email = user.getEmail(); this.id = user.getId(); }
Source:
public void sessionDestroyed(HttpSessionEvent se) { LocationService locationService; ServletContext context = se.getSession().getServletContext(); Object principal = getPrincipalFromSession(se.getSession()); if (principal != null) { try { START locationService = getBeanFormApplicationContext(context, LocationService.class, "locationService"); END locationService.clearUserLocation(principal); } catch (Exception ex) { logger.warn("Error clearing user location when session being destroyed: " + ex.getMessage()); } } } Is it possible to retrieve that bean only once? I'm not sure how performant this operation is in Spring..

Target:
public void sessionDestroyed(HttpSessionEvent se) { Object principal = getPrincipalFromSession(se.getSession()); if (principal != null) { try { locationService.clearUserLocation(principal); } catch (Exception ex) { logger.warn("Error clearing user location when session being destroyed: " + ex.getMessage()); } } }
Source:
public void activate(String username) { ClientResource clientResource = sendActivationRequest(username); START closeRestletConnection(clientResource); END } Shouldn't this be in `finally`?

Target:
public void activate(String username) { ClientResource clientResource = null; try { clientResource = sendActivationRequest(username); } finally { if (clientResource != null) closeRestletConnection(clientResource); } }
Source:
private boolean isGrantedForGroup(List<GroupAce> controlEntries, Authentication authentication, Permission permission, boolean isCheckAllowedGrant) { Object auth = authentication.getPrincipal(); START if (auth instanceof JCUser) { END List<Long> groupsIDs = ((JCUser) auth).getGroupsIDs(); for (GroupAce ace : controlEntries) { if (groupsIDs.contains(ace.getGroupId())){ if (isGrantedForGroup(ace, permission, isCheckAllowedGrant)) { return true; } } } } return false; } Too nested.. Can be simplified: ``` java Object auth = authentication.getPrincipal(); if (!(auth instanceof JCUser)) return false; List<Long> groupsIDs = ((JCUser) auth).getGroupsIDs(); for (GroupAce ace : controlEntries) { if (groupsIDs.contains(ace.getGroupId())) { if (isGrantedForGroup(ace, permission, isCheckAllowedGrant)) return true; } } return false; ```

Target:
private boolean isGrantedForGroup(List<GroupAce> controlEntries, Authentication authentication, Permission permission, boolean isCheckAllowedGrant) { Object auth = authentication.getPrincipal(); if (!(auth instanceof JCUser)) return false; List<Long> groupsIDs = ((JCUser) auth).getGroupsIDs(); for (GroupAce ace : controlEntries) { if (groupsIDs.contains(ace.getGroupId())) { if (isGrantedForGroup(ace, permission, isCheckAllowedGrant)) return true; } } return false; }
Source:
public void saveDraftShouldDeleteDraftIfTitleAndBodyAreEmptyAndRecipientIsNotExists() throws Exception { mockMvc = MockMvcBuilders.standaloneSetup(controller).build(); START saveDraft(EMPTY, EMPTY, null).andExpect(model() END .attributeHasErrors("privateMessageDto")) .andExpect(view().name("redirect:/drafts")) .andExpect(status().isMovedTemporarily()); verify(pmService).delete(anyList()); } You don't necessarily need constants for these.. Plain "" should be fine too.

Target:
public void saveDraftShouldDeleteDraftIfTitleAndBodyAreEmptyAndRecipientIsNotExists() throws Exception { saveDraft("", "", null) .andExpect(model() .attributeHasErrors("privateMessageDto")) .andExpect(view().name("redirect:/drafts")) .andExpect(status().isMovedTemporarily()); verify(pmService).delete(anyList()); }
Source:
public void rebuildIndexes() { long forumComponentId = componentService.getComponentOfForum().getId(); START componentService.checkPermissionsForComponent(forumComponentId); END topicSearchService.rebuildSearchIndex(); } I think we usually put these lines into `topicSearchService.rebuildSearchIndex()`.

Target:
public void rebuildIndexes() { topicSearchService.rebuildSearchIndex(); }
Source:
public void testCreateTopic() throws NotFoundException { Branch branch = createBranch(); START when(userService.getCurrentUser()).thenReturn(user); END createTopicStubs(branch); Topic dto = createTopic(); Topic createdTopic = topicService.createTopic(dto, ANSWER_BODY); Post createdPost = createdTopic.getFirstPost(); createTopicAssertions(branch, createdTopic, createdPost); createTopicVerifications(createdTopic); } Duplicates in `createTopicStubs`

Target:
public void testCreateTopic() throws NotFoundException { Branch branch = createBranch(); createTopicStubs(); Topic dto = createTopic(); Topic createdTopic = topicService.createTopic(dto, ANSWER_BODY); Post createdPost = createdTopic.getFirstPost(); createTopicAssertions(branch, createdTopic, createdPost); createTopicVerifications(createdTopic); }
Source:
public void testLoginNotActivatedUserShouldFail() START throws UnexpectedErrorException, NoConnectionException { END HttpServletRequest httpRequest = new MockHttpServletRequest(); HttpServletResponse httpResponse = new MockHttpServletResponse(); LoginUserDto loginUserDto = new LoginUserDto("username", "password", true, "192.168.1.1"); when(authenticator.authenticate(loginUserDto, httpRequest, httpResponse)) .thenReturn(AuthenticationStatus.NOT_ENABLED); AuthenticationStatus result = userService.loginUser(loginUserDto, httpRequest, httpResponse); assertEquals(result, AuthenticationStatus.NOT_ENABLED, "Login not activated user should fail."); } It doesn't matter in tests what exceptions get thrown, so it's easier to `throws Exception`.

Target:
public void testLoginNotActivatedUserShouldFail() throws Exception { HttpServletRequest httpRequest = new MockHttpServletRequest(); HttpServletResponse httpResponse = new MockHttpServletResponse(); LoginUserDto loginUserDto = new LoginUserDto("username", "password", true, "192.168.1.1"); when(authenticator.authenticate(loginUserDto, httpRequest, httpResponse)) .thenReturn(AuthenticationStatus.NOT_ENABLED); AuthenticationStatus result = userService.loginUser(loginUserDto, httpRequest, httpResponse); assertEquals(result, AuthenticationStatus.NOT_ENABLED, "Login not activated user should fail."); }
Source:
public boolean isContainsOwnerPostsOnly() { for (Post post : getDisplayedPosts()) { START if (post.getUserCreated().getId() != topicStarter.getId()) { END return false; } } return true; } You can compare users with equals method.

Target:
public boolean isContainsOwnerPostsOnly() { for (Post post : getDisplayedPosts()) { if (post.getUserCreated().equals(topicStarter)) { return false; } } return true; }
Source:
public Locale getLocale() { START return Optional.ofNullable(locale).orElse(DEFAULT_LOCALE); END } You don't need to do this. Skip any logic that requires `locale` to be set if it's used, but you can rely on the `@Required` annotation for the rest.

Target:
public Locale getLocale() { return locale; }
Source:
private boolean isSpanAnnotation(BratAnnotation ann) { START if (ann instanceof SpanAnnotation && END (nameTypes == null || nameTypes.size() == 0 || nameTypes.contains(ann.getType()))) { return true; } return false; } Probably better to be clear about what we expect: - Don't enable name type filtering, in that case pass null as nameTypes parameter - If an empty set is passed an IllegalArgumentException could be thrown, doesn't make sense to filter all

Target:
private boolean isSpanAnnotation(BratAnnotation ann) { if (ann instanceof SpanAnnotation && (nameTypes == null || nameTypes.contains(ann.getType()))) { return true; } return false; }
Source:
private LeipzigTestSampleStream(int sentencePerDocument, Tokenizer tokenizer, InputStreamFactory in) throws IOException { super(new PlainTextByLineStream(in, StandardCharsets.UTF_8)); this.sentencePerDocument = sentencePerDocument; this.tokenizer = tokenizer; START System.setOut(new PrintStream(System.out, true, "UTF-8")); END } Remove this line, no need to set this here.

Target:
private LeipzigTestSampleStream(int sentencePerDocument, Tokenizer tokenizer, InputStreamFactory in) throws IOException { super(new PlainTextByLineStream(in, StandardCharsets.UTF_8)); this.sentencePerDocument = sentencePerDocument; this.tokenizer = tokenizer; }
Source:
public void reset() throws IOException { START if (inputStreamFactory != null) { END in = new BufferedReader(new InputStreamReader(inputStreamFactory.createInputStream(), encoding)); } } Is this `if` needed since there is no `else` for it?

Target:
public void reset() throws IOException { in = new BufferedReader(new InputStreamReader(inputStreamFactory.createInputStream(), encoding)); }
Source:
public void discardCountsBelow(double i) { List<T> labelsToRemove = new ArrayList<>(); for (Entry<T, Double> entry : map.entrySet()) { START final T label = entry.getKey(); END Double sum = entry.getValue(); if (sum == null) sum = 0.0; if (sum < i) labelsToRemove.add(label); } for (T label : labelsToRemove) { map.remove(label); } } Don't use final.

Target:
public void discardCountsBelow(double i) { List<T> labelsToRemove = new ArrayList<>(); for (Entry<T, Double> entry : map.entrySet()) { T label = entry.getKey(); Double sum = entry.getValue(); if (sum == null) sum = 0.0; if (sum < i) labelsToRemove.add(label); } for (T label : labelsToRemove) { map.remove(label); } }
Source:
public void testDictionaryArtifactToSerializerMappingExtraction() throws IOException { START InputStream descIn = getClass().getResourceAsStream( END "/opennlp/tools/util/featuregen/TestDictionarySerializerMappingExtractionxml"); Map<String, ArtifactSerializer<?>> mapping = GeneratorFactory.extractArtifactSerializerMappings(descIn); Assert.assertTrue(mapping.get("test.dictionary") instanceof DictionarySerializer); } Please wrap this with a try-with-resources to get the stream closed. Some tools otherwise complain about it and place a compiler warning.

Target:
public void testDictionaryArtifactToSerializerMappingExtraction() throws IOException { try (InputStream descIn = getClass().getResourceAsStream( "/opennlp/tools/util/featuregen/TestDictionarySerializerMappingExtractionxml")) { Map<String, ArtifactSerializer<?>> mapping = GeneratorFactory.extractArtifactSerializerMappings(descIn); Assert.assertTrue(mapping.get("test.dictionary") instanceof DictionarySerializer); } }
Source:
public BreakIteratorSentenceDetector(Locale locale) { START breakIterator = BreakIterator.getSentenceInstance(Locale.US); END } When the local is supplied that one should be used, no?

Target:
public BreakIteratorSentenceDetector(Locale locale) { breakIterator = BreakIterator.getSentenceInstance(locale); }
Source:
public IrishSentenceBankDocument() { START sentences = new ArrayList<IrishSentenceBankSentence>(); END } no need to declare type on RHS

Target:
public IrishSentenceBankDocument() { sentences = new ArrayList<>(); }
Source:
public boolean equals(Object obj) { if (obj == this) { return true; } else if (obj instanceof EvalParameters) { EvalParameters evalParameters = (EvalParameters) obj; return Arrays.equals(params, evalParameters.params) && numOutcomes == evalParameters.numOutcomes && correctionConstant == evalParameters.correctionConstant && constantInverse == evalParameters.constantInverse && correctionParam == evalParameters.correctionParam; } else { return false; START } END } Rewrite the above as `if (obj instanceOf EvalParmeters) { ... return ... } return obj == this; `

Target:
public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof EvalParameters) { EvalParameters evalParameters = (EvalParameters) obj; return Arrays.equals(params, evalParameters.params) && numOutcomes == evalParameters.numOutcomes && correctionConstant == evalParameters.correctionConstant && constantInverse == evalParameters.constantInverse && correctionParam == evalParameters.correctionParam; } return false; }
Source:
private Span[] overrideDefaultType(Span[] names) { for (int i = 0; i < names.length; i++) { Span n = names[i]; if (Objects.isNull(n.getType())) { names[i] = new Span(n.getStart(), n.getEnd(), this.defaultType, n.getProb()); } } return names; START } END if modifying the same array in place, this method can return void

Target:
private void overrideDefaultType(Span[] names) { for (int i = 0; i < names.length; i++) { Span n = names[i]; if (Objects.isNull(n.getType())) { names[i] = new Span(n.getStart(), n.getEnd(), this.defaultType, n.getProb()); } } }
Source:
public final MaxentModel train(ObjectStream<Event> events) throws IOException { if (!isValid()) { throw new IllegalArgumentException("trainParams are not valid!"); } HashSumEventStream hses = new HashSumEventStream(events); DataIndexer indexer = getDataIndexer(hses); START MaxentModel model = doTrain(indexer); END parameters.addToReport("Training-Eventhash", hses.calculateHashSum().toString(16)); parameters.addToReport(AbstractTrainer.TRAINER_TYPE_PARAM, EventTrainer.EVENT_VALUE); return model; } Should we not just call the new train method from here?

Target:
public final MaxentModel train(ObjectStream<Event> events) throws IOException { if (!isValid()) { throw new IllegalArgumentException("trainParams are not valid!"); } HashSumEventStream hses = new HashSumEventStream(events); DataIndexer indexer = getDataIndexer(hses); return train(indexer); }
Source:
public int translate(int xid, FVSlicer fvSlicer) { int ret = this.nextID++; if (nextID < MIN_XID) nextID = MIN_XID; xidMap.put(Integer.valueOf(ret), new XidPair(xid, fvSlicer.getSliceName())); START FVLog.log(LogLevel.DEBUG,null,"The Translated xid is: "+ret); END return ret; } No need to add this.

Target:
public int translate(int xid, FVSlicer fvSlicer) { int ret = this.nextID++; if (nextID < MIN_XID) nextID = MIN_XID; xidMap.put(Integer.valueOf(ret), new XidPair(xid, fvSlicer.getSliceName())); return ret; }
Source:
START public void testFindAllUsers() END { List<User> findAllUsers = userRepository.findAllUsers(); assertNotNull(findAllUsers); assertEquals(2, findAllUsers.size()); assertEquals(2, findAllUsers.iterator().next().getRoles().size()); assertEquals(2, findAllUsers.iterator().next().getRoles().size()); } @anki2189 pls add a `@Transactional` annotation here and below as well.

Target:
public void testFindAllUsers() { List<User> findAllUsers = userRepository.findAllUsers(); assertNotNull(findAllUsers); assertEquals(2, findAllUsers.size()); assertEquals(3, findAllUsers.iterator().next().getRoles().size()); assertEquals(3, findAllUsers.iterator().next().getRoles().size()); }
Source:
public void addArtifact(Artifact artifact) { START Artifact artifactParent = Optional.of(artifact).map(a -> a.getHierarchyParent()).orElse(artifact); END artifacts.remove(artifactParent); artifacts.add(artifactParent); } Cosmetic: You could extract `Optional.of(artifact).map(a -> a.getHierarchyParent()).orElse(artifact)` into a private method (i.e. `private getArtifactHierarchyParent()`?) and re-use it in `removeArtifact` to avoid possible future issues when this logic needs to be changed (i.e. forgetting to apply the same change in `removeArtifact`)

Target:
public void addArtifact(Artifact artifact) { artifacts.remove(artifact); artifacts.add(artifact); }
Source:
public Collection<String> aliases() { START return Collections.unmodifiableList(Lists.newArrayList("readableSize")); END } No need to use guava here (and the import) :) ```suggestion return Collections.unmodifiableList(Arrays.asList("readableSize")); ```

Target:
public Collection<String> aliases() { return Collections.unmodifiableList(Arrays.asList("readableSize")); }
Source:
public void testDeleteMavenPathInRepository(@MavenRepository(repositoryId = MAVEN_REPOSITORY_RELEASES, setup = MavenIndexedRepositorySetup.class) Repository repository, @MavenTestArtifact(repositoryId = MAVEN_REPOSITORY_RELEASES, id = "com.artifacts.to.delete.releases:delete-foo", versions = "1.2.1") START Path path) END throws Exception { deleteRepositoryPath(repository, path); } Cosmetic: please align this `path` parameter with the annotation above.

Target:
public void testDeleteMavenPathInRepository(@MavenRepository(repositoryId = MAVEN_REPOSITORY_RELEASES, setup = MavenIndexedRepositorySetup.class) Repository repository, @MavenTestArtifact(repositoryId = MAVEN_REPOSITORY_RELEASES, id = "com.artifacts.to.delete.releases:delete-foo", versions = "1.2.1") Path path) throws Exception { deleteRepositoryPath(repository, path, false); }
Source:
private boolean isValidNpmUser(NpmUser npmUser) { START return npmUser != null && npmUser.getName() != null && npmUser.getPassword() != null && npmUser.getDate() != null && npmUser.getRoles() != null && npmUser.getType() != null && npmUser.getId() != null; END } Cosmetic: Indentation: ``` return npmUser != null && npmUser.getName() != null && npmUser.getPassword() != null && npmUser.getDate() != null && npmUser.getRoles() != null && npmUser.getType() != null && npmUser.getId() != null; ```

Target:
private boolean isValidNpmUser(NpmUser npmUser) { return npmUser != null && npmUser.getName() != null && npmUser.getPassword() != null; }
Source:
public void setMaxPerRepository(String repository, int max) { if (max > 0) { HttpRoute httpRoute = getHttpRouteFromRepository(repository); poolingHttpClientConnectionManager.setMaxPerRoute(httpRoute, max); } else { START LOGGER.warn("Not setting max repository connections to as it is no positive value", max); END } } All our loggers are actually lowercase. Would you mind checking the rest of the code aross the pull request for similar ones? Thanks! :) ```suggestion LOGGER.warn("Not setting max repository connections to as it is no positive value", max); ```

Target:
public void setMaxPerRepository(String repository, int max) { if (max > 0) { HttpRoute httpRoute = getHttpRouteFromRepository(repository); poolingHttpClientConnectionManager.setMaxPerRoute(httpRoute, max); } else { logger.warn("Not setting max repository connections to as it is no positive value", max); } }
Source:
protected void beforeExecute(Thread t, Runnable r) { try { JobDetail jobDetails = exposeJobDetails(r); Optional.ofNullable(jobDetails).ifPresent(this::bootstrapCronJobContext); } catch (Exception e) { START LOGGER.error("Before execute failed for [{}]", r, e); END } } Cosmetic: Please, change this to lowercase: ```suggestion logger.error("Before execute failed for [{}]", r, e); ```

Target:
protected void beforeExecute(Thread t, Runnable r) { try { JobDetail jobDetails = exposeJobDetails(r); Optional.ofNullable(jobDetails).ifPresent(this::bootstrapCronJobContext); } catch (Exception e) { logger.error("Before execute failed for [{}]", r, e); } }
Source:
public static MetadataExpirationStrategyType ofStrategy(String strategy) { return Stream.of(values()) START .filter(e -> e.strategy.equalsIgnoreCase(strategy)) END .findFirst() .orElse(null); } `equalsIgnoreCase` I think we should force `equals` here to be consistent

Target:
public static MetadataExpirationStrategyType ofStrategy(String strategy) { return Stream.of(values()) .filter(e -> e.strategy.equals(strategy)) .findFirst() .orElse(null); }
Source:
public void unauthorizedUserShouldReceiveExpectedUnauthorizedResponse() { START mockMvc.contentType("application/json") END .accept(ContentType.JSON) .when() .get("/api/configuration/strongbox") .peek() .then() .statusCode(HttpStatus.FORBIDDEN.value()) .contentType("application/json") .body("error", CoreMatchers.equalTo("forbidden")); } Could you use `MediaType.APPLICATION_JSON_VALUE` instead of the String constant? Thanks!

Target:
public void unauthorizedUserShouldReceiveExpectedUnauthorizedResponse() { mockMvc.contentType("application/json") .accept(ContentType.JSON) .when() .get("/api/configuration/strongbox") .peek() .then() .statusCode(HttpStatus.FORBIDDEN.value()) .contentType("application/json") .body("error", equalTo("forbidden")); }
Source:
private static void prepareResponseBuilderForPartialRequestWithSingleRange(ByteRange byteRange, long inputLength, HttpServletResponse response) { String contentRangeHeaderValue = String.format("bytes %d-%d/%d", byteRange.getOffset(), inputLength - 1L, inputLength); response.setHeader(HttpHeaders.CONTENT_RANGE, contentRangeHeaderValue); START response.setHeader(HttpHeaders.PRAGMA, "no-cache"); END response.setStatus(PARTIAL_CONTENT.value()); } is this required ?

Target:
private static void prepareResponseBuilderForPartialRequestWithSingleRange(ByteRange byteRange, long inputLength, HttpServletResponse response) { String contentRangeHeaderValue = String.format("bytes %d-%d/%d", byteRange.getOffset(), inputLength - 1L, inputLength); response.setHeader(HttpHeaders.CONTENT_RANGE, contentRangeHeaderValue); response.setStatus(PARTIAL_CONTENT.value()); }
Source:
private static void prepareResponseBuilderForPartialRequestWithMultipleRanges(HttpServletResponse response) { response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY); START response.setHeader(HttpHeaders.PRAGMA, "no-cache"); END response.setStatus(PARTIAL_CONTENT.value()); } is this required ?

Target:
private static void prepareResponseBuilderForPartialRequestWithMultipleRanges(HttpServletResponse response) { response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY); response.setStatus(PARTIAL_CONTENT.value()); }
Source:
public Set<CronTaskConfigurationDto> getCronTaskConfigurations() { START return cronTaskConfigurations != null ? cronTaskConfigurations : new LinkedHashSet<>(); END } it will have a bad result if the `cronTaskConfigurations == null` and someone will do `getCronTaskConfigurations().add(configuration)`. probably it will be better to do it like this: ``` return cronTaskConfigurations != null ? cronTaskConfigurations : cronTaskConfigurations = new LinkedHashSet<>(); ```

Target:
public Set<CronTaskConfigurationDto> getCronTaskConfigurations() { return cronTaskConfigurations != null ? cronTaskConfigurations : (cronTaskConfigurations = new LinkedHashSet<>()); }
Source:
private void store(Map.Entry<RepositoryPath, Path> e) { try (InputStream is = Files.newInputStream(e.getValue())) { artifactManagementService.store(e.getKey(), is); } catch (IOException ioe) { throw new UndeclaredThrowableException(ioe); } START ThrowingConsumer.unchecked(Files::delete).accept(e.getValue()); END } @adavid9 can you please add `throws IOException` and use `ThrowingConsumer` within `TestArtifactContext.deployArtifact()` foreach

Target:
private void store(Map.Entry<RepositoryPath, Path> e) throws IOException { try (InputStream is = Files.newInputStream(e.getValue())) { artifactManagementService.store(e.getKey(), is); } catch (IOException ioe) { throw new UndeclaredThrowableException(ioe); } Files.delete(e.getValue()); }
Source:
private Object doInit() { MutableConfiguration configuration; try { configuration = configurationFileManager.read(); setConfiguration(configuration); setRepositoryArtifactCoordinateValidators(); } catch (IOException e) { START throw new org.springframework.cglib.proxy.UndeclaredThrowableException(e); END } return null; } throw new org.springframework.cglib.proxy.UndeclaredThrowableException(e); ?

Target:
private Object doInit() { MutableConfiguration configuration; try { configuration = configurationFileManager.read(); setConfiguration(configuration); setRepositoryArtifactCoordinateValidators(); } catch (IOException e) { throw new UndeclaredThrowableException(e); } return null; }
Source:
START private Path generateArtifact(String id, END String version) throws IOException { try { return generate(id, version); } catch (NoSuchAlgorithmException | JAXBException | NugetFormatException e) { throw new IOException(e); } } you can make it public for not to use `generateArtifact(packageId, packageVersion, 0)` method calls below

Target:
public Path generateArtifact(String id, String version) throws IOException { try { return generate(id, version); } catch (NoSuchAlgorithmException | JAXBException | NugetFormatException e) { throw new IOException(e); } }
Source:
protected MavenArtifactCoordinates getArtifactCoordinates(RepositoryPath repositoryPath) throws IOException { MavenArtifact artifact = MavenArtifactUtils.convertPathToArtifact(repositoryPath); START return artifact != null ? new MavenArtifactCoordinates(artifact) : null; END } @fuss86 it seems that previous implementation not assumed to return `null`, is there any reasons to do it now?

Target:
protected MavenArtifactCoordinates getArtifactCoordinates(RepositoryPath repositoryPath) throws IOException { MavenArtifact artifact = MavenArtifactUtils.convertPathToArtifact(repositoryPath); return new MavenArtifactCoordinates(artifact); }
Source:
public Path generateArtifact(URI uri, int size) throws IOException { START PypiWheelArtifactCoordinates coordinates = PypiWheelArtifactCoordinates.parse(FilenameUtils.getName(uri.getPath())); END return generateArtifact(coordinates); } @Firstmol probably you should use `uri.toString()` here, instead of `uri.getPath()`

Target:
public Path generateArtifact(URI uri, int size) throws IOException { PypiWheelArtifactCoordinates coordinates = PypiWheelArtifactCoordinates.parse(FilenameUtils.getName(uri.toString())); return generateArtifact(coordinates); }
Source:
public void testValidDoubleQuotedQuerySpecificChars() { String query = "repository: \"releases#1\""; AqlQueryParser aqlParser = new AqlQueryParser(query); Map<Pair<Integer, Integer>, String> errorMap = null; try { aqlParser.parseQuery(); } catch (QueryParserException e) { START errorMap = aqlParser.getErrors(); END } logger.info(String.format("Query [%s] parse tree:\n[%s]", query, aqlParser)); assertFalse(aqlParser.hasErrors()); assertNull(errorMap); } we don't expect exceptions here, so no need to catch anything

Target:
public void testValidDoubleQuotedQuerySpecificChars() { String query = "repository: \"releases#1\""; AqlQueryParser aqlParser = new AqlQueryParser(query); aqlParser.parseQuery(); logger.info(String.format("Query [%s] parse tree:\n[%s]", query, aqlParser)); assertFalse(aqlParser.hasErrors()); }
Source:
public void testValidDoubleQuotedQuerySpecificChars() { String query = "repository: \"releases#1\""; AqlQueryParser aqlParser = new AqlQueryParser(query); Map<Pair<Integer, Integer>, String> errorMap = null; aqlParser.parseQuery(); logger.info(String.format("Query [%s] parse tree:\n[%s]", query, aqlParser)); assertFalse(aqlParser.hasErrors()); START assertNull(errorMap); END } `errorMap` and this assert don't need any more as well

Target:
public void testValidDoubleQuotedQuerySpecificChars() { String query = "repository: \"releases#1\""; AqlQueryParser aqlParser = new AqlQueryParser(query); aqlParser.parseQuery(); logger.info(String.format("Query [%s] parse tree:\n[%s]", query, aqlParser)); assertFalse(aqlParser.hasErrors()); }
Source:
public void testValidSingleQuotedQuerySpecificChars() { String query = "repository: 'releases#1'"; AqlQueryParser aqlParser = new AqlQueryParser(query); START Map<Pair<Integer, Integer>, String> errorMap = null; END aqlParser.parseQuery(); logger.info(String.format("Query [%s] parse tree:\n[%s]", query, aqlParser)); assertFalse(aqlParser.hasErrors()); } @timur27 could you please completely remove this `errorMap` variable as requested before thanks :)

Target:
public void testValidSingleQuotedQuerySpecificChars() { String query = "repository: 'releases#1'"; AqlQueryParser aqlParser = new AqlQueryParser(query); aqlParser.parseQuery(); logger.info(String.format("Query [%s] parse tree:\n[%s]", query, aqlParser)); assertFalse(aqlParser.hasErrors()); }
Source:
public final void run() { try (CloseableRestResponse response = artifactResolver.get(url)) { // Left empty because the original method had no other logic than the now-removed // closure of a CloseableRestResponse } catch (Exception e) { START LOGGER.error(e.getMessage(), e); END } } Cosmetic: Our loggers across the codebase are lowercase. Could you please change this? Thanks! :)

Target:
public final void run() { try (CloseableRestResponse response = artifactResolver.get(url)) { // Left empty because the original method had no other logic than the now-removed // closure of a CloseableRestResponse } catch (Exception e) { logger.error(e.getMessage(), e); } }
Source:
public T read() { Resource resource; resource = getResource(); if (!resource.exists()) { return null; } try (InputStream inputStream = new BufferedInputStream(resource.getInputStream())) { JavaType type = yamlMapper.getTypeFactory().constructType(myClazz); START return yamlMapper.readValue(inputStream, type); END } catch (IOException e) { throw new UndeclaredThrowableException(e); } } we probably can use `myClazz` directly here, without `JavaType` conversion.

Target:
public synchronized T read() { Resource resource = getResource(); if (!resource.exists()) { return null; } try (InputStream inputStream = new BufferedInputStream(resource.getInputStream())) { return yamlMapper.readValue(inputStream, myClazz); } catch (IOException e) { throw new UndeclaredThrowableException(e); } }