auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void lookupAddessAll() { START FavouritesDbHelper favorites = ctx.getFavorites(); END lookupAddressForPointToNavigate(); lookupAddessForStartPoint(); for (TargetPoint targetPoint : intermediatePoints) { lookupAddressForIntermediatePoint(targetPoint); } favorites.lookupAddressForHomePoint(); favorites.lookupAddressForWorkPoint(); favorites.lookupAddressForParkingPoint(); lookupAddressForMyLocationPoint(); } Why favorites here?? Run lookup for favorites before app.getTargetPointsHelper().lookupAddessAll();

Target:
public void lookupAddessAll() { lookupAddressForPointToNavigate(); lookupAddessForStartPoint(); for (TargetPoint targetPoint : intermediatePoints) { lookupAddressForIntermediatePoint(targetPoint); } lookupAddressForMyLocationPoint(); }
Source:
public int getOpacity() { START return PixelFormat.UNKNOWN; END } Why opacity unknown?

Target:
public int getOpacity() { return 0; }
Source:
public void setLocationFromService(net.osmand.Location location, boolean continuous) { if (locationSimulation.isRouteAnimating()) { return; } if (location != null) { notifyGpsLocationRecovered(); } // if continuous notify about lost location if (continuous) { scheduleCheckIfGpsLost(location); } START app.getSavingTrackHelper().updateLocation(location, app.getLocationProvider().heading); END OsmandPlugin.updateLocationPlugins(location); app.getRoutingHelper().updateLocation(location); app.getWaypointHelper().locationChanged(location); } app.getLocationProvider() ?

Target:
public void setLocationFromService(net.osmand.Location location, boolean continuous) { if (locationSimulation.isRouteAnimating()) { return; } if (location != null) { notifyGpsLocationRecovered(); } // if continuous notify about lost location if (continuous) { scheduleCheckIfGpsLost(location); } app.getSavingTrackHelper().updateLocation(location, heading); OsmandPlugin.updateLocationPlugins(location); app.getRoutingHelper().updateLocation(location); app.getWaypointHelper().locationChanged(location); }
Source:
LatLon getWorkPointLatLon() { LatLon workPointLatLon; if (hasWorkPoint()) { workPointLatLon = new LatLon(getWorkPoint().getLatitude(), getWorkPoint().getLongitude()); } else { START workPointLatLon = new LatLon(0, 0); END } return workPointLatLon; } If there is no point - return null

Target:
public LatLon getWorkPointLatLon() { LatLon workPointLatLon; if (hasWorkPoint()) { workPointLatLon = new LatLon(getWorkPoint().getLatitude(), getWorkPoint().getLongitude()); } else { workPointLatLon = null; } return workPointLatLon; }
Source:
public void onSensorChanged(SensorEvent event) { if (event.sensor.getType() == Sensor.TYPE_PROXIMITY) { if (event.values[0] >= -SENSOR_SENSITIVITY && event.values[0] <= SENSOR_SENSITIVITY) { START if (isSensorEnabled()) { END unlockEvent(); } } } } Such check must be at top of the method

Target:
public void onSensorChanged(SensorEvent event) { if (event.sensor.getType() == Sensor.TYPE_PROXIMITY) { if (event.values[0] >= -SENSOR_SENSITIVITY && event.values[0] <= SENSOR_SENSITIVITY) { unlockEvent(); } } }
Source:
START public static boolean removeAidlCallback (long id){ END return callbacks.remove(id) != null; } no static

Target:
public boolean removeAidlCallback(long id) { for (Long key : callbacks.keySet()) { if (key == id) { callbacks.remove(id); return true; } } return false; }
Source:
START private void onUpgrade(SQLiteConnection db, int oldVersion, int newVersion) { END db.execSQL("DROP TABLE IF EXISTS " + MARKERS_TABLE_NAME); db.execSQL("DROP TABLE IF EXISTS " + GROUPS_TABLE_NAME); onCreate(db); } So after upgrade we drop all existing markers?

Target:
private void onUpgrade(SQLiteConnection db, int oldVersion, int newVersion) { }
Source:
public Set<String> getSelectedPoiFilters() { Set<String> result = new LinkedHashSet<>(); String filtersId = SELECTED_POI_FILTER_FOR_MAP.get(); START if (filtersId != null) END Collections.addAll(result, filtersId.split(",")); return result; } Codestyle

Target:
public Set<String> getSelectedPoiFilters() { Set<String> result = new LinkedHashSet<>(); String filtersId = SELECTED_POI_FILTER_FOR_MAP.get(); if (filtersId != null) { Collections.addAll(result, filtersId.split(",")); } return result; }
Source:
public boolean checkMeasurementPointSize(int radius){ //check if proposed change to measurement point display size is within defined range START if(radius <= maxMeasurementPointRadius && radius >= minMeasurementPointRadius){ END return true; }else{ return false; } } return (radius <= maxMeasurementPointRadius && radius >= minMeasurementPointRadius);

Target:
public boolean checkMeasurementPointSize(int radius){ //check if proposed change to measurement point display size is within defined range return radius <= maxMeasurementPointRadius && radius >= minMeasurementPointRadius; }
Source:
private static int readIntFromByteChannel(ReadableByteChannel channel) { ByteBuffer intBuffer = ByteBuffer.allocate(INT_BYTES); int result = -1; try { while (intBuffer.hasRemaining() && (channel.read(intBuffer) >= 0)) { } if (!intBuffer.hasRemaining()) { intBuffer.rewind(); result = intBuffer.asIntBuffer().get(0); } } catch (Exception ignored) { START } END return result; } Let's just throw this exception to the caller than catch it here.

Target:
private static int readIntFromByteChannel(ReadableByteChannel channel) throws IOException { ByteBuffer intBuffer = ByteBuffer.allocate(INT_BYTES); int result = -1; while (intBuffer.hasRemaining() && (channel.read(intBuffer) >= 0)) { } if (!intBuffer.hasRemaining()) { intBuffer.rewind(); result = intBuffer.asIntBuffer().get(0); } return result; }
Source:
public String getPath() { try { URL url = new URL(getUrl()); return url.getPath(); } catch (MalformedURLException e) { START return ""; END } } are you sure this is the best way to handle this exception?

Target:
public String getPath() { try { URL url = new URL(getUrl()); return url.getPath(); } catch (MalformedURLException e) { return getUrl(); } }
Source:
public String getProperty(String key) { if (properties != null && !properties.isEmpty()) { if (properties.containsKey(key)) { return properties.get(key); } else { String key_prefixed = TargetConstants.PREFIX_CUSTOM_PROPERTY + key; if (properties.containsKey(key_prefixed)) { return properties.get(key_prefixed); } } } START return ""; END } Why return empty string instead of null?

Target:
public String getProperty(String key) { if (properties != null && !properties.isEmpty()) { if (properties.containsKey(key)) { return properties.get(key); } else { String key_prefixed = TargetConstants.PREFIX_CUSTOM_PROPERTY + key; if (properties.containsKey(key_prefixed)) { return properties.get(key_prefixed); } } } return null; }
Source:
public static boolean sleep(SleepCondition conn, int timeout, int minimumTimeout) { long start = System.currentTimeMillis(); START if(!sleep(conn, timeout)) return false; END long t; if((t = System.currentTimeMillis() - start) < minimumTimeout) { Time.sleep((int)(minimumTimeout - t)); } return true; } Please use brackets: ``` if(!sleep(conn, timeout)) { return false; } ```

Target:
public static boolean sleep(SleepCondition conn, int timeout, int minimumTimeout) { long start = System.currentTimeMillis(); if(!sleep(conn, timeout)) { return false; } long t; if((t = System.currentTimeMillis() - start) < minimumTimeout) { Time.sleep((int)(minimumTimeout - t)); } return true; }
Source:
public int compareTo(ServerDescription o) { START if (this.getServerName().equalsIgnoreCase(o.getServerName())) END return 1; return this.getServerName().compareTo(o.getServerName()); } Can you use brackets (`{ }`)

Target:
public int compareTo(ServerDescription o) { if (this.getServerName().equalsIgnoreCase(o.getServerName())) { return 1; } return this.getServerName().compareTo(o.getServerName()); }
Source:
public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { this.className = name; super.visit(version, access, name, signature, superName, interfaces); START if(class_out != null) END class_out.println(className + " References:"); } Missing a bracket.

Target:
public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { this.className = name; super.visit(version, access, name, signature, superName, interfaces); if(class_out != null) { class_out.println(className + " References:"); } }
Source:
public static MongoInstitution getInstance(final Authenticator authenticator) { MongoInstitution result = instance; if (result == null) { synchronized (MongoInstitution.class) { if (result == null) { START result = instance; END instance = result = new MongoInstitution(); result.auth = authenticator; } } } return result; } Why is this defined and then changed on the next line?

Target:
public static MongoInstitution getInstance(final Authenticator authenticator) { MongoInstitution result = instance; if (result == null) { synchronized (MongoInstitution.class) { if (result == null) { instance = result = new MongoInstitution(); result.auth = authenticator; } } } return result; }
Source:
private MongoInstitution(final String url) { MongoClient mongoClient = null; try { mongoClient = new MongoClient(url); } catch (UnknownHostException e) { START LOG.info(LoggingConstants.EXCEPTION_MESSAGE, e); END } if (mongoClient == null) { return; } database = mongoClient.getDB(DATABASE); } this should be error

Target:
private MongoInstitution(final String url) { MongoClient mongoClient = null; try { mongoClient = new MongoClient(url); } catch (UnknownHostException e) { LOG.error(LoggingConstants.EXCEPTION_MESSAGE, e); } if (mongoClient == null) { return; } database = mongoClient.getDB(DATABASE); }
Source:
public final void connectServers(final AbstractServerWebSocketHandler parent) { try { createAndAddConnection(parent, isConnectionLocal(), "srl02.tamu.edu", PORT, this.isSecure(), SubmissionClientWebSocket.class); } catch (ConnectionException e) { START LOG.info(LoggingConstants.EXCEPTION_MESSAGE, e); END } } change to error

Target:
public final void connectServers(final AbstractServerWebSocketHandler parent) { try { createAndAddConnection(parent, isConnectionLocal(), "srl02.tamu.edu", PORT, this.isSecure(), SubmissionClientWebSocket.class); } catch (ConnectionException e) { LOG.error(LoggingConstants.EXCEPTION_MESSAGE, e); } }
Source:
public void getExperimentAsUser(final String userId, final String problemId, final String sessionInfo, final MultiConnectionManager internalConnections) throws DatabaseAccessException { START LOG.info("Getting experiment for user: {}", userId); END LOG.info("Problem: {}", problemId); SubmissionManager.mongoGetExperiment(getInstance().database, userId, problemId, sessionInfo, internalConnections); } change this to debug.

Target:
public void getExperimentAsUser(final String userId, final String problemId, final String sessionInfo, final MultiConnectionManager internalConnections) throws DatabaseAccessException { LOG.debug("Getting experiment for user: {}", userId); LOG.info("Problem: {}", problemId); SubmissionManager.mongoGetExperiment(getInstance().database, userId, problemId, sessionInfo, internalConnections); }
Source:
private int checkGPS() { LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE); service.addGpsStatusListener(this); short gpsStatus = 0; boolean enabled = service .isProviderEnabled(LocationManager.GPS_PROVIDER); if (!enabled) gpsStatus = MainScreenActivity.GPS_NOT_ENABLED; else if (isConnected && (mLastRecordedLocation == null || mLastRecordedLocation .getAccuracy() > MyLocationListener.REQUIRED_ACCURACY)) gpsStatus = MainScreenActivity.NO_GPS_SIGNAL; else gpsStatus = MainScreenActivity.GPS_WORKING; START Database db = new Database(this); END return gpsStatus; } usuń tooooOoOoOo :D

Target:
private int checkGPS() { LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE); service.addGpsStatusListener(this); short gpsStatus = 0; boolean enabled = service .isProviderEnabled(LocationManager.GPS_PROVIDER); if (!enabled) { gpsStatus = MainScreenActivity.GPS_NOT_ENABLED; } else if (isConnected && (mLastRecordedLocation == null || mLastRecordedLocation .getAccuracy() > MyLocationListener.REQUIRED_ACCURACY)) { gpsStatus = MainScreenActivity.NO_GPS_SIGNAL; } else { gpsStatus = MainScreenActivity.GPS_WORKING; } return gpsStatus; }
Source:
private List<SingleRun> readfromDB() { Database db = new Database(this); List<SingleRun> runs; runs = db.getAllRuns(); START SingleRun[] run_data = new SingleRun[0]; END return runs; } to chyba już niepotrzebne?

Target:
private List<SingleRun> readfromDB() { Database db = new Database(this); List<SingleRun> runs; runs = db.getAllRuns(); return runs; }
Source:
public NettyHttpRequestWrapper(HttpRequest httpRequest) { checkNotNull(httpRequest); START this.httpRequest = httpRequest; END } Note you can put these on one line: `this.httpRequest = checkNotNull(httpRequest);` This can improve readability when there are several arguments (and helps you spot unchecked arguments).

Target:
public NettyHttpRequestWrapper(HttpRequest httpRequest) { this.httpRequest = checkNotNull(httpRequest); }
Source:
START public AsyncContext startAsync() throws IllegalStateException { END throw new UnsupportedOperationException(); } Java lets you drop `throws` arguments from implemented methods if the implemented method doesn't throw that exception, so you could drop this `throws` if you want and it would still compile ok.

Target:
public AsyncContext startAsync() { throw new UnsupportedOperationException(); }
Source:
private List<Future<Void>> executeTasksConcurrently(final List<ConcurrentTestWorker> testWorkers) throws InterruptedException { ExecutorService service = Executors.newFixedThreadPool(tasks.size()); START final List<Future<Void>> futures = service END .invokeAll(testWorkers, iterationTimeoutSeconds * iterations, TimeUnit.SECONDS); service.shutdown(); return futures; } ![CRITICAL](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/severity-critical.png) Result of integer multiplication cast to long in org.sonatype.sisu.litmus.testsupport.concurrent.ConcurrentRunner.executeTasksConcurrently(List) [![rule](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/rule.png)](http://nemo.sonarqube.org/coding_rules#rule_key=findbugs%3AICAST_INTEGER_MULTIPLY_CAST_TO_LONG)

Target:
private List<Future<Void>> executeTasksConcurrently(final List<ConcurrentTestWorker> testWorkers) throws InterruptedException { ExecutorService service = Executors.newFixedThreadPool(tasks.size()); final List<Future<Void>> futures = service .invokeAll(testWorkers, (long) iterationTimeoutSeconds * iterations, TimeUnit.SECONDS); service.shutdown(); return futures; }
Source:
public void blockPorts(final Range<Integer> blockedRange) { checkNotNull(blockedRange); START synchronized (reservedPorts) { END this.blockedPortRanges.add(blockedRange); } } might be more readable to mark the relevant methods as `synchronized` rather than use an arbitrary member for locking

Target:
public synchronized void blockPorts(final Range<Integer> blockedRange) { checkNotNull(blockedRange); this.blockedPortRanges.add(blockedRange); }
Source:
public void forceHealthChecks() { for (HealthCheck healthCheck : _badEndPoints.values()) { START healthCheck.run(); END } } Due to the nature of `run()`, this will potentially cause duplicate health check runs to be scheduled.

Target:
void forceHealthChecks() { for (HealthCheck healthCheck : _badEndPoints.values()) { healthCheck.run(); } }
Source:
public <T> Gauge<T> gauge(String name, Gauge<T> gauge) { checkNotNullOrEmpty(name); checkNotNull(gauge); // Unfortunately register doesn't call getOrAdd (probably a bug in metrics), and instead goes through // a code path that throws an exception if this metric already exists. String fullName = name(name); START Gauge<T> metric = (Gauge<T>) _metrics.get(fullName); END if (metric == null) { metric = _registry.register(fullName, gauge); } return metric; } Is this thread-safe?

Target:
public synchronized <T> Gauge<T> gauge(String name, Gauge<T> gauge) { checkNotNullOrEmpty(name); checkNotNull(gauge); // Unfortunately register doesn't call getOrAdd (probably a bug in metrics), and instead goes through // a code path that throws an exception if this metric already exists. String fullName = name(name); Gauge<T> metric = (Gauge<T>) _metrics.get(fullName); if (metric == null) { metric = _registry.register(fullName, gauge); } return metric; }
Source:
public ZooKeeperServiceRegistry(ZooKeeperConnection connection) { checkNotNull(connection); CuratorFramework curator = ((CuratorConnection) connection).getCurator(); checkNotNull(curator); START checkArgument(curator.isStarted()); END _zooKeeperConnection = connection; } We probably don't need to check that it's started anymore since we take a ZooKeeperConnection now, so we can get rid of this and the previous two lines.

Target:
public ZooKeeperServiceRegistry(ZooKeeperConnection connection) { checkNotNull(connection); _zooKeeperConnection = connection; }
Source:
private String getTestJavaCommandPath() { START return new File(testJDKHome, "bin/java").getAbsolutePath(); END } may explode if the parameter is null

Target:
private String getTestJavaCommandPath() { if(testJDKHome==null) { return null; } return new File(testJDKHome, "bin/java").getAbsolutePath(); }
Source:
public boolean check(Map<String, Object> info) throws Exception { START return BlueOceanHook.isBOPlugin(info) || DeclarativePipelineHook.isDPPlugin(info) END || StructsHook.isStructsPlugin(info) || HaHook.isHaPlugin(info); } This is starting to get out of control, I do not really like the idea of having to add here every plugin but I understand that is for a follow up pr so I have created [JENKINS-49367](https://issues.jenkins-ci.org/browse/JENKINS-49367)

Target:
public boolean check(Map<String, Object> info) throws Exception { return BlueOceanHook.isBOPlugin(info) || DeclarativePipelineHook.isDPPlugin(info) || StructsHook.isStructsPlugin(info); }
Source:
public final @Nonnull Stream<OWLAxiom> axiomBase() { Stream<OWLAxiom> toReturn = axiomBase.stream(); toReturn = Stream.concat(tautologies.stream().flatMap(Set::stream), toReturn); START return axiomBase.stream(); END } Was this the intention? globals is no longer involved and the stream creation with tautologies and base axioms is unused

Target:
public final @Nonnull Stream<OWLAxiom> axiomBase() { return axiomBase.stream(); }
Source:
private void setEntityStatus(Entity entity, MachinePoolMemberStatus status) { START checkNotNull(entity, "What?"); END ((EntityInternal) entity).setAttribute(SERVER_STATUS, status); } Better message, such as `checkNotNull(entity, "entity")`

Target:
private void setEntityStatus(Entity entity, MachinePoolMemberStatus status) { ((EntityInternal) entity).setAttribute(SERVER_STATUS, status); }
Source:
protected void assertNoMachinesAvailableForApp(TestApplication app) { try { app.start(ImmutableList.of(pool.getDynamicLocation())); fail("Expected exception when starting app with too many entities for pool"); } catch (Exception e) { START Throwable t = Exceptions.getFirstThrowableOfType(e, NoMachinesAvailableException.class); END assertTrue(t != null, "expected " + NoMachinesAvailableException.class.getName() + " to be thrown, not found in " + e); } } I generally do `if (t == null) throw e` or some such, so we get the full stacktrace of the exception if it was an unexpected one.

Target:
protected void assertNoMachinesAvailableForApp(TestApplication app) { try { app.start(ImmutableList.of(pool.getDynamicLocation())); fail("Expected exception when starting app with too many entities for pool"); } catch (Exception e) { Throwable t = Exceptions.getFirstThrowableOfType(e, NoMachinesAvailableException.class); if (t == null) { throw new RuntimeException(e); } } }
Source:
protected EntitySpec<?> getMemberSpec() { @SuppressWarnings("unchecked") EntitySpec<ElasticSearchNode> spec = (EntitySpec<ElasticSearchNode>)getConfig(MEMBER_SPEC, EntitySpec.create(ElasticSearchNode.class)); START spec.configure(ElasticSearchNode.CLUSTER_NAME, getConfig(ElasticSearchClusterImpl.CLUSTER_NAME)) END .configure(ElasticSearchNode.NODE_NAME, "elasticsearch-" + nextMemberId.incrementAndGet()); return spec; } Don't modify the spec object retrieved from the config. Instead copy it. Otherwise this can modify the default value of MEMBER_SPEC, or of inherited config that might be shared by multiple instances.

Target:
protected EntitySpec<?> getMemberSpec() { EntitySpec<?> spec = EntitySpec.create(getConfig(MEMBER_SPEC, EntitySpec.create(ElasticSearchNode.class))); spec.configure(ElasticSearchNode.CLUSTER_NAME, getConfig(ElasticSearchClusterImpl.CLUSTER_NAME)) .configure(ElasticSearchNode.NODE_NAME, "elasticsearch-" + nextMemberId.incrementAndGet()); return spec; }
Source:
public Map<String, String> getShellEnvironment() { MutableMap<String, String> result = MutableMap.copyOf(super.getShellEnvironment()); // how to change epmd port, according to // http://serverfault.com/questions/582787/how-to-change-listening-interface-of-rabbitmqs-epmd-port-4369 START result.put("ERL_EPMD_PORT", "" + getEntity().getEpmdListenerPort()); END return result; } Use `Integer.toString(getEntity().getEpmdListenerPort())` rather than automagic coercion with String addition.

Target:
public Map<String, String> getShellEnvironment() { MutableMap<String, String> result = MutableMap.copyOf(super.getShellEnvironment()); // how to change epmd port, according to // http://serverfault.com/questions/582787/how-to-change-listening-interface-of-rabbitmqs-epmd-port-4369 result.put("ERL_EPMD_PORT", "" + Integer.toString(getEntity().getEpmdListenerPort())); return result; }
Source:
private Boolean hasJoinedCluster() { START return Optional.fromNullable(entity.getAttribute(RiakNode.RIAK_NODE_HAS_JOINED_CLUSTER)).or(Boolean.FALSE); END } call `getEntity().hasJoinedCluster()` after moving code to `RiakNode` as mentioned above

Target:
private Boolean hasJoinedCluster() { return ((RiakNode) entity).hasJoinedCluster(); }
Source:
public static <T> Predicate<Location> isChildOf(final Location parent) { return new Predicate<Location>() { @Override START public boolean apply(@Nullable Location input) { END return Objects.equal(input.getParent(), parent); } }; } Actually this _isn't_ `@Nullable` so should either remove the annotation or add a guard that returns `false`.

Target:
public static <T> Predicate<Location> isChildOf(final Location parent) { return new Predicate<Location>() { @Override public boolean apply(@Nullable Location input) { return (input != null) && Objects.equal(input.getParent(), parent); } }; }
Source:
public static <T> Predicate<Location> displayNameEqualTo(final T val) { return new Predicate<Location>() { @Override START public boolean apply(@Nullable Location input) { END return Objects.equal(input.getDisplayName(), val); } }; } `input` is not `@Nullable`, remove annotation or add null check.

Target:
public static <T> Predicate<Location> displayNameEqualTo(final T val) { return new Predicate<Location>() { @Override public boolean apply(@Nullable Location input) { return (input != null) && Objects.equal(input.getDisplayName(), val); } }; }
Source:
public static <T> Predicate<Location> idEqualTo(final T val) { return new Predicate<Location>() { @Override START public boolean apply(@Nullable Location input) { END return Objects.equal(input.getId(), val); } }; } `input` is not `@Nullable`, remove annotation or add null check.

Target:
public static <T> Predicate<Location> idEqualTo(final T val) { return new Predicate<Location>() { @Override public boolean apply(@Nullable Location input) { return (input != null) && Objects.equal(input.getId(), val); } }; }
Source:
public static <T> TypeToken<T> getTypeToken(TypeToken<T> token, Class<? super T> raw) { if (raw!=null) return TypeToken.of((Class<T>)raw); START if (token!=null) return token; END throw new IllegalStateException("Both indicators of type are null"); } Should this not prefer the token over the raw?

Target:
public static <T> TypeToken<T> getTypeToken(TypeToken<T> token, Class<? super T> raw) { if (token!=null) return token; if (raw!=null) return TypeToken.of((Class<T>)raw); throw new IllegalStateException("Both indicators of type are null"); }
Source:
public void pillowfight(String targetHostnameAndPort, String bucket, String username, String password, Integer iterations, Integer numItems, String keyPrefix, Integer numThreads, Integer numInstances, Integer randomSeed, Integer ratio, Integer minSize, Integer maxSize) { START ((CouchbaseLoadGeneratorDriver)getDriver()).pillowfight(targetHostnameAndPort, bucket, username, password, END iterations, numItems, keyPrefix, numThreads, numInstances, randomSeed, ratio, minSize, maxSize); } Can also add a `getDriver()` override that returns a cast of `super.getDriver()` to make this look neater

Target:
public void pillowfight(String targetHostnameAndPort, String bucket, String username, String password, Integer iterations, Integer numItems, String keyPrefix, Integer numThreads, Integer numInstances, Integer randomSeed, Integer ratio, Integer minSize, Integer maxSize) { getDriver().pillowfight(targetHostnameAndPort, bucket, username, password, iterations, numItems, keyPrefix, numThreads, numInstances, randomSeed, ratio, minSize, maxSize); }
Source:
public static File mkdirs(File dir) { if (dir.isDirectory()) return dir; boolean success = dir.mkdirs(); if (!success) { // A race condition can cause dir.mkdirs() to return false if the dir has been created on a separate thread // since the initial check above if (dir.isDirectory()) return dir; throw Exceptions.propagate(new IOException("Failed to create directory " + dir + (dir.isFile() ? "(is file)" : ""))); START } END return dir; } Could eliminate the duplication by always attempting `dir.mkdirs()`: ``` dir.mkdirs(); // don't care if this succeeds or fails if (dir.isDirectory()) return dir; throw ... ```

Target:
public static File mkdirs(File dir) { dir.mkdirs(); if (dir.isDirectory()) { return dir; } throw Exceptions.propagate(new IOException("Failed to create directory " + dir + (dir.isFile() ? "(is file)" : ""))); }
Source:
public int execute(List<String> script, String summaryForLogging) { if (failExecution) { throw new TestException("Simulated driver exception"); } START return super.execute(script, summaryForLogging); END } Could simply `return 0` here, rather than relying on SSH. Arguably not necessary to restrict this to `Integration` tests once we've weeded-out SSH.

Target:
public int execute(List<String> script, String summaryForLogging) { if (failExecution) { throw new TestException("Simulated driver exception"); } return 0; }
Source:
public void setup() throws Exception { DynamicSequentialTask<Object> t = new DynamicSequentialTask<Object>(); START DynamicTasks.setTaskQueueingContext(t); END app = ApplicationBuilder.newManagedApp(TestApplication.class); mgmt = app.getManagementContext(); LocalhostMachineProvisioningLocation localhost = mgmt.getLocationManager().createLocation( LocationSpec.create(LocalhostMachineProvisioningLocation.class)); host = localhost.obtain(); app.start(Arrays.asList(host)); } Not a good idea -- this sets a thread local so could interfere with other tests. Also I suspect `DynamicTasks.queue(anotherTask)` won't run `anotherTask` because the `TaskQueueingContext t` here is never submitted to an executor. (Another reason to let getMachineDetails fail gracefully if used from outwith a TQC or `executionContext`.)

Target:
public void setup() throws Exception { app = ApplicationBuilder.newManagedApp(TestApplication.class); mgmt = app.getManagementContext(); LocalhostMachineProvisioningLocation localhost = mgmt.getLocationManager().createLocation( LocationSpec.create(LocalhostMachineProvisioningLocation.class)); host = localhost.obtain(); app.start(Arrays.asList(host)); }
Source:
public MachineDetails getMachineDetails() { MachineDetails details = machineDetails; if (details == null) { // Or could just load and store several times Tasks.setBlockingDetails("Waiting for machine details"); synchronized (machineDetailsLock) { details = machineDetails; if (details == null) { machineDetails = details = BasicMachineDetails.forSshMachineLocation(this); } } START Tasks.resetBlockingDetails(); END } return details; } do the reset in a finally block.

Target:
public MachineDetails getMachineDetails() { MachineDetails details = machineDetails; if (details == null) { // Or could just load and store several times Tasks.setBlockingDetails("Waiting for machine details"); try { synchronized (machineDetailsLock) { details = machineDetails; if (details == null) { machineDetails = details = BasicMachineDetails.forSshMachineLocation(this); } } } finally { Tasks.resetBlockingDetails(); } } return details; }
Source:
public void reloadBrooklynProperties() { log.info("Reloading brooklyn properties from " + builder); BrooklynProperties properties = builder.build(); configMap = properties; if (brooklynAdditionalProperties != null) { log.info("Reloading additional brooklyn properties from " + brooklynAdditionalProperties); configMap.addFromMap(brooklynAdditionalProperties); } this.downloadsManager = BasicDownloadsManager.newDefault(configMap); // Force reload of location registry this.locationRegistry = null; // Notify listeners that properties have been reloaded for (PropertiesReloadListener listener : reloadListeners) { START if (listener != null) END listener.reloaded(); } } Better to prevent null in the first place; i.e. fail early in the `addPropertiesReloadListener` with: ``` `import static com.google.common.base.Preconditions.checkNotNull;` `reloadListeners.add(checkNotNull(listener, "listener"));` ```

Target:
public void reloadBrooklynProperties() { log.info("Reloading brooklyn properties from " + builder); BrooklynProperties properties = builder.build(); configMap = properties; if (brooklynAdditionalProperties != null) { log.info("Reloading additional brooklyn properties from " + brooklynAdditionalProperties); configMap.addFromMap(brooklynAdditionalProperties); } this.downloadsManager = BasicDownloadsManager.newDefault(configMap); // Force reload of location registry this.locationRegistry = null; // Notify listeners that properties have been reloaded for (PropertiesReloadListener listener : reloadListeners) { listener.reloaded(); } }
Source:
public static Throwable getError(Task<?> t) { if (t==null) return null; if (!t.isDone()) return null; if (t.isCancelled()) return new CancellationException(); try { t.get(); return null; } catch (Throwable error) { START Exceptions.propagateIfFatal(error); END return error; } } I don't think we want to propagate the exception in this thread. We just want to return the throwable. It wasn't this thread that had the error.

Target:
public static Throwable getError(Task<?> t) { if (t==null) return null; if (!t.isDone()) return null; if (t.isCancelled()) return new CancellationException(); try { t.get(); return null; } catch (Throwable error) { // do not propagate as we are pretty much guaranteed above that it wasn't this // thread which originally threw the error return error; } }
Source:
protected void handleGenerateMementoException(Exception e, String context) { Exceptions.propagateIfFatal(e); if (isActive()) { LOG.warn("Problem generating memento for "+context, e); } else { START Exceptions.propagateIfFatal(e); END LOG.debug("Problem generating memento for "+context+", but no longer active (ignoring)", e); } } already done this 3 lines up!

Target:
protected void handleGenerateMementoException(Exception e, String context) { Exceptions.propagateIfFatal(e); if (isActive()) { LOG.warn("Problem generating memento for "+context, e); } else { LOG.debug("Problem generating memento for "+context+", but no longer active (ignoring)", e); } }
Source:
public void setManagementContext(ManagementContextInternal val) { if (val == null && (val instanceof NonDeploymentManagementContext)) { START System.out.println("fafe"); END } this.initialManagementContext = checkNotNull(val, "initialManagementContext"); this.entityManager = new NonDeploymentEntityManager(val); this.locationManager = new NonDeploymentLocationManager(val); this.accessManager = new NonDeploymentAccessManager(val); this.usageManager = new NonDeploymentUsageManager(val); } Delete this - it was just there during debugging.

Target:
public void setManagementContext(ManagementContextInternal val) { this.initialManagementContext = checkNotNull(val, "initialManagementContext"); this.entityManager = new NonDeploymentEntityManager(val); this.locationManager = new NonDeploymentLocationManager(val); this.accessManager = new NonDeploymentAccessManager(val); this.usageManager = new NonDeploymentUsageManager(val); }
Source:
public void setOrigin(BigInteger shift) { START Preconditions.checkNotNull(shift, "shift"); END this.origin = shift; } I'd do: `this.origin = checkNotNull(shift, "shift");` Note I like using static imports for this. We and others use it so much that static imports are clear enough (same goes for things like `Assert.assertTrue` in tests).

Target:
public void setOrigin(BigInteger shift) { this.origin = Preconditions.checkNotNull(shift, "shift"); }
Source:
public FunctionPollConfig<S, T> supplier(final Supplier<? extends S> val) { checkNotNull(val, "supplier"); this.callable = new Callable<S>() { @Override public S call() throws Exception { START return (S) val.get(); END } }; return this; } Do you really have to cast? Am I missing something? No strong feelings.

Target:
public FunctionPollConfig<S, T> supplier(final Supplier<? extends S> val) { checkNotNull(val, "supplier"); this.callable = new Callable<S>() { @Override public S call() throws Exception { return val.get(); } }; return this; }
Source:
public Map<String, String> getShellEnvironment() { Map<String, String> orig = super.getShellEnvironment(); String kafkaJmxOpts = orig.remove("JAVA_OPTS"); START if (Strings.isBlank(kafkaJmxOpts)) kafkaJmxOpts = " "; // FIXME - this is required to prevent jmxremote being setup in bin/kafka-run-class.sh END return MutableMap.<String, String>builder() .putAll(orig) .putIfNotNull("KAFKA_JMX_OPTS", kafkaJmxOpts) .build(); } This line isn't required. It was just a temporary hack to disable kafka-zookeeper jmx.

Target:
public Map<String, String> getShellEnvironment() { Map<String, String> orig = super.getShellEnvironment(); String kafkaJmxOpts = orig.remove("JAVA_OPTS"); return MutableMap.<String, String>builder() .putAll(orig) .putIfNotNull("KAFKA_JMX_OPTS", kafkaJmxOpts) .build(); }
Source:
START void close() throws IOException { END client.close(); } Why not have this implement `Closeable`, out of interest?

Target:
public void close() throws IOException { client.close(); }
Source:
public void testEqualsDifferentTypes() { List<Object> a = MutableList.<Object>of("a", 1, "b", false); List<Object> b = Arrays.<Object>asList("a", 1, "b", false); START Assert.assertEquals(a, b); END } I'd also do `assertEquals(b, a)`. We can probably rely on a sensible impl of assertEquals that it will do `firstArg.equals(secondArg)` but just in case...

Target:
public void testEqualsDifferentTypes() { List<Object> a = MutableList.<Object>of("a", 1, "b", false); List<Object> b = Arrays.<Object>asList("a", 1, "b", false); Assert.assertEquals(a, b); Assert.assertEquals(b, a); }
Source:
public Task<?> expunge(final Entity entity, final boolean release) { return mgmt.getExecutionManager().submit( MutableMap.of("displayName", "expunging " + entity, "description", "REST call to expunge entity " + entity.getDisplayName() + " (" + entity + ")"), new Runnable() { @Override public void run() { if (release) START Entities.destroyCatching(entity); END mgmt.getEntityManager().unmanage(entity); } }); } When I did expunge(true) on a jboss7 entity, I saw logging of: ``` 2014-01-28 22:18:47,089 WARN brooklyn.management.internal.LocalEntityManager@2524e205 call to stop management of unknown entity (already unmanaged?) JBoss7ServerImpl{id=mPXYvab1}; skipping, and all descendants ``` This is because Entities.destroyCatching will also unmanage. So you want an if-else, to only do the `mgmt.getEntityManager().unmanage(entity)` in the else block.

Target:
public Task<?> expunge(final Entity entity, final boolean release) { return mgmt.getExecutionManager().submit( MutableMap.of("displayName", "expunging " + entity, "description", "REST call to expunge entity " + entity.getDisplayName() + " (" + entity + ")"), new Runnable() { @Override public void run() { if (release) Entities.destroyCatching(entity); else mgmt.getEntityManager().unmanage(entity); } }); }
Source:
protected List<String> initialKnifeParameters() { START MutableList<String> result = new MutableList<String>(); END result.add("node"); result.add("show"); result.add("-l"); result.add(nodeName); result.add("--format"); result.add("json"); return result; } I'd go for: `return ImmutableList.of("node", "show", "-l", nodeName, "--format", "json")`

Target:
protected List<String> initialKnifeParameters() { return ImmutableList.of("node", "show", "-l", nodeName, "--format", "json"); }
Source:
public void onFailure(SshPollValue val) { START log.error("Chef attribute query did not respond as expected. exitcode={} stdout={} stderr={}", new Object[]{val.getExitStatus(), val.getStdout(), val.getStderr()}); END for (AttributeSensor attribute : chefAttributeSensors) { if (!attribute.getName().startsWith(CHEF_ATTRIBUTE_PREFIX)) continue; entity.setAttribute(attribute, null); } } Again suggesting giving more info (e.g. what we tried to connect to). Hopefully stderr will be very helpful though!

Target:
public void onFailure(SshPollValue val) { log.error("Chef attribute query did not respond as expected. exitcode={} stdout={} stderr={}", new Object[]{val.getExitStatus(), val.getStdout(), val.getStderr()}); for (AttributeSensor attribute : chefAttributeSensors.values()) { if (!attribute.getName().startsWith(CHEF_ATTRIBUTE_PREFIX)) continue; entity.setAttribute(attribute, null); } }
Source:
public static Status statusFromLifecycle(Lifecycle state) { if (state == null) return UNKNOWN; switch (state) { case CREATED: return ACCEPTED; case STARTING: return STARTING; case RUNNING: return RUNNING; case STOPPING: return STOPPING; case STOPPED: return STOPPED; case DESTROYED: START return TERMINATED; END case ON_FIRE: default: return UNKNOWN; } } this really does feel wrong. :)

Target:
public static Status statusFromLifecycle(Lifecycle state) { if (state == null) return UNKNOWN; switch (state) { case CREATED: return ACCEPTED; case STARTING: return STARTING; case RUNNING: return RUNNING; case STOPPING: return STOPPING; case STOPPED: return STOPPED; case DESTROYED: return DESTROYED; case ON_FIRE: default: return UNKNOWN; } }
Source:
START public static Long ifPositive(Long time) { END if (time==null || time<=0) return null; return time; } I'd make this private rather than part of a public API. If we want it to be called by other things, it should be moved to an appropriate utility place (and perhaps renamed to make it clearer that it will return null if not positive).

Target:
private static Long ifPositive(Long time) { if (time==null || time<=0) return null; return time; }
Source:
public static RuntimeException propagate(Throwable throwable) { if (throwable instanceof InterruptedException) throw new RuntimeInterruptedException((InterruptedException) throwable); START if (throwable instanceof ExecutionException) END return Throwables.propagate(throwable.getCause()); return Throwables.propagate(throwable); } Yikes. I didn't see this before. Is it in master?! We shouldn't unwrap ExecutionException like this. It makes it look like the exception happened in this thread, rather than in the other thread. For example, if the other thread was interrupted then ExecutionException.getCause() will return an InterruptedException. Rethrowing the cause make it look like _this_ thread is being interrupted (and looks like the interrupt is being handled incorrectly, because it is just caught and wrapped without marking this thread as `Thread.interrupt()`.

Target:
public static RuntimeException propagate(Throwable throwable) { if (throwable instanceof InterruptedException) throw new RuntimeInterruptedException((InterruptedException) throwable); return Throwables.propagate(throwable); }
Source:
public static void propagateIfFatal(Throwable throwable) { if (throwable instanceof InterruptedException) throw new RuntimeInterruptedException((InterruptedException) throwable); if (throwable instanceof ExecutionException) START propagateIfFatal(throwable.getCause()); END if (throwable instanceof Error) throw (Error) throwable; } Again, we shouldn't do this.

Target:
public static void propagateIfFatal(Throwable throwable) { if (throwable instanceof InterruptedException) throw new RuntimeInterruptedException((InterruptedException) throwable); if (throwable instanceof Error) throw (Error) throwable; }
Source:
public void recordPublicIpHostname(String publicIpId, String hostnameOrPublicIpAddress) { START String old = publicIpIdToHostname.put(publicIpId, hostnameOrPublicIpAddress); END if (old!=null && !old.equals(hostnameOrPublicIpAddress)) log.warn("Changing hostname recorded against public IP "+publicIpId+"; from "+old+" to "+hostnameOrPublicIpAddress); } Needs to be a ConcurrentHashMap, or synchronization here (and in the getters etc).

Target:
public void recordPublicIpHostname(String publicIpId, String hostnameOrPublicIpAddress) { synchronized (publicIpIdToHostname) { String old = publicIpIdToHostname.put(publicIpId, hostnameOrPublicIpAddress); if (old!=null && !old.equals(hostnameOrPublicIpAddress)) log.warn("Changing hostname recorded against public IP "+publicIpId+"; from "+old+" to "+hostnameOrPublicIpAddress); } }
Source:
public BasicLocationDefinition(String id, String name, String spec, Map<String,? extends Object> config) { START this.id = id != null ? id : LanguageUtils.newUid(); END this.name = name; this.spec = Preconditions.checkNotNull(spec); this.config = config==null ? ImmutableMap.<String, Object>of() : ImmutableMap.<String, Object>copyOf(config); } Do we really want the LocationDefinition to generate the id if null is passed in? That will hide some programming errors. If we really want it, better to overload the constructor to have a version without the id parameter.

Target:
public BasicLocationDefinition(String id, String name, String spec, Map<String,? extends Object> config) { this.id = Preconditions.checkNotNull(id); this.name = name; this.spec = Preconditions.checkNotNull(spec); this.config = config==null ? ImmutableMap.<String, Object>of() : ImmutableMap.<String, Object>copyOf(config); }
Source:
public boolean accepts(String spec, LocationRegistry registry) { if (BasicLocationRegistry.isResolverPrefixForSpec(this, spec, true)) return true; START JcloudsSpecParser details = JcloudsSpecParser.parse(spec, false); END if (details==null) return false; if (details.isProvider() || details.isApi()) return true; return false; } Should this pass `true` for dryrun, when calling parse?

Target:
public boolean accepts(String spec, LocationRegistry registry) { if (BasicLocationRegistry.isResolverPrefixForSpec(this, spec, true)) return true; JcloudsSpecParser details = JcloudsSpecParser.parse(spec, true); if (details==null) return false; if (details.isProvider() || details.isApi()) return true; return false; }
Source:
public Map<ConfigKey<?>,Object> getLocalConfig() { START Map<ConfigKey<?>,Object> result = new LinkedHashMap<ConfigKey<?>,Object>(inheritedConfig.size()+ownConfig.size()); END result.putAll(ownConfig); return Collections.unmodifiableMap(result); } Initial size can be ownConfig.size() rather than `+inheritedConfig.size()`. And could create copy with with `return Collections.unmodifiableMap(Maps.newLinkedHashMap(ownConfig))`

Target:
public Map<ConfigKey<?>,Object> getLocalConfig() { Map<ConfigKey<?>,Object> result = new LinkedHashMap<ConfigKey<?>,Object>(ownConfig.size()); result.putAll(ownConfig); return Collections.unmodifiableMap(result); }
Source:
public ImmutableEntityType(Class<? extends Entity> clazz) { START super(clazz, null); END } Ok, I see why you want to pass in null. But instead would be better to have a super constructor that takes just class, so if someone calls the other constructor with a null entity instance we can fail fast.

Target:
public ImmutableEntityType(Class<? extends Entity> clazz) { super(clazz); }
Source:
public ListConfigKey(Class<V> subType, String name, String description, List<? extends V> defaultValue) { START super((Class)List.class, name, description, (List<? extends V>) defaultValue); END this.subType = subType; } Is the cast to `(List<? extends V>)` really needed? It looks the same as in the method signature.

Target:
public ListConfigKey(Class<V> subType, String name, String description, List<? extends V> defaultValue) { super((Class)List.class, name, description, defaultValue); this.subType = subType; }
Source:
START public TrustingSslSocketFactory() { END super(); try { sslContext.init(null, new TrustManager[] { TRUST_ALL }, null); } catch (Exception e) { throw Throwables.propagate(e); } } If treating as singleton (with static INSTANCE field etc), then should constructor be private?

Target:
protected TrustingSslSocketFactory() { super(); try { sslContext.init(null, new TrustManager[] { TRUST_ALL }, null); } catch (Exception e) { throw Throwables.propagate(e); } }
Source:
protected String getEntityVersionLabel(String separator) { return elvis(entity.getClass().getSimpleName(), START entity.getClass().getName())+(!getVersion().equals(NO_VERSION_INFO) ? separator+getVersion() : ""); END } Could getVersion ever return null?

Target:
protected String getEntityVersionLabel(String separator) { return elvis(entity.getClass().getSimpleName(), entity.getClass().getName())+(!NO_VERSION_INFO.equals(getVersion()) ? separator+getVersion() : ""); }
Source:
START public MachineSet all(Function<MachineSet, MachineSet> ...ops) { END return compose(ops).apply(getAllMachines()); } Seems strange to take a Function rather than a Predicate when matching a given criteria.

Target:
public MachineSet all(Function<MachineSet, MachineSet> ...ops) { return compose(ops).apply(all()); }
Source:
public MachineSet ensureExists(int count, ReusableMachineTemplate template) { MachineSet current; synchronized (this) { START current = all(matching(template)); END } if (current.size() >= count) return current; //have to create more MachineSet moreNeeded = create(count-current.size(), template); return current.added(moreNeeded); } Don't think this has to be synchronized. It does a volatile read under the covers. Or if it does need to be synchronized, then does that imply all other calls to all() need to be synchronized?!

Target:
public MachineSet ensureExists(int count, ReusableMachineTemplate template) { MachineSet current; current = all(matching(template)); if (current.size() >= count) return current; //have to create more MachineSet moreNeeded = create(count-current.size(), template); return current.added(moreNeeded); }
Source:
START public void remove(int id) { END locations.remove(id); } Perhaps return boolean to say if the id was found (similar semantics to Set.remove)?

Target:
public boolean remove(int id) { return locations.remove(id) != null; }
Source:
public Randomizer<?> getRandomizer(Field field) { EnhancedRandom enhancedRandom = EnhancedRandomBuilder.aNewEnhancedRandomBuilder() .seed(seed) START .dateRange(LocalDate.now().minusYears(Constants.DEFAULT_DATE_RANGE), LocalDate.now()) END .build(); return (() -> enhancedRandom.nextObject(field.getType())); } I think this delegate `enhancedRandom` can be a field and initialized in the constructor. This avoids creating it each time we call `getRandomizer`. Does this make sense?

Target:
public Randomizer<?> getRandomizer(Field field) { if (enhancedRandom == null) { enhancedRandom = EnhancedRandomBuilder.aNewEnhancedRandomBuilder() .seed(seed) .dateRange(LocalDate.now().minusYears(Constants.DEFAULT_DATE_RANGE), LocalDate.now()) .build(); } return () -> enhancedRandom.nextObject(field.getType()); }
Source:
protected List<E> getFilteredList() { List<E> filteredValues = new ArrayList<>(); Collections.addAll(filteredValues, enumeration.getEnumConstants()); START if (excludedValues != null) { END for (E element : excludedValues) { filteredValues.remove(element); } } return filteredValues; } this should be checked at construction time. don't create the object with an inconsistent state.

Target:
private List<E> getFilteredList() { List<E> filteredValues = new ArrayList<>(); Collections.addAll(filteredValues, enumeration.getEnumConstants()); if (excludedValues != null) { for (E element : excludedValues) { filteredValues.remove(element); } } return filteredValues; }