auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public long getAge() { return (System.nanoTime() - timestamp) / 1000; }

Target:
I'm not sure this is correct. It looks like timestamp is in millis. so `(System.nanoTime()/1000) - timestamp)` may be more correct. Two things: 1) If I'm wrong, and we are using nano stamps to mark a file to indicate its age, we shouldn't do that. 2) if we're just concerned about getting the age of the file, `System.currentTimeMillis()` is good enough. Nanos would be needed if we were getting multiple files per millisecond. Even then, nanos wouldn't give a good indication of age--millis-since-epoch would still need to be part of the file name.
Source:
public synchronized void start() { fileUploader = new DoneFileUploader(); if (uploaderThread != null) { throw new RuntimeException("StorageManager is already started"); } uploaderThread = new Thread(fileUploader, "StorageManager uploader"); uploaderThread.start(); log.info("Storage Manager fully started"); }

Target:
disregardable nit: this method could do a better job to protect against stupid programmers. `fileManager` will get replaced if `start()` is called twice.
Source:
public boolean equals(Object obj) { if (!(obj instanceof CounterRollup) || obj == null) return false; CounterRollup other = (CounterRollup)obj; return this.getCount().equals(other.getCount()) && this.rate == other.rate; }

Target:
I think this should be obj == null || !(obj instanceof CounterRollup)
Source:
public boolean equals(Object obj) { return obj instanceof Locator && obj.hashCode() == this.hashCode(); }

Target:
null check?
Source:
public Emitter once(final String event, final Listener<T> fn) { Listener on = new Listener<T>() { @Override public void call(T... arg) { Emitter.this.off(event, this); fn.call(arg); } }; this.onceCallbacks.put(fn, on); this.on(event, on); return this; }

Target:
args
Source:
public String toString() { switch (type) { case INTEGER: return String.format("%d (int)", intValue); case LONG: return String.format("%d (long)", longValue); case DOUBLE: return String.format("%s (double)", doubleValue); default: return "ERROR"; } }

Target:
throw new RuntimeException() maybe?
Source:
public void start() { synchronized (running) { if (running.get()) return; else { running.set(true); run(); } } }

Target:
I think we can just make the method synchronized. Might be easier to read.
Source:
public final boolean test(IPerson person) { Object[] atts = person.getAttributeValues(getAttributeName()); if (atts != null && atts.length > 0) { return false; } return true; }

Target:
:art: `return atts == null || atts.length < 1`
Source:
public String lookupEntityName(Entity entity) { if (entity != null) { EntityEnum entityEnum = EntityEnum.getEntityEnum(entity.getEntityType()); return lookupEntityName(entityEnum, entity.getId()); } return null; }

