auphong2707/dl4se-code-review-dataset huggingface dataset:
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) { START errors = new ArrayList<Throwable>(); END } errors.add(ex); } } Exceptions.throwIfAny(errors); } nit: `(1)`

Target:
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>(1); } errors.add(ex); } } Exceptions.throwIfAny(errors); }
Source:
public void onError(Throwable e) { START long r = get(); END if (r != Long.MIN_VALUE) { actual.onError(e); } } nit: inline

Target:
public void onError(Throwable e) { if (get() != Long.MIN_VALUE) { actual.onError(e); } }
Source:
public void innerNext(InnerQueuedSubscriber<R> inner, R value) { START if (!inner.queue().offer(value)) { END inner.cancel(); innerError(inner, new MissingBackpressureException()); } else { drain(); } } nit: same here about reversing `if-else`. I think PMD complains about it btw

Target:
public void innerNext(InnerQueuedSubscriber<R> inner, R value) { if (inner.queue().offer(value)) { drain(); } else { inner.cancel(); innerError(inner, new MissingBackpressureException()); } }
Source:
public void onNext(T t) { if (fusionMode != ASYNC) { START if (!queue.offer(t)) { END onError(new IllegalStateException("Queue is full?!")); return; } } drain(); } nested `if`s could be collapsed with `&&`

Target:
public void onNext(T t) { if (fusionMode != ASYNC && !queue.offer(t)) { onError(new IllegalStateException("Queue is full?!")); return; } drain(); }
Source:
public void onCompleted() { if (done) { return; } List<GroupedUnicast<K, V>> list = new ArrayList<GroupedUnicast<K, V>>(groups.values()); groups.clear(); START for (GroupedUnicast<K, V> e : list) { END e.onComplete(); } done = true; GROUP_COUNT.decrementAndGet(this); drain(); } 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.

Target:
public void onCompleted() { if (done) { return; } for (GroupedUnicast<K, V> e : groups.values()) { e.onComplete(); } groups.clear(); done = true; GROUP_COUNT.decrementAndGet(this); drain(); }
Source:
public void onNext(T t) { List<T> b = buffer; if (b == null) { START b = new ArrayList<T>(); END buffer = b; } b.add(t); if (b.size() == count) { buffer = null; actual.onNext(b); } } Don't you want to give `count` as the capacity hint?

Target:
public void onNext(T t) { List<T> b = buffer; if (b == null) { b = new ArrayList<T>(count); buffer = b; } b.add(t); if (b.size() == count) { buffer = null; actual.onNext(b); } }
Source:
public void call() { try { subscriber.onSuccess(value); } catch (Throwable t) { subscriber.onError(t); START return; END } } No need for `return` here

Target:
public void call() { try { subscriber.onSuccess(value); } catch (Throwable t) { subscriber.onError(t); } }
Source:
public int compare(TimedAction action1, TimedAction action2) { if (action1.time == action2.time) { START return Long.valueOf(action1.count).compareTo(action2.count); END } else { return Long.valueOf(action1.time).compareTo(action2.time); } } Could you turn these into `a < b ? -1 : ((a > b) ? 1 : 0)` instead?

Target:
public int compare(TimedAction action1, TimedAction action2) { if (action1.time == action2.time) { return action1.count < action2.count ? -1 : ((action1.count > action2.count) ? 1 : 0); } else { return action1.time < action2.time ? -1 : ((action1.time > action2.time) ? 1 : 0); } }
Source:
public SubscriberIterator() { this.notifications = new LinkedBlockingQueue<Notification<? extends T>>(); START this.buf = null; END } 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.

