auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static void tryFailure(Promise<?> p, Throwable cause, InternalLogger logger) { if (!p.tryFailure(cause) && logger != null) { Throwable err = p.cause(); if (err == null) { logger.warn("Failed to mark a promise as failure because it has succeeded already: {}", p, cause); } else { if (logger.isWarnEnabled()) { logger.warn( "Failed to mark a promise as failure because it has failed already: {}, unnotified cause: {}", p, ThrowableUtil.stackTraceToString(err), cause); } } } }

Target:
Just merge this with the else and make it an else if?
Source:
private void parse8(int nameStart, int valueStart, int valueEnd) { if (header.regionMatches(true, nameStart, CookieHeaderNames.HTTPONLY, 0, 8)) { httpOnly = true; } else if (header.regionMatches(true, nameStart, CookieHeaderNames.SAMESITE, 0, 8)) { String sameSiteValue = computeValue(valueStart, valueEnd); try { sameSite = SameSite.of(sameSiteValue); } catch (IllegalArgumentException e) { logger.debug("Skipping SameSite attribute because value '{}' is invalid", sameSiteValue); } } }

Target:
IMHO, you don't need to throw an IllegalArgumentException from SameSite.of and catch it right after. You could just return null.
Source:
public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception { if (writabilityStates.equals("")) { writabilityStates = String.valueOf(ctx.channel().isWritable()); } else { writabilityStates += "," + ctx.channel().isWritable(); } super.channelWritabilityChanged(ctx); }

Target:
if there is possibility of `writabilityStates` to be `null`, it might be better to write this as `"".equals(writabilityStates)`
Source:
public SSLEngine wrapSslEngine(SSLEngine engine, ByteBufAllocator alloc, JdkApplicationProtocolNegotiator applicationNegotiator, boolean isServer) { if (JettyAlpnSslEngineSubstitution.isAvailable()) { return isServer ? (SSLEngine) (Object) JettyAlpnSslEngineSubstitution.newServerEngine(engine, applicationNegotiator) : (SSLEngine) (Object) JettyAlpnSslEngineSubstitution.newClientEngine(engine, applicationNegotiator); } throw new RuntimeException("Unable to wrap SSLEngine of type " + engine.getClass().getName()); }

Target:
Use `IllegalStateException` ....
Source:
public Queue<AbstractMap.SimpleEntry<Object, ChannelPromise>> tempInboundMessages() { if (tempInboundMessages == null) { tempInboundMessages = new ArrayDeque<AbstractMap.SimpleEntry<Object, ChannelPromise>>(); } return tempInboundMessages; }

Target:
This is not needed in unit tests... please keep it private
Source:
public ChannelFuture writeOneInbound(Object msg, ChannelPromise promise) { if (checkOpen(true)) { if (!config().isAutoRead()) { Queue<AbstractMap.SimpleEntry<Object, ChannelPromise>> tempInboundMessages = tempInboundMessages(); if (tempInboundMessages != null) { tempInboundMessages.add(new AbstractMap.SimpleEntry<Object, ChannelPromise>(msg, promise)); } return promise; } else { pipeline().fireChannelRead(msg); } } return checkException(promise); }

Target:
nit: this never can be `null`. Remove the check
Source:
private void encodeUtf8Component(CharSequence s) { for (int i = 0, len = s.length(); i < len; i++) { char c = s.charAt(i); if (!dontNeedEncoding(c)) { if (i > 0) { uriBuilder.append(s, 0, i); } encodeUtf8ComponentSlow(s, i); return; } } uriBuilder.append(s); }

