auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
START public DeleteManager(ClusterMap clusterMap, ResponseHandler responseHandler, NotificationSystem notificationSystem, END RouterConfig routerConfig, NonBlockingRouterMetrics routerMetrics, Time time) { this.clusterMap = clusterMap; this.responseHandler = responseHandler; this.notificationSystem = notificationSystem; this.routerConfig = routerConfig; this.routerMetrics = routerMetrics; this.time = time; deleteOperations = Collections.newSetFromMap(new ConcurrentHashMap<DeleteOperation, Boolean>()); correlationIdToDeleteOperation = new HashMap<Integer, DeleteOperation>(); } why `public`?

Target:
DeleteManager(ClusterMap clusterMap, ResponseHandler responseHandler, NotificationSystem notificationSystem, RouterConfig routerConfig, NonBlockingRouterMetrics routerMetrics, Time time) { this.clusterMap = clusterMap; this.responseHandler = responseHandler; this.notificationSystem = notificationSystem; this.routerConfig = routerConfig; this.routerMetrics = routerMetrics; this.time = time; deleteOperations = Collections.newSetFromMap(new ConcurrentHashMap<DeleteOperation, Boolean>()); correlationIdToDeleteOperation = new HashMap<Integer, DeleteOperation>(); }
Source:
public void testGoodCase() throws Exception { initialize(); BlobId convertedBlobId = RouterUtils.getBlobIdFromString(blobIdStr, clusterMap); START assertTrue("The converted BlobId should be the same as the original.", convertedBlobId.equals(originalBlobId)); END } use assertEquals