Target:
public SubscriberIterator() { this.notifications = new LinkedBlockingQueue<Notification<? extends T>>(); }
Source:
public Subscriber<? super T> call(final Subscriber<? super T> child) { START return new Subscriber<T>(child) { END @Override public void onCompleted() { child.onCompleted(); } @Override public void onError(Throwable e) { child.onError(e); } @Override public void onNext(T t) { // ignore element } }; } 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; ```

Target:
public Subscriber<? super T> call(final Subscriber<? super T> child) { Subscriber<T> parent = new Subscriber<T>() { @Override public void onCompleted() { child.onCompleted(); } @Override public void onError(Throwable e) { child.onError(e); } @Override public void onNext(T t) { // ignore element } }; child.add(parent); return parent; }
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)) { START request(Long.MAX_VALUE); END return; } } else if (s == NOT_REQUESTED_COMPLETED) { if (state.compareAndSet(NOT_REQUESTED_COMPLETED, REQUESTED_COMPLETED)) { emit(); return; } } else // already requested so we exit return; } } } 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.

Target:
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)) { return; } } else if (s == NOT_REQUESTED_COMPLETED) { if (state.compareAndSet(NOT_REQUESTED_COMPLETED, REQUESTED_COMPLETED)) { emit(); return; } } else // already requested so we exit return; } } }
Source:
START protected String render (Object item) { END //do nothing by default return null; } Experimental on this as well.

Target:
protected String render (Object item) throws InterruptedException { //do nothing by default return null; }
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 START unsubscribe(); END selection.unsubscribeLosers(); return false; } } } `unsubscribe();` is redundant because `unsubscribeLosers` will call it. LGTM if removing this line.

Target:
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 selection.unsubscribeLosers(); return false; } } }
Source:
public void unsubscribe() { START synchronized (this) { END if (ONCE_UPDATER.getAndSet(this, 1) == 0) { worker.schedule(new Action0() { @Override public void call() { worker.unsubscribe(); } }); } } } This synchronized should be removed.

