auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected final boolean trySuccessInternal(V result) { boolean done = super.trySuccess(result); START return clearTaskAfterCompletion(done, COMPLETED); END } nit: you can merge these lines

Target:
protected final boolean trySuccessInternal(V result) { return clearTaskAfterCompletion(super.trySuccess(result), COMPLETED); }
Source:
public boolean cancel(boolean mayInterruptIfRunning) { boolean cancelled = super.cancel(mayInterruptIfRunning); START return clearTaskAfterCompletion(cancelled, CANCELLED); END } nit you can merge these lines

Target:
public boolean cancel(boolean mayInterruptIfRunning) { return clearTaskAfterCompletion(super.cancel(mayInterruptIfRunning), CANCELLED); }
Source:
protected final boolean tryFailureInternal(Throwable cause) { boolean done = super.tryFailure(cause); START return clearTaskAfterCompletion(done, FAILED); END } nit: these two lines can be merged

Target:
protected final boolean tryFailureInternal(Throwable cause) { return clearTaskAfterCompletion(super.tryFailure(cause), FAILED); }
Source:
START private boolean dontNeedEncoding(char ch) { END return ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch >= '0' && ch <= '9' || ch == '-' || ch == '_' || ch == '.' || ch == '*'; } static

Target:
private static boolean dontNeedEncoding(char ch) { return ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch >= '0' && ch <= '9' || ch == '-' || ch == '_' || ch == '.' || ch == '*'; }
Source:
void add(ChannelOutboundBuffer buffer, boolean connected) throws Exception { processor.connected = connected; try { buffer.forEachFlushedMessage(processor); } finally { processor.connected = false; START } END } not sure resetting this is really needed now since it's always set before use?

Target:
void add(ChannelOutboundBuffer buffer, boolean connected) throws Exception { processor.connected = connected; buffer.forEachFlushedMessage(processor); }
Source:
public void testCancellationExceptionIsReturnedAsCause() throws InterruptedException, ExecutionException, TimeoutException { final Promise<Void> promise = new DefaultPromise<Void>(ImmediateEventExecutor.INSTANCE); START promise.cancel(false); END assertThat(promise.cause(), instanceOf(CancellationException.class)); } please also assert return value

