auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testAssumptionFailure( Failure failure ) { this.reporter.testAssumptionFailure( SimpleReportEntry.ignored( getClassName( failure.getDescription() ) , failure.getDescription().getDisplayName() , failure.getMessage() ) ); failureFlag.set( Boolean.TRUE ); }

Target:
@jimma Can you please introduce a new constructor `public SimpleReportEntry( String source, String name, String message )` and call it instead of `SimpleReportEntry.ignored`? Can you call that constructor in `SimpleReportEntry.ignored` as well? Thx.
Source:
public MockSCMSource build() { MockSCMSource source = controller == null ? new MockSCMSource(controllerId, repository, traits()) : new MockSCMSource(controller, repository, traits()); source.setId(id); return source; }

Target:
Perhaps make `id` optional for `MockSCMSourceBuilder` too.
Source:
public MockSCMSource build() { MockSCMSource source = controller == null ? new MockSCMSource(controllerId, repository, traits()) : new MockSCMSource(controller, repository, traits()); if (id != null) { source.setId(id()); } return source; }

Target:
harmless to call even if null, so could use `withId` IIUC
Source:
@Override protected void after() { tmp.delete(); }

Target:
Scm api has rules on the placement of annotations for methods
Source:
@Override public final String toString() { return sampleRepo.getAbsolutePath(); }

Target:
Annotations on wrong line
Source:
public static SCMHead readResolveSCMHead(@NonNull SCMSource source, @NonNull SCMHead head) { for (SCMHeadMigration m : ExtensionList.lookup(SCMHeadMigration.class)) { if (m.sourceClass.equals(source.getClass()) && m.headClass.equals(head.getClass())) { SCMHead migrated = m.migrate(source, head); if (migrated != null) { return migrated; } } } return head; }

Target:
Can use `==` for `Class`es.
Source:
public ChangeRequestSCMHeadCategory() { super("change-requests", Messages._ChangeRequestSCMHeadCategory_DisplayName()); }

Target:
Why is this in the `impl` package? Would not an SCM implementation wish to return this among others?
Source:
public <T extends Action> T getAction(@NonNull Class<T> type) { // TODO should be deleted but old versions of blue ocean api rely on this return ChangeRequestAction.class.equals(type) ? (T)new ChangeRequestAction(){} : null; }

Target:
No, I meant to actually implement the methods!
Source:
public List<Action> retrieveActions(@NonNull SCMNavigatorOwner owner, @CheckForNull SCMNavigatorEvent event, @NonNull TaskListener listener) throws IOException, InterruptedException { return Collections.emptyList(); }

Target:
I don't really see the difference between this and `fetchActions`? Maybe my speed reading isn't up to snuff?
Source:
@Override public SCMNavigator newInstance(String name) { return null; }

Target:
style guide
Source:
public void put(String URL, String key, String value) { if (parseMap.containsKey(URL)) { parseMap.get(URL).getMetadata().addValue(key, value); } else { ParseData parse = ParseData.empty; parse.put(key, value); parseMap.put(URL, parse); } }

Target:
isn't 'ParseData.empty' immutable?
Source:
public void setValues(String key, String[] values) { md.put(key, values); }

Target:
SHould we check that values is neither null nor empty?
Source:
public static NotificationCompat.Builder setSecretVisibility(NotificationCompat.Builder builder) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { return builder.setVisibility(Notification.VISIBILITY_SECRET).setPriority(Notification.PRIORITY_MIN); } return builder; }

Target:
Extract the Priority into a constant so we don't have to change it in 2 places
Source:
public void setUp() throws Exception { super.setUp(); localPhone = new ClippingDto().setContent("+919876543210") .setType(ClippingDto.ClippingType.PHONE_NUMBER) .setClippingProvider(ClippingDto.ClippingProvider.LOCAL).setCreateAt(new Date()) .setDeviceId("uniqueId"); remoteAddress = new ClippingDto(localPhone).setContent("H.No. 22/7, India") .setType(ClippingDto.ClippingType.ADDRESS) .setClippingProvider(ClippingDto.ClippingProvider.CLOUD); context = DroidOmniApplication_.getAppContext(); }

Target:
the name is poorly chose, the object created is not a Phone is a clipping the name should be `localClipping`, the content of the clipping is not relevant for the test.
Source:
protected void onPostExecute(String result) { a.setProgressBarIndeterminateVisibility(false); if(result != null && result.length() > 0) { Toast.makeText(a, result, Toast.LENGTH_LONG).show(); } if (operation == RESTORE_OPERATION || operation == BACKUP_OPERATION || operation == CLEAR_TILES_OPERATION) { a.reloadLocalIndexes(); } else { a.newDownloadIndexes(); } getMyApplication().getPoiHelper().readPoiTypesFromMapAsync(); }