Target:
I would pack this entire branch in a differet method
Source:
final int drainTasks() { int numTasks = 0; for (;;) { Runnable runnable = taskQueue.poll(); if (runnable == null) { break; } // WAKEUP_TASKS should be just discarded as these are added internally. // The important bit is that we not have any user tasks left. if (AbstractScheduledEventExecutor.WAKEUP_TASK != runnable) { numTasks++; } } return numTasks; }

Target:
nit: can just use `WAKEUP_TASK` here since `AbstractScheduledEventExecutor` is a superclass
Source:
public ByteBufOutputStream(ByteBuf buffer) { ObjectUtil.checkNotNull(buffer, "buffer"); this.buffer = buffer; startIndex = buffer.writerIndex(); }

Target:
nit: you can merge both lines above as `checkNotNull` will return the given argument
Source:
private EmptyByteBuf(ByteBufAllocator alloc, ByteOrder order) { ObjectUtil.checkNotNull(alloc, "alloc"); this.alloc = alloc; this.order = order; str = StringUtil.simpleClassName(this) + (order == ByteOrder.BIG_ENDIAN? "BE" : "LE"); }

Target:
nit: you can merge both lines above as `checkNotNull` will return the given argument
Source:
public SwappedByteBuf(ByteBuf buf) { ObjectUtil.checkNotNull(buf, "buf"); this.buf = buf; if (buf.order() == ByteOrder.BIG_ENDIAN) { order = ByteOrder.LITTLE_ENDIAN; } else { order = ByteOrder.BIG_ENDIAN; } }

Target:
nit: you can merge both lines above as `checkNotNull` will return the given argument
Source:
public ByteBuf order(ByteOrder endianness) { ObjectUtil.checkNotNull(endianness, "endianness"); if (endianness == order) { return this; } return buf; }

Target:
nit: you can merge both lines above as `checkNotNull` will return the given argument
Source:
protected AbstractCompositeByteBufTest(ByteOrder order) { ObjectUtil.checkNotNull(order, "order"); this.order = order; }

Target:
nit: you can merge both lines above as `checkNotNull` will return the given argument
Source:
public DefaultHttpContent(ByteBuf content) { ObjectUtil.checkNotNull(content, "content"); this.content = content; }

Target:
nit: you can merge both lines above as `checkNotNull` will return the given argument
Source:
public HttpMessage setProtocolVersion(HttpVersion version) { ObjectUtil.checkNotNull(version, "version"); this.version = version; return this; }

Target:
nit: you can merge both lines above as `checkNotNull` will return the given argument
Source:
public HttpResponse setStatus(HttpResponseStatus status) { ObjectUtil.checkNotNull(status, "status"); this.status = status; return this; }

Target:
nit: you can merge both lines above as `checkNotNull` will return the given argument
Source:
public void setContentType(String contentType) { ObjectUtil.checkNotNull(contentType, "contentType"); this.contentType = contentType; }

Target:
consider merging both lines
Source:
private CompositeByteBuf(ByteBufAllocator alloc, boolean direct, int maxNumComponents, int initSize) { super(AbstractByteBufAllocator.DEFAULT_MAX_CAPACITY); if (maxNumComponents < 1) { throw new IllegalArgumentException( "maxNumComponents: " + maxNumComponents + " (expected: >= 1)"); } this.alloc = ObjectUtil.checkNotNull(alloc, "alloc"); this.direct = direct; this.maxNumComponents = maxNumComponents; components = newCompArray(initSize, maxNumComponents); }

Target:
@carryxyh lets move this check (and assignment) above the `maxNumComponents` check again (just like before).
Source:
public static void watch(Thread thread, Runnable task) { ObjectUtil.checkNotNull(thread, "thread"); if (!thread.isAlive()) { throw new IllegalArgumentException("thread must be alive."); } schedule(thread, ObjectUtil.checkNotNull(task, "task"), true); }

Target:
move the mull check under the null check for thread to ensure we not change behaviour.
Source:
public boolean awaitInactivity(long timeout, TimeUnit unit) throws InterruptedException { final Thread thread = this.thread; if (thread == null) { throw new IllegalStateException("thread was not started"); } thread.join(ObjectUtil.checkNotNull(unit, "unit").toMillis(timeout)); return !thread.isAlive(); }

Target:
move null check back as first action in the method to not change behaviour
Source:
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { if (inEventLoop()) { throw new IllegalStateException("cannot await termination of the current thread"); } threadLock.await(timeout, ObjectUtil.checkNotNull(unit, "unit")); return isTerminated(); }

Target:
move check back as first in the method to not change behaviour if null is passed as `unit` but we are in the `EventLoop` thread.
Source:
public ChunkedFile(RandomAccessFile file, long offset, long length, int chunkSize) throws IOException { ObjectUtil.checkPositiveOrZero(offset, "offset"); ObjectUtil.checkPositiveOrZero(length, "length"); this.file = ObjectUtil.checkNotNull(file, "file"); this.chunkSize = ObjectUtil.checkPositive(chunkSize, "chunkSize"); this.offset = startOffset = offset; endOffset = offset + length; file.seek(offset); }

Target:
move this assignment and check as first in the method to not change behaviour.
Source:
public boolean clear(String hostname) { return resolveCache.clear( appendDot( checkNotNull(hostname, "hostname"))); }

Target:
nit: maybe merge the lines as the formatting looks a bit strange.
Source:
public DefaultAddressedEnvelope(M message, A recipient, A sender) { if (recipient == null && sender == null) { throw new NullPointerException("recipient and sender"); } this.message = ObjectUtil.checkNotNull(message, "message"); this.sender = sender; this.recipient = recipient; }

Target:
move this assignment and check as first in the method to not change behaviour
Source:
public SslContextBuilder trustManager(TrustManager trustManager) { trustCertCollection = null; try { this.trustManagerFactory = new TrustManagerFactoryWrapper(trustManager); } catch (Exception e) { throw new Error(e.toString()); } return this; }

Target:
can we just throw an `IllegalStateException` here and wrap the original `Exception` ?
Source:
protected KeyManager[] engineGetKeyManagers() { ObjectUtil.checkNotNull(km, "KeyManagerFactoryWrapper is created with null KeyManager value"); return new KeyManager[] {km}; }

Target:
remove this and do the check in the constructor to fail fast
Source:
KeyManagerFactoryWrapper(KeyManager km) { ObjectUtil.checkNotNull(km, "km"); this.km = km; }

Target:
nit: you can merge both of the above line as `checkNotNull(...)` returns `km`.
Source:
TrustManagerFactoryWrapper(TrustManager tm) throws Exception { ObjectUtil.checkNotNull(tm, "tm"); this.tm = tm; }

Target:
nit: you can merge both of the above line as `checkNotNull(...)` returns `tm`.
Source:
WeakOrderQueue newWeakOrderQueue(Thread thread) { return WeakOrderQueue.newQueue(this, thread); }

Target:
private?
Source:
void relink(Link link) { if (this.link != link) { reclaimSpace(LINK_CAPACITY); } this.link = link; }

Target:
I don't think this check was there before, was it intentional? If so then the `this.link = link;` below could be moved inside the if block?
Source:
public StringEncoder(Charset charset) { if (charset == null) { throw new NullPointerException("charset"); } this.encoder = CharsetUtil.encoder(charset); }

Target:
@johnou @carl-mastrangelo is right... it is `@Sharable` so this will not work.
Source:
public Attribute createAttribute(HttpRequest request, String name) { Attribute attribute; if (useDisk) { attribute = new DiskAttribute(name, charset); } else if (checkSize) { attribute = new MixedAttribute(name, minSize, charset); } else { attribute = new MemoryAttribute(name); } attribute.setMaxSize(maxSize); List<HttpData> list = getList(request); list.add(attribute); return attribute; }

Target:
nit: make this final
Source:
protected final boolean trySuccessInternal(V result) { boolean done = super.trySuccess(result); return clearTaskAfterCompletion(done, COMPLETED); }

Target:
nit: you can merge these lines
Source:
public boolean cancel(boolean mayInterruptIfRunning) { boolean cancelled = super.cancel(mayInterruptIfRunning); return clearTaskAfterCompletion(cancelled, CANCELLED); }

Target:
nit you can merge these lines
Source:
protected final boolean tryFailureInternal(Throwable cause) { boolean done = super.tryFailure(cause); return clearTaskAfterCompletion(done, FAILED); }

Target:
nit: these two lines can be merged
Source:
private boolean dontNeedEncoding(char ch) { return ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch >= '0' && ch <= '9' || ch == '-' || ch == '_' || ch == '.' || ch == '*'; }

Target:
static
Source:
void add(ChannelOutboundBuffer buffer, boolean connected) throws Exception { processor.connected = connected; try { buffer.forEachFlushedMessage(processor); } finally { processor.connected = false; } }

Target:
not sure resetting this is really needed now since it's always set before use?
Source:
public void testCancellationExceptionIsReturnedAsCause() throws InterruptedException, ExecutionException, TimeoutException { final Promise<Void> promise = new DefaultPromise<Void>(ImmediateEventExecutor.INSTANCE); promise.cancel(false); assertThat(promise.cause(), instanceOf(CancellationException.class)); }

Target:
please also assert return value
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 return (slice == srcBuf ? srcBuf : srcBuf.slice()).duplicate(); }

Target:
Why do we need to first slice and then also duplicate ?
Source:
ByteBuf slice() { return slice != null ? slice : (slice = srcBuf.slice(srcIdx(offset), length())); }

Target:
please make this more readable... Sure its compact but its really hard to read.
Source:
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) { return null; } scheduledTaskQueue.remove(); return scheduledTask; }