Target:
public void unsubscribe() { if (ONCE_UPDATER.getAndSet(this, 1) == 0) { worker.schedule(new Action0() { @Override public void call() { worker.unsubscribe(); } }); } }
Source:
public void unsubscribe() { if (unsubscribed) { return; } START unsubscribed = true; END // we will only get here once unsubscribeFromAll(subscriptions); } The field `subscriptions` should be nulled to free memory.

Target:
public void unsubscribe() { if (unsubscribed) { return; } unsubscribed = true; // we will only get here once unsubscribeFromAll(subscriptions); subscriptions = null; }
Source:
void error(Throwable e) { START RxJavaPlugins.getInstance().getErrorHandler().handleError(e); END exceptions.add(e); complete(); } This does eventually emit the `CompositeException`. Is this consciously wanting to handle each error individually instead of only via the composite?

Target:
void error(Throwable e) { exceptions.add(e); complete(); }
Source:
public void unsubscribe() { synchronized (this) { START if (unsubscribed || subscriptions == null) { END return; } else { unsubscribed = true; } } // we will only get here once unsubscribeFromAll(subscriptions); } If the chain is never added, this won't set the chain to unsubscribed = true.

Target:
public void unsubscribe() { synchronized (this) { if (unsubscribed) { return; } unsubscribed = true; } // we will only get here once unsubscribeFromAll(subscriptions); }
Source:
public void clear() { List<Subscription> unsubscribe = null; synchronized (this) { if (unsubscribed || subscriptions == null) { return; } else { START unsubscribe = new ArrayList<Subscription>(subscriptions); END } } unsubscribeFromAll(unsubscribe); } 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); ```

Target:
public void clear() { Collection<Subscription> unsubscribe = null; synchronized (this) { if (unsubscribed || subscriptions == null) { return; } else { unsubscribe = subscriptions; subscriptions = null; } } unsubscribeFromAll(unsubscribe); }
Source:
private MostRecentObserver(T value) { START VALUE_UPDATER.lazySet(this, nl.next(value)); END } 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).

Target:
private MostRecentObserver(T value) { this.value = nl.next(value); }
Source:
public void next(T value) { if (!terminated) { list.addLast(enterTransform.call(nl.next(value))); evictionPolicy.evict(list); START TAIL_UPDATER.lazySet(this, list.tail); END } } Again, why is this safe to do? It seems the tail() method would want consistent reads on this?

Target:
public void next(T value) { if (!terminated) { list.addLast(enterTransform.call(nl.next(value))); evictionPolicy.evict(list); tail = list.tail; } }
Source:
public final Observable<T> takeLast(final int count) { START return lift(new OperatorTakeLast(count)); END } Could you add the type parameters to the constructor calls here and below?

Target:
public final Observable<T> takeLast(final int count) { return lift(new OperatorTakeLast<T>(count)); }
Source:
private void closeTestingServerSocket(ServerSocket serverSocket) throws IOException { serverSocket.close(); while (!serverSocket.isClosed()) { try { Thread.sleep(500); } catch (InterruptedException e) { START e.printStackTrace(); END } } } Did you take a look at our conventions regarding the use of exception.printStackTrace? https://wiki.openmrs.org/display/docs/Java+Conventions

Target:
private void closeTestingServerSocket(ServerSocket serverSocket) throws IOException { serverSocket.close(); while (!serverSocket.isClosed()) { try { Thread.sleep(500); } catch (InterruptedException e) { log.debug(e.toString()); } } }
Source:
public void setPropertyValue(String propertyName, String value){ START setParam("property."+propertyName+".default", value); END } Shouldn't you be calling setParam("property." + propertyName, value) to be concise with distro.properties?

Target:
public void setPropertyValue(String propertyName, String value){ setParam("property."+propertyName, value); }
Source:
protected void showMessage(String message) { START System.out.print(message); END } I'd use println

Target:
protected void showMessage(String message) { System.out.println(message); }
Source:
public Iterable<NodeMetadata> listNodesByIds(Iterable<String> ids) { START return Iterables.transform(Maps.filterKeys(nodes.get().asMap(), in(ImmutableSet.copyOf(ids))).values(), converter); END } 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**.

Target:
public Iterable<NodeMetadata> listNodesByIds(Iterable<String> ids) { return transform(filterKeys(nodes.get().asMap(), in(ImmutableSet.copyOf(ids))).values(), converter); }
Source:
public Iterable<Server> listNodesByIds(final Iterable<String> ids) { return Iterables.filter(listNodes(), new Predicate<Server>() { @Override public boolean apply(Server server) { START return Iterables.contains(ids, server.getId()); END } }); } More static imports here?

Target:
public Iterable<Server> listNodesByIds(final Iterable<String> ids) { return filter(listNodes(), new Predicate<Server>() { @Override public boolean apply(Server server) { return contains(ids, server.getId()); } }); }
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() START .describeInstancesInRegion(from, Iterables.toArray(idsByRegions.get(from), String.class)); END } }; } One more static import here?

Target:
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, toArray(idsByRegions.get(from), String.class)); } }; }
Source:
public Iterable<? extends NodeMetadata> listNodesByIds(Iterable<String> ids) { START return FluentIterable.from(listDetailsOnNodesMatching(all())).filter(withIds(Iterables.toArray(ids, String.class))).toSet(); END } Getting to the end of the static imports soon ;-)

Target:
public Iterable<? extends NodeMetadata> listNodesByIds(Iterable<String> ids) { return FluentIterable.from(listDetailsOnNodesMatching(all())).filter(withIds(toArray(ids, String.class))).toSet(); }
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() START .describeSpotInstanceRequestsInRegion(from, Iterables.toArray(idsByRegions.get(from), String.class)); END } }; } Another static here

Target:
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, toArray(idsByRegions.get(from), String.class)); } }; }
Source:
public String toString() { START return toStringHelper("").omitNullValues().add("id", id).add("name", name).toString(); END } Why the empty string in toStringHelper("") ?

Target:
public String toString() { return toStringHelper(this).omitNullValues().add("id", id).add("name", name).toString(); }
Source:
protected boolean isSafariApp() { if (wirApplicationName != null && SAFARI.equals(wirApplicationName) && wirApplicationBundleIdentifier != null && SAFARIBUNDLEIDENTIFIER.equals(wirApplicationBundleIdentifier)) { START return true; END } return false; } 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

Target:
protected boolean isSafariApp() { if (SAFARI.equals(wirApplicationName) && SAFARIBUNDLEIDENTIFIER.equals(wirApplicationBundleIdentifier)) { return true; } return 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); START List<LogEntry> entries = (log == null ? (Collections.<LogEntry>emptyList()) : log.getAndClearEntries()); END return createResponse(entries); } Have the IOSLogManager itself return an empty list, not null.

Target:
public Response handle() throws Exception { ServerSideSession session = getDriver().getSession(getRequest().getSession()); JSONObject payload = getRequest().getPayload(); String type = payload.getString("type"); List<LogEntry> entries = session.getLogManager().getLog(type); return createResponse(entries); }
Source:
public Group nextRow() throws TranslatorException, DataNotAvailableException { START while(true){ END try { Group row = nextRowInternal(); if (row == null) { return null; } return row; } catch (IOException e) { throw new TranslatorException(e); } } } what is need for the while?

Target:
public Group nextRow() throws TranslatorException, DataNotAvailableException { try { Group row = nextRowInternal(); if (row == null) { return null; } return row; } catch (IOException e) { throw new TranslatorException(e); } }
Source:
public void close() throws ResourceException { try { super.close(); } catch (Exception e) { START e.printStackTrace(); END } LogManager.logDetail(LogConstants.CTX_CONNECTOR, CassandraManagedConnectionFactory.UTIL.getString("shutting_down")); //$NON-NLS-1$ } 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.

Target:
public void close() { super.close(); LogManager.logDetail(LogConstants.CTX_CONNECTOR, CassandraManagedConnectionFactory.UTIL.getString("shutting_down")); //$NON-NLS-1$ }
Source:
public SipMessage.Builder<T> withRouteHeaders(final RouteHeader... routes) { if (routes != null) { this.routeHeaders = ensureList(this.routeHeaders); this.routeHeaders.clear(); START routeHeader = routes[0]; END this.routeHeaders.addAll(Arrays.asList(routes)); } return this; } I guess this could blow up...

Target:
public SipMessage.Builder<T> withRouteHeaders(final RouteHeader... routes) { if (routes != null && routes.length > 0) { this.routeHeaders = ensureList(this.routeHeaders); this.routeHeaders.clear(); routeHeader = routes[0]; this.routeHeaders.addAll(Arrays.asList(routes)); } return this; }
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); START viaHeader = via; END } } return this; } as with the others, need to "remember" the first via, not the last.

Target:
public SipMessage.Builder<T> withViaHeaders(final List<ViaHeader> vias) { if (vias != null && !vias.isEmpty()) { this.viaHeaders = ensureList(this.viaHeaders); this.viaHeaders.clear(); viaHeader = vias.get(0); this.viaHeaders.addAll(vias); } return this; }
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(); START Thread managementd = new Thread(() -> { END managementServer.serve(); },"management-server"); managementd.setDaemon(true); managementd.start(); } You have to run this thread before the call to `sever.serve()` because that method is blocking.

Target:
public void start() throws TTransportException { for (Engine engine : engines.values()) { engine.start(); } httpServer.start(); plugins.start(); Thread managementd = new Thread(() -> { managementServer.serve(); },"management-server"); managementd.setDaemon(true); managementd.start(); System.out.println("The Concourse server has started"); server.serve(); }
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); START addDefault(SystemPreference.ALIASES, Lists.newLinkedList()); END } @RaghavBabu never use a LinkedList

Target:
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); }
Source:
public boolean insert(Set<DatasetEntry<E, A, V>> entries) { START for (DatasetEntry<E, A, V> entry : entries) { END if(!insert(entry)) { return false; } } return true; } 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?

Target:
public int insert(Set<DatasetEntry<E, A, V>> entries) { int count = 0; for (DatasetEntry<E, A, V> entry : entries) { if(insert(entry)) { count++; } } return count; }
Source:
private boolean isExistingUsername0(ByteBuffer username) { START if(disabledUsers.contains(username)) END return false; return credentials.containsValue(ByteBuffers.encodeAsHex(username)); } add `{` after if statement. See style guide

Target:
private boolean isExistingUsername0(ByteBuffer username) { return credentials.containsValue(ByteBuffers.encodeAsHex(username)); }
Source:
public Iterator<V2> iterator() { return new Iterator<V2>(){ Iterator<V1> backing = original.iterator(); START int cursor; END @Override public boolean hasNext() { return cursor <= size(); } @Override public V2 next() { V1 backingNext = backing.next(); cursor += 1; return function.apply(backingNext); } }; } no need for a cursor

Target:
public Iterator<V2> iterator() { return new Iterator<V2>(){ Iterator<V1> backing = original.iterator(); @Override public boolean hasNext() { return backing.hasNext(); } @Override public V2 next() { V1 backingNext = backing.next(); return function.apply(backingNext); } }; }
Source:
public static OperatorSymbol parse(String string) { START Operator operator = Convert.stringToOperator(string); END if(operator != null) return new OperatorSymbol(operator); else throw new RuntimeException(MessageFormat.format( "Cannot parse {0} into an OperatorSymbol", string)); } Add braces to your if and else blocks to maintain consistency with the rest of the code-style :)

Target:
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)); } }
Source:
public void exit() { try { client.logout(creds); } catch (Exception e) { throw Throwables.propagate(e); } START client.getInputProtocol().getTransport().close(); END client.getOutputProtocol().getTransport().close(); } Place these last two lines within the try block

Target:
public void exit() { try { client.logout(creds); client.getInputProtocol().getTransport().close(); client.getOutputProtocol().getTransport().close(); } catch (Exception e) { throw Throwables.propagate(e); } }
Source:
private short getNewUid() { write.lock(); try { this.maxUid += 1; } finally { write.unlock(); } START return this.maxUid; END } This statement should go in the try block.

Target:
private short getNewUid() { write.lock(); try { this.maxUid += 1; return this.maxUid; } finally { write.unlock(); } }
Source:
public boolean verifyPasswordStructure(String password) { if (StringUtils.isBlank(password)) { return false; } if (StringUtils.length(password) < 6) { return false; START } END return true; } Silly thing but these two ifs can be collapsed...an empty password would have a length < 6 already.

Target:
public boolean verifyPasswordStructure(String password) { if (StringUtils.length(password) < 6) { return false; } return true; }
Source:
public void setup() { START context.turnOffAuthorisationSystem(); END configurationService.setProperty("webui.user.assumelogin", true); context.restoreAuthSystemState(); } it is not really needed, we can simplify the code here

Target:
public void setup() { configurationService.setProperty("webui.user.assumelogin", true); }
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 START throw new RuntimeException(e.getMessage(), e); END } } c.complete(); } } 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);`

Target:
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); } } c.complete(); } }
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(), START -1, -1, isLeft); END if (minCardinality != null && !(list.size() > minCardinality)) { return false; } return true; } Why do you change the call here? Both calls should be equal and the previous one is shorter, or am I missing something?

