auphong2707/dl4se-code-review-dataset huggingface dataset:
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; START deleteMetadata(repositoryPath); END super.delete(path, force); artifactEventListenerRegistry.dispatchArtifactPathDeletedEvent(path); logger.debug(String.format("Removed [%s]", path)); } @puneethps can you try to move this before `if (!Files.exists(path))` check?

Target:
public void delete(Path path, boolean force) throws IOException { logger.debug("Deleting in (" + path + ")..."); RepositoryPath repositoryPath=(RepositoryPath)path; deleteMetadata(repositoryPath); if (!Files.exists(path)) { logger.warn(String.format("Path not found: path-[%s]", path)); return; } super.delete(path, force); artifactEventListenerRegistry.dispatchArtifactPathDeletedEvent(path); logger.debug(String.format("Removed [%s]", path)); }
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); } START deleteMetadata(repositoryPath); END super.delete(repositoryPath, force); } we don't need it here as it already called in `super` method.

Target:
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); } super.delete(repositoryPath, force); }
Source:
START public void commit() throws IOException END { commit((RepositoryStreamWriteContext) getContext()); } It shouldn't be `public `

Target:
protected void commit() throws IOException { commit((RepositoryStreamWriteContext) getContext()); }
Source:
public void generate(Artifact artifact, String packaging) throws IOException, XmlPullParserException, NoSuchAlgorithmException { START synchronized (ArtifactUtils.convertArtifactToPath(artifact)) END { generatePom(artifact, packaging); createArchive(artifact); } } rolled back

