auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public AggregateFunction getAggregateFunction() { if (_function instanceof AggregateFunction) return (AggregateFunction) _function; START else END return null; } I'm also missing some brackets here to comply with our normal code style.

Target:
public AggregateFunction getAggregateFunction() { if (_function instanceof AggregateFunction) { return (AggregateFunction) _function; } else { return null; } }
Source:
protected Schema getMainSchema() throws MetaModelException { if (schema == null) { MutableSchema theSchema = new MutableSchema(getMainSchemaName()); for (SimpleTableDef tableDef: tableDefs) { MutableTable table = tableDef.toTable().setSchema(theSchema); theSchema.addTable(table); } START schema = theSchema; END } return schema; } No need to cache the schema here. The superclass will automatically cache the schema until "refreshSchemas" is called.

Target:
protected Schema getMainSchema() throws MetaModelException { MutableSchema theSchema = new MutableSchema(getMainSchemaName()); for (SimpleTableDef tableDef: tableDefs) { MutableTable table = tableDef.toTable().setSchema(theSchema); theSchema.addTable(table); } return theSchema; }
Source:
public int hashCode() { int bits = 1; bits = 31 * bits + this.type.ordinal(); bits = 31 * bits + getToX(); bits = 31 * bits + getToY(); bits = 31 * bits + getToZ(); START return bits; END } Please replace by `bits ^ (bits >> 31)`

Target:
public int hashCode() { int bits = 1; bits = 31 * bits + this.type.ordinal(); bits = 31 * bits + getToX(); bits = 31 * bits + getToY(); bits = 31 * bits + getToZ(); return bits ^ (bits >> 31); }
Source:
public int hashCode() { long bits = 1; bits = 31 * bits + Double.doubleToLongBits(getX1()); bits = 31 * bits + Double.doubleToLongBits(getY1()); bits = 31 * bits + Double.doubleToLongBits(getX2()); bits = 31 * bits + Double.doubleToLongBits(getY2()); final int b = (int) bits; START return b; END } Please replace all you change by something similar to `b ^ (b >> 31)`.

Target:
public int hashCode() { long bits = 1; bits = 31 * bits + Double.doubleToLongBits(getX1()); bits = 31 * bits + Double.doubleToLongBits(getY1()); bits = 31 * bits + Double.doubleToLongBits(getX2()); bits = 31 * bits + Double.doubleToLongBits(getY2()); final int b = (int) bits; return b ^ (b >> 31); }
Source:
public int hashCode() { int bits = 1; bits = 31 * bits + this.minx; bits = 31 * bits + this.miny; bits = 31 * bits + this.minz; bits = 31 * bits + this.maxx; bits = 31 * bits + this.maxy; bits = 31 * bits + this.maxz; START return bits; END } `b ^ (b >> 31)` is missed here.

Target:
public int hashCode() { int bits = 1; bits = 31 * bits + this.minx; bits = 31 * bits + this.miny; bits = 31 * bits + this.minz; bits = 31 * bits + this.maxx; bits = 31 * bits + this.maxy; bits = 31 * bits + this.maxz; return bits ^ (bits >> 31); }
Source:
public int hashCode() { long bits = 1; bits = 31 * bits + Double.doubleToLongBits(this.scalar); bits = 31 * bits + ((this.vector == null) ? 0 : this.vector.hashCode()); final int b = (int) bits; START return b; END } `b ^ (b >> 31)` is missed here.

Target:
public int hashCode() { long bits = 1; bits = 31 * bits + Double.doubleToLongBits(this.scalar); bits = 31 * bits + ((this.vector == null) ? 0 : this.vector.hashCode()); final int b = (int) bits; return b ^ (b >> 31); }
Source:
public double getY1() { START return y1; END } This access to the attribute is forbidden by the coding rules. Compiler says: ``` return x1; ^^ Unqualified access to the field BasicPathShadow2afp.CoordinatesParam.x1 ``` You must add the `this.` prefix.

Target:
public double getY1() { return this.y1; }
Source:
public boolean equals(Object obj) { START if (!super.equals(obj)) { END return false; } final ListResponseModel lObj = (ListResponseModel) obj; if (delegate.equals(lObj.delegate)) { return delegate.equals(lObj.delegate); } return false; } Should be: ``` java public boolean equals(Object obj) { return this.delegate.equals(obj); } ``` Indeed, this class is a delegation design pattern and does no have any attributes except the delegate.

Target:
public boolean equals(Object obj) { return this.delegate.equals(obj); }
Source:
START public int hashCode() { END int hash = 1; final int prime = 31; hash = hash * prime + (int) (delegate.hashCode()); return hash; } Should be: ``` java public int hashCode() { return this.delegate.hashCode(); } ```

Target:
public int hashCode() { return this.delegate.hashCode(); }
Source:
public D[] getAllUserData(D[] array) { if (this.data == null) { START return (D[]) Array.newInstance(array.getClass(),0); END } return this.data.toArray(array); } Caution: array parameter could be null.

Target:
public D[] getAllUserData(D[] array) { if (this.data == null) { return null; } return this.data.toArray(array); }
Source:
public double getProgressionFactor() { START final double extent = this.max - (double) this.min; END if (extent == 0.) { return 0.; } return (this.current - this.min) / extent; } here, extent must be an integer.

Target:
public double getProgressionFactor() { final int extent = this.max - this.min; if (extent == 0.) { return 0.; } return (this.current - this.min) / extent; }
Source:
public double getPercent() { START final double extent = this.max - (double) this.min; END if (extent == 0.) { return 0.; } return (this.current - this.min) * 100. / extent; } here, extent must be an integer.

Target:
public double getPercent() { final int extent = this.max - this.min; if (extent == 0.) { return 0.; } return (this.current - this.min) * 100. / extent; }
Source:
private void setAlpha(RoundedImageView view, float alpha) { START if (Build.VERSION.SDK_INT < 11) { END view.setAlpha((int) (255 * alpha)); } else { view.setAlpha(alpha); } } I suggest to use positive case for more often scenarios when SDK >= 11