Target:
Replace direct comparison using nanoTime with differences ie ```scheduledTask.deadlineNanos() - nanoTime > 0```
Source:
private boolean fetchFromScheduledTaskQueue() { if (scheduledTaskQueue == null || scheduledTaskQueue.isEmpty()) { return true; } long nanoTime = AbstractScheduledEventExecutor.nanoTime(); for (Runnable scheduledTask; (scheduledTask = pollScheduledTask(nanoTime)) != null;) { 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; }

Target:
imho it would be easier to read as: ```java for (;;) { Runnable scheduledTask = pollScheduledTask(nanoTime); if (scheduledTask == null) { break; } .... } ```
Source:
public static Set<String> normalizedLinuxClassifiers() { return Collections.unmodifiableSet(LINUX_OS_CLASSIFIERS); }

Target:
Why not create this once in the static method and return the same instance all the time ?
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 { unsafe.notifyReadComplete(allocHandle, true); } } }

Target:
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.
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()) { ctx.channel().close(); } }

Target:
`ctx.close();`
Source:
public 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 }

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

Target:
4 spaces
Source:
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; }

Target:
4 spaces
Source:
private LineHeaderExtractor(int maxHeaderSize) { super(maxHeaderSize); }

Target:
remove private
Source:
protected void deallocate() { for (HAProxyTLV tlv : tlvs) { tlv.release(); } final ResourceLeakTracker<HAProxyMessage> leak = this.leak; if (leak != null) { boolean closed = leak.close(this); assert closed; } }