Target:
public void generate(Artifact artifact, String packaging) throws IOException, NoSuchAlgorithmException { generatePom(artifact, packaging); createArchive(artifact); }
Source:
private void validateServerSettingsForm(ServerSettingsForm form, BindingResult bindingResult) { START if (form != null) END { 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); } } 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`).

Target:
private void validateServerSettingsForm(ServerSettingsForm form, BindingResult bindingResult) { 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); }
Source:
START protected LinkedHashSet<ArtifactCoordinatesValidator> versionValidators() END { return new LinkedHashSet<>(versionValidators); } Out of curiousity, why are these all `protected`?

Target:
LinkedHashSet<ArtifactCoordinatesValidator> versionValidators() { return new LinkedHashSet<>(versionValidators); }
Source:
public void deleteJob(String cronTaskConfigurationName) { TriggerKey triggerKey = TriggerKey.triggerKey(cronTaskConfigurationName); JobKey jobKey = JobKey.jobKey(cronTaskConfigurationName); try { scheduler.unscheduleJob(triggerKey); scheduler.deleteJob(jobKey); } START catch (SchedulerException e) END { logger.error(String.format("Failed to delete cron job [%s]", jobKey)); } logger.debug("Job '" + cronTaskConfigurationName + "' un-scheduled."); } From JavaDoc > Delete the identified <code>Job</code> from the Scheduler - and any * associated <code>Trigger</code>s. `unscheduleJob` looks unnecessary here

Target:
public void deleteJob(String cronTaskConfigurationName) { JobKey jobKey = JobKey.jobKey(cronTaskConfigurationName); try { scheduler.deleteJob(jobKey); } catch (SchedulerException e) { logger.error(String.format("Failed to delete cron job [%s]", jobKey)); } logger.debug("Job '" + cronTaskConfigurationName + "' un-scheduled."); }
Source:
public void onApplicationEvent(ContextStartedEvent event) { CronTasksConfigurationDto cronTasksConfiguration = getTasksConfigurationDto(); for (CronTaskConfigurationDto dto : cronTasksConfiguration.getCronTaskConfigurations()) { if (dto.isOneTimeExecution()) { START continue; END } cronJobSchedulerService.scheduleJob(dto); if (dto.shouldExecuteImmediately()) { cronJobSchedulerService.executeJob(dto); } } } I think that you've already handled `isOneTimeExecution()` properly in the `CronJobSchedulerServiceImpl.scheduleJob`, why are you skipping it here ?

Target:
public void onApplicationEvent(ContextStartedEvent event) { CronTasksConfigurationDto cronTasksConfiguration = getTasksConfigurationDto(); for (CronTaskConfigurationDto dto : cronTasksConfiguration.getCronTaskConfigurations()) { if (dto.isOneTimeExecution()) { continue; } cronJobSchedulerService.scheduleJob(dto); } }
Source:
public void initialize() { START layoutProviders.stream().forEach(lp -> addProvider(lp.getAlias(), lp)); END logger.info("Initialized the layout provider registry."); } 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.

Target:
public void initialize() { logger.info("Initialized the layout provider registry."); }
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) { START throw new IOException(); END } return new RepositoryInputStream(repositoryPath, is); } you have lost the cause `e`

Target:
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; } return new RepositoryInputStream(repositoryPath, is); }
Source:
public Void call() throws Exception { START mavenArtifactManagementService.store(repositoryPath, is); END return null; } @fuss86 we probably need to check that there were no exceptions here.

Target:
public Exception call() throws Exception { try { mavenArtifactManagementService.store(repositoryPath, is); } catch (Exception ex) { return ex; } return null; }
Source:
public Config hazelcastConfig() { final Config config = new Config() START .setInstanceName("hazelcast-instance") END .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; } 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!

Target:
public Config hazelcastConfig() { final Config config = new Config().setInstanceName("strongbox") .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; }
Source:
public Date getCreated() { START return created != null ? new Date(created.getTime()) : null; END } I think we should just return `created` property here wihtout any extra logic

Target:
public Date getCreated() { return created; }
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()) { START LOGGER.warn(String.format("Skip configuration resource store [%s]", configurationResource)); END return; } parser.store(configuration, configurationResource.getFile()); } catch (JAXBException | IOException e) { throw new ConfigurationSaveException(e); } } 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.

Target:
public void store(final Configuration configuration) { try { parser.store(configuration, getConfigurationResource()); } catch (JAXBException | IOException e) { throw new ConfigurationSaveException(e); } }
Source:
public ResponseEntity getRolesMapping() { if (!springSecurityLdapInternalsSupplier.isLdapAuthenticationEnabled()) { START return toResponseEntityError(LdapConstants.LdapMessages.NOT_CONFIGURED, HttpStatus.BAD_REQUEST); END } return ResponseEntity.ok(springSecurityLdapInternalsSupplier.getAuthoritiesMapper()); } Yes, please, extract the nested class into a public one.

Target:
public ResponseEntity getRolesMapping() { if (!springSecurityLdapInternalsSupplier.isLdapAuthenticationEnabled()) { return toResponseEntityError(LdapMessages.NOT_CONFIGURED, HttpStatus.BAD_REQUEST); } return ResponseEntity.ok(springSecurityLdapInternalsSupplier.getAuthoritiesMapper()); }
Source:
private boolean isInputStreamValid() throws IOException { START if (in.available()>0) END return true; else return false; } Please, always use braces, even for one-liners. Could you please change this across your pull?

Target:
private boolean isInputStreamValid() throws IOException { if (in.available() > 0) { return true; } else { return false; } }
Source:
public URI resolveResource(Repository repository, String path) throws IOException, START IllegalArgumentException END { RepositoryPath repositoryPath = resolve(repository).resolve(path); if (RepositoryFiles.isArtifact(repositoryPath)) { ArtifactCoordinates c = RepositoryFiles.readCoordinates(repositoryPath); return c.toResource(); } return URI.create(path); } 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 ?

Target:
public URI resolveResource(Repository repository, String path) throws IOException { RepositoryPath repositoryPath = resolve(repository).resolve(path); if (RepositoryFiles.isArtifact(repositoryPath)) { ArtifactCoordinates c = RepositoryFiles.readCoordinates(repositoryPath); return c.toResource(); } return URI.create(path); }
Source:
public RepositoryIndexer addRepositoryIndexer(String contextId, RepositoryIndexer value) { START logger.debug( END "RepositoryIndexManager = [{}]. Adding repository indexer. ContextId = [{}], RepositoryIndexer = [{}]", this, contextId, value); return indexes.put(contextId, value); } 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(); ```