Target:
private boolean checkMinCardinality(Context context, Item item, Relationship relationship, Integer minCardinality, boolean isLeft) throws SQLException { List<Relationship> list = this.findByItemAndRelationshipType(context, item, relationship.getRelationshipType(), isLeft, -1, -1); if (minCardinality != null && !(list.size() > minCardinality)) { return false; } return true; }
Source:
public void destroy() throws Exception { AuthorityServiceFactory.getInstance().getAuthorityIndexingService().cleanIndex(); START configurationService.setProperty("plugin.named.org.dspace.content.authority.ChoiceAuthority", null); END 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(); } 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)

Target:
public void destroy() throws Exception { AuthorityServiceFactory.getInstance().getAuthorityIndexingService().cleanIndex(); super.destroy(); }
Source:
private boolean verifyEntityTypes(Item itemToProcess, EntityType entityTypeToProcess) { START List<MetadataValue> list = itemService.getMetadata(itemToProcess, "relationship", "type", null, Item.ANY); END if (list.isEmpty()) { return false; } String leftEntityType = list.get(0).getValue(); if (!StringUtils.equals(leftEntityType, entityTypeToProcess.getLabel())) { return false; } return true; } Please use the `MetadataSchemaEnum` you created here in the same way you did above.

Target:
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(); return StringUtils.equals(leftEntityType, entityTypeToProcess.getLabel()); }
Source:
public boolean equals(Object obj) { if (obj == null) { return false; } START Class<?> objClass = HibernateProxyHelper.getClassWithoutInitializingProxy(obj); END if (getClass() != objClass) { return false; } final RelationshipMetadataValue other = (RelationshipMetadataValue) obj; if (this.isUseForPlace() != other.isUseForPlace()) { return false; } return super.equals(obj); } I don't think we need it, we'll verify it