Target:
public void testCancellationExceptionIsReturnedAsCause() throws InterruptedException, ExecutionException, TimeoutException { final Promise<Void> promise = new DefaultPromise<Void>(ImmediateEventExecutor.INSTANCE); assertTrue(promise.cancel(false)); assertThat(promise.cause(), instanceOf(CancellationException.class)); }
Source:
ByteBuf duplicate() { // We can only use the cached slice safely if it's equal to the source buffer, // otherwise it might not be fully visible to us START return (slice == srcBuf ? srcBuf : srcBuf.slice()).duplicate(); END } Why do we need to first slice and then also duplicate ?

Target:
ByteBuf duplicate() { return srcBuf.duplicate(); }
Source:
ByteBuf slice() { START return slice != null ? slice : (slice = srcBuf.slice(srcIdx(offset), length())); END } please make this more readable... Sure its compact but its really hard to read.

Target:
ByteBuf slice() { ByteBuf s = slice; if (s == null) { slice = s = srcBuf.slice(srcIdx(offset), length()); } return s; }
Source:
protected final Runnable pollScheduledTask(long nanoTime) { assert inEventLoop(); Queue<ScheduledFutureTask<?>> scheduledTaskQueue = this.scheduledTaskQueue; ScheduledFutureTask<?> scheduledTask = scheduledTaskQueue == null ? null : scheduledTaskQueue.peek(); START if (scheduledTask == null || scheduledTask.deadlineNanos() > nanoTime) { END return null; } scheduledTaskQueue.remove(); return scheduledTask; } Replace direct comparison using nanoTime with differences ie ```scheduledTask.deadlineNanos() - nanoTime > 0```

Target:
protected final Runnable pollScheduledTask(long nanoTime) { assert inEventLoop(); Queue<ScheduledFutureTask<?>> scheduledTaskQueue = this.scheduledTaskQueue; ScheduledFutureTask<?> scheduledTask = scheduledTaskQueue == null ? null : scheduledTaskQueue.peek(); if (scheduledTask == null || scheduledTask.deadlineNanos() - nanoTime > 0) { return null; } scheduledTaskQueue.remove(); return scheduledTask; }
Source:
private boolean fetchFromScheduledTaskQueue() { if (scheduledTaskQueue == null || scheduledTaskQueue.isEmpty()) { return true; } long nanoTime = AbstractScheduledEventExecutor.nanoTime(); START for (Runnable scheduledTask; (scheduledTask = pollScheduledTask(nanoTime)) != null;) { END if (!taskQueue.offer(scheduledTask)) { // No space left in the task queue add it back to the scheduledTaskQueue so we pick it up again. scheduledTaskQueue.add((ScheduledFutureTask<?>) scheduledTask); return false; } } return true; } imho it would be easier to read as: ```java for (;;) { Runnable scheduledTask = pollScheduledTask(nanoTime); if (scheduledTask == null) { break; } .... } ```

Target:
private boolean fetchFromScheduledTaskQueue() { if (scheduledTaskQueue == null || scheduledTaskQueue.isEmpty()) { return true; } long nanoTime = AbstractScheduledEventExecutor.nanoTime(); for (;;) { Runnable scheduledTask = pollScheduledTask(nanoTime); if (scheduledTask == null) { return true; } if (!taskQueue.offer(scheduledTask)) { // No space left in the task queue add it back to the scheduledTaskQueue so we pick it up again. scheduledTaskQueue.add((ScheduledFutureTask<?>) scheduledTask); return false; } } }
Source:
public static Set<String> normalizedLinuxClassifiers() { START return Collections.unmodifiableSet(LINUX_OS_CLASSIFIERS); END } Why not create this once in the static method and return the same instance all the time ?

Target:
public static Set<String> normalizedLinuxClassifiers() { return LINUX_OS_CLASSIFIERS; }
Source:
void fireChildRead(Http2Frame frame) { assert eventLoop().inEventLoop(); if (!isActive()) { ReferenceCountUtil.release(frame); } else { final RecvByteBufAllocator.Handle allocHandle = unsafe.recvBufAllocHandle(); flowControlledBytes += unsafe.doRead0(frame, allocHandle); // We currently don't need to check for readEOS because the parent channel and child channel are limited // to the same EventLoop thread. There are a limited number of frame types that may come after EOS is // read (unknown, reset) and the trade off is less conditionals for the hot path (headers/data) at the // cost of additional readComplete notifications on the rare path. if (allocHandle.continueReading()) { if (!readCompletePending) { readCompletePending = true; addChannelToReadCompletePendingQueue(); } } else { START unsafe.notifyReadComplete(allocHandle, true); END } } } Now that we're essentially eager-reading, why don't we always trigger read complete via `addChannelToReadCompletePendingQueue();`? This should avoid about as many `readComplete` calls as we can. As an aside, It seems to me that we shouldn't care much what `allocHandle.continueReading()` says at this point, or honestly at all with this strategy.

Target:
void fireChildRead(Http2Frame frame) { assert eventLoop().inEventLoop(); if (!isActive()) { ReferenceCountUtil.release(frame); } else { unsafe.doRead0(frame); if (!readCompletePending) { readCompletePending = true; addChannelToReadCompletePendingQueue(); } } }
Source:
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { System.out.println("Channel heartBeat lost"); if (evt instanceof IdleStateEvent && IdleState.READER_IDLE == ((IdleStateEvent) evt).state()) { START ctx.channel().close(); END } } `ctx.close();`

Target:
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { System.out.println("Channel heartBeat lost"); if (evt instanceof IdleStateEvent && IdleState.READER_IDLE == ((IdleStateEvent) evt).state()) { ctx.close(); } }
Source:
START public static void encodeDomainName(String name, ByteBuf buf) { END if (ROOT.equals(name)) { // Root domain buf.writeByte(0); return; } final String[] labels = name.split("\\."); for (String label : labels) { final int labelLen = label.length(); if (labelLen == 0) { // zero-length label means the end of the name. break; } buf.writeByte(labelLen); ByteBufUtil.writeAscii(buf, label); } buf.writeByte(0); // marks end of name field } Package private

Target:
static void encodeDomainName(String name, ByteBuf buf) { if (ROOT.equals(name)) { // Root domain buf.writeByte(0); return; } final String[] labels = name.split("\\."); for (String label : labels) { final int labelLen = label.length(); if (labelLen == 0) { // zero-length label means the end of the name. break; } buf.writeByte(labelLen); ByteBufUtil.writeAscii(buf, label); } buf.writeByte(0); // marks end of name field }
Source:
public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) { START return size; END } size = 0; for (int i = 0; i < location_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, location_.get(i)); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } 4 spaces

Target:
public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; for (int i = 0; i < location_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, location_.get(i)); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; }
Source:
public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized != -1) { START return isInitialized == 1; END } for (int i = 0; i < getLocalTimeCount(); i++) { if (!getLocalTime(i).isInitialized()) { memoizedIsInitialized = 0; return false; } } memoizedIsInitialized = 1; return true; } 4 spaces

Target:
public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized != -1) return isInitialized == 1; for (int i = 0; i < getLocalTimeCount(); i++) { if (!getLocalTime(i).isInitialized()) { memoizedIsInitialized = 0; return false; } } memoizedIsInitialized = 1; return true; }
Source:
START private LineHeaderExtractor(int maxHeaderSize) { END super(maxHeaderSize); } remove private

Target:
LineHeaderExtractor(int maxHeaderSize) { super(maxHeaderSize); }
Source:
protected void deallocate() { for (HAProxyTLV tlv : tlvs) { tlv.release(); } START final ResourceLeakTracker<HAProxyMessage> leak = this.leak; END if (leak != null) { boolean closed = leak.close(this); assert closed; } } put all of this in a finally block, just in case.

Target:
protected void deallocate() { try { for (HAProxyTLV tlv : tlvs) { tlv.release(); } } finally { final ResourceLeakTracker<HAProxyMessage> leak = this.leak; if (leak != null) { boolean closed = leak.close(this); assert closed; } } }
Source:
private void testUpdate(Checksum checksum, ByteBufChecksum wrapped, ByteBuf buf, int off, int len) { checksum.reset(); wrapped.reset(); checksum.update(BYTE_ARRAY, off, len); wrapped.update(buf, off, len); START assertEquals(checksum.getValue(), wrapped.getValue()); END } put all of this in a `try {...} finally { buf.release(); }` block

Target:
private static void testUpdate(Checksum checksum, ByteBufChecksum wrapped, ByteBuf buf, int off, int len) { checksum.reset(); wrapped.reset(); checksum.update(BYTE_ARRAY, off, len); wrapped.update(buf, off, len); assertEquals(checksum.getValue(), wrapped.getValue()); }
Source:
public static void freeDirectBuffer(ByteBuffer buffer) { // Copied locally to prevent race CustomCleaner localCustomCleaner = DirectCleaner.customCleaner; START if (!ALLOW_CUSTOM_CLEANER || localCustomCleaner == null) { END PlatformDependent.freeDirectBuffer(buffer); } else { localCustomCleaner.freeDirectMemory(buffer); } } Can we check `!ALLOW_CUSTOM_CLEANER` before we fetch the volatile field ? something like: ``` CustomCleaner localCustomCleaner; if (!ALLOW_CUSTOM_CLEANER || (localCustomCleaner = DirectCleaner.customCleaner) == null) { ... } else { .... } ```

Target:
public static void freeDirectBuffer(ByteBuffer buffer) { // Copied locally to prevent race CustomCleaner localCustomCleaner; if (!ALLOW_CUSTOM_CLEANER || (localCustomCleaner = DirectCleaner.customCleaner) == null) { PlatformDependent.freeDirectBuffer(buffer); } else { localCustomCleaner.freeDirectMemory(buffer); } }
Source:
void setNetworkInterface(NetworkInterface netInterface, InternetProtocolFamily family) throws IOException { InetAddress address = deriveInetAddress(netInterface, family == InternetProtocolFamily.IPv6); START if (address.equals(family == InternetProtocolFamily.IPv4 ? INET6_ANY : INET_ANY)) { END throw new IOException("NetworkInterface does not support " + family); } final NativeInetAddress nativeAddress = NativeInetAddress.newInstance(address); setInterface(intValue(), ipv6, nativeAddress.address(), nativeAddress.scopeId(), interfaceIndex(netInterface)); } is this reversed?

Target:
void setNetworkInterface(NetworkInterface netInterface, InternetProtocolFamily family) throws IOException { InetAddress address = deriveInetAddress(netInterface, family == InternetProtocolFamily.IPv6); if (address.equals(family == InternetProtocolFamily.IPv4 ? INET_ANY : INET6_ANY)) { throw new IOException("NetworkInterface does not support " + family); } final NativeInetAddress nativeAddress = NativeInetAddress.newInstance(address); setInterface(intValue(), ipv6, nativeAddress.address(), nativeAddress.scopeId(), interfaceIndex(netInterface)); }
Source:
public ChannelFuture bind(SocketAddress localAddress) { validate(); ObjectUtil.checkNotNull(localAddress, "localAddress"); START return doBind(localAddress); END } @qeesung: nit you can merge the above 2 lines

Target:
public ChannelFuture bind(SocketAddress localAddress) { validate(); return doBind(ObjectUtil.checkNotNull(localAddress, "localAddress")); }
Source:
public B handler(ChannelHandler handler) { ObjectUtil.checkNotNull(handler, "handler"); START this.handler = handler; END return self(); } nit you can merge the above two lines

Target:
public B handler(ChannelHandler handler) { this.handler = ObjectUtil.checkNotNull(handler, "handler"); return self(); }
Source:
public ServerBootstrap childHandler(ChannelHandler childHandler) { ObjectUtil.checkNotNull(childHandler, "childHandler"); START this.childHandler = childHandler; END return this; } nit: you can merge the above two lines

Target:
public ServerBootstrap childHandler(ChannelHandler childHandler) { this.childHandler = ObjectUtil.checkNotNull(childHandler, "childHandler"); return this; }
Source:
AnnotatedConnectException(ConnectException exception, SocketAddress remoteAddress) { super(exception.getMessage() + ": " + remoteAddress); initCause(exception); START setStackTrace(EmptyArrays.EMPTY_STACK_TRACE); END } @carl-mastrangelo shouldn't we just remove this line all together ?

Target:
AnnotatedConnectException(ConnectException exception, SocketAddress remoteAddress) { super(exception.getMessage() + ": " + remoteAddress); initCause(exception); }
Source:
AnnotatedNoRouteToHostException(NoRouteToHostException exception, SocketAddress remoteAddress) { super(exception.getMessage() + ": " + remoteAddress); initCause(exception); START setStackTrace(EmptyArrays.EMPTY_STACK_TRACE); END } same question as above

Target:
AnnotatedNoRouteToHostException(NoRouteToHostException exception, SocketAddress remoteAddress) { super(exception.getMessage() + ": " + remoteAddress); initCause(exception); }
Source:
private void transfer(EmbeddedChannel outChannel, EmbeddedChannel inChannel) { // Transfer encoded data into decoder // Loop because there might be multiple frames (gathering write) START while (true) { END ByteBuf encoded = outChannel.readOutbound(); if (encoded == null) { return; } inChannel.writeInbound(encoded); } } please use the same style we do in Netty: `for (;;) { ... }`

Target:
private void transfer(EmbeddedChannel outChannel, EmbeddedChannel inChannel) { // Transfer encoded data into decoder // Loop because there might be multiple frames (gathering write) for (;;) { ByteBuf encoded = outChannel.readOutbound(); if (encoded == null) { return; } inChannel.writeInbound(encoded); } }
Source:
public String toString() { // E.g.: "1000 Bye", "1009 Message too big" START return code() + " " + reasonText(); END } final field to it's computed once and for all, as most values should be constants

Target:
public String toString() { String text = this.text; if (text == null) { // E.g.: "1000 Bye", "1009 Message too big" this.text = text = code() + " " + reasonText(); } return text; }
Source:
private void remove0(HeaderEntry<K, V> entry) { int i = index(entry.hash); HeaderEntry<K, V> e = entries[i]; if (e == entry) { entries[i] = entry.next; } entry.remove(); START } END I think you also need to call `--size;` Can you please also adjust the unit test to check for this ?

Target:
private void remove0(HeaderEntry<K, V> entry) { int i = index(entry.hash); HeaderEntry<K, V> e = entries[i]; if (e == entry) { entries[i] = entry.next; } entry.remove(); --size; }
Source:
public InetAddress getInterface() { START throw new UnsupportedOperationException("Retrieval of network interface address not supported"); END } can we keep the old code as this is a "breaking" change ?

Target:
public InetAddress getInterface() { return null; }
Source:
public void testMulticast(Bootstrap sb, Bootstrap cb) throws Throwable { // Run this test with IP_RECVORIGDSTADDR option enabled START sb.option(EpollChannelOption.IP_RECVORIGDSTADDR, true); END super.testMulticast(sb, cb); sb.option(EpollChannelOption.IP_RECVORIGDSTADDR, false); } can you explain why ?

Target:
public void testMulticast(Bootstrap sb, Bootstrap cb) throws Throwable { super.testMulticast(sb, cb); }
Source:
protected static TrustManagerFactory buildTrustManagerFactory( START File certChainFile, TrustManagerFactory trustManagerFactory, String keyType) END throws NoSuchAlgorithmException, CertificateException, KeyStoreException, IOException { X509Certificate[] x509Certs = toX509Certificates(certChainFile); return buildTrustManagerFactory(x509Certs, trustManagerFactory, keyType); } we will need to keep the old method signature as well as this method is protected and so changing its signature is a API breaking change

Target:
static TrustManagerFactory buildTrustManagerFactory( File certChainFile, TrustManagerFactory trustManagerFactory, String keyType) throws NoSuchAlgorithmException, CertificateException, KeyStoreException, IOException { X509Certificate[] x509Certs = toX509Certificates(certChainFile); return buildTrustManagerFactory(x509Certs, trustManagerFactory, keyType); }
Source:
public OpenSslClientContext(File certChainFile, START TrustManagerFactory trustManagerFactory) throws SSLException { END this(certChainFile, trustManagerFactory, null, null, null, null, null, IdentityCipherSuiteFilter.INSTANCE, null, 0, 0, KeyStore.getDefaultType()); } revert please

Target:
public OpenSslClientContext(File certChainFile, TrustManagerFactory trustManagerFactory) throws SSLException { this(certChainFile, trustManagerFactory, null, null, null, null, null, IdentityCipherSuiteFilter.INSTANCE, null, 0, 0); }
Source:
DefaultChannelHandlerContext(DefaultChannelPipeline pipeline, String name, ChannelHandler handler) { this.name = requireNonNull(name, "name"); this.pipeline = pipeline; START this.executionMask = ChannelHandlerMask.mask(handler.getClass()); END this.handler = handler; } Could omit classname here since you have static * import

Target:
DefaultChannelHandlerContext(DefaultChannelPipeline pipeline, String name, ChannelHandler handler) { this.name = requireNonNull(name, "name"); this.pipeline = pipeline; this.executionMask = mask(handler.getClass()); this.handler = handler; }
Source:
public UnorderedThreadPoolEventExecutor(int corePoolSize, ThreadFactory threadFactory) { super(corePoolSize, threadFactory); START this.setThreadFactory(ThreadExecutorMap.apply(getThreadFactory(), this)); END } Is this is safe? I think the scheduled repeating trimming task could be run on an arbitrary thread, i.e. not necessarily the one from which it was scheduled that owns the referenced `PoolThreadCache` instance. Maybe for this one the scheduled task could just call `PoolThreadCache.trimCurrentThreadCache()`?

Target:
public UnorderedThreadPoolEventExecutor(int corePoolSize, ThreadFactory threadFactory) { super(corePoolSize, threadFactory); }
Source:
public <T> T getOption(ChannelOption<T> option) { if (option == EpollChannelOption.DOMAIN_SOCKET_READ_MODE) { return (T) getReadMode(); } START if (option == EpollChannelOption.ALLOW_HALF_CLOSURE) { END return (T) Boolean.valueOf(isAllowHalfClosure()); } return super.getOption(option); } I think you also need to add it to the `getOptions` method. See : https://github.com/netty/netty/blob/1c66815c8aadb53f373e8070279a510a2eda89a7/transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollSocketChannelConfig.java#L60

Target:
public <T> T getOption(ChannelOption<T> option) { if (option == DOMAIN_SOCKET_READ_MODE) { return (T) getReadMode(); } if (option == ALLOW_HALF_CLOSURE) { return (T) Boolean.valueOf(isAllowHalfClosure()); } return super.getOption(option); }
Source:
public Map<ChannelOption<?>, Object> getOptions() { START return getOptions(super.getOptions(), EpollChannelOption.DOMAIN_SOCKET_READ_MODE, ChannelOption.ALLOW_HALF_CLOSURE); END } use `EpollChannelOption.ALLOW_HALF_CLOSURE` here or use `ChannelOption.ALLOW_HALF_CLOSURE` bellow to make it consistent

Target:
public Map<ChannelOption<?>, Object> getOptions() { return getOptions(super.getOptions(), DOMAIN_SOCKET_READ_MODE, ALLOW_HALF_CLOSURE); }
Source:
public final void handlerRemoved(ChannelHandlerContext ctx) throws Exception { if (decodeState == STATE_CALLING_CHILD_DECODE) { decodeState = STATE_HANDLER_REMOVED_PENDING; return; } ByteBuf buf = cumulation; if (buf != null) { // Directly set this to null so we are sure we not access it in any other method here anymore. cumulation = null; int readable = buf.readableBytes(); if (readable > 0) { ctx.fireChannelRead(buf); ctx.fireChannelReadComplete(); } else { buf.release(); } } handlerRemoved0(ctx); START decodeState = STATE_REMOVED; END } I think this should be set in a `finally` block

Target:
public final void handlerRemoved(ChannelHandlerContext ctx) throws Exception { if (decodeState == STATE_CALLING_CHILD_DECODE) { decodeState = STATE_HANDLER_REMOVED_PENDING; return; } try { ByteBuf buf = cumulation; if (buf != null) { // Directly set this to null so we are sure we not access it in any other method here anymore. cumulation = null; int readable = buf.readableBytes(); if (readable > 0) { ctx.fireChannelRead(buf); ctx.fireChannelReadComplete(); } else { buf.release(); } } handlerRemoved0(ctx); } finally { decodeState = STATE_REMOVED; } }
Source:
public static boolean isKeepAlive(HttpMessage message) { boolean connectionClose = message.headers().containsValue(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE, true); if (connectionClose) { return false; } if (message.protocolVersion().isKeepAliveDefault()) { START return !connectionClose; END } else { return message.headers().containsValue(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE, true); } } connectionClose can only be false here

Target:
public static boolean isKeepAlive(HttpMessage message) { return !message.headers().containsValue(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE, true) && (message.protocolVersion().isKeepAliveDefault() || message.headers().containsValue(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE, true)); }
Source:
protected void decode(ChannelHandlerContext ctx, WebSocketFrame frame, List<Object> out) throws Exception { if (frame instanceof CloseWebSocketFrame) { serverReceivedCloseHandshake = true; START frame.retain(); END return; } super.decode(ctx, frame, out); } why do you retain here ? This looks like a possible memory leak.

Target:
protected void decode(ChannelHandlerContext ctx, WebSocketFrame frame, List<Object> out) throws Exception { if (frame instanceof CloseWebSocketFrame) { serverReceivedCloseHandshake = true; return; } super.decode(ctx, frame, out); }
Source:
public WebSocketClientHandshaker13 setForceCloseTimeoutMillis(long forceCloseTimeoutMillis) { START this.forceCloseTimeoutMillis = forceCloseTimeoutMillis; END return this; } nit: jut call `super.setForceCloseTimeoutMillis(...)` this will also ensure we do the correct thing if we ever change the super method content and will allow to make `forceCloseTimeMillis` private

Target:
public WebSocketClientHandshaker13 setForceCloseTimeoutMillis(long forceCloseTimeoutMillis) { super.setForceCloseTimeoutMillis(forceCloseTimeoutMillis); return this; }
Source:
START private PartialCumulationDecoder(int messageSize) { END this.messageSize = messageSize; setCumulator(new PartialCumulator()); } nit: make package-private

Target:
PartialCumulationDecoder(int messageSize) { this.messageSize = messageSize; setCumulator(new PartialCumulator()); }
Source:
private boolean release0(int decrement) { int rawCnt = nonVolatileRawCnt(), realCnt = toLiveRealCnt(rawCnt, decrement); if (decrement == realCnt) { if (refCntUpdater.compareAndSet(this, rawCnt, 1)) { START maxCapacity(-rawMaxCapacity()); END deallocate(); return true; } return retryRelease0(decrement); } return releaseNonFinal0(decrement, rawCnt, realCnt); } should we assert that this value will never be positive ?

Target:
private boolean release0(int decrement) { int rawCnt = nonVolatileRawCnt(), realCnt = toLiveRealCnt(rawCnt, decrement); if (decrement == realCnt) { if (refCntUpdater.compareAndSet(this, rawCnt, 1)) { maxCapacity(-maxCapacity()); deallocate(); return true; } return retryRelease0(decrement); } return releaseNonFinal0(decrement, rawCnt, realCnt); }
Source:
public final void deallocate() { // this is to avoid overriding isAccessible(), so that it can be // final in AbstractReferenceCountedByteBuf START maxCapacity(-rawMaxCapacity()); END wrapped.deallocate(); } should we assert that this value will never be positive ?

Target:
public final void deallocate() { wrapped.deallocate(); }
Source:
public void requiredHeadersInSeparateConnectionHeaders() { START setUpServerChannel(); END String upgradeString = "GET / HTTP/1.1\r\n" + "Host: example.com\r\n" + "Connection: keep-alive\r\n" + "Connection: HTTP2-Settings\r\n" + "Connection: Upgrade\r\n" + "Upgrade: h2c\r\n" + "HTTP2-Settings: AAMAAABkAAQAAP__\r\n\r\n"; validateClearTextUpgrade(upgradeString); } nit: you could also move all the `setUpServerChannel()` calls

Target:
public void requiredHeadersInSeparateConnectionHeaders() { String upgradeString = "GET / HTTP/1.1\r\n" + "Host: example.com\r\n" + "Connection: keep-alive\r\n" + "Connection: HTTP2-Settings\r\n" + "Connection: Upgrade\r\n" + "Upgrade: h2c\r\n" + "HTTP2-Settings: AAMAAABkAAQAAP__\r\n\r\n"; validateClearTextUpgrade(upgradeString); }
Source:
HeadContext(DefaultChannelPipeline pipeline) { START super(pipeline, pipeline.channel.eventLoop(), HEAD_NAME, HeadContext.class); END unsafe = pipeline.channel().unsafe(); setAddComplete(); } should this be `pipeline.executor`?

Target:
HeadContext(DefaultChannelPipeline pipeline) { super(pipeline, HEAD_NAME, HeadContext.class); unsafe = pipeline.channel().unsafe(); setAddComplete(); }
Source:
public ChannelHandlerContext firstContext() { synchronized (handlers) { START if (handlers.isEmpty()) { END return null; } return handlers.get(0); } } simplify with conditional operator? ```java return handlers.isEmpty() ? null : handlers.get(0); ```

Target:
public ChannelHandlerContext firstContext() { synchronized (handlers) { return handlers.isEmpty() ? null : handlers.get(0); } }
Source:
public ChannelHandlerContext lastContext() { synchronized (handlers) { START if (handlers.isEmpty()) { END return null; } return handlers.get(handlers.size() - 1); } } simplify with conditional operator?

Target:
public ChannelHandlerContext lastContext() { synchronized (handlers) { return handlers.isEmpty() ? null : handlers.get(handlers.size() - 1); } }
Source:
public void propagateEvent(Blackhole hole) { for (int i = 0; i < 100; i++) { START pipeline.fireChannelReadComplete(); END hole.consume(i); } } Maybe add some counter inside the handler just to be 100% sure the compiler doesn't throw this away.

Target:
public void propagateEvent(Blackhole hole) { for (int i = 0; i < 100; i++) { hole.consume(pipeline.fireChannelReadComplete()); } }
Source:
START public static SingleThreadEventLoop.IoHandlerFactory newFactory(final SelectorProvider selectorProvider, END final SelectStrategyFactory selectStrategyFactory) { ObjectUtil.checkNotNull(selectorProvider, "selectorProvider"); ObjectUtil.checkNotNull(selectStrategyFactory, "selectStrategyFactory"); return new SingleThreadEventLoop.IoHandlerFactory() { @Override public SingleThreadEventLoop.IoHandler newHandler() { return new NioHandler(selectorProvider, selectStrategyFactory.newSelectStrategy()); } }; } `final` on purpose (say still compiling against Java < 8)?

Target:
public static IoHandlerFactory newFactory(final SelectorProvider selectorProvider, final SelectStrategyFactory selectStrategyFactory) { ObjectUtil.checkNotNull(selectorProvider, "selectorProvider"); ObjectUtil.checkNotNull(selectStrategyFactory, "selectStrategyFactory"); return new IoHandlerFactory() { @Override public IoHandler newHandler() { return new NioHandler(selectorProvider, selectStrategyFactory.newSelectStrategy()); } }; }
Source:
START public static SingleThreadEventLoop.IoHandlerFactory newFactory(final int maxEvents, END final SelectStrategyFactory selectStrategyFactory) { ObjectUtil.checkPositiveOrZero(maxEvents, "maxEvents"); ObjectUtil.checkNotNull(selectStrategyFactory, "selectStrategyFactory"); return new SingleThreadEventLoop.IoHandlerFactory() { @Override public SingleThreadEventLoop.IoHandler newHandler() { return new EpollHandler(maxEvents, selectStrategyFactory.newSelectStrategy()); } }; } Same here, possibly unnecessarily `final`

Target:
public static IoHandlerFactory newFactory(final int maxEvents, final SelectStrategyFactory selectStrategyFactory) { ObjectUtil.checkPositiveOrZero(maxEvents, "maxEvents"); ObjectUtil.checkNotNull(selectStrategyFactory, "selectStrategyFactory"); return new IoHandlerFactory() { @Override public IoHandler newHandler() { return new EpollHandler(maxEvents, selectStrategyFactory.newSelectStrategy()); } }; }
Source:
START protected EventLoop newChild(Executor executor, Object... args) throws Exception { END return new LocalEventLoop(this, executor); } Should these args ever be set? Might be worth failing if any are.

Target:
protected EventLoop newChild(Executor executor, Object... args) throws Exception { assert args == null || args.length == 0; return new LocalEventLoop(this, executor); }
Source:
boolean allocate(PooledByteBuf<T> buf, int reqCapacity, int normCapacity) { final long handle; if ((normCapacity & subpageOverflowMask) != 0) { // >= pageSize handle = allocateRun(normCapacity); } else { handle = allocateSubpage(normCapacity); } START if (handle > 0) { END ByteBuffer nioBuffer = cachedNioBuffers != null ? cachedNioBuffers.pollLast() : null; initBuf(buf, nioBuffer, handle, reqCapacity); return true; } return false; } This was effectively `>= 0` before, not sure if it makes a difference. Might also read slightly simpler if inverted i.e. initBuf outside the if block

Target:
boolean allocate(PooledByteBuf<T> buf, int reqCapacity, int normCapacity) { final long handle; if ((normCapacity & subpageOverflowMask) != 0) { // >= pageSize handle = allocateRun(normCapacity); } else { handle = allocateSubpage(normCapacity); } if (handle < 0) { return false; } ByteBuffer nioBuffer = cachedNioBuffers != null ? cachedNioBuffers.pollLast() : null; initBuf(buf, nioBuffer, handle, reqCapacity); return true; }
Source:
public void trace(String format, Object arg) { if (isTraceEnabled()) { START log(TRACE_INT, org.slf4j.helpers.MessageFormatter.format(format, arg).getMessage(), arg); END } } I still don't follow (sorry I'm probably missing something) ... the additional args are only passed for the purpose of later substitution into the message, but now the substitution is done upfront. So the message passed won't have `{}` corresponding to the args..?

Target:
public void trace(String format, Object arg) { if (isTraceEnabled()) { log(TRACE_INT, org.slf4j.helpers.MessageFormatter.format(format, arg)); } }
Source:
START public synchronized void tearDown() { END executorToShutdown.shutdown(); } why synchronized ?

Target:
public void tearDown() { executorToShutdown.shutdown(); }
Source:
public void shutdown() { if (poisoned.compareAndSet(false, true)) { while (true) { START if (tasks.offer(POISON_PILL)) { END break; } } try { executorThread.join(); } catch (InterruptedException e) { //we're quite trusty :) } } } nit: But I think this could be re-factored to: ```java while (!task.offer(POISION_POLL) { // Just try again } ```

Target:
public void shutdown() { if (poisoned.compareAndSet(false, true)) { while (!tasks.offer(POISON_PILL)) { // Just try again } try { executorThread.join(); } catch (InterruptedException e) { //We're quite trusty :) } } }
Source:
public SpinExecutorService(int maxTasks) { tasks = PlatformDependent.newFixedMpscQueue(maxTasks); executorThread = new Thread(new Runnable() { @Override public void run() { final Queue<Runnable> tasks = SpinExecutorService.this.tasks; while (true) { final Runnable task = tasks.poll(); if (task != null) { if (task == POISON_PILL) { return; START } else { END task.run(); } } } } }); executorThread.start(); } nit this could be simplified: ```java Runnable task; while ((task = tasks.poll()) != POISON_PILL) { if (task != null) { task.run(); } } ```

Target:
public SpinExecutorService(int maxTasks) { tasks = PlatformDependent.newFixedMpscQueue(maxTasks); executorThread = new Thread(new Runnable() { @Override public void run() { final Queue<Runnable> tasks = SpinExecutorService.this.tasks; Runnable task; while ((task = tasks.poll()) != POISON_PILL) { if (task != null) { task.run(); } } } }); executorThread.start(); }
Source:
private static Channel connectionChannel(ChannelHandlerContext ctx) { final Channel ch = ctx.channel(); START return (ch instanceof Http2StreamChannel) ? ch.parent() : ch; END } nit: you can remove the `()`

Target:
private static Channel connectionChannel(ChannelHandlerContext ctx) { final Channel ch = ctx.channel(); return ch instanceof Http2StreamChannel ? ch.parent() : ch; }
Source:
START private void writeVoidPromise(ChannelHandlerContext ctx, CodecOutputList out) { END final ChannelPromise voidPromise = ctx.voidPromise(); for (int i = 0; i < out.size(); i++) { ctx.write(out.getUnsafe(i), voidPromise); } } static

Target:
private static void writeVoidPromise(ChannelHandlerContext ctx, CodecOutputList out) { final ChannelPromise voidPromise = ctx.voidPromise(); for (int i = 0; i < out.size(); i++) { ctx.write(out.getUnsafe(i), voidPromise); } }
Source:
START private void writePromiseCombiner(ChannelHandlerContext ctx, CodecOutputList out, ChannelPromise promise) { END final PromiseCombiner combiner = new PromiseCombiner(); for (int i = 0; i < out.size(); i++) { combiner.add(ctx.write(out.getUnsafe(i))); } combiner.finish(promise); } Static

Target:
private static void writePromiseCombiner(ChannelHandlerContext ctx, CodecOutputList out, ChannelPromise promise) { final PromiseCombiner combiner = new PromiseCombiner(); for (int i = 0; i < out.size(); i++) { combiner.add(ctx.write(out.getUnsafe(i))); } combiner.finish(promise); }
Source:
public boolean isSnapshot() { String version = getVersion(); START if (StringUtils.isNotBlank(version)) { END if (version.contains("SNAPSHOT")) {//$NON-NLS-1$ return true; } } return false; } Sorry, being picky: `return StringUtils.isNotBlank(version) && version.contains("SNAPSHOT");

Target:
public boolean isSnapshot() { String version = getVersion(); return StringUtils.isNotBlank(version) && version.contains("SNAPSHOT"); }
Source:
public boolean isSnapshotAllowed() { if (containsKey(SrampConstants.SRAMP_SNAPSHOT_ALLOWED)) { String value = getConfigProperty(SrampConstants.SRAMP_SNAPSHOT_ALLOWED, "false"); //$NON-NLS-1$ START if (StringUtils.isNotBlank(value) && value.equals("true")) { //$NON-NLS-1$ END return true; } else { return false; } } else { if (isSnapshot()) { return true; } else { return false; } } } `return StringUtils.isNotBlank(value) && value.equals("true");`

Target:
public boolean isSnapshotAllowed() { if (containsKey(SrampConstants.SRAMP_SNAPSHOT_ALLOWED)) { String value = getConfigProperty(SrampConstants.SRAMP_SNAPSHOT_ALLOWED, "false"); //$NON-NLS-1$ return StringUtils.isNotBlank(value) && value.equals("true"); //$NON-NLS-1$ } else { return isSnapshot(); } }
Source:
START public String getFeedbackUrl(String siteId) { END return ServerConfigurationService.getPortalUrl() + "/site/" + siteId + "/page/" + SkinnableCharonPortal.CONTACT_US_URL_SUFFIX; } This should be a private method, it doesn't need any docs.

Target:
private String getFeedbackUrl(String siteId) { return ServerConfigurationService.getPortalUrl() + "/site/" + siteId + "/page/" + SkinnableCharonPortal.CONTACT_US_URL_SUFFIX; }
Source:
public boolean isSitePublished(String siteId) { boolean siteIsPublished = false; try { Site site = SiteService.getSite(siteId); START if (site != null) { END siteIsPublished = site.isPublished(); } } catch (IdUnusedException e) { // not a site after all } return siteIsPublished; } Null check is redundant as it should never happen.

Target:
public boolean isSitePublished(String siteId) { boolean siteIsPublished = false; try { Site site = SiteService.getSite(siteId); siteIsPublished = site.isPublished(); } catch (IdUnusedException e) { // not a site after all } return siteIsPublished; }
Source:
protected Loader<CompletedTask> createLoader(int id, Bundle bundle) { if( id == LOADER_PERSONA ) { startLoadingDialog(); return new Bf3Loader(getContext(), UriFactory.getProfilePersonasUri(mProfileData.getId())); } else if( id == LOADER_STATS ) { startLoadingDialog(); return new Bf3Loader(getContext(), UriFactory.getPersonaOverviewUri(mSelectedPersona, mSelectedPlatformId)); } START return null; END } Bad, do not return null. Return is either one loader or other, there is nothing between. If you get here and have to return null you obviously didn't carry out appropriate checks or you do not trust your code

Target:
protected Loader<CompletedTask> createLoader(int id, Bundle bundle) { if( id == LOADER_PERSONA ) { startLoadingDialog(); return new Bf3Loader(getContext(), UriFactory.getProfilePersonasUri(mProfileData.getId())); } else { startLoadingDialog(); return new Bf3Loader(getContext(), UriFactory.getPersonaOverviewUri(mSelectedPersona, mSelectedPlatformId)); } }
Source:
private void updateScoreStatistics(PersonaInfo pi) { listScoreStatistics = scoreStatisticsFromJSON(pi); ContentValues contentValues = scoreStatisticsForDB(pi, mSelectedPersona); try { START getContext().getContentResolver().insert(ScoreStatistics.URI, contentValues); END } catch(SQLiteConstraintException ex) { getContext().getContentResolver().update( ScoreStatistics.URI, contentValues, ScoreStatistics.Columns.PERSONA_ID + "=?", new String[] { String.valueOf(pi.getPersonaId()) } ); } } If insert fails catch it and do update?

Target:
private void updateScoreStatistics(PersonaInfo pi) { listScoreStatistics = scoreStatisticsFromJSON(pi); ContentValues contentValues = scoreStatisticsForDB(pi, mSelectedPersona); getContext().getContentResolver().insert(ScoreStatistics.URI, contentValues); }
Source:
public void testSubstVarsTwoLevelsWithDefault() { // Example input taken from LOGBCK-943 bug report context.putProperty("APP_NAME", "LOGBACK"); context.putProperty("ARCHIVE_SUFFIX", "archive.log"); context.putProperty("LOG_HOME", "${logfilepath.default:-logs}"); START context.putProperty("LOG_PATH", "${LOG_HOME}/${APP_NAME}"); END context.putProperty("ARCHIVE_PATH", "${LOG_HOME}/archive/${APP_NAME}"); String result = OptionHelper.substVars("${ARCHIVE_PATH}_trace_${ARCHIVE_SUFFIX}", context); assertEquals("logs/archive/LOGBACK_trace_archive.log", result); } This looks unused. <del>Did you mean to use `LOG_PATH` instead of `LOG_HOME` in the last property below?</del> Never mind. I see now. This was copied from the JIRA report as sample input. It looks like it's the active log path while the archives are stored in the other path. Since we're not using the property for this test, let's remove it.

Target:
public void testSubstVarsTwoLevelsWithDefault() { // Example input taken from LOGBCK-943 bug report context.putProperty("APP_NAME", "LOGBACK"); context.putProperty("ARCHIVE_SUFFIX", "archive.log"); context.putProperty("LOG_HOME", "${logfilepath.default:-logs}"); context.putProperty("ARCHIVE_PATH", "${LOG_HOME}/archive/${APP_NAME}"); String result = OptionHelper.substVars("${ARCHIVE_PATH}_trace_${ARCHIVE_SUFFIX}", context); assertEquals("logs/archive/LOGBACK_trace_archive.log", result); }
Source:
FileExtensionFilter(String ext) { START extension = "."+ext; END } Do we need the "." (dot)? What if we have files without extension?

Target:
FileExtensionFilter(String ext) { extension = ext; }
Source:
public void start() throws Exception { LOG.info("Applying current configs..."); applyCurrentConfigs(); LOG.info("Starting leader latch..."); leaderLatch.start(); LOG.info("Adding to known-agents..."); START String agentKey = localHostname + ":" + Integer.toString(httpPort); END knownAgentsDatastore.addKnownAgent(loadBalancerConfiguration.getName(), baragonAgentMetadata, agentKey); } `String.format()` is preferable

Target:
public void start() throws Exception { LOG.info("Applying current configs..."); applyCurrentConfigs(); LOG.info("Starting leader latch..."); leaderLatch.start(); LOG.info("Adding to known-agents..."); knownAgentsDatastore.addKnownAgent(loadBalancerConfiguration.getName(), baragonAgentMetadata); }
Source:
START private static boolean objectsEqual(String object1, String object2) { END if (object1 == null && object2 == null) { return true; } return object1.equals(object2); } The code here fails if only the first parameter is `null`

Target:
private static boolean objectsEqual(String object1, String object2) { return object1 != null ? object1.equals(object2) : object2 == null; }
Source:
START public HomePresenter(EventBus eventBus, END MyView view, MyProxy proxy) { super(eventBus, view, proxy, ApplicationPresenter.SLOT_SetMainContent); } Remove public. Also let's reformat all the ctor to our latest code style.

Target:
HomePresenter(EventBus eventBus, MyView view, MyProxy proxy) { super(eventBus, view, proxy, ApplicationPresenter.SLOT_SetMainContent); }
Source:
public OrcidOAuth2AP(String clientId, String clientSecret, String userEndpoint) { START String s = null; if(userEndpoint != null){ s = userEndpoint.startsWith("https://pub") ? "/authenticate" : "/read-limited"; } scope = Arrays.asList(s); END this.clientId = clientId; this.clientSecret = clientSecret; this.baseUserEndpoint = userEndpoint; } One could argue that this can be done more compact with only one `if` and without an extra variable allocation. E. g. like ```java if(userEndpoint != null && userEndpoint.startsWith("https://pub")) { this.scope = Arrays.asList("/authenticate"); } else { this.scope = Arrays.asList("/read-limited"); } ``` Or you leave it to the code optimizer of the JVM... :wink:

Target:
public OrcidOAuth2AP(String clientId, String clientSecret, String userEndpoint) { if(userEndpoint != null && userEndpoint.startsWith("https://pub")) { this.scope = Arrays.asList("/authenticate"); } else { this.scope = Arrays.asList("/read-limited"); } this.clientId = clientId; this.clientSecret = clientSecret; this.baseUserEndpoint = userEndpoint; }
Source:
START public static String replaceExtension(String originalName, String newExtension) { END if (originalName == null | originalName == "") { return originalName; } int extensionIndex = originalName.lastIndexOf("."); if (extensionIndex != -1 ) { return originalName.substring(0, extensionIndex) + "."+newExtension ; } else if (newExtension != "") { return originalName +"."+newExtension ; } else { return originalName ; } } I understand the urge to make the code more robust, but the changes done to replaceExtension quite possibly have downstream changes. Code may be expecting an error output on null or "" that will no longer be there. Please revert this change.

Target:
public static String replaceExtension(String originalName, String newExtension) { int extensionIndex = originalName.lastIndexOf("."); if (extensionIndex != -1 ) { return originalName.substring(0, extensionIndex) + "."+newExtension ; } else { return originalName +"."+newExtension ; } }
Source:
public void incrementUsageCount(Long templateId) { // Use object instead of Native Queries to update count //also catch/log exceptions so that create dataset will succeed //Issue 4847 SEK 7/16/2018 try { Template toUpdate = em.find(Template.class, templateId); Long usage = toUpdate.getUsageCount(); usage++; toUpdate.setUsageCount(usage); em.merge(toUpdate); } catch (Exception e) { START logger.log(Level.INFO, "Increment usage count failed on template id {0}. ", templateId); END } } Should this log at a higher level?

Target:
public void incrementUsageCount(Long templateId) { Template toUpdate = em.find(Template.class, templateId); Long usage = toUpdate.getUsageCount(); usage++; toUpdate.setUsageCount(usage); em.merge(toUpdate); }
Source:
public boolean isIdentifierLocallyUnique(String identifier, Dataset dataset) { START boolean u = em.createNamedQuery("Dataset.findByIdentifierAuthorityProtocol") END .setParameter("identifier", identifier) .setParameter("authority", dataset.getAuthority()) .setParameter("protocol", dataset.getProtocol()) .getResultList().isEmpty(); return u; } just return, don't assign

Target:
public boolean isIdentifierLocallyUnique(String identifier, Dataset dataset) { return em.createNamedQuery("Dataset.findByIdentifierAuthorityProtocol") .setParameter("identifier", identifier) .setParameter("authority", dataset.getAuthority()) .setParameter("protocol", dataset.getProtocol()) .getResultList().isEmpty(); }
Source:
public void toggleAllSelected(){ START System.out.print("in toggle all"); END this.selectAllFiles = !this.selectAllFiles; toggleSelectedFiles(this.selectAllFiles); } Can you please remove this `System.out.print` or convert it to `logger.fine` if it might be valuable when debugging in production?

Target:
public void toggleAllSelected(){ //This is here so that if the user selects all on the dataset page // s/he will get all files on download this.selectAllFiles = !this.selectAllFiles; }
Source:
public boolean doesChecksumExistInDatasetVersion(DatasetVersion datasetVersion, String selectedChecksum) { if (datasetVersion == null){ throw new NullPointerException("datasetVersion cannot be null"); } String query = "SELECT df.md5 FROM datafile df, filemetadata fm" + " WHERE fm.datasetversion_id = " + datasetVersion.getId() + " AND fm.datafile_id = df.id" + " AND df.md5 = '" + selectedChecksum + "';"; Query nativeQuery = em.createNativeQuery(query); START List<String> checksumList = nativeQuery.getResultList(); END return checksumList.size() > 0; } Does this not need a `TypedQuery`?

Target:
public boolean doesChecksumExistInDatasetVersion(DatasetVersion datasetVersion, String selectedChecksum) { if (datasetVersion == null){ throw new NullPointerException("datasetVersion cannot be null"); } String query = "SELECT df.md5 FROM datafile df, filemetadata fm" + " WHERE fm.datasetversion_id = " + datasetVersion.getId() + " AND fm.datafile_id = df.id" + " AND df.md5 = '" + selectedChecksum + "';"; Query nativeQuery = em.createNativeQuery(query); List<?> checksumList = nativeQuery.getResultList(); return !checksumList.isEmpty(); }
Source:
public Dataverse findRootDataverse() { return (Dataverse) em.createQuery("select object(o) from Dataverse as o where o.owner.id = null").getSingleResult(); START } END You didn't change the `createQuery` call to include the return type.

Target:
public Dataverse findRootDataverse() { return em.createQuery("select object(o) from Dataverse as o where o.owner.id = null", Dataverse.class).getSingleResult(); }