Target:
private void setAlpha(RoundedImageView view, float alpha) { if (Build.VERSION.SDK_INT >= 11) { view.setAlpha(alpha); } else { view.setAlpha((int) (255 * alpha)); } }
Source:
private TarArchive getApplicationContent(Owner owner, Libraries libraries) { File jarFile = getJarFile(); START ImagePackager packager = getConfiguredPackager(() -> new ImagePackager(jarFile)); END if (jarFile.exists()) { return TarArchive.fromZip(jarFile, owner); } return new PackagedTarArchive(owner, libraries, packager); } The `packager` can be moved below the `if` as it doesn't seem to be used when the jar exists already, I guess.

Target:
private TarArchive getApplicationContent(Owner owner, Libraries libraries) { File jarFile = getJarFile(); if (jarFile.exists()) { return TarArchive.fromZip(jarFile, owner); } ImagePackager packager = getConfiguredPackager(() -> new ImagePackager(jarFile)); return new PackagedTarArchive(owner, libraries, packager); }
Source:
private boolean isEnabled() { DataSourceInitializationMode mode = this.properties.getInitializationMode(); if (mode == DataSourceInitializationMode.NEVER) { return false; } START return mode != DataSourceInitializationMode.EMBEDDED || isEmbedded(); END } We prefer multi if statements to stay separate for better readability.

Target:
private boolean isEnabled() { DataSourceInitializationMode mode = this.properties.getInitializationMode(); if (mode == DataSourceInitializationMode.NEVER) { return false; } if (mode == DataSourceInitializationMode.EMBEDDED && !isEmbedded()) { return false; } return true; }
Source:
private boolean isHelpShown(Command command) { START return !(command instanceof HelpCommand) && !(command instanceof HintCommand); END } I find this harder to read

Target:
private boolean isHelpShown(Command command) { if (command instanceof HelpCommand || command instanceof HintCommand) { return false; } return true; }
Source:
private List<Mojo> parseMojos(Node plugin) throws XPathExpressionException { List<Mojo> mojos = new ArrayList<>(); for (Node mojoNode : nodesAt("//plugin/mojos/mojo", plugin)) { START mojos.add(new Mojo(textAt("goal", mojoNode), format(requireNonNull(textAt("description", mojoNode))), END parseParameters(mojoNode))); } return mojos; } I don't think an explicit check is needed.

Target:
private List<Mojo> parseMojos(Node plugin) throws XPathExpressionException { List<Mojo> mojos = new ArrayList<>(); for (Node mojoNode : nodesAt("//plugin/mojos/mojo", plugin)) { mojos.add(new Mojo(textAt("goal", mojoNode), format(textAt("description", mojoNode)), parseParameters(mojoNode))); } return mojos; }
Source:
default String getServletUrlMapping() { START if ("".equals(getPath()) || "/".equals(getPath())) { END return "/"; } if (getPath().contains("*")) { return getPath(); } if (getPath().endsWith("/")) { return getPath() + "*"; } return getPath() + "/*"; } `getPath` does not return `null`.

Target:
default String getServletUrlMapping() { if (getPath().equals("") || getPath().equals("/")) { return "/"; } if (getPath().contains("*")) { return getPath(); } if (getPath().endsWith("/")) { return getPath() + "*"; } return getPath() + "/*"; }
Source:
default String getUrlMapping() { String path = getPath(); if (!path.startsWith("/")) { path = "/" + path; } START if ("/".equals(path)) { END return "/*"; } if (path.contains("*")) { return path; } if (path.endsWith("/")) { return path + "*"; } return path + "/*"; } There is a usage of `path` right above so that change isn't necessary.

Target:
default String getUrlMapping() { String path = getPath(); if (!path.startsWith("/")) { path = "/" + path; } if (path.equals("/")) { return "/*"; } if (path.contains("*")) { return path; } if (path.endsWith("/")) { return path + "*"; } return path + "/*"; }
Source:
private void disableGrabResolvers(List<? extends AnnotatedNode> nodes) { for (AnnotatedNode classNode : nodes) { List<AnnotationNode> annotations = classNode.getAnnotations(); for (AnnotationNode node : new ArrayList<>(annotations)) { START if ("GrabResolver".equals(node.getClassNode().getNameWithoutPackage())) { END node.setMember("initClass", new ConstantExpression(false)); } } } } This doesn't return null either.

Target:
private void disableGrabResolvers(List<? extends AnnotatedNode> nodes) { for (AnnotatedNode classNode : nodes) { List<AnnotationNode> annotations = classNode.getAnnotations(); for (AnnotationNode node : new ArrayList<>(annotations)) { if (node.getClassNode().getNameWithoutPackage().equals("GrabResolver")) { node.setMember("initClass", new ConstantExpression(false)); } } } }
Source:
private void addUrl(URL url) { START if ("file".equals(url.getProtocol()) && url.getPath().endsWith("/")) { END try { this.folders.add(ResourceUtils.getFile(url)); } catch (Exception ex) { logger.warn(LogMessage.format("Unable to get classpath URL %s", url)); logger.trace(LogMessage.format("Unable to get classpath URL %s", url), ex); } } } The protocol is mandatory so this isn't necessary.

Target:
private void addUrl(URL url) { if (url.getProtocol().equals("file") && url.getPath().endsWith("/")) { try { this.folders.add(ResourceUtils.getFile(url)); } catch (Exception ex) { logger.warn(LogMessage.format("Unable to get classpath URL %s", url)); logger.trace(LogMessage.format("Unable to get classpath URL %s", url), ex); } } }
Source:
protected boolean isMain(Thread thread) { START return "main".equals(thread.getName()) END && thread.getContextClassLoader().getClass().getName().contains("AppClassLoader"); } Thread name is mandatory.