Target:
:art: Personally I would lean toward using a guard statement. ```java if (entity == null) { return null } ... ```
Source:
public Collection<PhysicalAddress> fetchClusterMembers(String clusterName) { //If no DAO has been set just return an empty list if (pingDao == null) { log.info("No PingDao set, returning empty set for current cluster members"); return Collections.emptyList(); } //Add our address to the store getAndSavePhysicalAddress(clusterName); //Get the current cluster members final Map<Address, PhysicalAddress> existing_mbrs = pingDao.getAddresses(clusterName); //Return current members return existing_mbrs.values(); }

Target:
I don't agree with the above change. I think you want your list of existing members to be everyone BUT yourself. You don't want to send messages to yourself.
Source:
private Set<IGroupMember> primGetAllMembers(Set<IGroupMember> rslt) throws GroupsException { final Set<IGroupMember> members = getChildren(); for (IGroupMember gm : members) { rslt.add(gm); if (gm.isGroup()) { ((EntityGroupImpl) gm).primGetAllMembers(rslt); } } return rslt; }

Target:
This assignment could be removed
Source:
public boolean isMemberOf(IEntityGroup group) throws GroupsException { final Set<IEntityGroup> parents = getParentGroups(); return parents.contains(group); }

Target:
Refactor to 1 line?
Source:
private String getUsernameForUserId(int id) { if (id > 0) { String username = userIdentityStore.getPortalUserName(id); if (username != null) { return username; } logger.warn("Invalid userID found when exporting a portlet; return system username instead"); } return systemUsername; }

Target:
Placeholder `{}` without placeholder value?
Source:
private IPersonAttributesGroupDefinition getPagsGroupDefByName(String name) { Set<IPersonAttributesGroupDefinition> pagsGroups = personAttributesGroupDefinitionDao.getPersonAttributesGroupDefinitionByName(name); if (pagsGroups.size() > 1) { logger.warn("More than one PAGS group with name found.", name); } return pagsGroups.isEmpty() ? null : pagsGroups.iterator().next(); }

Target:
`warn` seems insufficiently dire for a violation of a fundamental assumption of the groups system. `error` at the least? I'm not sure returning what is effectively a random selection among the illegally multiple groups with the same name is the right behavior. I think I'd rather it fail with an exception. Not an exception that results in the entire portal falling over dead, of course, but an exception that at least fails the specific group operation being computed. Multiple groups with the same name is, alas, not okay.
Source:
private void updateStickyProfile(IPerson person, UserProfile stickyProfile, String profileName) { if (person.getID() == -1) { try { throw new RuntimeException(); } catch (Exception e) { e.printStackTrace(System.out); } } stickyProfile.setProfileName(profileName); layoutStore.updateUserProfile(person, stickyProfile); }

Target:
This seems... strange.
Source:
protected void doHeaders(RenderRequest request, RenderResponse response) { try { doDispatch(request, response); } catch (IOException ex) { logger.error("Exception rendering headers for portlet " + getPortletName() + ". Aborting doHeaders", ex); } catch (PortletException ex) { logger.error("Exception rendering headers for portlet " + getPortletName() + ". Aborting doHeaders", ex); } }

Target:
Opportunity to use JDK 7 multicatch `catch (IOException | PortletException ex)`.
Source:
public IEntityGroup find(String name) throws GroupsException { List<IPersonAttributesGroupDefinition> groups = personAttributesGroupDefinitionDao.getPersonAttributesGroupDefinitionByName(name); IPersonAttributesGroupDefinition pagsGroup = groups.get(0); GroupDefinition groupDef = initGroupDef(pagsGroup); IEntityGroup group = new EntityTestingGroupImpl(groupDef.getKey(), IPERSON_CLASS); group.setName(groupDef.getName()); group.setDescription(groupDef.getDescription()); return group; }

Target:
Undetected error condition where multiple groups match the name?
Source:
private IPersonAttributesGroupStoreDefinition getOrCreateStore() { List<IPersonAttributesGroupStoreDefinition> stores = personAttributesGroupStoreDefinitionDao.getPersonAttributesGroupStoreDefinitions(); if (stores.size() == 0) { return personAttributesGroupStoreDefinitionDao.createPersonAttributesGroupStoreDefinition("Default", "Default Person Attribute Group Store"); } else { return stores.get(0); } }

Target:
Undetected error condition where there are multiple `IPersonAttributesGroupStoreDefinition`s? Perhaps not a failure-inducing error, but at least an odd state of affairs worth logging?
Source:
private IPersonAttributesGroupDefinition getOrCreateGroup(IPersonAttributesGroupStoreDefinition store, String name, String description) { List<IPersonAttributesGroupDefinition> groups = personAttributesGroupDefinitionDao.getPersonAttributesGroupDefinitionByName(name); if (groups.size() == 0) { return personAttributesGroupDefinitionDao.createPersonAttributesGroupDefinition(store, name, description); } else { groups.get(0).setDescription(description); personAttributesGroupDefinitionDao.updatePersonAttributesGroupDefinition(groups.get(0)); return groups.get(0); } }

Target:
Undetected error condition where the `personAttributesGroupDefinitionDao` found multiple group definitions matching the `name`?
Source:
public Server(String clusterName, String mainDirectory, String languages, String transportAddresses) throws Exception { try { if (SystemUtils.IS_OS_WINDOWS) { setupDirectories(new URL("file:///" + mainDirectory)); } else { setupDirectories(new URL("file://" + mainDirectory)); } } catch (Exception e) { throw new RuntimeException("Can't create directories: ", e); } this.clusterName = clusterName; this.languages = languages.split(","); this.transportAddresses = transportAddresses; }

Target:
Delete 'throws Exception'? Also above.
Source:
public String convert(QueryBuilder anItem) { try { BytesReference bytes = anItem.toXContent(JsonXContent.contentBuilder(), new ToXContent.MapParams(null)) .bytes(); return bytes.utf8ToString(); } catch (IOException e) { log.error("Unable to transform querybuilder to a json string due to an exception", e); return null; } }

Target:
I know this was already there but I think we should throw an exception here instead of silently accepting it, e.g. `throw new RuntimeException("Unable to transform ....", e);`
Source:
public boolean isUsefulForIndex() { if("place".equals(tagKey) && "houses".equals(tagValue)) return false; if(houseNumber != null) return true; if(name.isEmpty()) return false; return linkedPlaceId <= 0; }

Target:
intellij is continuously recommending to simplify this code this way, but i think it is very hard to understand this way
Source:
public IndexPreprocessor(final String prefix, final String theNamespace_url, final String draftParameter) { this.prefix = prefix; this.namespace_url = theNamespace_url; this.excludedDraftSection.clear(); this.excludedDraftSection.add(false); includeDraft = draftParameter.equals(ARGS_DRAFT_YES) ? true : false; indexDitaProcessor = new IndexDitaProcessor(); indexGroupProcessor = new IndexGroupProcessor(); }

Target:
Simplify this to just ```java includeDraft = draftParameter.equals(ARGS_DRAFT_YES); ```
Source:
private void printPlugins() { final List<String> installedPlugins = getInstalledPlugins(); if (installedPlugins != null) { System.out.println("The following DITA-OT plugins are installed:"); for (final String plugin : installedPlugins) { System.out.println(" " + plugin); } } else { System.out.println("No DITA-OT plugins are installed."); } }

Target:
I'm not sure if I want to have this line output and each ID prefixed with spaces. My preference would be to just have one ID per line, without any prefixes. That way the output could be piped to other processes without parsing out the pretty printing. This is basically [plumbing vs porcelain](https://git-scm.com/book/en/v2/Git-Internals-Plumbing-and-Porcelain#_plumbing_porcelain) distinction.
Source:
private void insertAction(final Action action, final FilterKey key) { if (filterMap.get(key) == null) { filterMap.put(key, action); } else { logger.error(MessageUtils.getMessage("DOTJ007W", key.toString()).toString()); } }

Target:
This will still be logged as `error`. Shouldn't this be `logger.warn`?
Source:
public void endElement(final String uri, final String localName, final String qName) throws SAXException { // @processing-role processRoleStack.pop(); final DitaClass cls = classes.pop(); if ((cls == null || !cls.isValid()) && !ELEMENT_NAME_DITA.equals(localName)) { return; } getContentHandler().endElement(uri, localName, qName); }

Target:
This is a filter. If we return before passing the end element event to the next content handler, we'll end up with unbalanced tree. Is this really correct?
Source:
public ValidationLayer getValidationLayer() throws CatalogException { if(valLayer != null) { return valLayer; } else { throw new CatalogException("validation layer is not initialized"); } }

Target:
Let's keep this method unchanged since it is better we modify the interface `Catalog`. Instead let's add null checks when this method is being used.
Source:
public static OlapAnnotation getOlapAnnotationByName( final String name, List<OlapAnnotation> annotations) { OlapAnnotation foundAnnotation = null; for( OlapAnnotation annotation : annotations ) { if ( name.equals( annotation.getName() ) ) { foundAnnotation = annotation; } } return foundAnnotation; }

Target:
break from for loop if annotation is found
Source:
public static <T> Flowable<T> fromCompletionStage(@NonNull CompletionStage<T> stage) { ObjectHelper.requireNonNull(stage, "stage is null"); return RxJavaPlugins.onAssembly(new FlowableFromCompletionStage<>(stage)); }

Target:
+NonNull for return type
Source:
public static <T> Flowable<T> fromStream(@NonNull Stream<T> stream) { ObjectHelper.requireNonNull(stream, "stream is null"); return RxJavaPlugins.onAssembly(new FlowableFromStream<>(stream)); }

Target:
+NonNull for return type
Source:
public void onComplete() { subscribers.dispose(); synchronized (this) { Map<Long, C> bufs = buffers; if (bufs == null) { return; } for (C b : bufs.values()) { queue.offer(b); } bufs = null; } done = true; drain(); }

Target:
shouldn't this be `buffers = null`?
Source:
void boundaryError(Disposable subscriber, Throwable ex) { SubscriptionHelper.cancel(upstream); subscribers.delete(subscriber); if (errors.addThrowable(ex)) { subscribers.dispose(); synchronized (this) { buffers = null; } done = true; drain(); } else { RxJavaPlugins.onError(ex); } }

Target:
Can we just `dispose()` all subscribers here and remove `dispose()` call below?
Source:
public final Disposable subscribe(final Action onComplete, final Consumer<? super Throwable> onError) { ObjectHelper.requireNonNull(onError, "onError is null"); ObjectHelper.requireNonNull(onComplete, "onComplete is null"); return subscribe(onComplete, onError, Functions.emptyConsumer()); }

Target:
No need for null checks as you delegate to a common method.
Source:
public final Disposable subscribe(final Action onComplete) { ObjectHelper.requireNonNull(onComplete, "onComplete is null"); return subscribe(onComplete, Functions.ON_ERROR_MISSING); }

Target:
No need for null checks. Also since that subscribe delegates to a third method, one call indirection could be avoided by call the new method directly.
Source:
public final Maybe<T> defaultIfEmpty(T defaultItem) { ObjectHelper.requireNonNull(defaultItem, "item is null"); return switchIfEmpty(Single.just(defaultItem)); }

Target:
Why was this changed, the original `just` should still work?!
Source:
public void onError(Throwable e) { if (done) { return; } done = true; try { actual.onError(e); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); RxJavaHooks.onError(e); throw new OnErrorFailedException(new CompositeException(e, ex)); } }

Target:
You should have moved it here.
Source:
final void removeFirst() { Node head = get(); Node next = head.get(); size--; // can't just move the head because it would retain the very first value // can't null out the head's value because of late replayers would see null Node newHead = new Node(null); Node newNext = next.get(); newHead.set(newNext); setFirst(newHead); if (newNext == null) { tail = newHead; } }

Target:
This can be `lazySet`.
Source:
UnicastProcessor(int capacityHint) { this(capacityHint, true); }

Target:
Is this one really necessary?
Source:
public SingleScheduler(ThreadFactory threadFactory) { this.threadFactory = ObjectHelper.requireNonNull(threadFactory, "threadFactory was null"); executor.lazySet(createExecutor(threadFactory)); }

Target:
Either this is unnecessary or you forgot to do this with the other new constructors.
Source:
public ReduceSeedObserver(SingleObserver<? super R> actual, BiFunction<R, ? super T, R> reducer, R value) { this.actual = actual; this.value = value; this.reducer = reducer; this.value = value; }

Target:
2x `this.value = value`? L64 & L66.
Source:
public void onError(Throwable e) { if (done) { RxJavaPlugins.onError(e); return; } value = null; actual.onError(e); }

Target:
needs `done=true`
Source:
public void onNext(T value) { R v = this.value; try { this.value = ObjectHelper.requireNonNull(reducer.apply(v, value), "The reducer returned a null value"); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); d.dispose(); onError(ex); } }

Target:
`done` checks in this class?
Source:
public AsyncProcessor() { this.subscribers = new AtomicReference<AsyncSubscription<T>[]>(EMPTY); }

Target:
Seems redundant to have both static factories and public constructors in the public API. Especially when there's multiple overloads such as in some of the other processors. Can we choose one and expose only it?
Source:
@Override public Object call() { return null; // null scalar is interpreted as being empty }

Target:
nit: ~Square formatting
Source:
public OnSubscribeToMap(Observable<T> source, Func1<? super T, ? extends K> keySelector, Func1<? super T, ? extends V> valueSelector) { this(source, keySelector, valueSelector, DefaultMapFactory.<K, V>instance()); }

Target:
A small trick: make the OnSubscribeToMap also implement `Func0<Map<K, V>>` and assign `this` to the map factory function - of course you can't use `this()` constructor delegation but assign to the final fields explicitly. This way, there is no need for an extra class.
Source:
public void call(final Subscriber<? super T> child) { final Worker worker = scheduler.createWorker(); child.add(worker); SkipTimedSubscriber<T> subscriber = new SkipTimedSubscriber<T>(child); worker.schedule(subscriber, time, unit); source.unsafeSubscribe(subscriber); }

Target:
That's wrong because it calls `unsubscribe` in the `onError`/`onCompleted` path and unsubscribes the child. The `worker` should be added to `subscriber` instead and `subscriber` added to the `child`. No constructor forwarding.
Source:
public void unsubscribe() { if (once.compareAndSet(false, true)) { // unsubscribe should be idempotent, so only do this once // Release the worker _after_ the previous action (if any) has completed threadWorker.schedule(new Action0() { @Override public void call() { pool.release(threadWorker); } }); } innerSubscription.unsubscribe(); }

Target:
EventLoopWorker can implement Action0 and schedule itself to release.
Source:
public final Completable flatMapCompletable(final Func1<? super T, ? extends Completable> func) { return Completable.create(new CompletableFlatMapSingleToCompletable(this, func)); }

Target:
You forgot to commit the class itself. Plus, use `new CompletableFlatMapSingleToCompletable<T>(this, func)` as it is a generic class.
Source:
public void onError(Throwable e) { error = e; List<Throwable> errors = null; for (PublishSubjectProducer<T> pp : getAndSet(TERMINATED)) { try { pp.onError(e); } catch (Throwable ex) { if (errors == null) { errors = new ArrayList<Throwable>(); } errors.add(ex); } } Exceptions.throwIfAny(errors); }

Target:
nit: `(1)`
Source:
public void onError(Throwable e) { long r = get(); if (r != Long.MIN_VALUE) { actual.onError(e); } }

Target:
nit: inline
Source:
public void innerNext(InnerQueuedSubscriber<R> inner, R value) { if (!inner.queue().offer(value)) { inner.cancel(); innerError(inner, new MissingBackpressureException()); } else { drain(); } }

Target:
nit: same here about reversing `if-else`. I think PMD complains about it btw
Source:
public void onNext(T t) { if (fusionMode != ASYNC) { if (!queue.offer(t)) { onError(new IllegalStateException("Queue is full?!")); return; } } drain(); }

Target:
nested `if`s could be collapsed with `&&`
Source:
public void onCompleted() { if (done) { return; } List<GroupedUnicast<K, V>> list = new ArrayList<GroupedUnicast<K, V>>(groups.values()); groups.clear(); for (GroupedUnicast<K, V> e : list) { e.onComplete(); } done = true; GROUP_COUNT.decrementAndGet(this); drain(); }

Target:
Why not just iterate over `groups.values()` here and avoid `list` allocation? Or you want array structure for better performance? If so, not sure you're winning something big because you're iterating over `values()` in the constructor of `ArrayList` and then here.
Source:
public void onNext(T t) { List<T> b = buffer; if (b == null) { b = new ArrayList<T>(); buffer = b; } b.add(t); if (b.size() == count) { buffer = null; actual.onNext(b); } }

Target:
Don't you want to give `count` as the capacity hint?
Source:
public void call() { try { subscriber.onSuccess(value); } catch (Throwable t) { subscriber.onError(t); return; } }

Target:
No need for `return` here
Source:
public int compare(TimedAction action1, TimedAction action2) { if (action1.time == action2.time) { return Long.valueOf(action1.count).compareTo(action2.count); } else { return Long.valueOf(action1.time).compareTo(action2.time); } }

Target:
Could you turn these into `a < b ? -1 : ((a > b) ? 1 : 0)` instead?
Source:
public SubscriberIterator() { this.notifications = new LinkedBlockingQueue<Notification<? extends T>>(); this.buf = null; }

Target:
Setting variables to their default value on construction is a no-op semantically but still mean instructions executed which causes the construction of the object to take longer.
Source:
public Subscriber<? super T> call(final Subscriber<? super T> child) { return new Subscriber<T>(child) { @Override public void onCompleted() { child.onCompleted(); } @Override public void onError(Throwable e) { child.onError(e); } @Override public void onNext(T t) { // ignore element } }; }

Target:
This will forward the child's requests and will hang because the child doesn't receive an element and nobody is requesting more. I'd instead write this: ``` java Subscriber<T> result = new Subscribeer<T>() { ... } child.add(result); return result; ```
Source:
void requestMore(long n) { if (n > 0) { // CAS loop to atomically change state given that onCompleted() // or another requestMore() may be acting concurrently while (true) { //read the value of state and then try state transitions //only if the value of state does not change in the meantime //(in another requestMore() or onCompleted()). If the value // has changed and we expect to do a transition still then // we loop and try again. final int s = state.get(); if (s == NOT_REQUESTED_NOT_COMPLETED) { if (state.compareAndSet(NOT_REQUESTED_NOT_COMPLETED, REQUESTED_NOT_COMPLETED)) { request(Long.MAX_VALUE); return; } } else if (s == NOT_REQUESTED_COMPLETED) { if (state.compareAndSet(NOT_REQUESTED_COMPLETED, REQUESTED_COMPLETED)) { emit(); return; } } else // already requested so we exit return; } } }

Target:
Since you don't override `onStart` it will request MAX_VALUE on subcsription and as such this is no-op and can be removed. If the intention was to request only when downstream actually requests, then I think we can pre-start the upstream and they will meet.
Source:
protected String render (Object item) { //do nothing by default return null; }

Target:
Experimental on this as well.
Source:
private boolean isSelected() { if (selection.choice.get() == this) { // fast-path return true; } else { if (selection.choice.compareAndSet(null, this)) { selection.unsubscribeOthers(this); return true; } else { // we lost so unsubscribe ... and force cleanup again due to possible race conditions unsubscribe(); selection.unsubscribeLosers(); return false; } } }

Target:
`unsubscribe();` is redundant because `unsubscribeLosers` will call it. LGTM if removing this line.
Source:
public void unsubscribe() { synchronized (this) { if (ONCE_UPDATER.getAndSet(this, 1) == 0) { worker.schedule(new Action0() { @Override public void call() { worker.unsubscribe(); } }); } } }

Target:
This synchronized should be removed.
Source:
public void unsubscribe() { if (unsubscribed) { return; } unsubscribed = true; // we will only get here once unsubscribeFromAll(subscriptions); }

Target:
The field `subscriptions` should be nulled to free memory.
Source:
void error(Throwable e) { RxJavaPlugins.getInstance().getErrorHandler().handleError(e); exceptions.add(e); complete(); }

Target:
This does eventually emit the `CompositeException`. Is this consciously wanting to handle each error individually instead of only via the composite?
Source:
public void unsubscribe() { synchronized (this) { if (unsubscribed || subscriptions == null) { return; } else { unsubscribed = true; } } // we will only get here once unsubscribeFromAll(subscriptions); }

Target:
If the chain is never added, this won't set the chain to unsubscribed = true.
Source:
public void clear() { List<Subscription> unsubscribe = null; synchronized (this) { if (unsubscribed || subscriptions == null) { return; } else { unsubscribe = new ArrayList<Subscription>(subscriptions); } } unsubscribeFromAll(unsubscribe); }

Target:
This doesn't clear the subscriptions, just copies it. You could just pass out the Set and replace it with null. ``` java Set<Subscription> unsubscribe = null; synchronized (this) { if (unsubscribed || subscriptions == null) { return; } unsubscribe = subscriptions; subscriptions = null; } unsubscribeFromAll(unsubscribe); ```
Source:
private MostRecentObserver(T value) { VALUE_UPDATER.lazySet(this, nl.next(value)); }

Target:
I don't think we can use lazySet here. Take a look at this definition: http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6275329 > The semantics are that the write is guaranteed not to be re-ordered with any previous write, but may be reordered with subsequent operations (or equivalently, might not be visible to other threads) until some other volatile write or synchronizing action occurs).
Source:
public void next(T value) { if (!terminated) { list.addLast(enterTransform.call(nl.next(value))); evictionPolicy.evict(list); TAIL_UPDATER.lazySet(this, list.tail); } }

Target:
Again, why is this safe to do? It seems the tail() method would want consistent reads on this?
Source:
public final Observable<T> takeLast(final int count) { return lift(new OperatorTakeLast(count)); }

Target:
Could you add the type parameters to the constructor calls here and below?
Source:
private void closeTestingServerSocket(ServerSocket serverSocket) throws IOException { serverSocket.close(); while (!serverSocket.isClosed()) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } }

Target:
Did you take a look at our conventions regarding the use of exception.printStackTrace? https://wiki.openmrs.org/display/docs/Java+Conventions
Source:
public void setPropertyValue(String propertyName, String value){ setParam("property."+propertyName+".default", value); }

Target:
Shouldn't you be calling setParam("property." + propertyName, value) to be concise with distro.properties?
Source:
protected void showMessage(String message) { System.out.print(message); }

Target:
I'd use println
Source:
public Iterable<NodeMetadata> listNodesByIds(Iterable<String> ids) { return Iterables.transform(Maps.filterKeys(nodes.get().asMap(), in(ImmutableSet.copyOf(ids))).values(), converter); }

Target:
Static imports (of e.g. `Iterables.transform`) or no static imports? Mixed bunch further down, e.g. `EC2ListNodesStrategy` **with** imports and plenty of other cases **without**.
Source:
public Iterable<Server> listNodesByIds(final Iterable<String> ids) { return Iterables.filter(listNodes(), new Predicate<Server>() { @Override public boolean apply(Server server) { return Iterables.contains(ids, server.getId()); } }); }

Target:
More static imports here?
Source:
instancesByIdInRegion(final Multimap<String,String> idsByRegions) { return new Function<String, Set<? extends Reservation<? extends RunningInstance>>>() { @Override public Set<? extends Reservation<? extends RunningInstance>> apply(String from) { return client.getInstanceServices() .describeInstancesInRegion(from, Iterables.toArray(idsByRegions.get(from), String.class)); } }; }

Target:
One more static import here?
Source:
public Iterable<? extends NodeMetadata> listNodesByIds(Iterable<String> ids) { return FluentIterable.from(listDetailsOnNodesMatching(all())).filter(withIds(Iterables.toArray(ids, String.class))).toSet(); }

Target:
Getting to the end of the static imports soon ;-)
Source:
protected Function<String, Set<SpotInstanceRequest>> spotInstancesByIdInRegion(final Multimap<String,String> idsByRegions) { return new Function<String, Set<SpotInstanceRequest>>() { @Override public Set<SpotInstanceRequest> apply(String from) { return client.getSpotInstanceServices() .describeSpotInstanceRequestsInRegion(from, Iterables.toArray(idsByRegions.get(from), String.class)); } }; }

Target:
Another static here
Source:
public String toString() { return toStringHelper("").omitNullValues().add("id", id).add("name", name).toString(); }

Target:
Why the empty string in toStringHelper("") ?
Source:
protected boolean isSafariApp() { if (wirApplicationName != null && SAFARI.equals(wirApplicationName) && wirApplicationBundleIdentifier != null && SAFARIBUNDLEIDENTIFIER.equals(wirApplicationBundleIdentifier)) { return true; } return false; }

Target:
the null check is redundant here if you refactor this code to something like below ``` if (SAFARI.equals(wirApplicationName) && SAFARIBUNDLEIDENTIFER.equals(wirApplicationBundleIdentifier)){ return true; } ``` since we are now comparing a String constant with a variable contents, null check is automatically taken care of because `"".equals(null)` is always false
Source:
public Response handle() throws Exception { ServerSideSession session = getDriver().getSession(getRequest().getSession()); JSONObject payload = getRequest().getPayload(); String type = payload.getString("type"); WebDriverLog log = (WebDriverLog) session.getLogManager().getLog(type); List<LogEntry> entries = (log == null ? (Collections.<LogEntry>emptyList()) : log.getAndClearEntries()); return createResponse(entries); }

Target:
Have the IOSLogManager itself return an empty list, not null.
Source:
public Group nextRow() throws TranslatorException, DataNotAvailableException { while(true){ try { Group row = nextRowInternal(); if (row == null) { return null; } return row; } catch (IOException e) { throw new TranslatorException(e); } } }

Target:
what is need for the while?
Source:
public void close() throws ResourceException { try { super.close(); } catch (Exception e) { e.printStackTrace(); } LogManager.logDetail(LogConstants.CTX_CONNECTOR, CassandraManagedConnectionFactory.UTIL.getString("shutting_down")); //$NON-NLS-1$ }

Target:
Avoid printStackTrace. At first glance you can just throw a ResourceException. However you can avoid all of this by changing the base close method - does it really need to throw Exception? It looks like it doesn't need any checked exception thrown - which means it won't need any override in extending classes.
Source:
public SipMessage.Builder<T> withRouteHeaders(final RouteHeader... routes) { if (routes != null) { this.routeHeaders = ensureList(this.routeHeaders); this.routeHeaders.clear(); routeHeader = routes[0]; this.routeHeaders.addAll(Arrays.asList(routes)); } return this; }

Target:
I guess this could blow up...
Source:
public SipMessage.Builder<T> withViaHeaders(final List<ViaHeader> vias) { if (vias != null) { this.viaHeaders = ensureList(this.viaHeaders); this.viaHeaders.clear(); for (final ViaHeader via : vias) { this.viaHeaders.add(via); viaHeader = via; } } return this; }

Target:
as with the others, need to "remember" the first via, not the last.
Source:
public void start() throws TTransportException { for (Engine engine : engines.values()) { engine.start(); } httpServer.start(); plugins.start(); System.out.println("The Concourse server has started"); server.serve(); Thread managementd = new Thread(() -> { managementServer.serve(); },"management-server"); managementd.setDaemon(true); managementd.start(); }

Target:
You have to run this thread before the call to `sever.serve()` because that method is blocking.
Source:
protected PluginConfiguration(Path location) { if(Files.exists(location)) { try { this.prefs = new PreferencesHandler(location.toString()) {}; } catch (ConfigurationException e) { throw Throwables.propagate(e); } } else { this.prefs = null; } addDefault(SystemPreference.HEAP_SIZE, DEFAULT_HEAP_SIZE_IN_BYTES); addDefault(SystemPreference.LOG_LEVEL, Level.INFO.levelStr); addDefault(SystemPreference.ALIASES, Lists.newLinkedList()); }

Target:
@RaghavBabu never use a LinkedList
Source:
public boolean insert(Set<DatasetEntry<E, A, V>> entries) { for (DatasetEntry<E, A, V> entry : entries) { if(!insert(entry)) { return false; } } return true; }

Target:
Is this supposed to be atomic such that either all entries get added or none at all? For example, What should happen if I have 10 entires, and the 4th one already exists?
Source:
private boolean isExistingUsername0(ByteBuffer username) { if(disabledUsers.contains(username)) return false; return credentials.containsValue(ByteBuffers.encodeAsHex(username)); }

Target:
add `{` after if statement. See style guide
Source:
public Iterator<V2> iterator() { return new Iterator<V2>(){ Iterator<V1> backing = original.iterator(); int cursor; @Override public boolean hasNext() { return cursor <= size(); } @Override public V2 next() { V1 backingNext = backing.next(); cursor += 1; return function.apply(backingNext); } }; }

Target:
no need for a cursor
Source:
public static OperatorSymbol parse(String string) { Operator operator = Convert.stringToOperator(string); if(operator != null) return new OperatorSymbol(operator); else throw new RuntimeException(MessageFormat.format( "Cannot parse {0} into an OperatorSymbol", string)); }

Target:
Add braces to your if and else blocks to maintain consistency with the rest of the code-style :)
Source:
public void exit() { try { client.logout(creds); } catch (Exception e) { throw Throwables.propagate(e); } client.getInputProtocol().getTransport().close(); client.getOutputProtocol().getTransport().close(); }

Target:
Place these last two lines within the try block
Source:
private short getNewUid() { write.lock(); try { this.maxUid += 1; } finally { write.unlock(); } return this.maxUid; }

Target:
This statement should go in the try block.
Source:
public boolean verifyPasswordStructure(String password) { if (StringUtils.isBlank(password)) { return false; } if (StringUtils.length(password) < 6) { return false; } return true; }

Target:
Silly thing but these two ifs can be collapsed...an empty password would have a length < 6 already.
Source:
public void setup() { context.turnOffAuthorisationSystem(); configurationService.setProperty("webui.user.assumelogin", true); context.restoreAuthSystemState(); }

Target:
it is not really needed, we can simplify the code here
Source:
public static void deleteEPerson(UUID uuid) throws SQLException, IOException { try (Context c = new Context()) { c.turnOffAuthorisationSystem(); EPerson ePerson = ePersonService.find(c, uuid); if (ePerson != null) { try { ePersonService.delete(c, ePerson); } catch (AuthorizeException e) { // cannot occur, just wrap it to make the compiler happy throw new RuntimeException(e.getMessage(), e); } } c.complete(); } }

Target:
Tiny thing to mention (just cause I've seen it alot in this PR). It's sorta useless (to me) to use `e.getMessage()` here. We either should pass in a more specific error message, or just do `throw new RuntimeException(e);`
Source:
private boolean checkMinCardinality(Context context, Item item, Relationship relationship, Integer minCardinality, boolean isLeft) throws SQLException { List<Relationship> list = this.findByItemAndRelationshipType(context, item, relationship.getRelationshipType(), -1, -1, isLeft); if (minCardinality != null && !(list.size() > minCardinality)) { return false; } return true; }

Target:
Why do you change the call here? Both calls should be equal and the previous one is shorter, or am I missing something?
Source:
public void destroy() throws Exception { AuthorityServiceFactory.getInstance().getAuthorityIndexingService().cleanIndex(); configurationService.setProperty("plugin.named.org.dspace.content.authority.ChoiceAuthority", null); configurationService.setProperty("solr.authority.server", null); configurationService.setProperty("choices.plugin.dc.contributor.author", null); configurationService.setProperty("choices.presentation.dc.contributor.author", null); configurationService.setProperty("authority.controlled.dc.contributor.author", null); configurationService.setProperty("authority.author.indexer.field.1", null); super.destroy(); }

Target:
this seems a bit risky to me as essentially we are fixing the configuration of the test env in this destroy method. If we change the test env configuration we should remember to change also this method otherwise some test will run with different env configuration (pre and post this IT)
Source:
private boolean verifyEntityTypes(Item itemToProcess, EntityType entityTypeToProcess) { List<MetadataValue> list = itemService.getMetadata(itemToProcess, "relationship", "type", null, Item.ANY); if (list.isEmpty()) { return false; } String leftEntityType = list.get(0).getValue(); if (!StringUtils.equals(leftEntityType, entityTypeToProcess.getLabel())) { return false; } return true; }

Target:
Please use the `MetadataSchemaEnum` you created here in the same way you did above.
Source:
public boolean equals(Object obj) { if (obj == null) { return false; } Class<?> objClass = HibernateProxyHelper.getClassWithoutInitializingProxy(obj); if (getClass() != objClass) { return false; } final RelationshipMetadataValue other = (RelationshipMetadataValue) obj; if (this.isUseForPlace() != other.isUseForPlace()) { return false; } return super.equals(obj); }

Target:
I don't think we need it, we'll verify it
Source:
public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != RelationshipMetadataValue.class) { return false; } final RelationshipMetadataValue other = (RelationshipMetadataValue) obj; if (this.isUseForPlace() != other.isUseForPlace()) { return false; } return super.equals(obj); }

Target:
this seems a strange way to make the check to me. Is there a reason to do that instead than instaceof ?
Source:
private String getEntityTypeStringFromMetadata(List<MetadataValue> list) { String entityType = null; for (MetadataValue mdv : list) { if (StringUtils.equals(mdv.getMetadataField().getMetadataSchema().getName(), "relationship") && StringUtils.equals(mdv.getMetadataField().getElement(), "type")) { entityType = mdv.getValue(); } } return entityType; }

Target:
Trivial: missing 'break;'
Source:
public List<DSpaceObject> getdSpaceObjectsFromRequest(HttpServletRequest request) throws IOException { return constructDSpaceObjectList(ContextUtil.obtainContext(request), request); }

Target:
@benbosman : I'd still encourage us to start with minimal/basic unit tests rather than waiting for "perfection". As you'll see above, I already have concerns that the UUID parsing is very fragile. So, having unit tests to prove it is working at a basic level would be helpful here, especially since the client using the REST API can literally send *anything* in a `text/uri-list`...so we need to ensure the parsing works as we expect.
Source:
private RelationshipMetadataValue getRelationMetadataFromOtherItem(Context context, Item otherItem, String relationName, Integer relationshipId) { RelationshipMetadataValue metadataValue = constructMetadataValue(context, MetadataSchemaEnum.RELATION .getName() + "." + relationName); metadataValue.setAuthority(Constants.VIRTUAL_AUTHORITY_PREFIX + relationshipId); metadataValue.setValue(otherItem.getID().toString()); return metadataValue; }

Target:
Please consider that metadataValue can be null because constructMetadataValue might return null.
Source:
public void searchMethodsExist() throws Exception { context.turnOffAuthorisationSystem(); getClient().perform(get("/api/core/metadatafields")) .andExpect(jsonPath("$._links.search.href", notNullValue())); getClient().perform(get("/api/core/metadatafields/search")) .andExpect(status().isOk()) .andExpect(content().contentType(contentType)) .andExpect(jsonPath("$._links.bySchema", notNullValue())); }

Target:
I believe the Auth system should remain on in this method.
Source:
public void findByNullSchema() throws Exception { context.turnOffAuthorisationSystem(); getClient().perform(get("/api/core/metadatafields/search/bySchema")) .andExpect(status().isUnprocessableEntity()); }

Target:
I believe the Auth system should remain on in this method.
Source:
public void createUnauthorized() throws Exception { context.turnOffAuthorisationSystem(); MetadataFieldRest metadataFieldRest = new MetadataFieldRest(); metadataFieldRest.setElement(ELEMENT); metadataFieldRest.setQualifier(QUALIFIER); metadataFieldRest.setScopeNote(SCOPE_NOTE); getClient() .perform(post("/api/core/metadatafields") .param("schemaId", metadataSchema.getID() + "") .content(new ObjectMapper().writeValueAsBytes(metadataFieldRest)) .contentType(contentType)) .andExpect(status().isUnauthorized()); }

Target:
I believe the Auth system should remain on in this method.
Source:
public RegistrationData findByEmail(Context context, String email) throws SQLException { CriteriaBuilder criteriaBuilder = getCriteriaBuilder(context); CriteriaQuery criteriaQuery = getCriteriaQuery(criteriaBuilder, RegistrationData.class); Root<RegistrationData> registrationDataRoot = criteriaQuery.from(RegistrationData.class); criteriaQuery.select(registrationDataRoot); criteriaQuery.where(criteriaBuilder.equal(registrationDataRoot.get(RegistrationData_.email), email)); return uniqueResult(context, criteriaQuery, true, RegistrationData.class, -1, -1); }

Target:
Original query was not cacheable. This one is. I think the third param should be `false`.
Source:
public void addPolicies(Context c, List<ResourcePolicy> policies, DSpaceObject dest) throws SQLException, AuthorizeException { // now add them to the destination object List<ResourcePolicy> newPolicies = new LinkedList<>(); for (ResourcePolicy srp : policies) { ResourcePolicy policy = resourcePolicyService.create(c); policy = srp.copyToDSpaceObject(policy,dest); resourcePolicyService.update(c,policy); newPolicies.add(policy); } resourcePolicyService.update(c, newPolicies); }

Target:
This kind of beats the purpose of having the "copyToDSpaceObject" method. This code will force hibernate to execute two DB statements: an insert and an update. I think you should move the copyToDSpaceObject to the ResourcePolicyService: * Create a new empty resource policy * Copy over the values * Then pass that filled in resource policy to `resourcePolicyDAO.create()`. You can enable Hibernate DEBUG logging in hibernate.cfg.xml to see the SQL statements it executes.
Source:
public void consume(Context context, Event event) throws Exception { int subjectType = event.getSubjectType(); int eventType = event.getEventType(); switch (subjectType) { case Constants.ITEM: if (eventType == Event.INSTALL) { items.add((Item) event.getSubject(context)); } break; default: log.warn("consume() got unrecognized event: " + event.toString()); } }

Target:
I'm afraid this could spam the logs. I made bad experiences with logging when developing the DOIConsumer. Please reduce the log level to debug.
Source:
public static TableRow row(String table) throws SQLException { return new TableRow(canonicalize(table), getColumnNames(null, table)); }

Target:
You create a `getColumnNames(table)` method later on in this class. This change is unnecessary, as it should just use that other method.
Source:
public Page<SiteRest> findAll(Context context, Pageable pageable) { List<Site> sites = new ArrayList<Site>(); int total = 0; try { sites.add(sitesv.findSite(context)); } catch (SQLException e) { throw new RuntimeException(e.getMessage(), e); } Page<SiteRest> page = new PageImpl<Site>(sites, pageable, total).map(converter); return page; }

Target:
this should be set to 1 or increased when we manually add the site to the return list
Source:
public SiteRestRepository() { System.out.println("Repository initialized by Spring"); }

Target:
Shouldn't this go to the log, at DEBUG level?
Source:
public void setName(Context context, String name) throws SQLException { if (!permanent) getGroupService().setMetadataSingleValue(context, this, MetadataSchema.DC_SCHEMA, "title", null, null, name); }

Target:
I'd suggest we also log/throw an error here if anyone attempt to rename a permanent group. That way if the UI layer (or any caller) makes such an attempt, it will receive an error message in return, instead of no response.
Source:
public static void _destroyKernel() { if (kernel != null) { // cleanup the kernel try { kernel.destroy(); } catch (Exception e) { // keep going } kernel.destroy(); } // must null things out or JUnit will not clean them up kernel = null; }

Target:
Destroy the kernel twice? (See line 58.)
Source:
public List<Map> getCollectionsWithBitstreamSizesTotal(Context context) throws SQLException { return collectionDAO.getCollectionsWithBitstreamSizesTotal(context); }

Target:
It would be great if this map could use generics so we know what it contains.
Source:
public static String format(Date date, boolean init) { SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss.'000Z'"); if (!init) sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.'999Z'"); // We indicate that the returned date is in Zulu time (UTC) so we have // to set the time zone of sdf correct. sdf.setTimeZone(TimeZone.getTimeZone("ZULU")); String ret = sdf.format(date); return ret; }

Target:
If we add a line break here, we should use curly brackets as well. Everything else is error-prone.
Source:
private static void log(String text) { if (debug) { log(text); } }

Target:
If `debug = true`, `log` will just call itself recursively. Surely you mean `if(debug) { Log.d(text); }`
Source:
private Activity getCurrentActivity() { final Activity[] activity = new Activity[1]; java.util.Collection<Activity> activities = ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(Stage.RESUMED); activity[0] = Iterables.getOnlyElement(activities); return activity[0]; }

Target:
Why is an array necessary here? It looks like there is only ever one item.
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); AWSMobileClient.getInstance().initialize(getApplicationContext(), new Callback<UserStateDetails>() { @Override public void onResult(UserStateDetails userStateDetails) { Log.i(TAG, "AWSMobileClient initialized. User State is : " + userStateDetails.getUserState()); } @Override public void onError(Exception e) { Log.e(TAG, "Initialization error.", e); } }); initUI(); }

Target:
Not sure if this is still needed.
Source:
public IndexCoordinates getIndexCoordinates() { return indexCoordinatesResolver.resolve(getEvaluationContext(null), IndexCoordinates.of(getIndexName())); }

Target:
How about simplifying this method back to `IndexCoordinates.of(getIndexName()))` and keeping the evaluation within `getIndexName()`?
Source:
public boolean hasSeqNo() { return this.seqNo != null && SequenceNumbers.isAssignedSeqNo(this.seqNo); }

Target:
```suggestion return this.seqNo != null; ``` I wouldn't do the validity check here but at the place where a `SeqNoPrimaryTerm`is constructed. Here in the `MapDocument` these are just numeric values coming from ES.
Source:
public T doWith(@Nullable Document document) { if (document == null) { return null; } T materializedEntity = reader.read(type, document); return maybeCallbackAfterConvert(materializedEntity, document, index); }

Target:
I'd prefer `entity` here
Source:
public Mono<T> doWith(@Nullable Document document) { if (document == null) { return Mono.empty(); } T materializedEntity = reader.read(type, document); return maybeCallAfterConvert(materializedEntity, document, index); }

Target:
why not `entity`?
Source:
private SearchScrollHits<String> newSearchScrollHits(List<SearchHit<String>> hits) { return new SearchHitsImpl<String>(1, TotalHitsRelation.EQUAL_TO, 0, "1234", hits, null); }

Target:
```suggestion return new SearchHitsImpl<String>(hits.size(), TotalHitsRelation.EQUAL_TO, 0, "1234", hits, null); ```
Source:
public RuntimeException translateException(Exception exception) { RuntimeException runtimeException = exception instanceof RuntimeException ? (RuntimeException) exception : new RuntimeException(exception.getMessage(), exception); RuntimeException potentiallyTranslatedException = exceptionTranslator .translateExceptionIfPossible(runtimeException); return potentiallyTranslatedException != null ? potentiallyTranslatedException : runtimeException; }

Target:
Nit: Let's have this method private unless someone asks for it. It's an utility to the client callback.