Target:
public RepositoryIndexer addRepositoryIndexer(String contextId, RepositoryIndexer value) { return indexes.put(contextId, value); }
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); START return resultList; END } @sbespalov : Unless you intended this for debugging purposes, I think it sounds like a reasonable suggestion.

Target:
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); return getDelegate().query(query); }
Source:
private static RepositoryPath rebase(RepositoryPath source, RepositoryPath targetBase) { FileSystem sourceFileSystem = source.getTarget().getFileSystem(); FileSystem targetFileSystem = targetBase.getTarget().getFileSystem(); String sourceRelative = source.getRoot() START .relativize(source.getTarget()) END .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; } ![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)

Target:
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(); // XXX[SBESPALOV]: We try to convert path form source to target FileSystem and need to check this on different // Storage types. // Note that this is only draft implementation, and probably in the future we will need something like separate // `FileSystemPathConverter` to convert Paths from one FileSystem to another. Such `FileSystemPathConverter` can // be provided by the `ReposytoryFileSystem` instance. String sTargetPath = sourceRelative.replaceAll(sourceFileSystem.getSeparator(), targetFileSystem.getSeparator()); return targetBase.resolve(sTargetPath); }
Source:
public boolean equals(Object o) { START if (this == o) return true; END if (o == null || getClass() != o.getClass()) return false; Role role = (Role) o; return Objects.equal(name, role.name); } Could you please always use curly braces around the bodies of `if` statements, even if they're one-liners?

Target:
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); }
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(); START System.out.println(response.getStatus()); END return response.getStatus() == 200; } I don't think we need this.

Target:
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(); return response.getStatus() == 200; }
Source:
void testFindGetterIdentifier() { AggregateModel<SomeGetterIdAnnotatedHandlers> inspector = AnnotatedAggregateMetaModelFactory.inspectAggregate(SomeGetterIdAnnotatedHandlers.class); assertEquals("SomeGetterIdAnnotatedHandlers", inspector.type()); assertEquals("id", inspector.getIdentifier(new SomeGetterIdAnnotatedHandlers())); START assertEquals("getId", inspector.routingKey()); END } 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.

Target:
void testFindGetterIdentifier() { AggregateModel<SomeGetterIdAnnotatedHandlers> inspector = AnnotatedAggregateMetaModelFactory.inspectAggregate(SomeGetterIdAnnotatedHandlers.class); assertEquals("SomeGetterIdAnnotatedHandlers", inspector.type()); assertEquals("id", inspector.getIdentifier(new SomeGetterIdAnnotatedHandlers())); assertEquals("id", inspector.routingKey()); }
Source:
public Builder snapshotFilter(Predicate<? super DomainEventData<?>> snapshotFilter) { START snapshotFilter(snapshotFilter::test); END return this; } We had an `assertNonNull` before, should we keep it?

Target:
public Builder snapshotFilter(Predicate<? super DomainEventData<?>> snapshotFilter) { return snapshotFilter(snapshotFilter::test); }
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); START END }); } You could replace this for: ```java !delegate.canHandle(unitOfWork.getMessage()) ? interceptorChain.proceed() : delegate.handle(unitOfWork.getMessage(), target) ```

Target:
public Object handle(UnitOfWork<? extends CommandMessage<?>> unitOfWork, InterceptorChain interceptorChain) throws Exception { return InterceptorChainParameterResolverFactory.callWithInterceptorChain( interceptorChain, () -> delegate.canHandle(unitOfWork.getMessage()) ? delegate.handle(unitOfWork.getMessage(), target) : interceptorChain.proceed()); }
Source:
START private AxonServerEventScheduler(Builder builder) { END this.axonServerConnectionManager = builder.axonServerConnectionManager; this.axonServerConfiguration = builder.axonServerConfiguration; this.serializer = builder.eventSerializer.get(); this.converter = new GrpcMetaDataConverter(serializer); } ```suggestion protected AxonServerEventScheduler(Builder builder) { ```