Target:
public void testGoodCase() throws Exception { initialize(); BlobId convertedBlobId = RouterUtils.getBlobIdFromString(blobIdStr, clusterMap); assertEquals("The converted BlobId should be the same as the original.", originalBlobId, convertedBlobId); }
Source:
START MockSelector(MockServerLayout serverLayout, AtomicReference<MockSelectorState> state, Time time) END throws IOException { super(new NetworkMetrics(new MetricRegistry()), time, null); // we don't need the actual selector, close it. super.close(); this.serverLayout = serverLayout; this.state = state == null ? new AtomicReference<MockSelectorState>(MockSelectorState.Good) : state; this.time = time; } Why should the argument be an `AtomicReference`? If you really do need an `AtomicReference`, shouldn't the class take the input and turn it into an atomic reference?

Target:
MockSelector(MockServerLayout serverLayout, AtomicReference<MockSelectorState> state, Time time) throws IOException { super(new NetworkMetrics(new MetricRegistry()), time, null); // we don't need the actual selector, close it. super.close(); this.serverLayout = serverLayout; this.state = state == null ? new AtomicReference(MockSelectorState.Good) : state; this.time = time; }
Source:
START private PutChunk getChunkToFill() { END if (chunkToFill != null && chunkToFill.isBuilding()) { return chunkToFill; } else { for (PutChunk chunk : putChunks) { if (chunk.isFree()) { chunkCounter++; chunk.prepareForBuilding(chunkCounter, getSizeOfChunkAt(chunkCounter)); chunkToFill = chunk; return chunk; } } } // No free or building chunks. return null; } Can we have return only once at the end

Target:
private PutChunk getChunkToFill() { if (chunkToFill != null && chunkToFill.isBuilding()) { return chunkToFill; } chunkToFill = null; for (PutChunk chunk : putChunks) { if (chunk.isFree()) { chunkCounter++; chunk.prepareForBuilding(chunkCounter, getSizeOfChunkAt(chunkCounter)); chunkToFill = chunk; break; } } return chunkToFill; }
Source:
START private void ensureCallbackOrder(ChannelWriter channelWriter, int expectedCallbackId) { END for (int i = expectedCallbackId; i < channelWriter.writes.size(); i++) { WriteCallback writeCallback = channelWriter.writes.get(i).writeCallback; if (expectedCallbackId == i) { assertTrue("Callback for the expected oldest chunk not invoked", writeCallback.callbackInvoked.get()); } else { assertFalse("Callback for a chunk younger than the expected is invoked", writeCallback.callbackInvoked.get()); } } } this might be more readable if you simply took the expected case outside of the loop, and then had the loop run from `expectedCallbackId + 1` to the end.

Target:
private void ensureCallbackOrder(ChannelWriter channelWriter, int expectedCallbackId) { WriteCallback writeCallback = channelWriter.writes.get(expectedCallbackId).writeCallback; assertTrue("Callback for the expected oldest chunk not invoked", writeCallback.callbackInvoked.get()); for (int i = expectedCallbackId + 1; i < channelWriter.writes.size(); i++) { writeCallback = channelWriter.writes.get(i).writeCallback; assertFalse("Callback for a chunk younger than the expected is invoked", writeCallback.callbackInvoked.get()); } }
Source:
void checkInConnection(String connectionId) { START availableConnections.add(connectionId); END availableCount++; } Should we check if the `connectionId` actually belongs to this <host, port> pair? There could be possibly error cases that connections to <host1, port1> are checked into <host2, port2>.

Target:
void checkInConnection(String connectionId) { availableConnections.add(connectionId); }
Source:
NetworkClient getNetworkClient() throws IOException { START Selector selector = new Selector(networkMetrics, time, sslFactory); END ConnectionTracker connectionTracker = new ConnectionTracker(maxConnectionsPerPortPlainText, maxConnectionsPerPortSsl, time); return new NetworkClient(selector, connectionTracker, networkConfig, networkRequestMetrics, connectionCheckoutTimeoutMs, time); } How do you plan to embed MockSelector for testing purposes?

Target:
NetworkClient getNetworkClient() throws IOException { Selector selector = new Selector(networkMetrics, time, sslFactory); ConnectionTracker connectionTracker = new ConnectionTracker(maxConnectionsPerPortPlainText, maxConnectionsPerPortSsl); return new NetworkClient(selector, connectionTracker, networkConfig, connectionCheckoutTimeoutMs, time); }
Source:
public void testClose() throws IOException { initialize(); List<RequestInfo> requestInfoList = new ArrayList<RequestInfo>(); START { END networkClient.close(); try { networkClient.sendAndPoll(requestInfoList); requestInfoList.clear(); Assert.fail("Polling after close should throw"); } catch (IllegalStateException e) { } } } braces not needed?

Target:
public void testClose() throws IOException { List<RequestInfo> requestInfoList = new ArrayList<RequestInfo>(); networkClient.close(); try { networkClient.sendAndPoll(requestInfoList); Assert.fail("Polling after close should throw"); } catch (IllegalStateException e) { } }
Source:
public void addContent(HttpContent httpContent) throws RestServiceException { if (!isOpen()) { nettyMetrics.multipartRequestAlreadyClosedError.inc(); throw new RestServiceException("The request has been closed and is not accepting content", RestServiceErrorCode.RequestChannelClosed); } else { ReferenceCountUtil.retain(httpContent); START rawRequestContents.add(httpContent); END } } Do you intend to make the other change we discussed in a separate patch?

Target:
public void addContent(HttpContent httpContent) throws RestServiceException { if (!isOpen()) { nettyMetrics.multipartRequestAlreadyClosedError.inc(); throw new RestServiceException("The request has been closed and is not accepting content", RestServiceErrorCode.RequestChannelClosed); } else { rawRequestContents.add(ReferenceCountUtil.retain(httpContent)); } }
Source:
public void disconnect(ChannelHandlerContext ctx, ChannelPromise future) throws Exception { if (requestInProgress) { START requestInProgress = false; END logDurations(); logMessage.append(" : Channel disconnected while request in progress."); publicAccessLogger.logError(logMessage.toString()); } super.disconnect(ctx, future); } write a function for this. Looks like this code is not repeated in 3 places.

Target:
public void disconnect(ChannelHandlerContext ctx, ChannelPromise future) throws Exception { if (request != null) { logError(" : Channel disconnected while request in progress."); } super.disconnect(ctx, future); }
Source:
RouterNetworkComponentsFactory(NetworkMetrics networkMetrics, NetworkConfig networkConfig, SSLFactory sslFactory, int maxConnectionsPerPortPlainText, int maxConnectionsPerPortSsl, Time time) { START if (networkMetrics == null || networkConfig == null) { END throw new IllegalArgumentException("Invalid inputs passed in, NetworkMetrics: " + networkMetrics + " " + "NetworkConfig: " + networkConfig); } this.networkMetrics = networkMetrics; this.networkConfig = networkConfig; this.sslFactory = sslFactory; this.maxConnectionsPerPortPlainText = maxConnectionsPerPortPlainText; this.maxConnectionsPerPortSsl = maxConnectionsPerPortSsl; this.time = time; } Perhaps we can skip this check? Since this a package private class?

Target:
RouterNetworkComponentsFactory(NetworkMetrics networkMetrics, NetworkConfig networkConfig, SSLFactory sslFactory, int maxConnectionsPerPortPlainText, int maxConnectionsPerPortSsl, Time time) { this.networkMetrics = networkMetrics; this.networkConfig = networkConfig; this.sslFactory = sslFactory; this.maxConnectionsPerPortPlainText = maxConnectionsPerPortPlainText; this.maxConnectionsPerPortSsl = maxConnectionsPerPortSsl; this.time = time; }
Source:
RouterNetworkComponents getRouterNetworkComponents() START throws Exception { END Selector selector = new Selector(networkMetrics, time, sslFactory); ConnectionManager connectionManager = new NonBlockingConnectionManager(selector, networkConfig, maxConnectionsPerPortPlainText, maxConnectionsPerPortSsl, time); return new RouterNetworkComponents(selector, connectionManager); } Where is the `Exception` here? I know the `SSLFactory` constructor throws `Exception` but I don't see anything other than `IOException` from this function.

Target:
RouterNetworkComponents getRouterNetworkComponents() throws IOException { Selector selector = new Selector(networkMetrics, time, sslFactory); ConnectionManager connectionManager = new NonBlockingConnectionManager(selector, networkConfig, maxConnectionsPerPortPlainText, maxConnectionsPerPortSsl, time); return new RouterNetworkComponents(selector, connectionManager); }
Source:
private void completeRequest(boolean closeNetworkChannel) { if (closeNetworkChannel && ctx.channel().isOpen()) { writeFuture.addListener(ChannelFutureListener.CLOSE); logger.trace("Requested closing of channel {}", ctx.channel()); } START if (request != null && request.isOpen()) { END closeRequest(); } responseComplete = true; } why duplicating the checks. Already closeRequest() does this check

Target:
private void completeRequest(boolean closeNetworkChannel) { if (closeNetworkChannel && ctx.channel().isOpen()) { writeFuture.addListener(ChannelFutureListener.CLOSE); logger.trace("Requested closing of channel {}", ctx.channel()); } closeRequest(); responseComplete = true; }
Source:
public static void serializeMetadataContentRecord(ByteBuffer outputBuffer, List<StoreKey> keys) { int keySize = keys.get(0).sizeInBytes(); for (StoreKey storeKey : keys) { if (storeKey.sizeInBytes() != keySize) { throw new IllegalArgumentException("Keys are not of same size"); } } outputBuffer.putShort(Metadata_Content_Version_V1); START outputBuffer.putInt(keys.size()); END for (StoreKey storeKey : keys) { outputBuffer.put(storeKey.toBytes()); } } Ah I see. You intend to put the number of keys itself. But why? Isn't that information redundant?

Target:
public static void serializeMetadataContentRecord(ByteBuffer outputBuffer, List<StoreKey> keys) { int keySize = keys.get(0).sizeInBytes(); outputBuffer.putShort(Metadata_Content_Version_V1); outputBuffer.putInt(keys.size()); for (StoreKey storeKey : keys) { if (storeKey.sizeInBytes() != keySize) { throw new IllegalArgumentException("Keys are not of same size"); } outputBuffer.put(storeKey.toBytes()); } }
Source:
private List<StoreKey> deserializeMetadataContent(ByteBuffer metadataContent, StoreKeyFactory storeKeyFactory) throws MessageFormatException, IOException { ByteBufferInputStream byteBufferInputStream = new ByteBufferInputStream(metadataContent); DataInputStream inputStream = new DataInputStream(byteBufferInputStream); short metdataContentVersion = inputStream.readShort(); START Assert.assertEquals("Metadata Content Version mismatch ", metdataContentVersion, END MessageFormatRecord.Metadata_Content_Version_V1); return MessageFormatRecord.Metadata_Content_Format_V1.deserializeMetadataContentRecord(inputStream, storeKeyFactory); } flip

Target:
private List<StoreKey> deserializeMetadataContent(ByteBuffer metadataContent, StoreKeyFactory storeKeyFactory) throws MessageFormatException, IOException { ByteBufferInputStream byteBufferInputStream = new ByteBufferInputStream(metadataContent); DataInputStream inputStream = new DataInputStream(byteBufferInputStream); short metdataContentVersion = inputStream.readShort(); Assert.assertEquals("Metadata Content Version mismatch ", MessageFormatRecord.Metadata_Content_Version_V1, metdataContentVersion); return MessageFormatRecord.Metadata_Content_Format_V1 .deserializeMetadataContentRecord(inputStream, storeKeyFactory); }
Source:
START private static AsyncRequestResponseHandler buildInstance(RestServerMetrics restServerMetrics) { END lock.lock(); try { if (instance == null) { AsyncRequestResponseHandlerFactory.restServerMetrics = restServerMetrics; instance = new AsyncRequestResponseHandler(restServerMetrics); } // check if same instance of RestServerMetrics - otherwise it is a problem. if (AsyncRequestResponseHandlerFactory.restServerMetrics != restServerMetrics) { throw new IllegalStateException("RestServerMetrics instance provided during construction of " + "AsyncRequestResponseHandler differs from the one currently received"); } } finally { lock.unlock(); } return instance; } Since it's a "build" instead of "get", you can return null instead

Target:
private static void buildInstance(RestServerMetrics restServerMetrics) { lock.lock(); try { if (instance == null) { AsyncRequestResponseHandlerFactory.restServerMetrics = restServerMetrics; instance = new AsyncRequestResponseHandler(restServerMetrics); } // check if same instance of RestServerMetrics - otherwise it is a problem. if (AsyncRequestResponseHandlerFactory.restServerMetrics != restServerMetrics) { throw new IllegalStateException("RestServerMetrics instance provided during construction of " + "AsyncRequestResponseHandler differs from the one currently received"); } } finally { lock.unlock(); } }
Source:
public void handleResponse(RestRequest restRequest, RestResponseChannel restResponseChannel, ReadableStreamChannel response, Exception exception) throws RestServiceException { START if (isRunning() && asyncResponseHandler != null && asyncResponseHandler.isRunning()) { END asyncResponseHandler.submitResponse(restRequest, restResponseChannel, response, exception); } else { restServerMetrics.requestResponseHandlerUnavailableError.inc(); throw new RestServiceException( "Requests cannot be handled because the AsyncRequestResponseHandler is not available", RestServiceErrorCode.ServiceUnavailable); } } This should just be `if (isRunning())`

Target:
public void handleResponse(RestRequest restRequest, RestResponseChannel restResponseChannel, ReadableStreamChannel response, Exception exception) throws RestServiceException { if (isRunning()) { asyncResponseHandler.submitResponse(restRequest, restResponseChannel, response, exception); } else { restServerMetrics.requestResponseHandlerUnavailableError.inc(); throw new RestServiceException( "Requests cannot be handled because the AsyncRequestResponseHandler is not available", RestServiceErrorCode.ServiceUnavailable); } }
Source:
protected int getWorkersAlive() { int count = 0; for (int i = 0; i < requestWorkerThreads.size(); i++) { START if (asyncRequestWorkers.get(i).isRunning() && requestWorkerThreads.get(i).isAlive()) { END count++; } } return count; } We should ensure that `isRunning` is in sync with `isAlive()` and never have to check for both. Ideally, the `isAlive()` check should be dropped.

Target:
protected int getWorkersAlive() { int count = 0; for (int i = 0; i < asyncRequestWorkers.size(); i++) { if (asyncRequestWorkers.get(i).isRunning()) { count++; } } return count; }
Source:
private OperationController getOperationController() { ArrayList<OperationController> ocList = ocListRef.get(); if (ocList.size() == 0) { return null; } else { START return ocList.get(ThreadLocalRandom.current().nextInt(ocList.size())); END } } how sure are we that ThreadLocalRandom will not generate the same numbers for a given seed? For example, if each local random was generating the same series, you will not have a balanced scheduling.

Target:
private OperationController getOperationController() { return ocList.get(ThreadLocalRandom.current().nextInt(ocList.size())); }
Source:
START void completeOperation(FutureResult futureResult, Callback callback, Object operationResult, Exception exception) { END try { futureResult.done(operationResult, exception); if (callback != null) { callback.onCompletion(operationResult, exception); } } catch (Exception e) { //@todo add metric. logger.error("Exception caught during future and callback completion", e); } finally { //@todo add metric. } } private

Target:
private void completeOperation(FutureResult futureResult, Callback callback, Object operationResult, Exception exception) { try { futureResult.done(operationResult, exception); if (callback != null) { callback.onCompletion(operationResult, exception); } } catch (Exception e) { //@todo add metric. logger.error("Exception caught during future and callback completion", e); } finally { //@todo add metric. } }
Source:
public String connect(InetSocketAddress address, int sendBufferSize, int receiveBufferSize, PortType portType) throws IOException { String hostPortString = address.getHostString() + address.getPort(); Integer count = connectionIdToCount.get(hostPortString); if (count != null) { count++; } else { count = 1; } connectionIdToCount.put(hostPortString, count); START String connectionId = hostPortString + index++; END connections.add(connectionId); return connectionId; } why can't u use count instead of index?

Target:
public String connect(InetSocketAddress address, int sendBufferSize, int receiveBufferSize, PortType portType) throws IOException { String hostPortString = address.getHostString() + address.getPort(); Integer count = connectionIdToCount.get(hostPortString); if (count != null) { count++; } else { count = 1; } connectionIdToCount.put(hostPortString, count); String connectionId = hostPortString + count; connections.add(connectionId); return connectionId; }
Source:
START public DataNodeRemoteReplicaInfos(String datacenter, RemoteReplicaInfo remoteReplicaInfo) { END this.datacenter = datacenter; this.dataNodeToReplicaLists = new HashMap<DataNodeId, List<RemoteReplicaInfo>>(); this.dataNodeToReplicaLists.put(remoteReplicaInfo.getReplicaId().getDataNodeId(), Arrays.asList(remoteReplicaInfo)); } This constructor is a little weird right? You have a `addRemoteReplica()` - why do you need to send one `remoteReplicaInfo` here?

Target:
public DataNodeRemoteReplicaInfos(String datacenter, RemoteReplicaInfo remoteReplicaInfo) { this.datacenter = datacenter; this.dataNodeToReplicaLists = new HashMap<DataNodeId, List<RemoteReplicaInfo>>(); this.dataNodeToReplicaLists.put(remoteReplicaInfo.getReplicaId().getDataNodeId(), new ArrayList<RemoteReplicaInfo>(Arrays.asList(remoteReplicaInfo))); }
Source:
public int read() { int data = -1; if (loadData()) { START data = currentChunk.get() & 0xFF; END bytesAvailable--; } return data; } ByteBuffer get() will return 1 byte, why "&0xFF" then?

Target:
public int read() throws IOException { int data = -1; if (loadData()) { data = currentChunk.get() & 0xFF; bytesAvailable--; } return data; }
Source:
START private void maybeCloseNetworkChannel(boolean forceClose) { END lastWriteFuture.addListener(ChannelFutureListener.CLOSE); logger.trace("Requested closing of channel {}", ctx.channel()); } you haven't used the forceClose within the method

Target:
private boolean maybeCloseNetworkChannel(boolean forceClose) { lastWriteFuture.addListener(ChannelFutureListener.CLOSE); logger.trace("Requested closing of channel {}", ctx.channel()); return true; }
Source:
START public void run() { END while (isRunning()) { try { processResponses(); processRequests(); } catch (Exception e) { logger.error("Swallowing unexpected exception during processing of responses and requests", e); restServerMetrics.dequeuedRequestHandlerUnexpectedExceptionError.inc(); } } discardRequestsResponses(); logger.trace("AsyncHandlerWorker stopped"); shutdownLatch.countDown(); } how do you ensure that the caller dont start the thread w/o setting the blob storage service?

Target:
public void run() { while (isRunning()) { try { processRequests(); processResponses(); } catch (Exception e) { logger.error("Swallowing unexpected exception during processing of responses and requests", e); restServerMetrics.dequeuedRequestHandlerUnexpectedExceptionError.inc(); } } discardRequestsResponses(); logger.trace("AsyncHandlerWorker stopped"); shutdownLatch.countDown(); }
Source:
private void closeResponseChannel() { if (isOpen()) { START try { END channelWriteLock.lock(); responseChannelOpen.set(false); logger.trace("NettyResponseChannel for network channel closed", ctx.channel()); } finally { channelWriteLock.unlock(); } } } what is this `try-finally` for?

Target:
private void closeResponseChannel() { if (isOpen()) { channelWriteLock.lock(); try { responseChannelOpen.set(false); logger.trace("NettyResponseChannel for network channel closed", ctx.channel()); } finally { channelWriteLock.unlock(); } } }
Source:
public long writeTo(WritableByteChannel channel) throws IOException { START long written = 0; END if (!isSendComplete()) { written = channel.write(buffer); } return written; } ``` java return isSendComplete() ? 0 : channel.write(buffer); ``` if you want to make it more elegant.

Target:
public long writeTo(WritableByteChannel channel) throws IOException { return isSendComplete() ? 0 : channel.write(buffer); }
Source:
public GetBlobOperation(String datacenterName, ConnectionPool connectionPool, ExecutorService requesterPool, OperationContext oc, BlobId blobId, long operationTimeoutMs, ClusterMap clusterMap) throws CoordinatorException { super(datacenterName, connectionPool, requesterPool, oc, blobId, operationTimeoutMs, clusterMap, MessageFormatFlags.Blob); logger.trace( START "GetBlob: Datacenter name " + datacenterName + " Connection pool " + connectionPool + ", requester pool " + ( END requesterPool != null) + ", Operation context " + oc + ", blobId " + blobId + ", timeout " + operationTimeoutMs + ", clustermap " + (clusterMap != null)); this.blobOutput = null; } If you want to check if `connectionPool` is null or not, you should probably do what you did for `requesterPool`

Target:
public GetBlobOperation(String datacenterName, ConnectionPool connectionPool, ExecutorService requesterPool, OperationContext oc, BlobId blobId, long operationTimeoutMs, ClusterMap clusterMap) throws CoordinatorException { super(datacenterName, connectionPool, requesterPool, oc, blobId, operationTimeoutMs, clusterMap, MessageFormatFlags.Blob); logger.trace("GetBlob: Datacenter name " + datacenterName + " Connection pool " + (connectionPool != null) + ", requester pool " + (requesterPool != null) + ", Operation context " + oc + ", blobId " + blobId + ", timeout " + operationTimeoutMs + ", clustermap " + (clusterMap != null)); this.blobOutput = null; }
Source:
void prepare() throws IOException { START } END empty function? also no qualifier (public,private)?

Target:
public void prepare() throws IOException { }
Source:
START boolean ready() { END return true; } no qualifier?

Target:
public boolean ready() { return true; }
Source:
public int available() { return readableStreamChannel.getSize() - totalBytesRead.get() < Integer.MAX_VALUE ? START (int) readableStreamChannel.getSize() - totalBytesRead.get() : Integer.MAX_VALUE; END } And you have to be careful when casting long to int - basically you have to make sure you never cast a long > Integer.MAX_VALUE to int. Here you are casting too early, you have to cast after finding the difference when it is guaranteed to be less than Integer.MAX_VALUE. This should be `return readableStreamChannel.getSize() - totalBytesRead.get() < Integer.MAX_VALUE ? (int) (readableStreamChannel.getSize() - totalBytesRead.get()) : Integer.MAX_VALUE;`

Target:
public int available() { return readableStreamChannel.getSize() - totalBytesRead < Integer.MAX_VALUE ? (int) (readableStreamChannel.getSize() - totalBytesRead) : Integer.MAX_VALUE; }
Source:
public int read() throws IOException { ByteBuffer buffer = singleByteBufferChannel.getBuffer(); buffer.clear(); int data = -1; if (read(singleByteBufferChannel) != -1) { buffer.flip(); START data = buffer.get() & 0xFF; END totalBytesRead.incrementAndGet(); } return data; } byte to int is always safe, so why can't you simply do `data = buffer.get()`?

Target:
public int read() throws IOException { ByteBuffer buffer = singleByteBufferChannel.getBuffer(); buffer.clear(); int data = -1; if (read(singleByteBufferChannel) != -1) { buffer.flip(); data = buffer.get() & 0xFF; totalBytesRead++; } return data; }
Source:
HardDeleteThread() { START this.throttler = END new Throttler(config.storeHardDeleteBytesPerSec, throttlerCheckIntervalMs, true, SystemTime.getInstance()); } not related to this patch. Why hardDeleterSleepTimeWhenCaughtUpMs is not configurable and hardcoded?

Target:
HardDeleteThread() { this.throttler = new Throttler(config.storeHardDeleteBytesPerSec, throttlerCheckIntervalMs, true, time); }
Source:
private Transmissions transmissions(SelectionKey key) { START if (key == null) { END throw new IllegalStateException("Attempt to get attachment from a null key"); } return (Transmissions) key.attachment(); } do we need this check? You can argue such statements in all other methods.

Target:
private Transmissions transmissions(SelectionKey key) { return (Transmissions) key.attachment(); }
Source:
START @Override public String toString () { END return "DataNode[" + getHostname() + ":" + getPort() + "]"; } what formatting is this? @override should be above the method

Target:
public String toString() { return "DataNode[" + getHostname() + ":" + getPort() + "]"; }
Source:
@Override public boolean equals (Object o){ if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DataNode dataNode = (DataNode) o; if (port != dataNode.port) { return false; } START return hostname.equals(dataNode.hostname); END } do you need to check the other fields? two objects cannot be equal otherwise right?

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DataNode dataNode = (DataNode) o; if (port != dataNode.port) { return false; } return hostname.equals(dataNode.hostname); }
Source:
@Override public int compareTo (DataNodeId o){ if (o == null) { throw new NullPointerException("input argument null"); START } END DataNode other = (DataNode) o; int compare = (port < other.port) ? -1 : ((port == other.port) ? 0 : 1); if (compare == 0) { compare = hostname.compareTo(other.hostname); } return compare; } what does compare and hascode mean for datanode if they have different ssl ports?

Target:
public int compareTo(DataNodeId o) { if (o == null) { throw new NullPointerException("input argument null"); } DataNode other = (DataNode) o; int compare = (port < other.port) ? -1 : ((port == other.port) ? 0 : 1); if (compare == 0) { compare = hostname.compareTo(other.hostname); } return compare; }
Source:
protected OperationRequest makeOperationRequest(ReplicaId replicaId) { DeleteRequest deleteRequest = new DeleteRequest(context.getCorrelationId(), context.getClientId(), blobId); if (sslEnabledColos.contains(replicaId.getDataNodeId().getDatacenterName())) { START return new DeleteOperationRequest(connectionPool, responseQueue, context, blobId, replicaId, deleteRequest, true); END } else { return new DeleteOperationRequest(connectionPool, responseQueue, context, blobId, replicaId, deleteRequest, false); } } this check is not required if the colo info is in context.

Target:
protected OperationRequest makeOperationRequest(ReplicaId replicaId) { DeleteRequest deleteRequest = new DeleteRequest(context.getCorrelationId(), context.getClientId(), blobId); return new DeleteOperationRequest(connectionPool, responseQueue, context, blobId, replicaId, deleteRequest); }
Source:
public static void startAdminBlobStorageService() throws InstantiationException, IOException { START clusterMap = new MockClusterMap(false); END adminBlobStorageService = getAdminBlobStorageService(clusterMap); adminBlobStorageService.start(); } can we just keep the default constructor that sets this to false?

Target:
public static void startAdminBlobStorageService() throws InstantiationException, IOException { clusterMap = new MockClusterMap(); adminBlobStorageService = getAdminBlobStorageService(clusterMap); adminBlobStorageService.start(); }
Source:
public static JSONArray getJsonArrayDuplicateDataNodes(int dataNodeCount, String hostname, int basePort, HardwareState hardwareState, JSONArray disks) throws JSONException { JSONArray jsonArray = new JSONArray(); for (int i = 0; i < dataNodeCount; ++i) { START jsonArray.put(getJsonDataNode(hostname, basePort + i, hardwareState, disks)); END } return jsonArray; } why change it to basePort + i here?

Target:
public static JSONArray getJsonArrayDuplicateDataNodes(int dataNodeCount, String hostname, int basePort, HardwareState hardwareState, JSONArray disks) throws JSONException { JSONArray jsonArray = new JSONArray(); for (int i = 0; i < dataNodeCount; ++i) { jsonArray.put(getJsonDataNode(hostname, basePort, hardwareState, disks)); } return jsonArray; }
Source:
public String toString() { START return "Request metadata: " + (restRequestMetadata != null ? restRequestMetadata.toString() : "null") + END " Request content: " + (restRequestContent != null ? restRequestContent.toString() : "null") + " Response handler: " + (restResponseHandler != null ? restResponseHandler.toString() : "null"); } Actually using StringBuilder is better and faster here. The compiler will optimize string concatenation to use StringBuffer, not StringBuilder. StringBuilder is asynchronous and runs faster.

Target:
public String toString() { return "Request metadata: " + restRequestMetadata + " Request content: " + restRequestContent + " Response handler: " + restResponseHandler; }
Source:
public void onComplete(Exception e) { logger.trace("Firing onComplete() for listeners"); synchronized (listeners) { exception = e; START if (operationComplete.compareAndSet(false, true)) { END for (RestRequestInfoEventListener listener : listeners) { try { listener.onHandlingComplete(this, e); } catch (Exception ee) { logger.error("Swallowing onComplete listener exception", ee); } } } else { logger.error("onComplete for RestRequestInfo has already been fired. Ignoring current invocation"); } } } Yes, I meant 'if'.

Target:
public void onComplete(Exception e) { if (operationComplete.compareAndSet(false, true)) { logger.trace("Firing onComplete() for listeners"); exception = e; synchronized (listeners) { for (RestRequestInfoEventListener listener : listeners) { try { listener.onHandlingComplete(this, e); } catch (Exception ee) { logger.error("Swallowing onComplete listener exception", ee); } } } } else { logger.error("onComplete for RestRequestInfo has already been fired. Ignoring current invocation"); } }
Source:
public AdminMetrics(MetricRegistry metricRegistry) { //errors unknownActionErrorCount = START metricRegistry.counter(MetricRegistry.name(AdminBlobStorageService.class, "unknownActionErrorCount")); END } is this the only metric you need?

Target:
public AdminMetrics(MetricRegistry metricRegistry) { }
Source:
public void channelInactive(ChannelHandlerContext ctx) { // TODO: once we support keepalive, we need to do this at the end of a request too. try { if (requestHandler != null) { START requestHandler.onRequestComplete(request); END } if (responseHandler != null) { responseHandler.onRequestComplete(request); } } catch (Exception e) { logger.error("Unable to perform cleanup tasks. Swallowing exception..", e); nettyMetrics.channelInactiveTasksFailureCount.inc(); } } we would need to move this logic elsewhere and not rely on channelInactive for keep alive. Why not just do that now?

Target:
public void channelInactive(ChannelHandlerContext ctx) { onRequestComplete(null, true); }
Source:
public void run() { try { while (running) { if (!hardDelete()) { try { START Thread.sleep(hardDeleterSleepTimeWhenCaughtUpMs); END } catch (InterruptedException e) { logger.info("Caught interrupted exception"); } } } } finally { shutdownLatch.countDown(); } } I meant we need to know if the thread is running independent of the progress. you could be caught up but the thread can die and we will not know.

Target:
public void run() { try { while (running) { if (!hardDelete()) { try { Thread.sleep(hardDeleterSleepTimeWhenCaughtUpMs); } catch (InterruptedException e) { logger.info("Caught interrupted exception"); } } } } finally { close(); } }
Source:
public long appendFrom(ReadableByteChannel channel, long size) throws IOException { START int tempIndex = index; END index++; int sizeRead = 0; while(sizeRead < size) { sizeRead += channel.read(buflist.get(tempIndex)); tempIndex = index++; } if(sizeRead != size) { throw new IOException("Not able to read entire size. Expected " + size+" Actual " + sizeRead); } return sizeRead; } Do you really need a separate tempIndex variable?

Target:
public void appendFrom(ReadableByteChannel channel, long size) throws IOException { int sizeRead = 0; while(sizeRead < size) { sizeRead += channel.read(buflist.get(index++)); } }
Source:
public void onNodeTimeout() { String dataNodeStr; try { START dataNodeStr = toJSONObject().toString(); END } catch (JSONException e) { dataNodeStr = null; } logger.info("Node [" + dataNodeStr + "] timed out, informing resource state"); if (dataNodeStatePolicy.onError()) { logger.info("Node [" + dataNodeStr + "] was determined to be down"); } } It will be good to avoid converting the node to a JSON and then to a String which is expensive. We should just define a toString if it is not already defined and log(this).

Target:
public void onNodeTimeout() { dataNodeStatePolicy.onError(); }
Source:
private PartitionId getPartitionForPut() throws CoordinatorException { START List<? extends PartitionId> partitions = clusterMap.getWritablePartitionIds(); END if (partitions.isEmpty()) { throw new CoordinatorException("No writable partitions available.", CoordinatorError.AmbryUnavailable); } return partitions.get((int) getRandomLong(randomForPartitionSelection, partitions.size())); } List<PartitionId>?

Target:
private PartitionId getPartitionForPut() throws CoordinatorException { List<PartitionId> partitions = clusterMap.getWritablePartitionIds(); if (partitions.isEmpty()) { throw new CoordinatorException("No writable partitions available.", CoordinatorError.AmbryUnavailable); } return partitions.get((int) getRandomLong(randomForPartitionSelection, partitions.size())); }
Source:
public RemoteReplicaInfo(ReplicaId replicaId, Store localStore, FindToken token, long tokenPersistIntervalInMs) { this.replicaId = replicaId; this.currentToken = token; if (tokenToPersist == null) { this.tokenToPersist = token; timeTokenSetInMs = SystemTime.getInstance().milliseconds(); } this.tokenPersistIntervalInMs = tokenPersistIntervalInMs; START this.totalBytesReadFromLocalStore = new Long(0); END this.localStore = localStore; } "= 0" is sufficient to initialize 'long totalBytesReadFromLocalStore;'

Target:
public RemoteReplicaInfo(ReplicaId replicaId, Store localStore, FindToken token, long tokenPersistIntervalInMs) { this.replicaId = replicaId; this.currentToken = token; if (tokenToPersist == null) { this.tokenToPersist = token; timeTokenSetInMs = SystemTime.getInstance().milliseconds(); } this.tokenPersistIntervalInMs = tokenPersistIntervalInMs; this.totalBytesReadFromLocalStore = 0; this.localStore = localStore; }
Source:
public MockStore(List<MessageInfo> messageInfo, List<ByteBuffer> buffers) { if (messageInfo.size() != buffers.size()) { throw new IllegalArgumentException("message info size and buffer size does not match"); } messageInfoList = messageInfo; log = new DummyLog(buffers); START bytesWrittenSoFar = new Long(0); END } "= 0" seems sufficient?

Target:
public MockStore(List<MessageInfo> messageInfo, List<ByteBuffer> buffers) { if (messageInfo.size() != buffers.size()) { throw new IllegalArgumentException("message info size and buffer size does not match"); } messageInfoList = messageInfo; log = new DummyLog(buffers); }
Source:
START public long getAllocatedRawCapacityInBytes() { END long allocatedRawCapacityInBytes = 0; for (Partition partition : partitionMap.values()) { allocatedRawCapacityInBytes += partition.getAllocatedRawCapacityInBytes(); } return allocatedRawCapacityInBytes; } It might be better off to calculate all this on initialization of the clustermap. these are never going to change and recalculating them every minute is not useful.

Target:
public long getAllocatedRawCapacityInBytes() { return allocatedRawCapacityInBytes; }
Source:
public BlobProperties getBlobProperties(String blobIdString) throws CoordinatorException { OperationContext oc = getOperationContext(); BlobId blobId = getBlobIdFromString(blobIdString); GetBlobPropertiesOperation gbpo = new GetBlobPropertiesOperation(datacenterName, connectionPool, requesterPool, oc, blobId, operationTimeoutMs, clusterMap); START gbpo.execute(); END return gbpo.getBlobProperties(); } this is lot more clear

Target:
public BlobProperties getBlobProperties(String blobIdString) throws CoordinatorException { BlobId blobId = getBlobIdFromString(blobIdString); GetBlobPropertiesOperation gbpo = new GetBlobPropertiesOperation(datacenterName, connectionPool, requesterPool, getOperationContext(), blobId, operationTimeoutMs, clusterMap); gbpo.execute(); return gbpo.getBlobProperties(); }
Source:
public long sizeInBytes() { // header + blobId START return super.sizeInBytes() + Blob_Id_Size_In_Bytes + blobId.sizeInBytes(); END } This is a bug. blobId.sizeInBytes already returns the serialized form size.

Target:
public long sizeInBytes() { // header + blobId return super.sizeInBytes() + blobId.sizeInBytes(); }
Source:
public StoreMetrics(String storeName, ReadableMetricsRegistry registry) { super(registry); writes = newCounter(storeName + "-Writes"); reads = newCounter(storeName + "-Reads"); deletes = newCounter(storeName + "-Deletes"); START overflowWriteError = new Counter(storeName + "-OverflowWriteError"); END } I cannot tell if this is correct or not. Why not "newCounter" instead of "new Counter". Also, missing cancelTTLs = newCounter(storeName + "-Deletes"); On last project, we ended up with inconsistent metrics names ("a-b" mixed with "a_b"). We can either watch this via code reviews or try something like Metric.NameSeparator="-". I think code reviews are fine but we need to be vigilant because as soon as someone has a dashboard or alert set to metric name, its permanent.

Target:
public StoreMetrics(String storeName, ReadableMetricsRegistry registry) { super(registry); writes = newCounter(storeName + "-Writes"); reads = newCounter(storeName + "-Reads"); deletes = newCounter(storeName + "-Deletes"); overflowWriteError = newCounter(storeName + "-OverflowWriteError"); }
Source:
private void validateParameter(String name, String value) { Class<? extends IParameterValidator> validators[] = wrappedParameter.validateWith(); START if (validators != null && validators.length>0) { END for(final Class<? extends IParameterValidator> validator: validators) { validateParameter(this, validator, name, value); } } } Spaces: `length > 0`.

Target:
private void validateParameter(String name, String value) { final Class<? extends IParameterValidator> validators[] = wrappedParameter.validateWith(); if (validators != null && validators.length > 0) { for(final Class<? extends IParameterValidator> validator: validators) { validateParameter(this, validator, name, value); } } }
Source:
public static <T> T readBy(Session session, Class<T> clazz, String id) { LOG.trace("GenericDBUtil.readBy"); T entity = null; try { entity = session.get(clazz, id); LOG.trace("GenericDBUtil.readBy - entity = session.get()"); } catch (HibernateException | NullPointerException e) { START LOG.error("Exception during read caused by : {}", e.getMessage(), e); END throw e; } finally { closeSession(session); } return entity; } Either we log or rethrow exception but not both. See this https://sonarcloud.io/organizations/default/rules?open=squid%3AS2139&rule_key=squid%3AS2139

Target:
public static <T> T readBy(Session session, Class<T> clazz, String id) { LOG.trace("GenericDBUtil.readBy"); T entity = null; try { entity = session.get(clazz, id); LOG.trace("GenericDBUtil.readBy - entity = session.get()"); } catch (HibernateException | NullPointerException e) { throw e; } finally { closeSession(session); } return entity; }
Source:
public int pingEndpoint() { String sName = selectedEndpoint.getName(); START int pingResponse = 0; END for (ConnectionEndpoint connEndpoint : endpoints) { String eName = connEndpoint.getName(); if (sName.equals(eName)) { return exchangeService.pingService(connEndpoint); } } return pingResponse; } we never set this anywhere in the code. Either remove it and hardcode 0 as a return value or set pingResponse to 0 and break from the loop on line 348.

Target:
public int pingEndpoint() { for (ConnectionEndpoint connEndpoint : endpoints) { if (connEndpoint.getName().equals(selectedEndpoint.getName())) { return exchangeService.pingService(connEndpoint); } } return 0; }
Source:
public LoadTestDataSimpleResponseMessageType deleteAddress(DeleteAddressRequestMessageType request) { Address record = new Address(request.getAddress(), loadTestDataService.getPatientBy(request.getAddress().getPatientId())); START if (null == record) { END return buildSimpleResponse(Boolean.FALSE, ACT_FAIL); } loadTestDataService.deleteAddress(record); return buildSimpleResponse(Boolean.TRUE, ACT_SUCCESSFUL); } What are all these null checks for? These can never be null - You're creating the object in the lines directly above?

Target:
public LoadTestDataSimpleResponseMessageType deleteAddress(DeleteAddressRequestMessageType request) { Address record = new Address(request.getAddress(), loadTestDataService.getPatientBy(request.getAddress().getPatientId())); boolean result = loadTestDataService.deleteAddress(record); if (result) { return buildSimpleResponse(Boolean.TRUE, ACT_SUCCESSFUL); } return buildSimpleResponse(Boolean.FALSE, ACT_FAIL); }
Source:
public boolean checkDistinguishedName(String userName) { Name name = null; try { name = new LdapName(userName); } catch (InvalidNameException ex) { START LOG.error("Invalid distinguished name {}", userName); END LOG.debug("Invalid distinguished name {}", userName, ex); } return name != null; } change debug to warn or error. No need to include both inside here

Target:
public boolean checkDistinguishedName(String userName) { Name name = null; try { name = new LdapName(userName); } catch (InvalidNameException ex) { LOG.error("Invalid distinguished name {}", userName, ex); } return name != null; }
Source:
START public static String getExchangeAlias(String exchangeName) { END String alias = null; if (StringUtils.isNotBlank(exchangeName)) { List<ExchangeType> exchanges = ExchangeManager.getInstance().getAllExchanges(); if (CollectionUtils.isNotEmpty(exchanges)) { for (ExchangeType ex : exchanges) { if (exchangeName.equalsIgnoreCase(ex.getName())) { alias = ex.getCertificateAlias(); break; } } } } return alias; } exchangeManager.getGatewayAlias however the internalExchangeManager.getGatewayAlias will return an null and will default:CIENT_KEY_ALIAS

Target:
public static String getExchangeAlias(String exchangeName) { String alias = null; List<ExchangeType> exchanges = ExchangeManager.getInstance().getAllExchanges(); if (StringUtils.isNotBlank(exchangeName) && CollectionUtils.isNotEmpty(exchanges)) { for (ExchangeType ex : exchanges) { if (exchangeName.equalsIgnoreCase(ex.getName())) { alias = ex.getCertificateAlias(); break; } } } return alias; }
Source:
private void deleteFromMessageMonitoringDB(final MonitoredMessage trackMessage) { try { MessageMonitoringDAOImpl.getInstance().deleteCompletedMessages(trackMessage); } catch (final MessageMonitoringDAOException ex) { LOG.debug("Error While deleting Message from MessageMonitoring Table: {}", ex); START return; END } LOG.debug("Completed message deleted."); } can we remove return?

Target:
private void deleteFromMessageMonitoringDB(final MonitoredMessage trackMessage) { try { MessageMonitoringDAOImpl.getInstance().deleteCompletedMessages(trackMessage); } catch (final MessageMonitoringDAOException ex) { LOG.debug("Error While deleting Message from MessageMonitoring Table: {}", ex); } LOG.debug("Completed message deleted."); }
Source:
public void viewEvent() { LOG.debug("view-event: begin"); if (null == selectedEvent) { LOG.info("no event selected for view."); START HelperUtil.addMessageError(null, "You need to selected an event."); END return; } selectedEvent = service.getLogEvent(selectedEvent.getId()); if (StringUtils.isNotBlank(selectedEvent.getDescription())) { selectedEventJson = new JSONObject(selectedEvent.getDescription()); } HelperUtil.execPFShowDialog("wgvDlgViewEventErrorlog"); } Fix the error message something like, Select an event to view. Also what is labeled as event on screen, Service or exception? Replace event with appropriate label

Target:
public void viewEvent() { if (null == selectedEvent) { return; } selectedEvent = service.getLogEvent(selectedEvent.getId()); if (StringUtils.isNotBlank(selectedEvent.getDescription())) { selectedEventJson = new JSONObject(selectedEvent.getDescription()); } HelperUtil.execPFShowDialog("wgvDlgViewEventErrorlog"); }
Source:
public ErrorLogBean() { START try { END dropdowns = service.getDropdowns(); } catch (Exception ex) { LOG.error("Error calling service.dropdowns: {}", ex.getMessage(), ex); HelperUtil.addMessageError(null, SERVICE_ERROR); } } Don't like catching exception in the constructor. use an init method with @PostConstruct annotation.

Target:
public ErrorLogBean() { dropdowns = service.getDropdowns(); }
Source:
private AdhocQueryResponse respondingGatewayCrossGatewayQuery(AdhocQueryRequest request, AssertionType assertion, NhinTargetCommunitiesType targets) { AdhocQueryResponse response = null; if (targets == null) { targets = new ObjectFactory().createNhinTargetCommunitiesType(); } if (StringUtils.isBlank(targets.getUseSpecVersion())) { targets.setUseSpecVersion("3.0"); } response = outboundDocQuery.respondingGatewayCrossGatewayQuery(request, assertion, targets); START return response; END } can we remove: declare-response, useless-assign and just return the object from the method-call?

Target:
private AdhocQueryResponse respondingGatewayCrossGatewayQuery(AdhocQueryRequest request, AssertionType assertion, NhinTargetCommunitiesType targets) { if (targets == null) { targets = new ObjectFactory().createNhinTargetCommunitiesType(); } if (StringUtils.isBlank(targets.getUseSpecVersion())) { targets.setUseSpecVersion("3.0"); } return outboundDocQuery.respondingGatewayCrossGatewayQuery(request, assertion, targets); }
Source:
START public void errorResponseHasRegistryObjectList() throws Exception { END AdapterDocQueryOrchImpl impl = new AdapterDocQueryOrchImpl(); try { impl.respondingGatewayCrossGatewayQuery(null, null); Assert.fail(); } catch (ErrorEventException e) { AdhocQueryResponse response = (AdhocQueryResponse) e.getReturnOverride(); assertNotNull(response.getRegistryObjectList()); assertEquals(0, response.getRegistryObjectList().getIdentifiable().size()); } } Optional: no need to throws Exception since you already catch the runtime Exception here

Target:
public void errorResponseHasRegistryObjectList() { AdapterDocQueryOrchImpl impl = new AdapterDocQueryOrchImpl(); try { impl.respondingGatewayCrossGatewayQuery(null, null); Assert.fail(); } catch (ErrorEventException e) { AdhocQueryResponse response = (AdhocQueryResponse) e.getReturnOverride(); assertNotNull(response.getRegistryObjectList()); assertEquals(0, response.getRegistryObjectList().getIdentifiable().size()); } }