Target:
protected boolean isMain(Thread thread) { return thread.getName().equals("main") && thread.getContextClassLoader().getClass().getName().contains("AppClassLoader"); }
Source:
public void execute() throws MojoExecutionException, MojoFailureException { START if ("pom".equals(this.project.getPackaging())) { END getLog().debug("repackage goal could not be applied to pom project."); return; } if (this.skip) { getLog().debug("skipping repackaging as per configuration."); return; } repackage(); } packaging has a default so there is no need to do that.

Target:
public void execute() throws MojoExecutionException, MojoFailureException { if (this.project.getPackaging().equals("pom")) { getLog().debug("repackage goal could not be applied to pom project."); return; } if (this.skip) { getLog().debug("skipping repackaging as per configuration."); return; } repackage(); }
Source:
private boolean isJava13OrLater() { for (Method method : String.class.getMethods()) { START if ("stripIndent".equals(method.getName())) { END return true; } } return false; } No need to do this either.

Target:
private boolean isJava13OrLater() { for (Method method : String.class.getMethods()) { if (method.getName().equals("stripIndent")) { return true; } } return false; }
Source:
private boolean isSet(ConfigurableEnvironment environment, String property) { String value = environment.getProperty(property); START return (value != null && !"false".equals(value)); END } Can be replaced by `Boolean.parseBoolean`

Target:
private boolean isSet(ConfigurableEnvironment environment, String property) { String value = environment.getProperty(property); return (value != null && !value.equals("false")); }
Source:
START public int getRequestedChannelMax() { END return this.requestedChannelMax; } Getter/Setter should be co-located.

Target:
public Integer getRequestedChannelMax() { return this.requestedChannelMax; }
Source:
public Object findFilterId(Annotated a) { Object id = super.findFilterId(a); START return (id != null) ? id : CONFIGURATION_PROPERTIES_FILTER_ID; END } This is unrelated to the task at hand, please refrain from polishing code even if it's in the same class.

Target:
public Object findFilterId(Annotated a) { Object id = super.findFilterId(a); if (id == null) { id = CONFIGURATION_PROPERTIES_FILTER_ID; } return id; }
Source:
public void customDisableMaxHttpPostSize() { bind("server.tomcat.max-http-post-size=-1"); START bind("server.tomcat.max-http-form-post-size=-1"); END customizeAndRunServer((server) -> assertThat(server.getTomcat().getConnector().getMaxPostSize()).isEqualTo(-1)); } We should probably have two tests to make sure that the old property still works. As you've added `customDisableMaxHttpFormPostSize` below, this test should be left unchanged.

Target:
public void customDisableMaxHttpPostSize() { bind("server.tomcat.max-http-post-size=-1"); customizeAndRunServer((server) -> assertThat(server.getTomcat().getConnector().getMaxPostSize()).isEqualTo(-1)); }
Source:
public String getHostHeader() { START return this.remoteIpValve.getHostHeader() == null ? this.hostHeader : this.remoteIpValve.getHostHeader(); END } it should be just `return this.remoteIpValve.getHostHeader();`