Target:
protected AxonServerEventScheduler(Builder builder) { this.axonServerConnectionManager = builder.axonServerConnectionManager; this.axonServerConfiguration = builder.axonServerConfiguration; this.serializer = builder.eventSerializer.get(); this.converter = new GrpcMetaDataConverter(serializer); }
Source:
private void doPublish(EventMessage<?> message, T target) { START getHandler(message, target).ifPresent(h -> { END 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)); } Why provide the entire `target` if you're only using the `target` its class?

Target:
private void doPublish(EventMessage<?> message, T target) { getHandler(message, target.getClass()).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)); }
Source:
private Instant retrieveDeadlineTimestamp(JobDataMap jobDataMap) { Object timestamp = jobDataMap.get(MESSAGE_TIMESTAMP); START if (timestamp instanceof String) return Instant.parse(timestamp.toString()); END return Instant.ofEpochMilli((long) timestamp); } Same argument as with the `DeadlineJob`.

Target:
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); }
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"); START return result; END } 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.

Target:
public Object handle(CommandMessage<?> command) throws Exception { VersionedAggregateIdentifier iv = commandTargetResolver.resolveTarget(command); Aggregate<T> inst = repository.loadOrCreate(iv.getIdentifier(), 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; }
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))); START newTokens.put("token2", null); END MultiSourceTrackingToken tokenWithNullConstituent = new MultiSourceTrackingToken(newTokens); assertTrue(testSubject.covers(tokenWithNullConstituent)); assertTrue(tokenWithNullConstituent.covers(tokenWithNullConstituent)); } 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?

Target:
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))); }
Source:
START private ExponentialBackOffIntervalRetryScheduler(Builder builder) { END super(builder); builder.validate(); this.backoffFactor = builder.backoffFactor; } The constructor should be made `protected` so that users can easily make a wrapper for it.

Target:
protected ExponentialBackOffIntervalRetryScheduler(Builder builder) { super(builder); this.backoffFactor = builder.backoffFactor; }
Source:
START public void lowerBoundDifferentNumberOfTokens() { END 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)); } I think the `upperBound()` and `covers()` method would also benefit from a different number of tokens test.

Target:
public void lowerBoundDifferentNumberOfTokens() { Map<String, TrackingToken> newTokens = new HashMap<>(); newTokens.put("token1", new GlobalSequenceTrackingToken(1)); testSubject.lowerBound(new MultiSourceTrackingToken(newTokens)); }
Source:
START public MultiStreamableMessageSource(Builder builder) { END this.eventStreams = builder.messageSources(); this.trackedEventComparator = builder.trackedEventComparator; } Nit: I'd make the constructor `protected`.

Target:
protected MultiStreamableMessageSource(Builder builder) { this.eventStreams = builder.messageSources(); this.trackedEventComparator = builder.trackedEventComparator; }
Source:
public Builder addMessageSource(String messageSourceId, StreamableMessageSource<TrackedEventMessage<?>> messageSource) { START BuilderUtils.assertThat(messageSourceId, sourceName -> !messageSourceMap.containsKey(sourceName), END "the messageSource name must be unique"); messageSourceMap.put(messageSourceId, messageSource); return this; } Consistency-Nit: I think we do static imports for _any_ usage of the `BuilderUtils` in our other classes.

Target:
public Builder addMessageSource(String messageSourceId, StreamableMessageSource<TrackedEventMessage<?>> messageSource) { assertThat(messageSourceId, sourceName -> !messageSourceMap.containsKey(sourceName), "the messageSource name must be unique"); messageSourceMap.put(messageSourceId, messageSource); return this; }
Source:
public GrpcBackedCommandMessage(Command command, Serializer serializer) { START this.command = command; END this.serializedPayload = new LazyDeserializingObject<>(new GrpcSerializedObject(command.getPayload()), serializer); this.metaDataSupplier = new GrpcMetaData(command.getMetaDataMap(), serializer); } You could invoke the `GrpcBackedCommandMessage(Command, LazyDeserializingObject, Supplier)` constructor.