Target:
UI ?
Source:
public void addItem(ContextMenuItem item) { try { String id = item.getId(); if (id != null) { item.setHidden(isItemHidden(id)); item.setOrder(getItemOrder(id, item.getOrder())); } items.add(item.getPos(), item); } catch (IndexOutOfBoundsException ex) { items.add(item); } sortItemsByOrder(); }

Target:
Bad code. Remove try - catch.
Source:
public List<ContextMenuItem> getDefaultItems() { String idScheme = getIdScheme(); List<ContextMenuItem> items = new ArrayList<>(); for (ContextMenuItem item : this.items) { String id = item.getId(); if (id != null && (id.startsWith(idScheme) && !APP_PROFILES_ID.equals(id) || id.startsWith(AIDL_LAYERS_PREFIX))) { items.add(item); } } return items; }

Target:
Wrong code. Should be "if (id != null && (id.startsWith(idScheme))" only.
Source:
private List<String> readIdsList(JSONArray jsonArray, @NonNull String idScheme) { List<String> list = new ArrayList<>(); if (jsonArray != null) { for (int i = 0; i < jsonArray.length(); i++) { String id = jsonArray.optString(i); if (id.startsWith(AIDL_LAYERS_PREFIX)) { list.add(id); } else { list.add(idScheme + id); } } } return list; }

Target:
Not clear why AIDL_LAYERS_PREFIX here
Source:
public ContextMenuItem createItem() { return new ContextMenuItem(mTitleId, mTitle, mIcon, mColorRes, mSecondaryIcon, mSelected, mProgress, mLayout, mLoading, mIsCategory, mIsClickable, mSkipPaintingWithoutColor, mPosition, mOrder, mDescription, mItemClickListener, mIntegerListener, mProgressListener, mItemDeleteAction, mHideDivider, mHideCompoundButton, mMinHeight, mTag, mId); }

Target:
mPosition?
Source:
protected List<QuickActionType> getQuickActionTypes() { ArrayList<QuickActionType> quickActionTypes = new ArrayList<>(); quickActionTypes.add(AddPOIAction.TYPE); quickActionTypes.add(AddOSMBugAction.TYPE); quickActionTypes.add(ShowHideOSMBugAction.TYPE); return quickActionTypes; }

Target:
ArrayList -> List
Source:
public boolean isLoaded() { return gpxFile.modifiedTime != 0; }

Target:
better to use -1 if it is going to be used. Sometimes 0 is system time
Source:
private FavouritePoint getPersonalPoint(PersonalFavouritePoint.PointType pointType) { FavouritePoint personalPoint = null; for (FavouritePoint fp : cachedPersonalFavoritePoints) { if (fp instanceof PersonalFavouritePoint) { if (((PersonalFavouritePoint) fp).getType() == pointType) { personalPoint = fp; } } } return personalPoint; }

Target:
return fp;
Source:
public void lookupAddessAll() { FavouritesDbHelper favorites = ctx.getFavorites(); lookupAddressForPointToNavigate(); lookupAddessForStartPoint(); for (TargetPoint targetPoint : intermediatePoints) { lookupAddressForIntermediatePoint(targetPoint); } favorites.lookupAddressForHomePoint(); favorites.lookupAddressForWorkPoint(); favorites.lookupAddressForParkingPoint(); lookupAddressForMyLocationPoint(); }

Target:
Why favorites here?? Run lookup for favorites before app.getTargetPointsHelper().lookupAddessAll();
Source:
public int getOpacity() { return PixelFormat.UNKNOWN; }

Target:
Why opacity unknown?
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); } app.getSavingTrackHelper().updateLocation(location, app.getLocationProvider().heading); OsmandPlugin.updateLocationPlugins(location); app.getRoutingHelper().updateLocation(location); app.getWaypointHelper().locationChanged(location); }

Target:
app.getLocationProvider() ?
Source:
LatLon getWorkPointLatLon() { LatLon workPointLatLon; if (hasWorkPoint()) { workPointLatLon = new LatLon(getWorkPoint().getLatitude(), getWorkPoint().getLongitude()); } else { workPointLatLon = new LatLon(0, 0); } return workPointLatLon; }

Target:
If there is no point - return null
Source:
public void onSensorChanged(SensorEvent event) { if (event.sensor.getType() == Sensor.TYPE_PROXIMITY) { if (event.values[0] >= -SENSOR_SENSITIVITY && event.values[0] <= SENSOR_SENSITIVITY) { if (isSensorEnabled()) { unlockEvent(); } } } }