Target:
put all of this in a finally block, just in case.
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); assertEquals(checksum.getValue(), wrapped.getValue()); }

Target:
put all of this in a `try {...} finally { buf.release(); }` block
Source:
public static void freeDirectBuffer(ByteBuffer buffer) { // Copied locally to prevent race CustomCleaner localCustomCleaner = DirectCleaner.customCleaner; if (!ALLOW_CUSTOM_CLEANER || localCustomCleaner == null) { PlatformDependent.freeDirectBuffer(buffer); } else { localCustomCleaner.freeDirectMemory(buffer); } }

Target:
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 { .... } ```
Source:
void setNetworkInterface(NetworkInterface netInterface, InternetProtocolFamily family) throws IOException { InetAddress address = deriveInetAddress(netInterface, family == InternetProtocolFamily.IPv6); if (address.equals(family == InternetProtocolFamily.IPv4 ? INET6_ANY : INET_ANY)) { throw new IOException("NetworkInterface does not support " + family); } final NativeInetAddress nativeAddress = NativeInetAddress.newInstance(address); setInterface(intValue(), ipv6, nativeAddress.address(), nativeAddress.scopeId(), interfaceIndex(netInterface)); }

Target:
is this reversed?
Source:
public ChannelFuture bind(SocketAddress localAddress) { validate(); ObjectUtil.checkNotNull(localAddress, "localAddress"); return doBind(localAddress); }

Target:
@qeesung: nit you can merge the above 2 lines
Source:
public B handler(ChannelHandler handler) { ObjectUtil.checkNotNull(handler, "handler"); this.handler = handler; return self(); }

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

Target:
nit: you can merge the above two lines
Source:
AnnotatedConnectException(ConnectException exception, SocketAddress remoteAddress) { super(exception.getMessage() + ": " + remoteAddress); initCause(exception); setStackTrace(EmptyArrays.EMPTY_STACK_TRACE); }

Target:
@carl-mastrangelo shouldn't we just remove this line all together ?
Source:
AnnotatedNoRouteToHostException(NoRouteToHostException exception, SocketAddress remoteAddress) { super(exception.getMessage() + ": " + remoteAddress); initCause(exception); setStackTrace(EmptyArrays.EMPTY_STACK_TRACE); }

Target:
same question as above
Source:
private void transfer(EmbeddedChannel outChannel, EmbeddedChannel inChannel) { // Transfer encoded data into decoder // Loop because there might be multiple frames (gathering write) while (true) { ByteBuf encoded = outChannel.readOutbound(); if (encoded == null) { return; } inChannel.writeInbound(encoded); } }

Target:
please use the same style we do in Netty: `for (;;) { ... }`
Source:
public String toString() { // E.g.: "1000 Bye", "1009 Message too big" return code() + " " + reasonText(); }

Target:
final field to it's computed once and for all, as most values should be constants
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(); }

Target:
I think you also need to call `--size;` Can you please also adjust the unit test to check for this ?
Source:
public InetAddress getInterface() { throw new UnsupportedOperationException("Retrieval of network interface address not supported"); }

Target:
can we keep the old code as this is a "breaking" change ?
Source:
public void testMulticast(Bootstrap sb, Bootstrap cb) throws Throwable { // Run this test with IP_RECVORIGDSTADDR option enabled sb.option(EpollChannelOption.IP_RECVORIGDSTADDR, true); super.testMulticast(sb, cb); sb.option(EpollChannelOption.IP_RECVORIGDSTADDR, false); }

Target:
can you explain why ?
Source:
protected static TrustManagerFactory buildTrustManagerFactory( File certChainFile, TrustManagerFactory trustManagerFactory, String keyType) throws NoSuchAlgorithmException, CertificateException, KeyStoreException, IOException { X509Certificate[] x509Certs = toX509Certificates(certChainFile); return buildTrustManagerFactory(x509Certs, trustManagerFactory, keyType); }

Target:
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
Source:
public OpenSslClientContext(File certChainFile, TrustManagerFactory trustManagerFactory) throws SSLException { this(certChainFile, trustManagerFactory, null, null, null, null, null, IdentityCipherSuiteFilter.INSTANCE, null, 0, 0, KeyStore.getDefaultType()); }

Target:
revert please
Source:
DefaultChannelHandlerContext(DefaultChannelPipeline pipeline, String name, ChannelHandler handler) { this.name = requireNonNull(name, "name"); this.pipeline = pipeline; this.executionMask = ChannelHandlerMask.mask(handler.getClass()); this.handler = handler; }

Target:
Could omit classname here since you have static * import
Source:
public UnorderedThreadPoolEventExecutor(int corePoolSize, ThreadFactory threadFactory) { super(corePoolSize, threadFactory); this.setThreadFactory(ThreadExecutorMap.apply(getThreadFactory(), this)); }

Target:
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()`?
Source:
public <T> T getOption(ChannelOption<T> option) { if (option == EpollChannelOption.DOMAIN_SOCKET_READ_MODE) { return (T) getReadMode(); } if (option == EpollChannelOption.ALLOW_HALF_CLOSURE) { return (T) Boolean.valueOf(isAllowHalfClosure()); } return super.getOption(option); }

Target:
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
Source:
public Map<ChannelOption<?>, Object> getOptions() { return getOptions(super.getOptions(), EpollChannelOption.DOMAIN_SOCKET_READ_MODE, ChannelOption.ALLOW_HALF_CLOSURE); }

Target:
use `EpollChannelOption.ALLOW_HALF_CLOSURE` here or use `ChannelOption.ALLOW_HALF_CLOSURE` bellow to make it consistent
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); decodeState = STATE_REMOVED; }