Target:
public GrpcBackedCommandMessage(Command command, Serializer serializer) { this( command, new LazyDeserializingObject<>(new GrpcSerializedObject(command.getPayload()), serializer), new GrpcMetaData(command.getMetaDataMap(), serializer) ); }
Source:
public GrpcBackedQueryMessage(QueryRequest queryRequest, Serializer messageSerializer, Serializer serializer) { START this.query = queryRequest; END 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); } You could invoke private constructor.

Target:
public GrpcBackedQueryMessage(QueryRequest queryRequest, Serializer messageSerializer, Serializer serializer) { this( queryRequest, new LazyDeserializingObject<>(new GrpcSerializedObject(queryRequest.getPayload()), messageSerializer), new LazyDeserializingObject<>(new GrpcSerializedObject(queryRequest.getResponseType()), serializer), new GrpcMetaData(queryRequest.getMetaDataMap(), messageSerializer) ); }
Source:
public GrpcBackedQueryUpdateMessage(QueryUpdate queryUpdate, Serializer serializer) { this.queryUpdate = queryUpdate; START this.serializedPayload = END new LazyDeserializingObject<>(new GrpcSerializedObject(queryUpdate.getPayload()), serializer); this.metaDataSupplier = new GrpcMetaData(queryUpdate.getMetaDataMap(), serializer); } also here can be invoked the primary private constructor

Target:
public GrpcBackedQueryUpdateMessage(QueryUpdate queryUpdate, Serializer serializer) { this( queryUpdate, new LazyDeserializingObject<>(new GrpcSerializedObject(queryUpdate.getPayload()), serializer), new GrpcMetaData(queryUpdate.getMetaDataMap(), serializer) ); }
Source:
public DefaultEventGateway build() { START validate(); END return new DefaultEventGateway(this); } For consistency, I'd suggest not doing the `validate()` call here, but in the `AbstractEventGateway`.

Target:
public DefaultEventGateway build() { return new DefaultEventGateway(this); }
Source:
public MergedTrackingToken( @JsonProperty("lowerSegmentToken") TrackingToken lowerSegmentToken, @JsonProperty("upperSegmentToken") TrackingToken upperSegmentToken) { START this.lowerSegmentToken = lowerSegmentToken; END this.upperSegmentToken = upperSegmentToken; this.lowerSegmentAdvanced = false; this.upperSegmentAdvanced = false; } You could call a `protected` constructor from this one.

Target:
public MergedTrackingToken( @JsonProperty("lowerSegmentToken") TrackingToken lowerSegmentToken, @JsonProperty("upperSegmentToken") TrackingToken upperSegmentToken) { this(lowerSegmentToken, upperSegmentToken, false, false); }
Source:
START public StreamableMessageSource<TrackedEventMessage<?>> getMessageSource() { END return messageSource; } 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.

