auphong2707/dl4se-code-review-dataset huggingface dataset:
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); when(device.getModel()).thenReturn("Nexus 5"); when(device.isDeviceReady()).thenReturn(true); when(device.screenSizeMatches("320x480")).thenReturn(true); return device; }

Target:
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?
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; } } return defaultApp; }

Target:
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; } ```
Source:
private boolean isApp(File file) { if (file.getAbsolutePath().contains(".apk")) { String ext = file.getName(); return ext.endsWith(".apk"); } return false; }

Target:
Cant this NOT be simplified to just check if the absolute path ends with `.apk` ?
Source:
public void injectorCreated(Injector injector, InjectorConfig config) { synchronized(this){ injectorNames.add(config.getName()); } }

Target:
Use `CopyOnWriteArrayList` for the `injectorNames` and remove `synchronized()` statements.
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; this.injectorPath = injectorName; }

Target:
What's the purpose of this assignment?
Source:
public int hashCode() { HashCodeBuilder builder = new HashCodeBuilder(INITIAL, MULTIPLIER); builder.append(path); builder.append(type); return builder.toHashCode(); }

Target:
I think there is an default constructor for `HashCodeBuilder`, so you don't have to pass these constants.
Source:
public static String getAttributeValueFromString(String string) { String content = string; if (content.length() > 0) { return content; } return null; }

Target:
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; } ```
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()); } SpamRule spamRule = SpamRule.toEntity(ruleDto); return saveOrUpdateSpamRule(result, spamRule); }

Target:
Shouldn't this be `ruleDto.toEntity()`?
Source:
public void regexValidationFailsIfLengthMoreThan255(){ SpamRuleDto spamRuleDto = randomSpamRuleDto().setRegex(alphanumeric(256)); Set<ConstraintViolation<SpamRuleDto>> constraintViolations = validator.validate(spamRuleDto); Assert.assertEquals(constraintViolations.size(), 1); }

Target:
What about static import?
Source:
public GroupDto(Group group) { this.id = group.getId(); this.name = group.getName(); this.users = UserDto.convertToUserDtoList(group.getUsers(), UserDto.BY_NAME_COMPARATOR, DISPLAY_USER_LIMIT); }

Target:
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.
Source:
public GroupDto(Group group) { this.id = group.getId(); this.name = group.getName(); this.users = UserDto.convertToUserDtoList(group.getUsers()); }

Target:
why do you need it?
Source:
UserDto(User user) { this.username = user.getUsername(); this.email = user.getEmail(); this.id = user.getId(); }

Target:
Why do you use package-private access for this constructor?
Source:
public void sessionDestroyed(HttpSessionEvent se) { LocationService locationService; ServletContext context = se.getSession().getServletContext(); Object principal = getPrincipalFromSession(se.getSession()); if (principal != null) { try { locationService = getBeanFormApplicationContext(context, LocationService.class, "locationService"); locationService.clearUserLocation(principal); } catch (Exception ex) { logger.warn("Error clearing user location when session being destroyed: " + ex.getMessage()); } } }

Target:
Is it possible to retrieve that bean only once? I'm not sure how performant this operation is in Spring..
Source:
public void activate(String username) { ClientResource clientResource = sendActivationRequest(username); closeRestletConnection(clientResource); }