Target:
public boolean equals(Object obj) { if (obj == null) { return false; } if (! (obj instanceof RelationshipMetadataValue)) { return false; } final RelationshipMetadataValue other = (RelationshipMetadataValue) obj; if (this.isUseForPlace() != other.isUseForPlace()) { return false; } return super.equals(obj); }
Source:
public boolean equals(Object obj) { if (obj == null) { return false; } START if (getClass() != RelationshipMetadataValue.class) { END return false; } final RelationshipMetadataValue other = (RelationshipMetadataValue) obj; if (this.isUseForPlace() != other.isUseForPlace()) { return false; } return super.equals(obj); } this seems a strange way to make the check to me. Is there a reason to do that instead than instaceof ?

Target:
public boolean equals(Object obj) { if (obj == null) { return false; } if (! (obj instanceof RelationshipMetadataValue)) { return false; } final RelationshipMetadataValue other = (RelationshipMetadataValue) obj; if (this.isUseForPlace() != other.isUseForPlace()) { return false; } return super.equals(obj); }
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(); START } END } return entityType; } Trivial: missing 'break;'

Target:
private String getEntityTypeStringFromMetadata(List<MetadataValue> list) { for (MetadataValue mdv : list) { if (StringUtils.equals(mdv.getMetadataField().getMetadataSchema().getName(), "relationship") && StringUtils.equals(mdv.getMetadataField().getElement(), "type")) { return mdv.getValue(); } } return null; }
Source:
START public List<DSpaceObject> getdSpaceObjectsFromRequest(HttpServletRequest request) throws IOException { END return constructDSpaceObjectList(ContextUtil.obtainContext(request), request); } @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.