Target:
public StreamableMessageSource<? extends TrackedEventMessage<?>> getMessageSource() { return messageSource; }
Source:
protected void validate() throws AxonConfigurationException { START assertNonNull(repository, "The Repository is a hard requirement and should be provided"); END 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" ); } `Repository` cannot be `null`.

Target:
protected void validate() throws AxonConfigurationException { assertNonNull(repository, "The Repository 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" ); }
Source:
START AggregateModel<T> buildAggregateModel() { END if (aggregateModel == null) { return inspectAggregateModel(); } else { return aggregateModel; } } `private` or `protected`?

Target:
protected AggregateModel<T> buildAggregateModel() { if (aggregateModel == null) { return inspectAggregateModel(); } else { return aggregateModel; } }
Source:
START default Set<MessageHandlerInterceptor<? super EventMessage<?>>> getHandlerInterceptors() { END throw new UnsupportedOperationException("No implementation found to get the HandlerInterceptors"); } This method should return a List, as interceptors have an order.

Target:
default List<MessageHandlerInterceptor<? super EventMessage<?>>> getHandlerInterceptors() { throw new UnsupportedOperationException("No implementation found to get the HandlerInterceptors"); }
Source:
private boolean canClaimSegment(int segmentId) { if (segmentReleaseDeadlines.containsKey(segmentId) && segmentReleaseDeadlines.get(segmentId) > System.currentTimeMillis()){ return false; } START segmentReleaseDeadlines.remove(segmentId); END return true; } 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.

Target:
private boolean canClaimSegment(int segmentId) { return !segmentReleaseDeadlines.containsKey(segmentId) || segmentReleaseDeadlines.get(segmentId) < System.currentTimeMillis(); }
Source:
public GenericJpaRepository(EntityManagerProvider entityManagerProvider, Class<T> aggregateType, EventBus eventBus, LockFactory lockFactory, Function<String, ?> identifierConverter) { START this(entityManagerProvider, aggregateType, eventBus, null, null, lockFactory, identifierConverter); END } 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:

Target:
public GenericJpaRepository(EntityManagerProvider entityManagerProvider, Class<T> aggregateType, EventBus eventBus, LockFactory lockFactory, Function<String, ?> identifierConverter) { this(entityManagerProvider, aggregateType, eventBus, null, lockFactory, identifierConverter); }
Source:
public SimpleDeadlineManager(ScopeAwareProvider scopeAwareProvider) { START this(scopeAwareProvider, Executors.newSingleThreadScheduledExecutor(), NoTransactionManager.INSTANCE); END } Please construct the default Executor using the `AxonThreadFactory`. This makes all Axon managed threads recognizable. The (mandatory) group name could be "deadlineManager".

Target:
public SimpleDeadlineManager(ScopeAwareProvider scopeAwareProvider) { this(scopeAwareProvider, NoTransactionManager.INSTANCE); }
Source:
protected static AggregateLifecycle getInstance() { AggregateLifecycle instance = Scope.getCurrentScope(); START if (CurrentUnitOfWork.isStarted()) { END UnitOfWork<?> unitOfWork = CurrentUnitOfWork.get(); Set<AggregateLifecycle> managedAggregates = unitOfWork.getResource("ManagedAggregates"); if (managedAggregates != null && managedAggregates.size() == 1) { instance = managedAggregates.iterator().next(); } } return instance; } 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.

Target:
protected static AggregateLifecycle getInstance() { return Scope.getCurrentScope(); }
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)); START handlerDefinition = new ClasspathHandlerDefinition(Thread.currentThread().getContextClassLoader()); END } Use the `aggregateType`'s class loader

Target:
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 = ClasspathHandlerDefinition.forClass(aggregateType); }
Source:
START public GenericSubscriptionQueryMessage(Q payload, ResponseType<I> responseType, END ResponseType<U> updateResponseType) { super(payload, responseType); this.updateResponseType = updateResponseType; } Nit: would it make sense that this constructor calls the constructor on line 63?