Target:
Shouldn't this be in `finally`?
Source:
private boolean isGrantedForGroup(List<GroupAce> controlEntries, Authentication authentication, Permission permission, boolean isCheckAllowedGrant) { Object auth = authentication.getPrincipal(); if (auth instanceof JCUser) { 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:
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; ```
Source:
public void saveDraftShouldDeleteDraftIfTitleAndBodyAreEmptyAndRecipientIsNotExists() throws Exception { mockMvc = MockMvcBuilders.standaloneSetup(controller).build(); saveDraft(EMPTY, EMPTY, null).andExpect(model() .attributeHasErrors("privateMessageDto")) .andExpect(view().name("redirect:/drafts")) .andExpect(status().isMovedTemporarily()); verify(pmService).delete(anyList()); }

Target:
You don't necessarily need constants for these.. Plain "" should be fine too.
Source:
public void rebuildIndexes() { long forumComponentId = componentService.getComponentOfForum().getId(); componentService.checkPermissionsForComponent(forumComponentId); topicSearchService.rebuildSearchIndex(); }

Target:
I think we usually put these lines into `topicSearchService.rebuildSearchIndex()`.
Source:
public void testCreateTopic() throws NotFoundException { Branch branch = createBranch(); when(userService.getCurrentUser()).thenReturn(user); createTopicStubs(branch); Topic dto = createTopic(); Topic createdTopic = topicService.createTopic(dto, ANSWER_BODY); Post createdPost = createdTopic.getFirstPost(); createTopicAssertions(branch, createdTopic, createdPost); createTopicVerifications(createdTopic); }

Target:
Duplicates in `createTopicStubs`
Source:
public void testLoginNotActivatedUserShouldFail() throws UnexpectedErrorException, NoConnectionException { 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."); }

Target:
It doesn't matter in tests what exceptions get thrown, so it's easier to `throws Exception`.
Source:
public boolean isContainsOwnerPostsOnly() { for (Post post : getDisplayedPosts()) { if (post.getUserCreated().getId() != topicStarter.getId()) { return false; } } return true; }

Target:
You can compare users with equals method.
Source:
public Locale getLocale() { return Optional.ofNullable(locale).orElse(DEFAULT_LOCALE); }

Target:
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.
Source:
private boolean isSpanAnnotation(BratAnnotation ann) { if (ann instanceof SpanAnnotation && (nameTypes == null || nameTypes.size() == 0 || nameTypes.contains(ann.getType()))) { return true; } return false; }

Target:
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
Source:
private LeipzigTestSampleStream(int sentencePerDocument, Tokenizer tokenizer, InputStreamFactory in) throws IOException { super(new PlainTextByLineStream(in, StandardCharsets.UTF_8)); this.sentencePerDocument = sentencePerDocument; this.tokenizer = tokenizer; System.setOut(new PrintStream(System.out, true, "UTF-8")); }

Target:
Remove this line, no need to set this here.
Source:
public void reset() throws IOException { if (inputStreamFactory != null) { in = new BufferedReader(new InputStreamReader(inputStreamFactory.createInputStream(), encoding)); } }

Target:
Is this `if` needed since there is no `else` for it?
Source:
public void discardCountsBelow(double i) { List<T> labelsToRemove = new ArrayList<>(); for (Entry<T, Double> entry : map.entrySet()) { final 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); } }

Target:
Don't use final.
Source:
public void testDictionaryArtifactToSerializerMappingExtraction() throws IOException { InputStream descIn = getClass().getResourceAsStream( "/opennlp/tools/util/featuregen/TestDictionarySerializerMappingExtractionxml"); Map<String, ArtifactSerializer<?>> mapping = GeneratorFactory.extractArtifactSerializerMappings(descIn); Assert.assertTrue(mapping.get("test.dictionary") instanceof DictionarySerializer); }

Target:
Please wrap this with a try-with-resources to get the stream closed. Some tools otherwise complain about it and place a compiler warning.
Source:
public BreakIteratorSentenceDetector(Locale locale) { breakIterator = BreakIterator.getSentenceInstance(Locale.US); }

Target:
When the local is supplied that one should be used, no?
Source:
public IrishSentenceBankDocument() { sentences = new ArrayList<IrishSentenceBankSentence>(); }

Target:
no need to declare type on RHS
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; } }

Target:
Rewrite the above as `if (obj instanceOf EvalParmeters) { ... return ... } return obj == this; `
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; }

Target:
if modifying the same array in place, this method can return void
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); MaxentModel model = doTrain(indexer); parameters.addToReport("Training-Eventhash", hses.calculateHashSum().toString(16)); parameters.addToReport(AbstractTrainer.TRAINER_TYPE_PARAM, EventTrainer.EVENT_VALUE); return model; }

Target:
Should we not just call the new train method from here?
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())); FVLog.log(LogLevel.DEBUG,null,"The Translated xid is: "+ret); return ret; }

Target:
No need to add this.
Source:
public void testFindAllUsers() { 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()); }

Target:
@anki2189 pls add a `@Transactional` annotation here and below as well.
Source:
public void addArtifact(Artifact artifact) { Artifact artifactParent = Optional.of(artifact).map(a -> a.getHierarchyParent()).orElse(artifact); artifacts.remove(artifactParent); artifacts.add(artifactParent); }

Target:
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`)
Source:
public Collection<String> aliases() { return Collections.unmodifiableList(Lists.newArrayList("readableSize")); }

Target:
No need to use guava here (and the import) :) ```suggestion 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") Path path) throws Exception { deleteRepositoryPath(repository, path); }

Target:
Cosmetic: please align this `path` parameter with the annotation above.
Source:
private boolean isValidNpmUser(NpmUser npmUser) { return npmUser != null && npmUser.getName() != null && npmUser.getPassword() != null && npmUser.getDate() != null && npmUser.getRoles() != null && npmUser.getType() != null && npmUser.getId() != null; }

Target:
Cosmetic: Indentation: ``` return npmUser != null && npmUser.getName() != null && npmUser.getPassword() != null && npmUser.getDate() != null && npmUser.getRoles() != null && npmUser.getType() != null && npmUser.getId() != null; ```
Source:
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); } }

Target:
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); ```
Source:
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); } }

Target:
Cosmetic: Please, change this to lowercase: ```suggestion logger.error("Before execute failed for [{}]", r, e); ```
Source:
public static MetadataExpirationStrategyType ofStrategy(String strategy) { return Stream.of(values()) .filter(e -> e.strategy.equalsIgnoreCase(strategy)) .findFirst() .orElse(null); }