Target:
public List<DSpaceObject> getdSpaceObjectsFromRequest(HttpServletRequest request) { return constructDSpaceObjectList(ContextUtil.obtainContext(request), request); }
Source:
private RelationshipMetadataValue getRelationMetadataFromOtherItem(Context context, Item otherItem, String relationName, Integer relationshipId) { RelationshipMetadataValue metadataValue = constructMetadataValue(context, MetadataSchemaEnum.RELATION .getName() + "." + relationName); START metadataValue.setAuthority(Constants.VIRTUAL_AUTHORITY_PREFIX + relationshipId); END metadataValue.setValue(otherItem.getID().toString()); return metadataValue; } Please consider that metadataValue can be null because constructMetadataValue might return null.

Target:
private RelationshipMetadataValue getRelationMetadataFromOtherItem(Context context, Item otherItem, String relationName, Integer relationshipId) { RelationshipMetadataValue metadataValue = constructMetadataValue(context, MetadataSchemaEnum.RELATION .getName() + "." + relationName); if (metadataValue != null) { metadataValue.setAuthority(Constants.VIRTUAL_AUTHORITY_PREFIX + relationshipId); metadataValue.setValue(otherItem.getID().toString()); return metadataValue; } return null; }
Source:
public void searchMethodsExist() throws Exception { START context.turnOffAuthorisationSystem(); END 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())); } I believe the Auth system should remain on in this method.