Target:
Such check must be at top of the method
Source:
public static boolean removeAidlCallback (long id){ return callbacks.remove(id) != null; }

Target:
no static
Source:
private void onUpgrade(SQLiteConnection db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + MARKERS_TABLE_NAME); db.execSQL("DROP TABLE IF EXISTS " + GROUPS_TABLE_NAME); onCreate(db); }

Target:
So after upgrade we drop all existing markers?
Source:
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; }

Target:
Codestyle
Source:
public boolean checkMeasurementPointSize(int radius){ //check if proposed change to measurement point display size is within defined range if(radius <= maxMeasurementPointRadius && radius >= minMeasurementPointRadius){ return true; }else{ return false; } }

Target:
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) { } return result; }

Target:
Let's just throw this exception to the caller than catch it here.
Source:
public String getPath() { try { URL url = new URL(getUrl()); return url.getPath(); } catch (MalformedURLException e) { return ""; } }

Target:
are you sure this is the best way to handle this exception?
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); } } } return ""; }

Target:
Why return empty string instead of null?
Source:
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; }

Target:
Please use brackets: ``` if(!sleep(conn, timeout)) { return false; } ```
Source:
public int compareTo(ServerDescription o) { if (this.getServerName().equalsIgnoreCase(o.getServerName())) return 1; return this.getServerName().compareTo(o.getServerName()); }

Target:
Can you use brackets (`{ }`)
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); if(class_out != null) class_out.println(className + " References:"); }

Target:
Missing a bracket.
Source:
public static MongoInstitution getInstance(final Authenticator authenticator) { MongoInstitution result = instance; if (result == null) { synchronized (MongoInstitution.class) { if (result == null) { result = instance; instance = result = new MongoInstitution(); result.auth = authenticator; } } } return result; }

Target:
Why is this defined and then changed on the next line?
Source:
private MongoInstitution(final String url) { MongoClient mongoClient = null; try { mongoClient = new MongoClient(url); } catch (UnknownHostException e) { LOG.info(LoggingConstants.EXCEPTION_MESSAGE, e); } if (mongoClient == null) { return; } database = mongoClient.getDB(DATABASE); }

Target:
this should be error
Source:
public final void connectServers(final AbstractServerWebSocketHandler parent) { try { createAndAddConnection(parent, isConnectionLocal(), "srl02.tamu.edu", PORT, this.isSecure(), SubmissionClientWebSocket.class); } catch (ConnectionException e) { LOG.info(LoggingConstants.EXCEPTION_MESSAGE, e); } }

Target:
change to error
Source:
public void getExperimentAsUser(final String userId, final String problemId, final String sessionInfo, final MultiConnectionManager internalConnections) throws DatabaseAccessException { LOG.info("Getting experiment for user: {}", userId); LOG.info("Problem: {}", problemId); SubmissionManager.mongoGetExperiment(getInstance().database, userId, problemId, sessionInfo, internalConnections); }

Target:
change this to debug.
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; Database db = new Database(this); return gpsStatus; }

Target:
usuń tooooOoOoOo :D
Source:
private List<SingleRun> readfromDB() { Database db = new Database(this); List<SingleRun> runs; runs = db.getAllRuns(); SingleRun[] run_data = new SingleRun[0]; return runs; }

Target:
to chyba już niepotrzebne?
Source:
public NettyHttpRequestWrapper(HttpRequest httpRequest) { checkNotNull(httpRequest); this.httpRequest = httpRequest; }

Target:
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).
Source:
public AsyncContext startAsync() throws IllegalStateException { throw new UnsupportedOperationException(); }

Target:
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.
Source:
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, iterationTimeoutSeconds * iterations, TimeUnit.SECONDS); service.shutdown(); return futures; }

Target:
![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)
Source:
public void blockPorts(final Range<Integer> blockedRange) { checkNotNull(blockedRange); synchronized (reservedPorts) { this.blockedPortRanges.add(blockedRange); } }

Target:
might be more readable to mark the relevant methods as `synchronized` rather than use an arbitrary member for locking
Source:
public void forceHealthChecks() { for (HealthCheck healthCheck : _badEndPoints.values()) { healthCheck.run(); } }

Target:
Due to the nature of `run()`, this will potentially cause duplicate health check runs to be scheduled.
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); Gauge<T> metric = (Gauge<T>) _metrics.get(fullName); if (metric == null) { metric = _registry.register(fullName, gauge); } return metric; }

Target:
Is this thread-safe?
Source:
public ZooKeeperServiceRegistry(ZooKeeperConnection connection) { checkNotNull(connection); CuratorFramework curator = ((CuratorConnection) connection).getCurator(); checkNotNull(curator); checkArgument(curator.isStarted()); _zooKeeperConnection = connection; }