Target:
public String getHostHeader() { return this.remoteIpValve.getHostHeader(); }
Source:
public SpringApplicationAdminMXBeanRegistrar springApplicationAdminRegistrar( ObjectProvider<MBeanExporter> mbeanExporters, Environment environment) throws MalformedObjectNameException { String jmxName = environment.getProperty(JMX_NAME_PROPERTY, DEFAULT_JMX_NAME); if (mbeanExporters != null) { // Make sure to not register that MBean twice START mbeanExporters.orderedStream().forEach(mbeanExporter -> { END mbeanExporter.addExcludedBean(jmxName); }); } return new SpringApplicationAdminMXBeanRegistrar(jmxName); } I don't think the ordering is important here.

Target:
public SpringApplicationAdminMXBeanRegistrar springApplicationAdminRegistrar( ObjectProvider<MBeanExporter> mbeanExporters, Environment environment) throws MalformedObjectNameException { String jmxName = environment.getProperty(JMX_NAME_PROPERTY, DEFAULT_JMX_NAME); if (mbeanExporters != null) { // Make sure to not register that MBean twice // ordering is not important for exporters, thus just iterate them for (MBeanExporter mbeanExporter : mbeanExporters) { mbeanExporter.addExcludedBean(jmxName); } } return new SpringApplicationAdminMXBeanRegistrar(jmxName); }
Source:
void bindDataSourcesToRegistry(Map<String, DataSource> dataSources, MeterRegistry registry, ObjectProvider<DataSourcePoolMetadataProvider> metadataProviders) { START List<DataSourcePoolMetadataProvider> metadataProvidersList = metadataProviders.orderedStream() END .collect(Collectors.toList()); dataSources.forEach( (name, dataSource) -> bindDataSourceToRegistry(name, dataSource, metadataProvidersList, registry)); } Does ordering matter here? The providers are used in a first wins manner. For the ordering to be important there would have to be overlap between providers.

Target:
void bindDataSourcesToRegistry(Map<String, DataSource> dataSources, MeterRegistry registry, ObjectProvider<DataSourcePoolMetadataProvider> metadataProviders) { // doesn't matter the ordering here since they are usually distinct and are // used as first match wins basis. List<DataSourcePoolMetadataProvider> metadataProvidersList = metadataProviders.stream() .collect(Collectors.toList()); dataSources.forEach( (name, dataSource) -> bindDataSourceToRegistry(name, dataSource, metadataProvidersList, registry)); }
Source:
void redisSessionStoreWithCustomizations() { this.contextRunner.withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)) .withPropertyValues("spring.session.store-type=redis", "spring.session.redis.namespace=foo", START "spring.session.redis.flush-mode=immediate", "spring.session.redis.save-mode=on-get-attribute", END "spring.session.redis.cleanup-cron=0 0 12 * * *", "spring.redis.port=" + redis.getFirstMappedPort()) .run(validateSpringSessionUsesRedis("foo:event:0:created:", FlushMode.IMMEDIATE, "0 0 12 * * *", SaveMode.ON_GET_ATTRIBUTE)); } Can you please put the save-mode after the cron so that the order of properties are aligned with the assertion?

Target:
void redisSessionStoreWithCustomizations() { this.contextRunner.withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)) .withPropertyValues("spring.session.store-type=redis", "spring.session.redis.namespace=foo", "spring.session.redis.flush-mode=immediate", "spring.session.redis.cleanup-cron=0 0 12 * * *", "spring.session.redis.save-mode=on-get-attribute", "spring.redis.port=" + redis.getFirstMappedPort()) .run(validateSpringSessionUsesRedis("foo:event:0:created:", FlushMode.IMMEDIATE, "0 0 12 * * *", SaveMode.ON_GET_ATTRIBUTE)); }
Source:
public Cluster couchbaseCluster() { CouchbaseCluster couchbaseCluster = CouchbaseCluster .create(couchbaseEnvironment(), determineBootstrapHosts()); if (this.properties.getUsername() != null START && this.properties.getPassword() != null) { END return couchbaseCluster.authenticate(this.properties.getUsername(), this.properties.getPassword()); } return couchbaseCluster; } The `username` and `password` properties are initialized to empty string (`""`). Will they ever be null? A better check might be `.isEmpty()`.

Target:
public Cluster couchbaseCluster() { CouchbaseCluster couchbaseCluster = CouchbaseCluster .create(couchbaseEnvironment(), determineBootstrapHosts()); if (this.properties.getUsername().isEmpty() || this.properties.getPassword().isEmpty()) { return couchbaseCluster; } return couchbaseCluster.authenticate(this.properties.getUsername(), this.properties.getPassword()); }
Source:
public Bucket couchbaseClient() { if (this.properties.getUsername().isEmpty() || this.properties.getPassword().isEmpty()) { START return couchbaseCluster().openBucket(this.properties.getBucket().getName()); END } return couchbaseCluster().openBucket(this.properties.getBucket().getName(), this.properties.getBucket().getPassword()); } This condition should be inverted. If RBAC `username` or `password` are empty we should call the openBucket method that takes a bucket password. Sorry if I missed this earlier.

Target:
public Bucket couchbaseClient() { if (this.properties.getUsername().isEmpty() || this.properties.getPassword().isEmpty()) { return couchbaseCluster().openBucket(this.properties.getBucket().getName(), this.properties.getBucket().getPassword()); } return couchbaseCluster().openBucket(this.properties.getBucket().getName()); }
Source:
void configure(MeterRegistry registry) { // Customizers must be applied before binders, as they may add custom // tags or alter timer or summary configuration. customize(registry); addFilters(registry); START if (this.hasCompositeMeterRegistry) { END if ((registry instanceof CompositeMeterRegistry)) { addBinders(registry); } } else { if (!(registry instanceof CompositeMeterRegistry)) { addBinders(registry); } } if (this.addToGlobalRegistry && registry != Metrics.globalRegistry) { Metrics.addRegistry(registry); } } Rather than `hasCompositeMeterRegistry` it might be better to be straightforward about what this controls. Something like `onlyBindToCompositeRegistry`.

Target:
void configure(MeterRegistry registry) { // Customizers must be applied before binders, as they may add custom // tags or alter timer or summary configuration. customize(registry); addFilters(registry); if (this.hasCompositeMeterRegistry) { if (registry instanceof CompositeMeterRegistry) { addBinders(registry); } } else { addBinders(registry); } if (this.addToGlobalRegistry && registry != Metrics.globalRegistry) { Metrics.addRegistry(registry); } }
Source:
private PushGateway getPushGateway(String url) { try { START return new PushGateway(new URL(Objects.toString(url, ""))); END } catch (MalformedURLException ex) { return new PushGateway(url); } } I don't think we need to do `Objects.toString(url, "")` since the property has a default value of `localhost:9091`.

Target:
private PushGateway getPushGateway(String url) { try { return new PushGateway(new URL(url)); } catch (MalformedURLException ex) { return new PushGateway(url); } }
Source:
public TomcatConnectorCustomizer connectorCustomizer() { START return (connector) -> connector.setPort(9001); END } This might cause a port clash if something else is used port 9001. It would be safer if the customizer didn't do anything to the connector.

Target:
public TomcatConnectorCustomizer connectorCustomizer() { return (connector) -> { }; }
Source:
public void tomcatContextCustomizerBeanIsAddedToFactory() { WebApplicationContextRunner runner = new WebApplicationContextRunner( AnnotationConfigServletWebServerApplicationContext::new) .withConfiguration(AutoConfigurations .of(ServletWebServerFactoryAutoConfiguration.class)) .withUserConfiguration( TomcatContextCustomizerConfiguration.class); runner.run((context) -> { TomcatServletWebServerFactory factory = context .getBean(TomcatServletWebServerFactory.class); START assertThat(factory.getTomcatContextCustomizers()).hasSize(1); END }); } If this test passes then this assertion isn't quite right as `TomcatContextCustomizerConfiguration` doesn't define a `TomcatContextCustomizer`. The assertions needs to be written such that if you remove `.withUserConfiguration(TomcatContextCustomizerConfiguration.class)` the test will fail.

Target:
public void tomcatContextCustomizerBeanIsAddedToFactory() { WebApplicationContextRunner runner = new WebApplicationContextRunner( AnnotationConfigServletWebServerApplicationContext::new) .withConfiguration(AutoConfigurations .of(ServletWebServerFactoryAutoConfiguration.class)); runner.run((context) -> { TomcatServletWebServerFactory factory = context .getBean(TomcatServletWebServerFactory.class); assertThat(factory.getTomcatContextCustomizers()).hasSize(1); }); }
Source:
START public HierarchicalNameMapper graphiteHierarchicalNameMapper(GraphiteConfig config) { END return new GraphiteHierarchicalNameMapper(config.tagsAsPrefix()); } This should declare that `GraphiteHierarchicalNameMapper` is returned to provide as much type information to the bean factory as possible.

Target:
public GraphiteHierarchicalNameMapper graphiteHierarchicalNameMapper( GraphiteConfig config) { return new GraphiteHierarchicalNameMapper(config.tagsAsPrefix()); }
Source:
void shutdown() { this.executorService.shutdown(); if (this.pushgatewayProperties.isPushOnShutdown()) { push(); } if (this.pushgatewayProperties.isDeleteOnShutdown()) { START try { END this.pushGateway.delete(job(), this.pushgatewayProperties.getGroupingKeys()); } catch (Throwable throwable) { this.logger.error( "Unable to delete metrics from Prometheus Pushgateway", throwable); } } } Perhaps extract a `delete()` method here?

Target:
void shutdown() { this.executorService.shutdown(); if (this.pushgatewayProperties.isPushOnShutdown()) { push(); } if (this.pushgatewayProperties.isDeleteOnShutdown()) { delete(); } }
Source:
START protected List<String> getAndProcessPropertySourceProperties( END MergedContextConfiguration mergedConfig) { List<String> propertySourceProperties = new ArrayList<>( Arrays.asList(mergedConfig.getPropertySourceProperties())); String differentiator = getDifferentiatorPropertySourceProperty(); if (differentiator != null) { propertySourceProperties.add(differentiator); } processPropertySourceProperties(mergedConfig, propertySourceProperties); return propertySourceProperties; } If `org.springframework.boot.test.context.SpringBootTestContextBootstrapper.getProperties(Class<?>)` was overridden instead, I think this method could continue to be `private`. Perhaps I have missed something?

Target:
private List<String> getAndProcessPropertySourceProperties( MergedContextConfiguration mergedConfig) { List<String> propertySourceProperties = new ArrayList<>( Arrays.asList(mergedConfig.getPropertySourceProperties())); String differentiator = getDifferentiatorPropertySourceProperty(); if (differentiator != null) { propertySourceProperties.add(differentiator); } processPropertySourceProperties(mergedConfig, propertySourceProperties); return propertySourceProperties; }
Source:
public SpringBootConfigurationFinder() { START this.scanner = new ClassPathScanningCandidateComponentProvider(false); END this.scanner.addIncludeFilter( new AnnotationTypeFilter(SpringBootConfiguration.class)); this.scanner.setResourcePattern("*.class"); } Rather than a copy/paste, this should call the other constructor you've created with `SpringBootConfiguration.class`

Target:
public SpringBootConfigurationFinder() { this(SpringBootConfiguration.class); }
Source:
START public void afterPropertiesSet() { END this.embeddedDatabase = this.factory.getEmbeddedDatabase(); } This change appears to be unrelated.

Target:
public void afterPropertiesSet() throws Exception { this.embeddedDatabase = this.factory.getEmbeddedDatabase(); }
Source:
START public DataSource getObject() { END return this.embeddedDatabase; } This change appears to be unrelated.

Target:
public DataSource getObject() throws Exception { return this.embeddedDatabase; }
Source:
START EmbeddedDatabase getEmbeddedDatabase() { END EmbeddedDatabaseConnection connection = this.environment.getProperty( "spring.test.database.connection", EmbeddedDatabaseConnection.class, EmbeddedDatabaseConnection.NONE); if (EmbeddedDatabaseConnection.NONE.equals(connection)) { connection = EmbeddedDatabaseConnection.get(getClass().getClassLoader()); } Assert.state(connection != EmbeddedDatabaseConnection.NONE, "Failed to replace DataSource with an embedded database for tests. If " + "you want an embedded database please put a supported one " + "on the classpath or tune the replace attribute of " + "@AutoConfigureTestDatabase."); return new EmbeddedDatabaseBuilder().generateUniqueName(true) .setType(connection.getType()).build(); } This change appears to be unrelated.

Target:
public EmbeddedDatabase getEmbeddedDatabase() { EmbeddedDatabaseConnection connection = this.environment.getProperty( "spring.test.database.connection", EmbeddedDatabaseConnection.class, EmbeddedDatabaseConnection.NONE); if (EmbeddedDatabaseConnection.NONE.equals(connection)) { connection = EmbeddedDatabaseConnection.get(getClass().getClassLoader()); } Assert.state(connection != EmbeddedDatabaseConnection.NONE, "Failed to replace DataSource with an embedded database for tests. If " + "you want an embedded database please put a supported one " + "on the classpath or tune the replace attribute of " + "@AutoConfigureTestDatabase."); return new EmbeddedDatabaseBuilder().generateUniqueName(true) .setType(connection.getType()).build(); }
Source:
START private static synchronized void disableCaching() { END if (!cacheDisabled) { cacheDisabled = true; doDisableCaching(); } } Why is this now `synchronized`?

Target:
private static void disableCaching() { if (!cacheDisabled) { cacheDisabled = true; doDisableCaching(); } }
Source:
START public void setCurrentUrl( URL urlCurrent ) { END oldFeedSource.setCurrentUrl( urlCurrent ); newFeedSource.setCurrentUrl( urlCurrent ); } Hm... Migration feed is where it probably does not make sense to have Archive URLs. Maybe we can make these methods no-op?

Target:
public void setCurrentUrl( URL urlCurrent ) { // No op - migration adapter isn't used on archive feeds }
Source:
public boolean hasRequiredProperties(MessageAddressingProperties map) { if (map.getAction() == null) { return false; } if ((map.getReplyTo() != null && !hasAnonymousAddress(map.getReplyTo()) && !hasNoneAddress(map.getReplyTo())) || (map.getFaultTo() != null && !hasAnonymousAddress(map.getFaultTo()) && !hasNoneAddress(map.getFaultTo()))){ START return map.getMessageId() != null; END } return true; } Reading six boolean expressions chained together in collection of "ands", "ors" and "nots" takes me back to logical gate construction and makes me need a Venn diagram to grok. Could you extract some functions that embody the intent so its more readable?

Target:
public boolean hasRequiredProperties(MessageAddressingProperties map) { if (map.getAction() == null) { return false; } if (map.getReplyTo() != null || map.getFaultTo() != null) { return map.getMessageId() != null; } return true; }
Source:
private void logoutIfNeeded() throws InterruptedException { START if (isViewDisplayed(getViewById(R.id.list_root)) == false) { END return; } loadSettingsFromNotesList(); // Swipe to perform a scroll (because I couldn't get a reference to a scrollable view) // that will reveal the logout button. onView(withId(R.id.preferences_container)).perform(swipeUp()); // Logout selectSettingsOption(R.string.log_out, logoutPosition); // Give time to the logout to finish waitForViewMatching(withId(R.id.button_login), 1000); } ```suggestion if (!isViewDisplayed(getViewById(R.id.list_root))) { ``` We can simplify `!isViewDisplayed(getViewById(R.id.list_root))` to `isViewDisplayed(getViewById(R.id.list_root)) == false`.

Target:
private void logoutIfNeeded() { if (!isViewDisplayed(getViewById(R.id.list_root))) { return; } loadSettingsFromNotesList(); // Swipe to perform a scroll (because I couldn't get a reference to a scrollable view) // that will reveal the logout button. onView(withId(R.id.preferences_container)).perform(swipeUp()); // Logout selectSettingsOption(R.string.log_out, logoutPosition); // Give time to the logout to finish waitForViewMatching(withId(R.id.button_login), 1000); }
Source:
private void enterThenDisablePasscodeIfNeeded() { START if (isViewDisplayed(getViewById(R.id.button1)) == false) { END return; } typeFullPasscode(); loadSettingsFromNotesList(); loadPasscodeUnsetterFromSettings(); typeFullPasscode(); dismissSettings(); } ```suggestion if (!isViewDisplayed(getViewById(R.id.button1))) { ``` We can simplify `isViewDisplayed(getViewById(R.id.button1)) == false` to `!isViewDisplayed(getViewById(R.id.button1))`.

Target:
private void enterThenDisablePasscodeIfNeeded() { if (!isViewDisplayed(getViewById(R.id.button1))) { return; } typeFullPasscode(); loadSettingsFromNotesList(); loadPasscodeUnsetterFromSettings(); typeFullPasscode(); dismissSettings(); }
Source:
public static void removePref(Context context, String prefKey){ SharedPreferences prefs = getPrefs(context); if (!prefs.contains(prefKey)){ return; } SharedPreferences.Editor editor = prefs.edit(); editor.remove(prefKey); START editor.commit(); END } We can now use `apply()` instead of `commit()`, which will save the preference outside of the UI thread.

Target:
public static void removePref(Context context, String prefKey){ SharedPreferences prefs = getPrefs(context); if (!prefs.contains(prefKey)){ return; } SharedPreferences.Editor editor = prefs.edit(); editor.remove(prefKey); editor.apply(); }
Source:
START private HttpURLConnection openConnection(URL url) throws IOException { END return (HttpURLConnection) url.openConnection(); } ```suggestion private static HttpURLConnection openConnection(URL url) throws IOException { ```

Target:
private static HttpURLConnection openConnection(URL url) throws IOException { return (HttpURLConnection) url.openConnection(); }
Source:
START private InputStream openStream(String url) throws IOException { END return new URL(url).openStream(); } ```suggestion private static InputStream openStream(String url) throws IOException { ```

Target:
private static InputStream openStream(String url) throws IOException { return new URL(url).openStream(); }
Source:
public static ConfigurationLoader from(final Properties props) throws IOException { return new ConfigurationLoader(new Function<String, String>() { @SuppressFBWarnings(value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", justification = "False positive. I don't know what spotbugs is doing here.") public String apply(String from) { START return props.getProperty(from); END } }); } BTW could convert to lambda

Target:
public static ConfigurationLoader from(final Properties props) throws IOException { return new ConfigurationLoader(from -> props.getProperty(from)); }
Source:
public void controller(FragmentModel model, @FragmentParam(required = true, value = "uuid") String uuid) throws Exception { PersonAttributeType personAttributeType = Context.getPersonService().getPersonAttributeTypeByUuid(uuid); START if(personAttributeType.getFormat().contentEquals(Concept.class.getCanonicalName())){ END int foreignKey = personAttributeType.getForeignKey(); model.put("foreignKey", foreignKey); model.put("codedPersonAttribute", true); } else{ model.put("codedPersonAttribute", false); } } I think this should be `personAttributeType.getFormat().equals(Concept.class.getName())`

Target:
public void controller(FragmentModel model, @FragmentParam(required = true, value = "uuid") String uuid) throws Exception { PersonAttributeType personAttributeType = Context.getPersonService().getPersonAttributeTypeByUuid(uuid); if(personAttributeType.getFormat().equals(Concept.class.getName())){ int foreignKey = personAttributeType.getForeignKey(); model.put("foreignKey", foreignKey); model.put("codedPersonAttribute", true); } else{ model.put("codedPersonAttribute", false); } }
Source:
public void sendMessageSync(String destAddress, String message, boolean command) throws MessageException { Response response = getRequestBuilder().post(Entity.entity( START preparePayload(destAddress, message.trim()), mediaType)); END if (response.getStatus() / 100 != 2) { throw new MessageException(response.readEntity(String.class)); } } I think we should do trim in the `preparePayload` method.

Target:
public void sendMessageSync(String destAddress, String message, boolean command) throws MessageException { Response response = getRequestBuilder().post(Entity.entity(preparePayload(destAddress, message), mediaType)); if (response.getStatus() / 100 != 2) { throw new MessageException(response.readEntity(String.class)); } }
Source:
public void testDecode() throws Exception { GpsmtaProtocolDecoder decoder = new GpsmtaProtocolDecoder(new GpsmtaProtocol()); verifyPosition(decoder, text( "3085a94ef459 1446536867 49.81621 24.054207 1 0 22 0 10 12 24 0 0")); verifyPosition(decoder, text( "864528021249771 1446116686 49.85073 24.004438 0 217 6 338 00 59 27 0 0")); verifyPosition(decoder, text( "359144048138856 1442932957 49.85064 24.003979 1 0 40 0 10 110 26 0 0")); verifyPosition(decoder, text( "359144048138856 1442932957 -49.85064 24.003979 1 0 40 0 10 110 26 0 0")); START verifyPosition(decoder, text( END "359144048138856 1442932957 49.85064 -24.003979 1 0 40 0 10 110 26 0 0")); verifyPosition(decoder, text( "359144048138856 1442932957 -49.85064 -24.003979 1 0 40 0 10 110 26 0 0")); } I don't think we need tests for all possible combinations. Just one would be enough.

Target:
public void testDecode() throws Exception { GpsmtaProtocolDecoder decoder = new GpsmtaProtocolDecoder(new GpsmtaProtocol()); verifyPosition(decoder, text( "3085a94ef459 1446536867 49.81621 24.054207 1 0 22 0 10 12 24 0 0")); verifyPosition(decoder, text( "864528021249771 1446116686 49.85073 24.004438 0 217 6 338 00 59 27 0 0")); verifyPosition(decoder, text( "359144048138856 1442932957 -49.85064 -24.003979 1 0 40 0 10 110 26 0 0")); }
Source:
public void sendMessageSync(String destAddress, String message, boolean command) throws InterruptedException, MessageException { Response response = getRequestBuilder().post(Entity.json(preparePayload(destAddress, message))); if (!response.getStatusInfo().equals(Response.Status.OK)) { String output = response.readEntity(String.class); START throw new MessageException(new Exception(output)); END } } Please add `MessageException(String message)` constructor to `MessageException` class instead of creating proxy `Exception`

Target:
public void sendMessageSync(String destAddress, String message, boolean command) throws InterruptedException, MessageException { Response response = getRequestBuilder().post(Entity.json(preparePayload(destAddress, message))); if (!response.getStatusInfo().equals(Response.Status.OK)) { String output = response.readEntity(String.class); throw new MessageException(output); } }
Source:
public static String formatShortMessage(long userId, Event event, Position position) { START String templatePath = Context.getConfig().getString("message.short.templatesPath", "short"); END return formatMessage(null, userId, event, position, templatePath); } Not really related to this pull request, but I think we should just assume "full" and "short" sub-paths here. Base path can still be configurable.

Target:
public static String formatShortMessage(long userId, Event event, Position position) { return formatMessage(null, userId, event, position, "short"); }
Source:
public void testEncodePositionSingle() throws Exception { Tk103ProtocolEncoder encoder = new Tk103ProtocolEncoder(); Command command = new Command(); command.setDeviceId(1); command.setType(Command.TYPE_POSITION_SINGLE); Assert.assertEquals("(123456789012345AP00)", encoder.encodeCommand(command)); IdentityManager old = Context.getIdentityManager(); Context.init(t580wManager); try { Assert.assertEquals("[begin]sms2,*getposl*,[end]", encoder.encodeCommand(command)); START } finally { END Context.init(old); } } This is just wrong.

Target:
public void testEncodePositionSingle() throws Exception { Tk103ProtocolEncoder encoder = new Tk103ProtocolEncoder(); Command command = new Command(); command.setDeviceId(1); command.setType(Command.TYPE_POSITION_SINGLE); Assert.assertEquals("(123456789012345AP00)", encoder.encodeCommand(command)); }
Source:
public MultiPartEventForwarder() { payloadParamName = Context.getConfig().getString("event.forward.paramMode.payloadParamName", "payload"); START additionalParams = Context.getConfig().getString("event.forward.paramMode.additionalParams", ""); END } Why empty string and not null?

Target:
public MultiPartEventForwarder() { payloadParamName = Context.getConfig().getString("event.forward.paramMode.payloadParamName", "payload"); additionalParams = Context.getConfig().getString("event.forward.paramMode.additionalParams"); }
Source:
protected String formatCommand(Command command, String format, String... keys) { START return super.formatCommand(command, format, this, keys); END } Why `super`?

Target:
protected String formatCommand(Command command, String format, String... keys) { return formatCommand(command, format, this, keys); }
Source:
public OsmAndProtocolDecoder(OsmAndProtocol protocol) { super(protocol); START speedUnits = Context.getConfig().getString("osmand.speedUnits", "kn"); END } Please make it consistent with other places: https://github.com/tananaev/traccar/blob/master/src/org/traccar/protocol/Tk103ProtocolDecoder.java#L256 Possibly updating TK103 decoder would be even better.

Target:
public OsmAndProtocolDecoder(OsmAndProtocol protocol) { super(protocol); }
Source:
public User login(String email, String password) throws SQLException { User user = QueryBuilder.create(dataSource, getQuery("database.loginUser")) START .setString("email", email.trim().toLowerCase()) END .executeQuerySingle(User.class); if (user != null && user.isPasswordValid(password)) { return user; } else { return null; } } I agree with trimming, but I don't understand why we need to lower-case it.

Target:
public User login(String email, String password) throws SQLException { User user = QueryBuilder.create(dataSource, getQuery("database.loginUser")) .setString("email", email.trim()) .executeQuerySingle(User.class); if (user != null && user.isPasswordValid(password)) { return user; } else { return null; } }
Source:
public MotionEventHandler() { START if (Context.getConfig() != null) { END tripsConfig = ReportUtils.initTripsConfig(); } } Is there any case when we don't have config?

Target:
public MotionEventHandler() { tripsConfig = ReportUtils.initTripsConfig(); }
Source:
public Response update(Attribute entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); START Context.getPermissionsManager().checkPermission("attribute", getUserId(), entity.getId()); END Context.getAttributesManager().updateItem(entity); return Response.ok(entity).build(); } I think it would make sense to use some constant for type names.

Target:
public Response update(Attribute entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getPermissionsManager().checkPermission(Attribute.class, getUserId(), entity.getId()); Context.getAttributesManager().updateItem(entity); return Response.ok(entity).build(); }
Source:
public AttributesManager(DataManager dataManager) { super(dataManager, Attribute.class, AttributePermission.class, DeviceAttribute.class, GroupAttribute.class); refreshItems(); START refreshExtendedPermissions(); END } It seems like we refresh everything. Do you think there will be a performance issues with it?

Target:
public AttributesManager(DataManager dataManager) { super(dataManager, Attribute.class); refreshItems(); refreshExtendedPermissions(); }
Source:
protected Object encodeCommand(Command command) { START initDevicePassword(command, ""); END switch (command.getType()) { case Command.TYPE_CUSTOM: return encodeContent(command.getString(Command.KEY_DATA)); case Command.TYPE_ENGINE_STOP: return encodeContent("AT$IOGP3=1"); case Command.TYPE_ENGINE_RESUME: return encodeContent("AT$IOGP3=0"); default: Log.warning(new UnsupportedOperationException(command.getType())); break; } return null; } Why do we need this line? I think it should be removed.

Target:
protected Object encodeCommand(Command command) { switch (command.getType()) { case Command.TYPE_CUSTOM: return encodeContent(command.getString(Command.KEY_DATA)); case Command.TYPE_ENGINE_STOP: return encodeContent("AT$IOGP3=1"); case Command.TYPE_ENGINE_RESUME: return encodeContent("AT$IOGP3=0"); default: Log.warning(new UnsupportedOperationException(command.getType())); break; } return null; }
Source:
public void setTimezone(String timezone) { if (timezone != null) { START this.timezone = TimeZone.getTimeZone(timezone).getID(); END } else { this.timezone = null; } } Use ternary operator here. It should make code easier to read in this case.

Target:
public void setTimezone(String timezone) { this.timezone = timezone != null ? TimeZone.getTimeZone(timezone).getID() : null; }
Source:
START public Response add(Command entity) throws RecoverablePduException, UnrecoverablePduException, END SmppTimeoutException, SmppChannelException, InterruptedException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getPermissionsManager().checkDevice(getUserId(), entity.getDeviceId()); Context.getDeviceManager().sendCommand(entity); return Response.ok(entity).build(); } Maybe we should just declare generic exception here.

Target:
public Response add(Command entity) throws Exception { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getPermissionsManager().checkDevice(getUserId(), entity.getDeviceId()); Context.getDeviceManager().sendCommand(entity); return Response.ok(entity).build(); }
Source:
public void run() { SmppSession smppSession = smppClient.getSession(); if (smppSession != null && smppSession.isBound()) { try { smppSession.enquireLink(new EnquireLink(), enquireLinkTimeout); } catch (SmppTimeoutException | SmppChannelException | RecoverablePduException | UnrecoverablePduException error) { START Log.warning("Enquire link failed, executing reconnect: " + error); END smppClient.reconnect(); } catch (InterruptedException error) { Log.info("Enquire link interrupted, probably killed by reconnecting"); } } else { Log.error("Enquire link running while session is not connected"); } } Exception can be included as a separate parameter.

Target:
public void run() { SmppSession smppSession = smppClient.getSession(); if (smppSession != null && smppSession.isBound()) { try { smppSession.enquireLink(new EnquireLink(), enquireLinkTimeout); } catch (SmppTimeoutException | SmppChannelException | RecoverablePduException | UnrecoverablePduException error) { Log.warning("Enquire link failed, executing reconnect: ", error); smppClient.reconnect(); } catch (InterruptedException error) { Log.info("Enquire link interrupted, probably killed by reconnecting"); } } else { Log.warning("Enquire link running while session is not connected"); } }
Source:
private String decodeAlarm(int value) { switch (value) { case 1: return Position.ALARM_SOS; case 2: START return null; END case 3: return Position.ALARM_GEOFENCE; case 4: return Position.ALARM_POWER_CUT; case 5: return null; case 6: return null; default: return null; } } Remove all "null" cases. There is a default case for that.

Target:
private String decodeAlarm(int value) { switch (value) { case 1: return Position.ALARM_SOS; case 3: return Position.ALARM_GEOFENCE; case 4: return Position.ALARM_POWER_CUT; default: return null; } }
Source:
public DeviceManager(DataManager dataManager) { this.dataManager = dataManager; this.config = Context.getConfig(); dataRefreshDelay = config.getLong("database.refreshDelay", DEFAULT_REFRESH_DELAY) * 1000; if (dataManager != null) { try { updateDeviceCache(true); START updateGroupCache(true); END for (Position position : dataManager.getLatestPositions()) { positions.put(position.getDeviceId(), position); } } catch (SQLException error) { Log.warning(error); } } } Should we init group cache first? Because devices reference it...

Target:
public DeviceManager(DataManager dataManager) { this.dataManager = dataManager; this.config = Context.getConfig(); dataRefreshDelay = config.getLong("database.refreshDelay", DEFAULT_REFRESH_DELAY) * 1000; if (dataManager != null) { try { updateGroupCache(true); updateDeviceCache(true); for (Position position : dataManager.getLatestPositions()) { positions.put(position.getDeviceId(), position); } } catch (SQLException error) { Log.warning(error); } } }
Source:
public QueryBuilder setLong(String name, long value) throws SQLException { for (int i : indexes(name)) { try { if (value == 0) { statement.setNull(i, Types.INTEGER); } else { START statement.setLong(i, value); END } } catch (SQLException error) { statement.close(); connection.close(); throw error; } } return this; } Replace tab with spaces.

Target:
public QueryBuilder setLong(String name, long value) throws SQLException { return setLong(name, value, false); }
Source:
public void onWebSocketConnect(Session session) { super.onWebSocketConnect(session); START Map<String, Collection<?>> data = new HashMap<String, Collection<?>>(); END data.put(KEY_POSITIONS, Context.getConnectionManager().getInitialState(userId)); sendData(data); Context.getConnectionManager().addListener(userId, this); } Traccar targets Java 7 and higher, so you can use diamond operator on the right hand side.

Target:
public void onWebSocketConnect(Session session) { super.onWebSocketConnect(session); Map<String, Collection<?>> data = new HashMap<>(); data.put(KEY_POSITIONS, Context.getConnectionManager().getInitialState(userId)); sendData(data); Context.getConnectionManager().addListener(userId, this); }