Target:
I think this should be set in a `finally` block
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()) { return !connectionClose; } else { return message.headers().containsValue(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE, true); } }

Target:
connectionClose can only be false here
Source:
protected void decode(ChannelHandlerContext ctx, WebSocketFrame frame, List<Object> out) throws Exception { if (frame instanceof CloseWebSocketFrame) { serverReceivedCloseHandshake = true; frame.retain(); return; } super.decode(ctx, frame, out); }

Target:
why do you retain here ? This looks like a possible memory leak.
Source:
public WebSocketClientHandshaker13 setForceCloseTimeoutMillis(long forceCloseTimeoutMillis) { this.forceCloseTimeoutMillis = forceCloseTimeoutMillis; return this; }

Target:
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
Source:
private PartialCumulationDecoder(int messageSize) { this.messageSize = messageSize; setCumulator(new PartialCumulator()); }

Target:
nit: make package-private
Source:
private boolean release0(int decrement) { int rawCnt = nonVolatileRawCnt(), realCnt = toLiveRealCnt(rawCnt, decrement); if (decrement == realCnt) { if (refCntUpdater.compareAndSet(this, rawCnt, 1)) { maxCapacity(-rawMaxCapacity()); deallocate(); return true; } return retryRelease0(decrement); } return releaseNonFinal0(decrement, rawCnt, realCnt); }

Target:
should we assert that this value will never be positive ?
Source:
public final void deallocate() { // this is to avoid overriding isAccessible(), so that it can be // final in AbstractReferenceCountedByteBuf maxCapacity(-rawMaxCapacity()); wrapped.deallocate(); }

Target:
should we assert that this value will never be positive ?
Source:
public void requiredHeadersInSeparateConnectionHeaders() { setUpServerChannel(); 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); }

Target:
nit: you could also move all the `setUpServerChannel()` calls
Source:
HeadContext(DefaultChannelPipeline pipeline) { super(pipeline, pipeline.channel.eventLoop(), HEAD_NAME, HeadContext.class); unsafe = pipeline.channel().unsafe(); setAddComplete(); }

Target:
should this be `pipeline.executor`?
Source:
public ChannelHandlerContext firstContext() { synchronized (handlers) { if (handlers.isEmpty()) { return null; } return handlers.get(0); } }

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

Target:
simplify with conditional operator?
Source:
public void propagateEvent(Blackhole hole) { for (int i = 0; i < 100; i++) { pipeline.fireChannelReadComplete(); hole.consume(i); } }

Target:
Maybe add some counter inside the handler just to be 100% sure the compiler doesn't throw this away.
Source:
public static SingleThreadEventLoop.IoHandlerFactory newFactory(final SelectorProvider selectorProvider, 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()); } }; }

Target:
`final` on purpose (say still compiling against Java < 8)?
Source:
public static SingleThreadEventLoop.IoHandlerFactory newFactory(final int maxEvents, 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()); } }; }

Target:
Same here, possibly unnecessarily `final`
Source:
protected EventLoop newChild(Executor executor, Object... args) throws Exception { return new LocalEventLoop(this, executor); }

Target:
Should these args ever be set? Might be worth failing if any are.
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); } if (handle > 0) { ByteBuffer nioBuffer = cachedNioBuffers != null ? cachedNioBuffers.pollLast() : null; initBuf(buf, nioBuffer, handle, reqCapacity); return true; } return false; }