Target:
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.
Source:
private String getTestJavaCommandPath() { return new File(testJDKHome, "bin/java").getAbsolutePath(); }

Target:
may explode if the parameter is null
Source:
public boolean check(Map<String, Object> info) throws Exception { return BlueOceanHook.isBOPlugin(info) || DeclarativePipelineHook.isDPPlugin(info) || StructsHook.isStructsPlugin(info) || HaHook.isHaPlugin(info); }

Target:
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)
Source:
public final @Nonnull Stream<OWLAxiom> axiomBase() { Stream<OWLAxiom> toReturn = axiomBase.stream(); toReturn = Stream.concat(tautologies.stream().flatMap(Set::stream), toReturn); return axiomBase.stream(); }

Target:
Was this the intention? globals is no longer involved and the stream creation with tautologies and base axioms is unused
Source:
private void setEntityStatus(Entity entity, MachinePoolMemberStatus status) { checkNotNull(entity, "What?"); ((EntityInternal) entity).setAttribute(SERVER_STATUS, status); }

Target:
Better message, such as `checkNotNull(entity, "entity")`
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) { Throwable t = Exceptions.getFirstThrowableOfType(e, NoMachinesAvailableException.class); assertTrue(t != null, "expected " + NoMachinesAvailableException.class.getName() + " to be thrown, not found in " + e); } }

Target:
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.
Source:
protected EntitySpec<?> getMemberSpec() { @SuppressWarnings("unchecked") EntitySpec<ElasticSearchNode> spec = (EntitySpec<ElasticSearchNode>)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; }

Target:
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.
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 result.put("ERL_EPMD_PORT", "" + getEntity().getEpmdListenerPort()); return result; }

Target:
Use `Integer.toString(getEntity().getEpmdListenerPort())` rather than automagic coercion with String addition.
Source:
private Boolean hasJoinedCluster() { return Optional.fromNullable(entity.getAttribute(RiakNode.RIAK_NODE_HAS_JOINED_CLUSTER)).or(Boolean.FALSE); }

Target:
call `getEntity().hasJoinedCluster()` after moving code to `RiakNode` as mentioned above
Source:
public static <T> Predicate<Location> isChildOf(final Location parent) { return new Predicate<Location>() { @Override public boolean apply(@Nullable Location input) { return Objects.equal(input.getParent(), parent); } }; }

Target:
Actually this _isn't_ `@Nullable` so should either remove the annotation or add a guard that returns `false`.
Source:
public static <T> Predicate<Location> displayNameEqualTo(final T val) { return new Predicate<Location>() { @Override public boolean apply(@Nullable Location input) { return Objects.equal(input.getDisplayName(), val); } }; }

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

Target:
`input` is not `@Nullable`, remove annotation or add null check.
Source:
public static <T> TypeToken<T> getTypeToken(TypeToken<T> token, Class<? super T> raw) { if (raw!=null) return TypeToken.of((Class<T>)raw); if (token!=null) return token; throw new IllegalStateException("Both indicators of type are null"); }

Target:
Should this not prefer the token over the raw?
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) { ((CouchbaseLoadGeneratorDriver)getDriver()).pillowfight(targetHostnameAndPort, bucket, username, password, iterations, numItems, keyPrefix, numThreads, numInstances, randomSeed, ratio, minSize, maxSize); }

Target:
Can also add a `getDriver()` override that returns a cast of `super.getDriver()` to make this look neater
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)" : ""))); } return dir; }

Target:
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 ... ```
Source:
public int execute(List<String> script, String summaryForLogging) { if (failExecution) { throw new TestException("Simulated driver exception"); } return super.execute(script, summaryForLogging); }

Target:
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.
Source:
public void setup() throws Exception { DynamicSequentialTask<Object> t = new DynamicSequentialTask<Object>(); DynamicTasks.setTaskQueueingContext(t); 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)); }

Target:
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`.)
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); } } Tasks.resetBlockingDetails(); } return details; }

Target:
do the reset in a finally block.
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) { if (listener != null) listener.reloaded(); } }

Target:
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"));` ```
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) { Exceptions.propagateIfFatal(error); return error; } }

Target:
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.
Source:
protected void handleGenerateMementoException(Exception e, String context) { Exceptions.propagateIfFatal(e); if (isActive()) { LOG.warn("Problem generating memento for "+context, e); } else { Exceptions.propagateIfFatal(e); LOG.debug("Problem generating memento for "+context+", but no longer active (ignoring)", e); } }