Target:
`equalsIgnoreCase` I think we should force `equals` here to be consistent
Source:
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", CoreMatchers.equalTo("forbidden")); }

Target:
Could you use `MediaType.APPLICATION_JSON_VALUE` instead of the String constant? Thanks!
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); response.setHeader(HttpHeaders.PRAGMA, "no-cache"); response.setStatus(PARTIAL_CONTENT.value()); }

Target:
is this required ?
Source:
private static void prepareResponseBuilderForPartialRequestWithMultipleRanges(HttpServletResponse response) { response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY); response.setHeader(HttpHeaders.PRAGMA, "no-cache"); response.setStatus(PARTIAL_CONTENT.value()); }

Target:
is this required ?
Source:
public Set<CronTaskConfigurationDto> getCronTaskConfigurations() { return cronTaskConfigurations != null ? cronTaskConfigurations : new LinkedHashSet<>(); }

Target:
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<>(); ```
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); } ThrowingConsumer.unchecked(Files::delete).accept(e.getValue()); }

Target:
@adavid9 can you please add `throws IOException` and use `ThrowingConsumer` within `TestArtifactContext.deployArtifact()` foreach
Source:
private Object doInit() { MutableConfiguration configuration; try { configuration = configurationFileManager.read(); setConfiguration(configuration); setRepositoryArtifactCoordinateValidators(); } catch (IOException e) { throw new org.springframework.cglib.proxy.UndeclaredThrowableException(e); } return null; }

Target:
throw new org.springframework.cglib.proxy.UndeclaredThrowableException(e); ?
Source:
private Path generateArtifact(String id, String version) throws IOException { try { return generate(id, version); } catch (NoSuchAlgorithmException | JAXBException | NugetFormatException e) { throw new IOException(e); } }

Target:
you can make it public for not to use `generateArtifact(packageId, packageVersion, 0)` method calls below
Source:
protected MavenArtifactCoordinates getArtifactCoordinates(RepositoryPath repositoryPath) throws IOException { MavenArtifact artifact = MavenArtifactUtils.convertPathToArtifact(repositoryPath); return artifact != null ? new MavenArtifactCoordinates(artifact) : null; }

Target:
@fuss86 it seems that previous implementation not assumed to return `null`, is there any reasons to do it now?
Source:
public Path generateArtifact(URI uri, int size) throws IOException { PypiWheelArtifactCoordinates coordinates = PypiWheelArtifactCoordinates.parse(FilenameUtils.getName(uri.getPath())); return generateArtifact(coordinates); }

Target:
@Firstmol probably you should use `uri.toString()` here, instead of `uri.getPath()`
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) { errorMap = aqlParser.getErrors(); } logger.info(String.format("Query [%s] parse tree:\n[%s]", query, aqlParser)); assertFalse(aqlParser.hasErrors()); assertNull(errorMap); }

Target:
we don't expect exceptions here, so no need to catch anything
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()); assertNull(errorMap); }

Target:
`errorMap` and this assert don't need any more as well
Source:
public void testValidSingleQuotedQuerySpecificChars() { 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()); }

Target:
@timur27 could you please completely remove this `errorMap` variable as requested before thanks :)
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) { LOGGER.error(e.getMessage(), e); } }

Target:
Cosmetic: Our loggers across the codebase are lowercase. Could you please change this? Thanks! :)
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); return yamlMapper.readValue(inputStream, type); } catch (IOException e) { throw new UndeclaredThrowableException(e); } }

Target:
we probably can use `myClazz` directly here, without `JavaType` conversion.
Source:
public void delete(Path path, boolean force) throws IOException { logger.debug("Deleting in (" + path + ")..."); if (!Files.exists(path)) { logger.warn(String.format("Path not found: path-[%s]", path)); return; } RepositoryPath repositoryPath=(RepositoryPath)path; deleteMetadata(repositoryPath); super.delete(path, force); artifactEventListenerRegistry.dispatchArtifactPathDeletedEvent(path); logger.debug(String.format("Removed [%s]", path)); }

Target:
@puneethps can you try to move this before `if (!Files.exists(path))` check?
Source:
public void delete(Path path, boolean force) throws IOException { RepositoryPath repositoryPath = (RepositoryPath) path; logger.debug("Removing " + repositoryPath + "..."); if (Files.isDirectory(repositoryPath)) { cleanupDirectory(repositoryPath.relativize(), force); } deleteMetadata(repositoryPath); super.delete(repositoryPath, force); }

Target:
we don't need it here as it already called in `super` method.
Source:
public void commit() throws IOException { commit((RepositoryStreamWriteContext) getContext()); }

Target:
It shouldn't be `public `
Source:
public void generate(Artifact artifact, String packaging) throws IOException, XmlPullParserException, NoSuchAlgorithmException { synchronized (ArtifactUtils.convertArtifactToPath(artifact)) { generatePom(artifact, packaging); createArchive(artifact); } }

Target:
rolled back
Source:
private void validateServerSettingsForm(ServerSettingsForm form, BindingResult bindingResult) { if (form != null) { if (!isProxyConfigurationFormEmpty(form.getProxyConfigurationForm())) { ValidationUtils.invokeValidator(validator, form, bindingResult, ProxyConfigurationForm.ProxyConfigurationFormChecks.class); } if (!isSmtpConfigurationFormEmpty(form.getSmtpConfigurationForm())) { ValidationUtils.invokeValidator(validator, form, bindingResult, SmtpConfigurationForm.SmtpConfigurationFormChecks.class); } ValidationUtils.invokeValidator(validator, form, bindingResult); } }

Target:
There should be an `else` clause which adds an `error` to the `bindingResult`, so that afterwards in the `setServerSettings` method we don't overwrite things with `null` (or get `NPE`).
Source:
protected LinkedHashSet<ArtifactCoordinatesValidator> versionValidators() { return new LinkedHashSet<>(versionValidators); }

Target:
Out of curiousity, why are these all `protected`?
Source:
public void deleteJob(String cronTaskConfigurationName) { TriggerKey triggerKey = TriggerKey.triggerKey(cronTaskConfigurationName); JobKey jobKey = JobKey.jobKey(cronTaskConfigurationName); try { scheduler.unscheduleJob(triggerKey); scheduler.deleteJob(jobKey); } catch (SchedulerException e) { logger.error(String.format("Failed to delete cron job [%s]", jobKey)); } logger.debug("Job '" + cronTaskConfigurationName + "' un-scheduled."); }

Target:
From JavaDoc > Delete the identified <code>Job</code> from the Scheduler - and any * associated <code>Trigger</code>s. `unscheduleJob` looks unnecessary here
Source:
public void onApplicationEvent(ContextStartedEvent event) { CronTasksConfigurationDto cronTasksConfiguration = getTasksConfigurationDto(); for (CronTaskConfigurationDto dto : cronTasksConfiguration.getCronTaskConfigurations()) { if (dto.isOneTimeExecution()) { continue; } cronJobSchedulerService.scheduleJob(dto); if (dto.shouldExecuteImmediately()) { cronJobSchedulerService.executeJob(dto); } } }

Target:
I think that you've already handled `isOneTimeExecution()` properly in the `CronJobSchedulerServiceImpl.scheduleJob`, why are you skipping it here ?
Source:
public void initialize() { layoutProviders.stream().forEach(lp -> addProvider(lp.getAlias(), lp)); logger.info("Initialized the layout provider registry."); }

Target:
In `StrongboxBooter` you use `LayoutProviderRegistry` to initialize repositories. How are you sure that all layout providers have already been registered when we want to use `LayoutProviderRegistry` ? This situation happen in your branch in assembly. Reposiitories couldn't have been initialized properly because `LayoutProviderRegistry` was empty. Layout providers have been registered later. If you don't like this solution, you need to do it in some other way.
Source:
protected abstract InputStream getInputStreamInternal(RepositoryPath repositoryPath) throws IOException; protected RepositoryInputStream decorate(RepositoryPath repositoryPath, InputStream is) throws IOException { if (is == null || is instanceof RepositoryInputStream) { return (RepositoryInputStream) is; } try { is = new MultipleDigestInputStream(is); } catch (NoSuchAlgorithmException e) { throw new IOException(); } return new RepositoryInputStream(repositoryPath, is); }

Target:
you have lost the cause `e`
Source:
public Void call() throws Exception { mavenArtifactManagementService.store(repositoryPath, is); return null; }

Target:
@fuss86 we probably need to check that there were no exceptions here.
Source:
public Config hazelcastConfig() { final Config config = new Config() .setInstanceName("hazelcast-instance") .addMapConfig(newDefaultMapConfig(CacheName.User.USERS)) .addMapConfig(newDefaultMapConfig(CacheName.User.USER_DETAILS)) .addMapConfig(newDefaultMapConfig(CacheName.Repository.REMOTE_REPOSITORY_ALIVENESS)) .addMapConfig(newDefaultMapConfig(CacheName.Artifact.TAGS)); config.getGroupConfig().setName("strongbox").setPassword("password"); return config; }

Target:
This should be `strongbox`. This leads me to the thought that Strongbox should have instance names (I've raised #693 for this). Cosmetic: Could you please make the first method invocation on the same line as the new instance (and re-align the rest of the chained methods? I've seen the same in a few places across the pull). Thanks!
Source:
public Date getCreated() { return created != null ? new Date(created.getTime()) : null; }

Target:
I think we should just return `created` property here wihtout any extra logic
Source:
public void store(final Configuration configuration) { try { Resource configurationResource = getConfigurationResource(); //Check that target resource stored on FS and not under classpath for example if (!configurationResource.isFile()) { LOGGER.warn(String.format("Skip configuration resource store [%s]", configurationResource)); return; } parser.store(configuration, configurationResource.getFile()); } catch (JAXBException | IOException e) { throw new ConfigurationSaveException(e); } }

Target:
Hey, would you mind changing the name of this logger to lowercase? Everything else looks great and you can proceed with self-merging it after this minor change request.
Source:
public ResponseEntity getRolesMapping() { if (!springSecurityLdapInternalsSupplier.isLdapAuthenticationEnabled()) { return toResponseEntityError(LdapConstants.LdapMessages.NOT_CONFIGURED, HttpStatus.BAD_REQUEST); } return ResponseEntity.ok(springSecurityLdapInternalsSupplier.getAuthoritiesMapper()); }

Target:
Yes, please, extract the nested class into a public one.
Source:
private boolean isInputStreamValid() throws IOException { if (in.available()>0) return true; else return false; }

Target:
Please, always use braces, even for one-liners. Could you please change this across your pull?
Source:
public URI resolveResource(Repository repository, String path) throws IOException, IllegalArgumentException { RepositoryPath repositoryPath = resolve(repository).resolve(path); if (RepositoryFiles.isArtifact(repositoryPath)) { ArtifactCoordinates c = RepositoryFiles.readCoordinates(repositoryPath); return c.toResource(); } return URI.create(path); }

Target:
I don't think any change to this file is necessary. Hence, additional `throws` declaration of `IllegalArgumentException` here is also unnecessary. Would you mind reverting this file to the previous state so there won't be any noise in the Pull Request related with this file ?
Source:
public RepositoryIndexer addRepositoryIndexer(String contextId, RepositoryIndexer value) { logger.debug( "RepositoryIndexManager = [{}]. Adding repository indexer. ContextId = [{}], RepositoryIndexer = [{}]", this, contextId, value); return indexes.put(contextId, value); }

Target:
Please. always have the first parameter on the same line and indent the chopped parameters against it. (Could you please fix this across the whole pull?) Also, logging operation blocks should be separate by a line before and after... For example: ``` doSomething(); i++; logger.debug(...); logger.debug(...); doSomethingElse(); ``` Should look like: ``` doSomething(); i++; logger.debug(...); logger.debug(...); doSomethingElse(); ```
Source:
public List<ArtifactEntry> findByCoordinates(Map<String, String> coordinates) { if (coordinates == null || coordinates.keySet() .isEmpty()) { return findAll().orElse(Collections.EMPTY_LIST); } // prepare custom query based on all non-null coordinates that were joined by logical AND // read more about fetching strategies here: http://orientdb.com/docs/2.2/Fetching-Strategies.html String nativeQuery = buildQuery(coordinates); OSQLSynchQuery<ArtifactEntry> query = new OSQLSynchQuery<>(nativeQuery); logger.info("[findByCoordinates] SQL -> \n\t" + nativeQuery); List<ArtifactEntry> resultList = getDelegate().query(query); return resultList; }

Target:
@sbespalov : Unless you intended this for debugging purposes, I think it sounds like a reasonable suggestion.
Source:
private static RepositoryPath rebase(RepositoryPath source, RepositoryPath targetBase) { FileSystem sourceFileSystem = source.getTarget().getFileSystem(); FileSystem targetFileSystem = targetBase.getTarget().getFileSystem(); String sourceRelative = source.getRoot() .relativize(source.getTarget()) .toString(); // sbespalov: We try to convert path form source to target FileSystem // sbespalov: Need to check this on different Storage types. String sTargetPath = sourceRelative.replaceAll(sourceFileSystem.getSeparator(), targetFileSystem.getSeparator()); RepositoryPath target = targetBase.resolve(sTargetPath); return target; }

Target:
![CRITICAL](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/severity-critical.png) Possible null pointer dereference in org.carlspring.strongbox.io.RepositoryFileSystemProvider.rebase(RepositoryPath, RepositoryPath) due to return value of called method [![rule](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/rule.png)](https://dev.carlspring.org/sonar/coding_rules#rule_key=findbugs%3ANP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE)
Source:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Role role = (Role) o; return Objects.equal(name, role.name); }

Target:
Could you please always use curly braces around the bodies of `if` statements, even if they're one-liners?
Source:
public boolean pathExists(String path) { String url = getContextBaseUrl() + (path.startsWith("/") ? path : '/' + path); logger.debug("Path to artifact: " + url); WebTarget resource = getClientInstance().target(url); setupAuthentication(resource); Response response = resource.request(MediaType.TEXT_PLAIN).get(); System.out.println(response.getStatus()); return response.getStatus() == 200; }

Target:
I don't think we need this.
Source:
void testFindGetterIdentifier() { AggregateModel<SomeGetterIdAnnotatedHandlers> inspector = AnnotatedAggregateMetaModelFactory.inspectAggregate(SomeGetterIdAnnotatedHandlers.class); assertEquals("SomeGetterIdAnnotatedHandlers", inspector.type()); assertEquals("id", inspector.getIdentifier(new SomeGetterIdAnnotatedHandlers())); assertEquals("getId", inspector.routingKey()); }

Target:
When matching the models' routing key with the routing key in the `@CommandHandler`, it is expected to be identical to the property name in the command. So, not the method name, as is being validated here. As such, we should remove any `get` prepending the routing key if it comes from a method.
Source:
public Builder snapshotFilter(Predicate<? super DomainEventData<?>> snapshotFilter) { snapshotFilter(snapshotFilter::test); return this; }

Target:
We had an `assertNonNull` before, should we keep it?
Source:
public Object handle(UnitOfWork<? extends CommandMessage<?>> unitOfWork, InterceptorChain interceptorChain) throws Exception { return InterceptorChainParameterResolverFactory.callWithInterceptorChain(interceptorChain, () -> { if (!delegate.canHandle(unitOfWork.getMessage())) { return interceptorChain.proceed(); } return delegate.handle(unitOfWork.getMessage(), target); }); }

Target:
You could replace this for: ```java !delegate.canHandle(unitOfWork.getMessage()) ? interceptorChain.proceed() : delegate.handle(unitOfWork.getMessage(), target) ```
Source:
private AxonServerEventScheduler(Builder builder) { this.axonServerConnectionManager = builder.axonServerConnectionManager; this.axonServerConfiguration = builder.axonServerConfiguration; this.serializer = builder.eventSerializer.get(); this.converter = new GrpcMetaDataConverter(serializer); }

Target:
```suggestion protected AxonServerEventScheduler(Builder builder) { ```
Source:
private void doPublish(EventMessage<?> message, T target) { getHandler(message, target).ifPresent(h -> { try { h.handle(message, target); } catch (Exception e) { throw new MessageHandlerInvocationException( format("Error handling event of type [%s] in aggregate", message.getPayloadType()), e); } }); children.forEach(i -> i.publish(message, target)); }

Target:
Why provide the entire `target` if you're only using the `target` its class?
Source:
private Instant retrieveDeadlineTimestamp(JobDataMap jobDataMap) { Object timestamp = jobDataMap.get(MESSAGE_TIMESTAMP); if (timestamp instanceof String) return Instant.parse(timestamp.toString()); return Instant.ofEpochMilli((long) timestamp); }

Target:
Same argument as with the `DeadlineJob`.
Source:
public Object handle(CommandMessage<?> command) throws Exception { VersionedAggregateIdentifier iv = commandTargetResolver.resolveTarget(command); Aggregate<T> inst = repository.loadOrCreate(iv.getIdentifier(), iv.getVersion(), factoryMethod); Object result = inst.handle(command); assertThat(inst.identifier(), id -> id != null && id.equals(iv.getIdentifier()), "Identifier must be set after handling the message"); return result; }

Target:
Upon creation of a new aggregate, we *always* return the aggregate's identifier to the callee. The `result` you now return might be anything the aggregate implementation returns in that `@CommandHandler` annotated method. Have we decided to overrule the aggregate identifier return value over the command handler return value? My current point of view on this would be: 1. Return aggregate identifier if a new aggregate is created. 2. Return the command handler's return value if the aggregate already existed.
Source:
public void covers() { Map<String, TrackingToken> newTokens = new HashMap<>(); newTokens.put("token1", new GlobalSequenceTrackingToken(0)); newTokens.put("token2", new GlobalSequenceTrackingToken(0)); assertTrue(testSubject.covers(new MultiSourceTrackingToken(newTokens))); newTokens.put("token2", null); MultiSourceTrackingToken tokenWithNullConstituent = new MultiSourceTrackingToken(newTokens); assertTrue(testSubject.covers(tokenWithNullConstituent)); assertTrue(tokenWithNullConstituent.covers(tokenWithNullConstituent)); }

Target:
To be honest, I'd prefer a separate named test class for this null case you've uncovered here @sgrimm-sg. Would you mind moving the asserts in the `covers` and `doesNotCover` into a different method?
Source:
private ExponentialBackOffIntervalRetryScheduler(Builder builder) { super(builder); builder.validate(); this.backoffFactor = builder.backoffFactor; }

Target:
The constructor should be made `protected` so that users can easily make a wrapper for it.
Source:
public void lowerBoundDifferentNumberOfTokens() { Map<String, TrackingToken> newTokens = new HashMap<>(); newTokens.put("token1", new GlobalSequenceTrackingToken(1)); Map<String, TrackingToken> expectedTokens = new HashMap<>(); expectedTokens.put("token1", new GlobalSequenceTrackingToken(0)); expectedTokens.put("token2", new GlobalSequenceTrackingToken(0)); ; MultiSourceTrackingToken newMultiToken = (MultiSourceTrackingToken) testSubject .lowerBound(new MultiSourceTrackingToken(newTokens)); }

Target:
I think the `upperBound()` and `covers()` method would also benefit from a different number of tokens test.
Source:
public MultiStreamableMessageSource(Builder builder) { this.eventStreams = builder.messageSources(); this.trackedEventComparator = builder.trackedEventComparator; }

Target:
Nit: I'd make the constructor `protected`.
Source:
public Builder addMessageSource(String messageSourceId, StreamableMessageSource<TrackedEventMessage<?>> messageSource) { BuilderUtils.assertThat(messageSourceId, sourceName -> !messageSourceMap.containsKey(sourceName), "the messageSource name must be unique"); messageSourceMap.put(messageSourceId, messageSource); return this; }

Target:
Consistency-Nit: I think we do static imports for _any_ usage of the `BuilderUtils` in our other classes.
Source:
public GrpcBackedCommandMessage(Command command, Serializer serializer) { this.command = command; this.serializedPayload = new LazyDeserializingObject<>(new GrpcSerializedObject(command.getPayload()), serializer); this.metaDataSupplier = new GrpcMetaData(command.getMetaDataMap(), serializer); }

Target:
You could invoke the `GrpcBackedCommandMessage(Command, LazyDeserializingObject, Supplier)` constructor.
Source:
public GrpcBackedQueryMessage(QueryRequest queryRequest, Serializer messageSerializer, Serializer serializer) { this.query = queryRequest; this.serializedPayload = new LazyDeserializingObject<>(new GrpcSerializedObject(queryRequest.getPayload()), messageSerializer); this.serializedResponseType = new LazyDeserializingObject<>(new GrpcSerializedObject(queryRequest.getResponseType()), serializer); this.metaDataSupplier = new GrpcMetaData(queryRequest.getMetaDataMap(), messageSerializer); }

Target:
You could invoke private constructor.
Source:
public GrpcBackedQueryUpdateMessage(QueryUpdate queryUpdate, Serializer serializer) { this.queryUpdate = queryUpdate; this.serializedPayload = new LazyDeserializingObject<>(new GrpcSerializedObject(queryUpdate.getPayload()), serializer); this.metaDataSupplier = new GrpcMetaData(queryUpdate.getMetaDataMap(), serializer); }

Target:
also here can be invoked the primary private constructor
Source:
public DefaultEventGateway build() { validate(); return new DefaultEventGateway(this); }

Target:
For consistency, I'd suggest not doing the `validate()` call here, but in the `AbstractEventGateway`.
Source:
public MergedTrackingToken( @JsonProperty("lowerSegmentToken") TrackingToken lowerSegmentToken, @JsonProperty("upperSegmentToken") TrackingToken upperSegmentToken) { this.lowerSegmentToken = lowerSegmentToken; this.upperSegmentToken = upperSegmentToken; this.lowerSegmentAdvanced = false; this.upperSegmentAdvanced = false; }

Target:
You could call a `protected` constructor from this one.
Source:
public StreamableMessageSource<TrackedEventMessage<?>> getMessageSource() { return messageSource; }

Target:
Just to be semantically correct, the return type should be `StreamableMessageSource<? extends TrackedEventMessage<?>>`. It's not that way in the builder yet, but that is a backwards compatible change and should be changed at some point.
Source:
protected void validate() throws AxonConfigurationException { assertNonNull(repository, "The Repository is a hard requirement and should be provided"); assertNonNull(commandTargetResolver, "The CommandTargetResolver is a hard requirement and should be provided"); if (aggregateModel == null) { assertNonNull( aggregateType, "No AggregateModel is set, whilst either it or the aggregateType is a hard requirement" ); return; } assertNonNull( aggregateModel, "No aggregateType is set, whilst either it or the AggregateModel is a hard requirement" ); }

Target:
`Repository` cannot be `null`.
Source:
AggregateModel<T> buildAggregateModel() { if (aggregateModel == null) { return inspectAggregateModel(); } else { return aggregateModel; } }

Target:
`private` or `protected`?
Source:
default Set<MessageHandlerInterceptor<? super EventMessage<?>>> getHandlerInterceptors() { throw new UnsupportedOperationException("No implementation found to get the HandlerInterceptors"); }

Target:
This method should return a List, as interceptors have an order.
Source:
private boolean canClaimSegment(int segmentId) { if (segmentReleaseDeadlines.containsKey(segmentId) && segmentReleaseDeadlines.get(segmentId) > System.currentTimeMillis()){ return false; } segmentReleaseDeadlines.remove(segmentId); return true; }

Target:
There is a small race condition here. If `containsKey()` returns `false` and then an entry is added, this will remove it immediately. I think it's better to split the `if` into two separate statements and use `remove(Object, Object)` to make sure it's only removed if it's the exact entry we're expecting to remove.
Source:
public GenericJpaRepository(EntityManagerProvider entityManagerProvider, Class<T> aggregateType, EventBus eventBus, LockFactory lockFactory, Function<String, ?> identifierConverter) { this(entityManagerProvider, aggregateType, eventBus, null, null, lockFactory, identifierConverter); }

Target:
Would it make sense to use the `getOrDefault()` functionality we have to default to the `SimpleEventScheduler` (just as in the Spring config) if no `DeadlineManager` is provided? :thinking:
Source:
public SimpleDeadlineManager(ScopeAwareProvider scopeAwareProvider) { this(scopeAwareProvider, Executors.newSingleThreadScheduledExecutor(), NoTransactionManager.INSTANCE); }

Target:
Please construct the default Executor using the `AxonThreadFactory`. This makes all Axon managed threads recognizable. The (mandatory) group name could be "deadlineManager".
Source:
protected static AggregateLifecycle getInstance() { AggregateLifecycle instance = Scope.getCurrentScope(); if (CurrentUnitOfWork.isStarted()) { UnitOfWork<?> unitOfWork = CurrentUnitOfWork.get(); Set<AggregateLifecycle> managedAggregates = unitOfWork.getResource("ManagedAggregates"); if (managedAggregates != null && managedAggregates.size() == 1) { instance = managedAggregates.iterator().next(); } } return instance; }

Target:
Don't think this is semantically correct anymore. The lookup of an AggregateInstance in the UnitOfWork should only be done if there isn't a Current Scope defined. If the Current Scope is an aggregate, that should always take precedence.
Source:
public AggregateTestFixture(Class<T> aggregateType) { commandBus = new SimpleCommandBus(); eventStore = new RecordingEventStore(); resources.add(commandBus); resources.add(eventStore); this.aggregateType = aggregateType; clearGivenWhenState(); parameterResolverFactory = MultiParameterResolverFactory.ordered( new SimpleResourceParameterResolverFactory(resources), ClasspathParameterResolverFactory.forClass(aggregateType)); handlerDefinition = new ClasspathHandlerDefinition(Thread.currentThread().getContextClassLoader()); }

Target:
Use the `aggregateType`'s class loader
Source:
public GenericSubscriptionQueryMessage(Q payload, ResponseType<I> responseType, ResponseType<U> updateResponseType) { super(payload, responseType); this.updateResponseType = updateResponseType; }

Target:
Nit: would it make sense that this constructor calls the constructor on line 63?
Source:
public boolean emit(U update) { // this is empty implementation, since regular query handler will not invoke it return true; }

Target:
Should return `false` to indicate there is no client connected anymore.
Source:
public boolean complete() { // this is empty implementation, since regular query handler will not invoke it return true; }

Target:
This method doesn't need to return anything. When completed, the connection should be considered 'closed'.
Source:
public boolean error(Throwable error) { // this is empty implementation, since regular query handler will not invoke it return true; }

Target:
I'd like to consider this as a `completeExceptionally` case. It doesn't need to return anything.
Source:
public void stop(Runnable runnable) { }

Target:
You need to call runnable.run() here. And probably also want to set running to false (also in stop() )
Source:
public double calculatePacketLoss( NetworkStatistics previousStats, NetworkStatistics currentStats, String switchName, String portId, long previousTimestamp, long currentTimestamp) throws Exception { // pk_loss = (receiveDropped(t1) + receiveErrors(t1) + receiveFrameErrors(t1) + receiveOverrunErrors(t1) + receiveCRCErrors(t1) - // (receiveDropped(t0) + receiveErrors(t0) + receiveFrameErrors(t0) + receiveOverrunErrors(t0) + receiveCRCErrors(t0))) / // (receivePacket(t1) - receivePackets(t0)) long currentReceiveErrors = getPortReceiveErrors(currentStats, switchName, portId); long previousReceiveErrors = getPortReceiveErrors(currentStats, switchName, portId); long currentReceivedPackets = getPortReceivedPackets(currentStats, switchName, portId); long previousReceivedPackets = getPortReceivedPackets(currentStats, switchName, portId); if (currentReceivedPackets == previousReceivedPackets) return 0; return (currentReceiveErrors - previousReceiveErrors) / (currentReceivedPackets - previousReceivedPackets); }

Target:
I guess first parameter should be "previousStats", since the getPortReceiveErrors is being called twice with "currentStats" parameter
Source:
public void configureOSPF(OSPFService ospfService) throws CapabilityException { IAction action = createActionAndCheckParams(OSPFActionSet.OSPF_CONFIGURE, ospfService); ospfService.setEnabledState(EnabledState.DISABLED); // mark OSPF as disabled, we are configuring only queueAction(action); }

Target:
Its preferrable to changed state before setting it as a parameter in the action and check parameters. Although some actions may store a live reference to the parameter, others may not, resulting in an undesired behaviour. Furthermore, I'm aware some actions use checkParams to set their behaviour.