Target:
public void searchMethodsExist() throws Exception { 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())); }
Source:
public void findByNullSchema() throws Exception { START context.turnOffAuthorisationSystem(); END getClient().perform(get("/api/core/metadatafields/search/bySchema")) .andExpect(status().isUnprocessableEntity()); } I believe the Auth system should remain on in this method.

Target:
public void findByNullSchema() throws Exception { getClient().perform(get("/api/core/metadatafields/search/bySchema")) .andExpect(status().isUnprocessableEntity()); }
Source:
public void createUnauthorized() throws Exception { START context.turnOffAuthorisationSystem(); END 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()); } I believe the Auth system should remain on in this method.

Target:
public void createUnauthorized() throws Exception { 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()); }
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)); START return uniqueResult(context, criteriaQuery, true, RegistrationData.class, -1, -1); END } Original query was not cacheable. This one is. I think the third param should be `false`.

Target:
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, false, RegistrationData.class, -1, -1); }
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); START policy = srp.copyToDSpaceObject(policy,dest); END resourcePolicyService.update(c,policy); newPolicies.add(policy); } resourcePolicyService.update(c, newPolicies); } 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.

Target:
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.copyToDSpaceObject(c,srp,dest); newPolicies.add(policy); } resourcePolicyService.update(c, newPolicies); }
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: START log.warn("consume() got unrecognized event: " + event.toString()); END } } 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.

Target:
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.debug("consume() got unrecognized event: " + event.toString()); } }
Source:
public static TableRow row(String table) throws SQLException { START return new TableRow(canonicalize(table), getColumnNames(null, table)); END } You create a `getColumnNames(table)` method later on in this class. This change is unnecessary, as it should just use that other method.

Target:
public static TableRow row(String table) throws SQLException { return new TableRow(canonicalize(table), getColumnNames(table)); }
Source:
public Page<SiteRest> findAll(Context context, Pageable pageable) { List<Site> sites = new ArrayList<Site>(); START int total = 0; END 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; } this should be set to 1 or increased when we manually add the site to the return list

Target:
public Page<SiteRest> findAll(Context context, Pageable pageable) { List<Site> sites = new ArrayList<Site>(); int total = 1; 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; }
Source:
public SiteRestRepository() { START System.out.println("Repository initialized by Spring"); END } Shouldn't this go to the log, at DEBUG level?

Target:
public SiteRestRepository() { }
Source:
public void setName(Context context, String name) throws SQLException { if (!permanent) getGroupService().setMetadataSingleValue(context, this, START MetadataSchema.DC_SCHEMA, "title", null, null, name); END } 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.