Target:
already done this 3 lines up!
Source:
public void setManagementContext(ManagementContextInternal val) { if (val == null && (val instanceof NonDeploymentManagementContext)) { System.out.println("fafe"); } 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); }

Target:
Delete this - it was just there during debugging.
Source:
public void setOrigin(BigInteger shift) { Preconditions.checkNotNull(shift, "shift"); this.origin = shift; }

Target:
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).
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 { return (S) val.get(); } }; return this; }

Target:
Do you really have to cast? Am I missing something? No strong feelings.
Source:
public Map<String, String> getShellEnvironment() { Map<String, String> orig = super.getShellEnvironment(); String kafkaJmxOpts = orig.remove("JAVA_OPTS"); if (Strings.isBlank(kafkaJmxOpts)) kafkaJmxOpts = " "; // FIXME - this is required to prevent jmxremote being setup in bin/kafka-run-class.sh return MutableMap.<String, String>builder() .putAll(orig) .putIfNotNull("KAFKA_JMX_OPTS", kafkaJmxOpts) .build(); }

Target:
This line isn't required. It was just a temporary hack to disable kafka-zookeeper jmx.
Source:
void close() throws IOException { client.close(); }

Target:
Why not have this implement `Closeable`, out of interest?
Source:
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); }

Target:
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...
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) Entities.destroyCatching(entity); mgmt.getEntityManager().unmanage(entity); } }); }

Target:
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.
Source:
protected List<String> initialKnifeParameters() { MutableList<String> result = new MutableList<String>(); result.add("node"); result.add("show"); result.add("-l"); result.add(nodeName); result.add("--format"); result.add("json"); return result; }

Target:
I'd go for: `return ImmutableList.of("node", "show", "-l", nodeName, "--format", "json")`
Source:
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) { if (!attribute.getName().startsWith(CHEF_ATTRIBUTE_PREFIX)) continue; entity.setAttribute(attribute, null); } }

Target:
Again suggesting giving more info (e.g. what we tried to connect to). Hopefully stderr will be very helpful though!
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: return TERMINATED; case ON_FIRE: default: return UNKNOWN; } }

Target:
this really does feel wrong. :)
Source:
public static Long ifPositive(Long time) { if (time==null || time<=0) return null; return time; }

Target:
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).
Source:
public static RuntimeException propagate(Throwable throwable) { if (throwable instanceof InterruptedException) throw new RuntimeInterruptedException((InterruptedException) throwable); if (throwable instanceof ExecutionException) return Throwables.propagate(throwable.getCause()); return Throwables.propagate(throwable); }