Target:
public GenericSubscriptionQueryMessage(Q payload, ResponseType<I> responseType, ResponseType<U> updateResponseType) { this(payload, payload.getClass().getName(), responseType, updateResponseType); }
Source:
public boolean emit(U update) { // this is empty implementation, since regular query handler will not invoke it START return true; END } Should return `false` to indicate there is no client connected anymore.

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

Target:
public void complete() { // this is empty implementation, since regular query handler will not invoke it }
Source:
START public boolean error(Throwable error) { END // this is empty implementation, since regular query handler will not invoke it return true; } I'd like to consider this as a `completeExceptionally` case. It doesn't need to return anything.

Target:
public void error(Throwable error) { // this is empty implementation, since regular query handler will not invoke it }
Source:
START public void stop(Runnable runnable) { END } You need to call runnable.run() here. And probably also want to set running to false (also in stop() )

Target:
public void stop(Runnable runnable) { stop(); runnable.run(); }
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); START long previousReceiveErrors = getPortReceiveErrors(currentStats, switchName, portId); END long currentReceivedPackets = getPortReceivedPackets(currentStats, switchName, portId); long previousReceivedPackets = getPortReceivedPackets(currentStats, switchName, portId); if (currentReceivedPackets == previousReceivedPackets) return 0; return (currentReceiveErrors - previousReceiveErrors) / (currentReceivedPackets - previousReceivedPackets); } I guess first parameter should be "previousStats", since the getPortReceiveErrors is being called twice with "currentStats" parameter

Target:
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(previousStats, switchName, portId); long currentReceivedPackets = getPortReceivedPackets(currentStats, switchName, portId); long previousReceivedPackets = getPortReceivedPackets(previousStats, switchName, portId); if (currentReceivedPackets == previousReceivedPackets) return 0; return (currentReceiveErrors - previousReceiveErrors) / (currentReceivedPackets - previousReceivedPackets); }
Source:
public void configureOSPF(OSPFService ospfService) throws CapabilityException { IAction action = createActionAndCheckParams(OSPFActionSet.OSPF_CONFIGURE, ospfService); START ospfService.setEnabledState(EnabledState.DISABLED); // mark OSPF as disabled, we are configuring only END queueAction(action); } 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.

Target:
public void configureOSPF(OSPFService ospfService) throws CapabilityException { ospfService.setEnabledState(EnabledState.DISABLED); // mark OSPF as disabled, we are configuring only IAction action = createActionAndCheckParams(OSPFActionSet.OSPF_CONFIGURE, ospfService); queueAction(action); }
Source:
public void executeQueueTest() { try { startResource(); QueueCapability queueCapability = (QueueCapability) networkResource.getCapability(getOSPFInformation(CAPABILIY_TYPE)); queueCapability.execute(); stopResource(); START } catch (ResourceException e) { END e.printStackTrace(); Assert.fail(e.getMessage()); } catch (ProtocolException e) { e.printStackTrace(); Assert.fail(e.getMessage()); } } You don't need to catch, print and fail these exception. Simply declare them as part of the method signature and JUnit will fail the test for you if the exceptions should be thrown.

Target:
public void executeQueueTest() throws ResourceException, ProtocolException { startResource(); QueueCapability queueCapability = (QueueCapability) networkResource.getCapability(getOSPFInformation(CAPABILIY_TYPE)); queueCapability.execute(); stopResource(); }
Source:
START public ConfigImpl(IAggregator aggregator, boolean forTest) throws URISyntaxException, FileNotFoundException { END this.aggregator = aggregator; rawConfig = null; lastModified = 0; configUri = loadConfigUri(); } This constructor should have package visibility instead of public

Target:
protected ConfigImpl(IAggregator aggregator, boolean forTest) throws URISyntaxException, FileNotFoundException { this.aggregator = aggregator; rawConfig = null; lastModified = 0; configUri = loadConfigUri(); }
Source:
START public Map<String, CacheEntry> getLayerBuildMap() { END return _layerBuilds.getMap(); } Restore visibility of fields and methods in this class to package level when unit tests are moved to jaggr-core

Target:
Map<String, CacheEntry> getLayerBuildMap() { return _layerBuilds.getMap(); }
Source:
START public List<IModule> getModules() { END List<IModule> result = new ArrayList<IModule>(size()); for (ModuleListEntry entry : this) { result.add(entry.getModule()); } return result; } Restore visibility of methods in this class to package level when unit tests are moved to jaggr-core

Target:
List<IModule> getModules() { List<IModule> result = new ArrayList<IModule>(size()); for (ModuleListEntry entry : this) { result.add(entry.getModule()); } return result; }
Source:
START public static InstallationChecker getInstance() throws ProvisionException { END if (INSTANCE == null) { INSTANCE = new InstallationChecker(); } return INSTANCE; } prefer the Initialization on Demand Holder pattern to cope with singletons http://blog.crazybob.org/2007/01/lazy-loading-singletons.html

Target:
public synchronized static InstallationChecker getInstance() throws ProvisionException { if (INSTANCE == null) { INSTANCE = new InstallationChecker(); } return INSTANCE; }
Source:
public void testVertexCentricQuery() { START int noVertices = 10000; END } is this what you wanted to do here? this is different from the previous PR that called `testVertexCentricQuery(10000)`

Target:
public void testVertexCentricQuery() { testVertexCentricQuery(10000 /*noVertices*/); }
Source:
protected void setParentNode(GoloElement parent) { START if (!(parent instanceof Union) || parent == null) { END throw new IllegalArgumentException("UnionValue can only be defined in a Union"); } super.setParentNode(parent); } Findbugs says "redundant nullcheck", indeed `parent instanceof Union` is `false` if `parent` is `null`.

Target:
protected void setParentNode(GoloElement parent) { if (!(parent instanceof Union)) { throw new IllegalArgumentException("UnionValue can only be defined in a Union"); } super.setParentNode(parent); }
Source:
START public Tuple destruct() { END LinkedList<T> vals = new LinkedList<>(); for (T v : this) { vals.add(v); } return Tuple.fromArray(vals.toArray()); } Why not making an array right from the start, and avoid a `LinkedList`?

Target:
public Tuple destruct() { Object[] data = new Object[this.size()]; int i = 0; for (T v : this) { data[i] = v; i++; } return Tuple.fromArray(data); }
Source:
private List<String> visitInvocationArguments(AbstractInvocation invocation) { List<String> argumentNames = new ArrayList<>(); for (ExpressionStatement argument : invocation.getArguments()) { START if (invocation instanceof FunctionInvocation && ((FunctionInvocation) invocation).usesNamedArguments()) { END NamedArgument namedArgument = (NamedArgument) argument; argumentNames.add(namedArgument.getName()); argument = namedArgument.getExpression(); } argument.accept(this); } return argumentNames; } Can't we use named arguments on method invocation?

Target:
private List<String> visitInvocationArguments(AbstractInvocation invocation) { List<String> argumentNames = new ArrayList<>(); for (ExpressionStatement argument : invocation.getArguments()) { if (invocation.usesNamedArguments()) { NamedArgument namedArgument = (NamedArgument) argument; argumentNames.add(namedArgument.getName()); argument = namedArgument.getExpression(); } argument.accept(this); } return argumentNames; }
Source:
public MethodHandle find() { try { return resolve().asType(type); } catch (NoSuchMethodException | IllegalAccessException e) { START throw new Error(e); END } } Is `Error` the right exception type? /cc @yloiseau

Target:
public MethodHandle find() { try { return resolve().asType(type); } catch (NoSuchMethodException | IllegalAccessException e) { throw new RuntimeException(e); } }
Source:
public boolean hasMethod(String method) { Object obj = properties.get(method); START if(obj != null) { END return (obj instanceof MethodHandle); } else { return false; } } `if` `space` `(` (...)

Target:
public boolean hasMethod(String method) { Object obj = properties.get(method); if (obj != null) { return (obj instanceof MethodHandle); } return false; }
Source:
public GoloFunction(String name, Visibility visibility, Scope scope) { this.name = name; this.visibility = visibility; this.scope = scope; START this.main = this.name.equals("main"); END } It would be better to also check that the function is unary.

Target:
public GoloFunction(String name, Visibility visibility, Scope scope) { this.name = name; this.visibility = visibility; this.scope = scope; }
Source:
public static void addCodedObs(Patient p, String conceptName, String conceptAnswer, String date) { Obs o = new Obs(); o.setPerson(p); o.setConcept(MohCacheUtils.getConcept(conceptName)); o.setValueCoded(MohCacheUtils.getConcept(conceptAnswer)); o.setObsDatetime(MohTestUtils.makeDate(date)); START Obs obs = Context.getObsService().saveObs(o, null); END } Why was this change necessary? I don't see a reason for it if we do not use `obs` later.

Target:
public static void addCodedObs(Patient p, String conceptName, String conceptAnswer, String date) { Obs o = new Obs(); o.setPerson(p); o.setConcept(MohCacheUtils.getConcept(conceptName)); o.setValueCoded(MohCacheUtils.getConcept(conceptAnswer)); o.setObsDatetime(MohTestUtils.makeDate(date)); Context.getObsService().saveObs(o, null); }