Target:
void setName(Context context, String name) throws SQLException { getGroupService().setMetadataSingleValue(context, this, MetadataSchema.DC_SCHEMA, "title", null, null, name); }
Source:
public static void _destroyKernel() { if (kernel != null) { // cleanup the kernel try { kernel.destroy(); } catch (Exception e) { // keep going } START kernel.destroy(); END } // must null things out or JUnit will not clean them up kernel = null; } Destroy the kernel twice? (See line 58.)

Target:
public static void _destroyKernel() { if (kernel != null) { // cleanup the kernel kernel.destroy(); } // must null things out or JUnit will not clean them up kernel = null; }
Source:
START public List<Map> getCollectionsWithBitstreamSizesTotal(Context context) throws SQLException { END return collectionDAO.getCollectionsWithBitstreamSizesTotal(context); } It would be great if this map could use generics so we know what it contains.

Target:
public List<Map.Entry<Collection, Long>> getCollectionsWithBitstreamSizesTotal(Context context) throws SQLException { return collectionDAO.getCollectionsWithBitstreamSizesTotal(context); }
Source:
public static String format(Date date, boolean init) { SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss.'000Z'"); START if (!init) END 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; } If we add a line break here, we should use curly brackets as well. Everything else is error-prone.

Target:
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; }
Source:
private static void log(String text) { if (debug) { START log(text); END } } If `debug = true`, `log` will just call itself recursively. Surely you mean `if(debug) { Log.d(text); }`

Target:
private static void log(String text) { if (debug) { Log.d(TAG, text); } }
Source:
private Activity getCurrentActivity() { START final Activity[] activity = new Activity[1]; END java.util.Collection<Activity> activities = ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(Stage.RESUMED); activity[0] = Iterables.getOnlyElement(activities); return activity[0]; } Why is an array necessary here? It looks like there is only ever one item.

Target:
private Activity getCurrentActivity() { Activity activity; java.util.Collection<Activity> activities = ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(Stage.RESUMED); activity = Iterables.getOnlyElement(activities); return activity; }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); START AWSMobileClient.getInstance().initialize(getApplicationContext(), new Callback<UserStateDetails>() { END @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(); } Not sure if this is still needed.

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initUI(); }
Source:
public IndexCoordinates getIndexCoordinates() { START return indexCoordinatesResolver.resolve(getEvaluationContext(null), IndexCoordinates.of(getIndexName())); END } How about simplifying this method back to `IndexCoordinates.of(getIndexName()))` and keeping the evaluation within `getIndexName()`?

Target:
public IndexCoordinates getIndexCoordinates() { return resolve(IndexCoordinates.of(getIndexName())); }
Source:
public boolean hasSeqNo() { START return this.seqNo != null && SequenceNumbers.isAssignedSeqNo(this.seqNo); END } ```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.

Target:
public boolean hasSeqNo() { return this.seqNo != null; }
Source:
public T doWith(@Nullable Document document) { if (document == null) { return null; } START T materializedEntity = reader.read(type, document); END return maybeCallbackAfterConvert(materializedEntity, document, index); } I'd prefer `entity` here

Target:
public T doWith(@Nullable Document document) { if (document == null) { return null; } T entity = reader.read(type, document); return maybeCallbackAfterConvert(entity, document, index); }
Source:
public Mono<T> doWith(@Nullable Document document) { if (document == null) { return Mono.empty(); } START T materializedEntity = reader.read(type, document); END return maybeCallAfterConvert(materializedEntity, document, index); } why not `entity`?

Target:
public Mono<T> doWith(@Nullable Document document) { if (document == null) { return Mono.empty(); } T entity = reader.read(type, document); return maybeCallAfterConvert(entity, document, index); }
Source:
private SearchScrollHits<String> newSearchScrollHits(List<SearchHit<String>> hits) { START return new SearchHitsImpl<String>(1, TotalHitsRelation.EQUAL_TO, 0, "1234", hits, null); END } ```suggestion return new SearchHitsImpl<String>(hits.size(), TotalHitsRelation.EQUAL_TO, 0, "1234", hits, null); ```

Target:
private SearchScrollHits<String> newSearchScrollHits(List<SearchHit<String>> hits) { return new SearchHitsImpl<String>(hits.size(), TotalHitsRelation.EQUAL_TO, 0, "1234", hits, null); }
Source:
START public RuntimeException translateException(Exception exception) { END RuntimeException runtimeException = exception instanceof RuntimeException ? (RuntimeException) exception : new RuntimeException(exception.getMessage(), exception); RuntimeException potentiallyTranslatedException = exceptionTranslator .translateExceptionIfPossible(runtimeException); return potentiallyTranslatedException != null ? potentiallyTranslatedException : runtimeException; } Nit: Let's have this method private unless someone asks for it. It's an utility to the client callback.

Target:
private 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; }