Target:
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()`.
Source:
public static void propagateIfFatal(Throwable throwable) { if (throwable instanceof InterruptedException) throw new RuntimeInterruptedException((InterruptedException) throwable); if (throwable instanceof ExecutionException) propagateIfFatal(throwable.getCause()); if (throwable instanceof Error) throw (Error) throwable; }

Target:
Again, we shouldn't do this.
Source:
public void recordPublicIpHostname(String publicIpId, String hostnameOrPublicIpAddress) { 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); }

Target:
Needs to be a ConcurrentHashMap, or synchronization here (and in the getters etc).
Source:
public BasicLocationDefinition(String id, String name, String spec, Map<String,? extends Object> config) { this.id = id != null ? id : LanguageUtils.newUid(); this.name = name; this.spec = Preconditions.checkNotNull(spec); this.config = config==null ? ImmutableMap.<String, Object>of() : ImmutableMap.<String, Object>copyOf(config); }

Target:
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.
Source:
public boolean accepts(String spec, LocationRegistry registry) { if (BasicLocationRegistry.isResolverPrefixForSpec(this, spec, true)) return true; JcloudsSpecParser details = JcloudsSpecParser.parse(spec, false); if (details==null) return false; if (details.isProvider() || details.isApi()) return true; return false; }

Target:
Should this pass `true` for dryrun, when calling parse?
Source:
public Map<ConfigKey<?>,Object> getLocalConfig() { Map<ConfigKey<?>,Object> result = new LinkedHashMap<ConfigKey<?>,Object>(inheritedConfig.size()+ownConfig.size()); result.putAll(ownConfig); return Collections.unmodifiableMap(result); }

Target:
Initial size can be ownConfig.size() rather than `+inheritedConfig.size()`. And could create copy with with `return Collections.unmodifiableMap(Maps.newLinkedHashMap(ownConfig))`
Source:
public ImmutableEntityType(Class<? extends Entity> clazz) { super(clazz, null); }

Target:
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.
Source:
public ListConfigKey(Class<V> subType, String name, String description, List<? extends V> defaultValue) { super((Class)List.class, name, description, (List<? extends V>) defaultValue); this.subType = subType; }

Target:
Is the cast to `(List<? extends V>)` really needed? It looks the same as in the method signature.
Source:
public TrustingSslSocketFactory() { super(); try { sslContext.init(null, new TrustManager[] { TRUST_ALL }, null); } catch (Exception e) { throw Throwables.propagate(e); } }

Target:
If treating as singleton (with static INSTANCE field etc), then should constructor be private?
Source:
protected String getEntityVersionLabel(String separator) { return elvis(entity.getClass().getSimpleName(), entity.getClass().getName())+(!getVersion().equals(NO_VERSION_INFO) ? separator+getVersion() : ""); }

Target:
Could getVersion ever return null?
Source:
public MachineSet all(Function<MachineSet, MachineSet> ...ops) { return compose(ops).apply(getAllMachines()); }

Target:
Seems strange to take a Function rather than a Predicate when matching a given criteria.
Source:
public MachineSet ensureExists(int count, ReusableMachineTemplate template) { MachineSet current; synchronized (this) { 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); }

Target:
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?!
Source:
public void remove(int id) { locations.remove(id); }

Target:
Perhaps return boolean to say if the id was found (similar semantics to Set.remove)?
Source:
public Randomizer<?> getRandomizer(Field field) { EnhancedRandom enhancedRandom = EnhancedRandomBuilder.aNewEnhancedRandomBuilder() .seed(seed) .dateRange(LocalDate.now().minusYears(Constants.DEFAULT_DATE_RANGE), LocalDate.now()) .build(); return (() -> enhancedRandom.nextObject(field.getType())); }

Target:
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?
Source:
protected 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; }

Target:
this should be checked at construction time. don't create the object with an inconsistent state.
Source:
RawBsonDocument mark(final String databaseName, final RawBsonDocument command) { spawnIfNecesary(); try { try { System.out.println(command); return executeCommand(databaseName, command); } catch (MongoTimeoutException e) { spawnIfNecesary(); return executeCommand(databaseName, command); } } catch (MongoException e) { throw wrapInClientException(e); } }

Target:
Ditch the debugging :)
Source:
public ChangeStreamIterable<TResult> showMigrationEvents(final boolean showMigrationEvents) { this.showMigrationEvents = notNull("showMigrationEvents", showMigrationEvents); return this; }

Target:
Remove this line. Doesn't make sense for a primitive value. What's happening here is that the primitive boolean is being auto-boxed into a `Boolean`.
Source:
private String readStringFromExtendedJson() { JsonToken patternToken = popToken(); if (patternToken.getType() != JsonTokenType.STRING && patternToken.getType() != JsonTokenType.UNQUOTED_STRING) { throw new JsonParseException("JSON reader expected a string but found '%s'.", patternToken.getValue()); } return patternToken.getValue(String.class); }

Target:
This change casts too wide a net, as this method is called from both methods implementing "Extended JSON" and for methods implementing "Shell" mode, e.g. JsonReader#visitObjectIdConstructor, and it's not correct in the shell to do something like: { _id : ObjectId(5aaff8caa33024673db4cddf) } It's also called to read values in some places, not just keys. To address this, I think you will need to leave the current method alone and add a new method that is used only to read extended JSON keys, e.g. in JsonReader#visitTimestampExtendedJson
Source:
private static TypeData<?> getTypeData(final Method method) { if (isGetter(method.getName())) { return getTypeData(method.getGenericReturnType(), method.getReturnType()); } else { if (method.getGenericParameterTypes().length != 1) { throw new CodecConfigurationException(format("Invalid count of arguments for setter method: %s", method.getName())); } return getTypeData(method.getGenericParameterTypes()[0], method.getParameterTypes()[0]); } }

Target:
A method starting with "set" that has more than one parameter does not define a property, so should just be ignored rather than thrown an exception.
Source:
public void close() { try { if (channel != null) { channel.close(); } } catch (final IOException e) { // NOPMD // ignore } finally { channel = null; isClosed = true; } }

Target:
There are not parameters though. I really do not want to go through and make these all final, since we have not configured checkstyle to do that. I also don't see a big benefit, as I don't think I've ever accidentally modified an exception reference in a catch clause.
Source:
public void stateChanged(final ChangeEvent<ServerDescription> event) { description = event.getNewValue(); for (final ChangeListener<ServerDescription> listener : changeListeners) { listener.stateChanged(event); } }

Target:
Local variable: no final needed. Is your IDE configured differently that checkstyle?
Source:
public MeasurementKey(StudyOutcomeMeasure<? extends Variable> som, Arm a, WhenTaken wt) { if (som.getValue() == null) { throw new NullPointerException("Variable may not be null"); } if (som.getValue() instanceof OutcomeMeasure && a == null) { throw new NullPointerException( "Arm may not be null for Endpoints/ADEs"); } if (wt == null) { throw new NullPointerException("Moment of measurement may not be null"); } d_som = som; d_arm = a; d_wt = wt; }

Target:
I guess we _will_ allow the variable to be null, or are you planning to use a placeholder of some kind?
Source:
public static JButton createExtendSimulationButton(final MCMCWrapper model) { JButton button = new JButton(Main.IMAGELOADER.getIcon(FileNames.ICON_RESTART)); button.setEnabled(false); button.setText("No, extend"); button.setToolTipText("Extend the simulation"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { ((MixedTreatmentComparison) getMTCModel(model.getModel())).setExtendSimulation(ExtendSimulation.EXTEND); } }); return button; }

Target:
What if the simulation is in the "decision phase" when you build the panel?
Source:
private synchronized void createResults() { if (d_results.getNumberOfSamples() < 2) return; d_quantiles = new double[3]; d_quantiles[1] = RANDOM.nextDouble() * 4 - 2; d_quantiles[2] = d_quantiles[1] + RANDOM.nextDouble() * 1.5; d_quantiles[0] = d_quantiles[2] - d_quantiles[1]; d_defined = true; firePropertyChange(PROPERTY_DEFINED, null, d_defined); }

Target:
I think this should be d_quantiles[1] - (d_quantiles[2] - d_quantiles[1]);
Source:
Collection<LocationProvider> getProviders() { return this.providers; }

Target:
nit: I´d like the ´this.´ usages to be only whenever are necessary, to be consistent with the style used in the rest of the library code.
Source:
public int registerCallback(CordovaPlugin receiver, int requestCode) { int mappedId = this.currentCallbackId++; callbacks.put(mappedId, new Pair<CordovaPlugin, Integer>(receiver, requestCode)); return mappedId; }

Target:
Can this be called concurrently? If so, consider using java.util.concurrent.atomic.AtomicInteger.
Source:
public Boolean shouldAllowRequest(String url) { return true; }

Target:
Aye; I missed it when I changed that one from a _b_ oolean.
Source:
private Set<String> parseFileNames(String input) { Set<String> names = new HashSet<>(); names.addAll(Stream.of(input.split(",")).map(String::trim).collect(Collectors.toList())); return names; }

Target:
will this skip empty strings?
Source:
public void createDirectory(CreateDirectoryPRequest request, StreamObserver<CreateDirectoryPResponse> responseObserver) { CreateDirectoryPOptions options = request.getOptions(); RpcUtils.call(LOG, () -> { AlluxioURI pathUri = getAlluxioURI(request.getPath()); mFileSystemMaster.createDirectory(pathUri, (CreateDirectoryContext) CreateDirectoryContext .create(options.toBuilder()).withTracker(new GrpcCallTracker(responseObserver))); return CreateDirectoryPResponse.newBuilder().build(); }, "CreateDirectory", "request=%s", responseObserver, request); }

Target:
if `withTracker` returns the generic type of the `OperationContext` (`C` in your implementation), then is it necessary to include the cast to `CreateDirectoryContext`? It just doesn't seem clean. edit - I looked into it and figured out the issue. Poor use of generics. Change the class definition of `CreatePathContext` to remove the need to cast old: ```java public abstract class CreatePathContext<T extends GeneratedMessageV3.Builder<?>, K> extends OperationContext<T, CreatePathContext> { ``` new: ```java public abstract class CreatePathContext<T extends GeneratedMessageV3.Builder<?>, K extends OperationContext> extends OperationContext<T, K> { ```
Source:
private JobAttempt newJob(AlluxioURI filePath, int replication) { final ClientContext clientContext = ClientContext.create(mFsContext.getPathConf(filePath)); if (mClient == null) { mClient = JobMasterClient.Factory.create( JobMasterClientContext.newBuilder(clientContext).build()); } JobAttempt jobAttempt = new JobAttempt(new LoadConfig(filePath.getPath(), replication), new CountingRetry(3)); jobAttempt.run(); return jobAttempt; }

Target:
Do you need the path-conf here?
Source:
public static synchronized CacheManager get(AlluxioConfiguration conf) throws IOException { // TODO(feng): support multiple cache managers if (sCacheManager == null) { try { sCacheManager = Optional.of(create(conf)); } catch (IOException e) { sCacheManager = Optional.empty(); throw e; } } return sCacheManager.orElse(null); }

Target:
Do we need to throw the exception here, I thought we are using null as the signal of failed to create?
Source:
public BackupLeaderRole(CoreMasterContext masterContext) { super(masterContext); LOG.info("Creating backup-leader role."); // Store state lock manager pausing state change when necessary. mStateLockManager = masterContext.getStateLockManager(); // Read properties. mStateLockTimeout = ServerConfiguration.getMs(PropertyKey.MASTER_SHELL_BACKUP_STATE_LOCK_TIMEOUT); mBackupAbandonTimeout = ServerConfiguration.getMs(PropertyKey.MASTER_BACKUP_ABANDON_TIMEOUT); }

Target:
Is this supposed to be shell?
Source:
public BlockManagementTaskResult() { mBlockOpResults = new Hashtable<>(); }

Target:
Any reason we want to use `HashTable` here?
Source:
public void seek(long position) throws IOException { if (Math.abs(position - mPos) > MOVEMENT_LIMIT) { mSequentialReadCount = 0; } else { ((FSDataInputStream) in).seek(position); } mPos = position; }

Target:
If we seek backward should sequential count always be set to 0?
Source:
public long skip(long n) throws IOException { if (n > MOVEMENT_LIMIT) { mSequentialReadCount = 0; mPos += n; return n; } else { long skipped = ((FSDataInputStream) in).skip(n); mPos += skipped; return skipped; } }

Target:
Is it guaranteed that `in` is positioned correctly?
Source:
public void seek(long position) throws IOException { if (position < mPos || position - mPos > MOVEMENT_LIMIT) { mSequentialReadCount = 0; } else { ((Seekable) in).seek(position); } mPos = position; }

Target:
what if 1. stream is in random read mode and `mPos=0` 2. `HdfsPositionedUnderFileInputeStream.seek(MOVEMENT_LIMIT-1)` 3. we end up calling seek on `FSDataInputStream` and that is undesired? instead can we refactor this by creating an auxiliary method `isSequentialReadMode=mSequentialReadCount> SEQUENTIAL_READ_LIMIT` ``` if (position < mPos || position - mPos > MOVEMENT_LIMIT) { mSequentialReadCount = 0; } if (isSequentialReadMode()) { ((Seekable) in).seek(position); ```
Source:
public void addStatus(AlluxioURI path, UfsStatus status) { UfsStatus prev = mStatuses.putIfAbsent(path, status); if (!path.getName().equals(status.getName())) { throw new IllegalArgumentException( String.format("path name %s does not match ufs status name %s", path.getName(), status.getName())); } }

Target:
what is `prev` for, and if it was already there, what should we do?
Source:
public BlockSortedField updateSortedField(long blockId, LRUSortedField oldValue) { long clockValue = 0; if (oldValue != null) { clockValue = mLRUClock.incrementAndGet(); } if (LOG.isDebugEnabled()) { LOG.debug("LRU update for Block: {}. Clock: {}", blockId, clockValue); } return new LRUSortedField(clockValue); }

Target:
@ggezer For the LRU evictor: ``` @Override public void onCommitBlock(long sessionId, long blockId, BlockStoreLocation location) { // Since the temp block has been committed, update Evictor about the new added blocks mLRUCache.put(blockId, UNUSED_MAP_VALUE); } ``` Doesn't this mean newly created blocks are added to the tail of the LRU cache (most recently used)?
Source:
protected synchronized long getRemoteServiceVersion() throws AlluxioStatusException { return retryRPC(() -> mVersionService.getServiceVersion( GetServiceVersionPRequest.newBuilder().setServiceType(getRemoteServiceType()).build()) .getVersion(), LOG, "getRemoteServiceVersion", ""); }

Target:
Why did we add synchronization here?
Source:
public String getMetricsJson(String url) throws IOException { String responseJson; responseJson = HttpUtils.get(url, COLLECT_METRICS_TIMEOUT); return String.format("Url: %s%nResponse: %s", url, responseJson); }

Target:
Why is this two lines?
Source:
public void validateArgs(CommandLine cl) throws InvalidArgumentException { CommandUtils.checkNumOfArgsEquals(this, cl, 2); }

Target:
`-h` is optional so I think the num of args will stay 1. Can you please build Alluxio and give it a manual test?
Source:
public synchronized void close() { if (mSaslClient != null) { try { mSaslClient.dispose(); mSaslClient = null; } catch (SaslException exc) { LOG.debug("Failed to close SaslClient.", exc); } } }

Target:
do we want to keep this non-null if there is an issue with `dispose`? Basically, should we set it to null in finally or here?
Source:
public String toString() { return MoreObjects.toStringHelper("") .add("HostName", mHostName) .add("SocketAddress", mSocketAddress) .toString(); }

Target:
I am confused when this is supposed to be "" or `this`?