Target:
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
Source:
public void trace(String format, Object arg) { if (isTraceEnabled()) { log(TRACE_INT, org.slf4j.helpers.MessageFormatter.format(format, arg).getMessage(), arg); } }

Target:
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..?
Source:
public synchronized void tearDown() { executorToShutdown.shutdown(); }

Target:
why synchronized ?
Source:
public void shutdown() { if (poisoned.compareAndSet(false, true)) { while (true) { if (tasks.offer(POISON_PILL)) { break; } } try { executorThread.join(); } catch (InterruptedException e) { //we're quite trusty :) } } }

Target:
nit: But I think this could be re-factored to: ```java while (!task.offer(POISION_POLL) { // Just try again } ```
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; } else { task.run(); } } } } }); executorThread.start(); }

Target:
nit this could be simplified: ```java Runnable task; while ((task = tasks.poll()) != POISON_PILL) { if (task != null) { task.run(); } } ```
Source:
private static Channel connectionChannel(ChannelHandlerContext ctx) { final Channel ch = ctx.channel(); return (ch instanceof Http2StreamChannel) ? ch.parent() : ch; }

Target:
nit: you can remove the `()`
Source:
private 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); } }

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

Target:
Static
Source:
public boolean isSnapshot() { String version = getVersion(); if (StringUtils.isNotBlank(version)) { if (version.contains("SNAPSHOT")) {//$NON-NLS-1$ return true; } } return false; }

Target:
Sorry, being picky: `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$ if (StringUtils.isNotBlank(value) && value.equals("true")) { //$NON-NLS-1$ return true; } else { return false; } } else { if (isSnapshot()) { return true; } else { return false; } } }

Target:
`return StringUtils.isNotBlank(value) && value.equals("true");`
Source:
public String getFeedbackUrl(String siteId) { return ServerConfigurationService.getPortalUrl() + "/site/" + siteId + "/page/" + SkinnableCharonPortal.CONTACT_US_URL_SUFFIX; }

Target:
This should be a private method, it doesn't need any docs.
Source:
public boolean isSitePublished(String siteId) { boolean siteIsPublished = false; try { Site site = SiteService.getSite(siteId); if (site != null) { siteIsPublished = site.isPublished(); } } catch (IdUnusedException e) { // not a site after all } return siteIsPublished; }

Target:
Null check is redundant as it should never happen.
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)); } return null; }

Target:
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
Source:
private void updateScoreStatistics(PersonaInfo pi) { listScoreStatistics = scoreStatisticsFromJSON(pi); ContentValues contentValues = scoreStatisticsForDB(pi, mSelectedPersona); try { getContext().getContentResolver().insert(ScoreStatistics.URI, contentValues); } catch(SQLiteConstraintException ex) { getContext().getContentResolver().update( ScoreStatistics.URI, contentValues, ScoreStatistics.Columns.PERSONA_ID + "=?", new String[] { String.valueOf(pi.getPersonaId()) } ); } }

Target:
If insert fails catch it and do update?
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}"); context.putProperty("LOG_PATH", "${LOG_HOME}/${APP_NAME}"); 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); }

Target:
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.
Source:
FileExtensionFilter(String ext) { extension = "."+ext; }

Target:
Do we need the "." (dot)? What if we have files without extension?
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..."); String agentKey = localHostname + ":" + Integer.toString(httpPort); knownAgentsDatastore.addKnownAgent(loadBalancerConfiguration.getName(), baragonAgentMetadata, agentKey); }

Target:
`String.format()` is preferable
Source:
private static boolean objectsEqual(String object1, String object2) { if (object1 == null && object2 == null) { return true; } return object1.equals(object2); }

Target:
The code here fails if only the first parameter is `null`
Source:
public HomePresenter(EventBus eventBus, MyView view, MyProxy proxy) { super(eventBus, view, proxy, ApplicationPresenter.SLOT_SetMainContent); }

Target:
Remove public. Also let's reformat all the ctor to our latest code style.
Source:
public OrcidOAuth2AP(String clientId, String clientSecret, String userEndpoint) { String s = null; if(userEndpoint != null){ s = userEndpoint.startsWith("https://pub") ? "/authenticate" : "/read-limited"; } scope = Arrays.asList(s); this.clientId = clientId; this.clientSecret = clientSecret; this.baseUserEndpoint = userEndpoint; }

Target:
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:
Source:
public static String replaceExtension(String originalName, String newExtension) { 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 ; } }

Target:
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.
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) { logger.log(Level.INFO, "Increment usage count failed on template id {0}. ", templateId); } }

Target:
Should this log at a higher level?
Source:
public boolean isIdentifierLocallyUnique(String identifier, Dataset dataset) { boolean u = em.createNamedQuery("Dataset.findByIdentifierAuthorityProtocol") .setParameter("identifier", identifier) .setParameter("authority", dataset.getAuthority()) .setParameter("protocol", dataset.getProtocol()) .getResultList().isEmpty(); return u; }

Target:
just return, don't assign
Source:
public void toggleAllSelected(){ System.out.print("in toggle all"); this.selectAllFiles = !this.selectAllFiles; toggleSelectedFiles(this.selectAllFiles); }

Target:
Can you please remove this `System.out.print` or convert it to `logger.fine` if it might be valuable when debugging in production?
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); List<String> checksumList = nativeQuery.getResultList(); return checksumList.size() > 0; }

Target:
Does this not need a `TypedQuery`?
Source:
public Dataverse findRootDataverse() { return (Dataverse) em.createQuery("select object(o) from Dataverse as o where o.owner.id = null").getSingleResult(); }

Target:
You didn't change the `createQuery` call to include the return type.
Source:
public List<Object[]> getDvObjectInfoForMyData(List<Long> dvObjectIdList){ //msgt("getAssigneeAndRoleIdListFor"); String dvObjectClause = getDvObjectIdListClause(dvObjectIdList); if (dvObjectClause==null){ return null; } String qstr = "SELECT dv.id, dv.dtype, dv.owner_id"; // dv.modificationtime, qstr += " FROM dvobject dv"; qstr += " WHERE dv.id IN " + dvObjectClause; qstr += ";"; return em.createNativeQuery(qstr, Object[].class).getResultList(); }

Target:
Isn't this the default return type?
Source:
public String init() { System.out.println("_YE_OLDE_QUERY_COUNTER_"); // for debug purposes if ((session.getUser() != null) && (session.getUser().isAuthenticated()) && (session.getUser().isSuperuser())) { authUser = (AuthenticatedUser) session.getUser(); userListMaker = new UserListMaker(userService); runUserSearch(); } else { return permissionsWrapper.notAuthorized(); // redirect to login OR give some type ‘you must be logged in message' } return null; }

Target:
cruft removed
Source:
public Long getTotalUserCount(){ return getUserCount(null); }

Target:
As getUserCount immediate checks for null and changes it, why not pass an empty string instead?
Source:
void idIsGeneratedUUID() { class Entity { @GeneratedValue(strategy = GenerationStrategy.UNIQUE) @Id UUID id; } Entity entity = new Entity(); CouchbaseDocument converted = new CouchbaseDocument(); converter.write(entity, converted); assertThat(converted.getId()).isEqualTo(entity.id.toString()); System.out.println(entity.id); }

Target:
Looks like there are leftover printlns in addition to the assertions?
Source:
public T one(final String id) { try { return reactiveSupport.one(id).block(); } catch(DocumentNotFoundException dnfe){ dnfe.printStackTrace(); return null; } }

Target:
this is a leftover I assume?
Source:
public JsonValue getParameters() { return parameters; }

Target:
I think it could be benefitial to have two overloads (jsonObject, jsonarray), very similar to what the sdk has
Source:
private Boolean executeRequest(URIBuilder builder) throws Exception { try { HttpGet request = new HttpGet(builder.build()); HttpClient client = HttpClientBuilder.create().build(); HttpResponse response = client.execute(request); int status = response.getStatusLine().getStatusCode(); if (status < 200 || status > 300) { return false; } return true; } catch (Exception ex) { Thread.sleep(1000); throw ex; } }

Target:
What if status is 300? Should the check be`status >= 300` ?
Source:
public KeySettings delimiter(String delimiter) { this.delimiter = delimiter; return this; }

Target:
should probably test for `null` delimiter and either ignore or preferably interpret null as "no delimiter" (the empty `String`)
Source:
protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception { ByteBuf payloadAndCrc = (ByteBuf) super.decode(ctx, in); assert header != null; if (payloadAndCrc == null) { return null; } else { Segment segment = segmentCodec.decode(header, payloadAndCrc); header = null; return segment; } }

Target:
```suggestion header = null; return null; ``` I think you need to also null out the header here in cases where the input buffer doesn't have enough readable bytes to decode the full payload. As it is, the next time `super.decode` is called it hits the assertion in `getUnadjustedFrameLength`
Source:
private Optional<Long> gettimeofdayImpl(POSIX posix) { Timeval tv = posix.allocateTimeval(); int rv = posix.gettimeofday(tv); if (rv != 0) { LOG.info("Expected 0 return value from gettimeofday(), observed " + rv); return Optional.empty(); } return Optional.of(tv.sec() * 1_000_000 + tv.usec()); }

Target:
`Log.debug` maybe?
Source:
public static String getCpu() { return CPU.name().toLowerCase(LOCALE); }

Target:
Since this is class is becoming a shell that delegates all of its operations to a `NativeImpl` instance, wouldn't it be a better design to also include `getCpu()` in `NativeImpl`?
Source:
public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof ReplicationFactor)) return false; ReplicationFactor that = (ReplicationFactor) o; return allReplicas == that.allReplicas && fullReplicas == that.fullReplicas; }

Target:
missing braces
Source:
public MappingCodec( @NonNull TypeCodec<InnerT> innerCodec, @NonNull GenericType<OuterT> outerJavaType) { this.innerCodec = Objects.requireNonNull(innerCodec, "innerCodec cannot be null"); this.outerJavaType = Objects.requireNonNull(outerJavaType, "outerJavaType cannot be null"); }

Target:
nit: maybe make this constructor protected (although I don't see any real issue with it being public)
Source:
public static void maybeCreateSchema(CqlSession session) throws Exception { session.execute( SimpleStatement.newInstance( "CREATE KEYSPACE IF NOT EXISTS killrvideo WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}") .setExecutionProfileName("slow")); session.execute("USE killrvideo"); for (String statement : getStatements("killrvideo_schema.cql")) { session.execute(SimpleStatement.newInstance(statement).setExecutionProfileName("slow")); } }

Target:
Can be private
Source:
boolean nullSavingStrategyExplicitlySet(Element methodElement, Class<?> javaClass) { Optional<AnnotationMirror> annotationMirrorForJavaClass = getAnnotationMirrorForJavaClass(methodElement, javaClass); // Find out if NullSavingStrategy was set explicitly if (annotationMirrorForJavaClass.isPresent()) { for (ExecutableElement executableElement : annotationMirrorForJavaClass.get().getElementValues().keySet()) { if (executableElement.getSimpleName().contentEquals("nullSavingStrategy")) { return true; } } } return false; }

Target:
If we were to remove `default NullSavingStrategy.DO_NOT_SET` from all annotations so they are null instead couldn't this be more effective as all you would have to do is null check?
Source:
public static void setValue( CodeBlock cqlName, PropertyType type, CodeBlock valueExtractor, String targetName, MethodSpec.Builder methodBuilder, BindableHandlingSharedCode enclosingClass) { // invoke with SET_TO_NULL to preserve default behaviour when retrieving an entity setValue( cqlName, type, valueExtractor, targetName, methodBuilder, enclosingClass, CodeBlock.of("$T.$L", NullSavingStrategy.class, NullSavingStrategy.SET_TO_NULL)); }

Target:
Its an interesting decision point because it's possible that fields may be initialized with some non-null value in their default constructors. However, conceptually, I think what you are doing is the right thing here. If the value is unset in C*, it should be effectively null in the entity itself.
Source:
public String addQueryProvider( ExecutableElement methodElement, TypeMirror providerClass, List<ClassName> entityHelperTypes) { // Invokers are not shared between methods, so always generate a new name String fieldName = nameIndex.uniqueField(methodElement.getSimpleName().toString() + "Invoker"); List<String> entityHelperNames = new ArrayList<>(); for (ClassName type : entityHelperTypes) { entityHelperNames.add(addEntityHelperField(type)); } queryProviders.add( new GeneratedQueryProvider(methodElement, fieldName, providerClass, entityHelperNames)); return fieldName; }

Target:
Nice, i was wondering if this would work for overloaded methods and it appears it does (i.e. `findSliceInvoker1` is defined if a previous `findSliceInvoker` exists.
Source:
private CqlNameGenerator(NamingConvention namingConvention, TypeMirror converterClassMirror) { Preconditions.checkArgument(namingConvention == null ^ converterClassMirror == null); this.namingConvention = namingConvention; this.converterClassMirror = converterClassMirror; }

Target:
If this check fails will it be converted to easy to read the message? I am assuming that not every client will know the meaning of using `^` in this part of the code and if this will propagate to exception message he maybe confused
Source:
public SimpleStatementBuilder builder() { return SimpleStatement.builder(asCql()).setIdempotence(IS_IDEMPOTENT); }

Target:
Please don't use a constant here. `setIdempotence(true)` is perfectly clear, and it's not like we might decide to use "false" to mean "idempotent" at any point in the future.
Source:
public ByteBuffer encode(@Nullable T value, @NonNull ProtocolVersion protocolVersion) { if (value == null) return null; try { return ByteBuffer.wrap(objectMapper.writeValueAsBytes(value)); } catch (JsonProcessingException e) { throw new InvalidTypeException(e.getMessage(), e); } }

Target:
As I said in #1208 : In driver 4.0 we don't have any specific exception for codecs except `CodecNotFoundException`. When a codec cannot serialize or deserialize something, we use `IllegalArgumentException`. I don't think you need to introduce a special exception in these examples.