auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof FreeOptions)) { return false; } FreeOptions that = (FreeOptions) o; START return Objects.equal(mForced, that.mForced) END && Objects.equal(mCommonOptions, that.mCommonOptions) && Objects.equal(mRecursive, that.mRecursive); } can you sort ?

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof FreeOptions)) { return false; } FreeOptions that = (FreeOptions) o; return Objects.equal(mCommonOptions, that.mCommonOptions) && Objects.equal(mForced, that.mForced) && Objects.equal(mRecursive, that.mRecursive); }
Source:
public int hashCode() { START return Objects.hashCode(mLoadMetadataType, mCommonOptions); END } ditto and others.

Target:
public int hashCode() { return Objects.hashCode(mCommonOptions, mLoadMetadataType); }
Source:
public int hashCode() { return Objects START .hashCode(mAllowExists, mMode, mRecursive, mTtl, mTtlAction, mWriteType, mCommonOptions); END } sort

Target:
public int hashCode() { return Objects .hashCode(mAllowExists, mCommonOptions, mMode, mRecursive, mTtl, mTtlAction, mWriteType); }
Source:
public static void printHelp(String message) { System.err.println(message); HelpFormatter formatter = new HelpFormatter(); START formatter.printHelp(USAGE, null, OPTIONS, null, true); END } (nit) You can probably use the shorter version `formatter.printHelp(USAGE, OPTIONS, true);`

Target:
public static void printHelp(String message) { System.err.println(message); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(USAGE, OPTIONS, true); }
Source:
protected void updateStreams() throws IOException { long blockId = mPositionState.getBlockId(); if (blockId == mCurrentBlockId && mCurrentBlockInStream != null && mCurrentBlockInStream.remaining() != 0) { return; } checkCacheStreamInSync(); updateBlockInStream(blockId); if (PASSIVE_CACHE_ENABLED) { updateCacheStream(blockId); } mCurrentBlockId = blockId; mCurrentBlockStartPos = mPositionState.getBlockStartPos(); START mCurrentBlockEndPos = mPositionState.getNextBlockStartPos(); END } Can we use the state in `mPositionState` instead of using the other member variables?

Target:
private void updateStreams() throws IOException { long blockId = mPositionState.getBlockId(); if (mCurrentBlockInStream != null && mCurrentBlockInStream.getId() == blockId && mCurrentBlockInStream.remaining() != 0) { return; } checkCacheStreamInSync(); updateBlockInStream(blockId); if (PASSIVE_CACHE_ENABLED) { updateCacheStream(blockId); } }
Source:
public void operationComplete(ChannelFuture future) { if (!future.isSuccess()) { future.channel().close(); } try (LockResource lr = new LockResource(mLock)) { if (future.cause() != null) { updateException(future.cause()); mDoneOrFailed.signal(); mBufferNotFullOrFailed.signal(); mBufferEmptyOrFailed.signal(); START } END } } Do we want to signal even if there is no cause but the future returns failure?

Target:
public void operationComplete(ChannelFuture future) { if (!future.isSuccess()) { future.channel().close(); try (LockResource lr = new LockResource(mLock)) { updateException(future.cause()); mDoneOrFailed.signal(); mBufferNotFullOrFailed.signal(); mBufferEmptyOrFailed.signal(); } } }
Source:
public void zookeeper() throws Exception { mCluster = MultiProcessCluster.newBuilder() .setClusterName("zookeeper") .addProperty(PropertyKey.ZOOKEEPER_ENABLED, "true") .setNumMasters(3) .setNumWorkers(2) .build(); START boolean success = false; END try { mCluster.start(); FileSystem fs = mCluster.getFileSystemClient(); createAndOpenFile(fs); mSuccess = true; } finally { cleanup(); } } is this var ever used any where?

Target:
public void zookeeper() throws Exception { mCluster = MultiProcessCluster.newBuilder() .setClusterName("zookeeper") .addProperty(PropertyKey.ZOOKEEPER_ENABLED, "true") .setNumMasters(3) .setNumWorkers(2) .build(); try { mCluster.start(); FileSystem fs = mCluster.getFileSystemClient(); createAndOpenFile(fs); mSuccess = true; } finally { cleanup(); } }
Source:
public JvmPauseMonitor reset() { mJvmMonitorThread = null; START mThreadStarted = true; END return this; } the thread is not started, since it's set to null above,right?

Target:
public void reset() { mJvmMonitorThread = null; }
Source:
START private boolean shouldCachePartiallyReadBlock() throws IOException { END return mShouldCache && mCachePartiallyReadBlock; } Does this throw `IOException`?

Target:
private boolean shouldCachePartiallyReadBlock() { return mShouldCache && mCachePartiallyReadBlock; }
Source:
public void getNonExistingBucket() throws Exception { final String bucketName = "non-existing-bucket"; try { // Delete a non-existing bucket should fail. new TestCase(mHostname, mPort, S3_SERVICE_PREFIX + AlluxioURI.SEPARATOR + bucketName, NO_PARAMS, HttpMethod.GET, null, TestCaseOptions.defaults().setContentType(TestCaseOptions.XML_CONTENT_TYPE)).run(); START Assert.fail("get a non-existing bucket should fail"); END } catch (AssertionError e) { // expected } } this will throw AssertionError too, then if the test fails, there is no way to detect the error

Target:
public void getNonExistingBucket() throws Exception { final String bucketName = "non-existing-bucket"; try { // Delete a non-existing bucket should fail. new TestCase(mHostname, mPort, S3_SERVICE_PREFIX + AlluxioURI.SEPARATOR + bucketName, NO_PARAMS, HttpMethod.GET, null, TestCaseOptions.defaults().setContentType(TestCaseOptions.XML_CONTENT_TYPE)).run(); } catch (AssertionError e) { // expected return; } Assert.fail("get a non-existing bucket should fail"); }
Source:
private UserLimitValidationTask(String name, String command, Integer lowerBound, Integer upperBound) { mName = name; START mCommand = new String[] {"bash", "-c", command}; END mLowerBound = lowerBound; mUpperBound = upperBound; } `mCommand` can be a string as input. Add `bash -c` to the place when you call it.

Target:
private UserLimitValidationTask(String name, String command, Integer lowerBound, Integer upperBound) { mName = name; mCommand = command; mLowerBound = lowerBound; mUpperBound = upperBound; }
Source:
public static void stopProcessOnShutdown(final Process process) { Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { try { process.stop(); } catch (Exception e) { START LOG.error("Failed to shutdown process."); END System.exit(0); } } }); } include the error message

Target:
public static void stopProcessOnShutdown(final Process process) { Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { try { process.stop(); } catch (Exception e) { LOG.error("Failed to shutdown process.", e); System.exit(0); } } }); }
Source:
public void stop() { START synchronized (this) { END if (!mStopped) { mLoggingWorkerThread.interrupt(); try { mLoggingWorkerThread.join(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { mStopped = true; mLoggingWorkerThread = null; LOG.info("AsyncUserAccessAuditLogWriter thread stopped."); } } } } This just synchronizes the entire method? If so, you can just define the method as: `public synchronized void stop()`

Target:
public synchronized void stop() { if (!mStopped) { mLoggingWorkerThread.interrupt(); try { mLoggingWorkerThread.join(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { mStopped = true; mLoggingWorkerThread = null; LOG.info("AsyncUserAccessAuditLogWriter thread stopped."); } } }
Source:
START public synchronized Inode getLastExistingInode() { END Inode<?> inode = mInodes.get(mInodes.size() - 1); return inode; } NIT: extra space

Target:
public synchronized Inode getLastExistingInode() { return mInodes.get(mInodes.size() - 1); }
Source:
public static boolean isValid(String input) { // Check if input matches any default keys if (DEFAULT_KEYS_MAP.containsKey(input)) { return true; } // Check if the input matches any alias if (DEFAULT_ALIAS_MAP.containsKey(input)) { return true; START } END // Check if input matches any parameterized keys for (Template template : Template.values()) { Matcher matcher = template.mPattern.matcher(input); if (matcher.matches()) { return true; } } return false; } Put these two conditions together?

Target:
public static boolean isValid(String input) { // Check if input matches any default keys or aliases if (DEFAULT_KEYS_MAP.containsKey(input) || DEFAULT_ALIAS_MAP.containsKey(input)) { return true; } // Check if input matches any parameterized keys for (Template template : Template.values()) { Matcher matcher = template.mPattern.matcher(input); if (matcher.matches()) { return true; } } return false; }
Source:
private void init() { START mMasterInquireClient = MasterInquireClient.Factory.create(); END mFileSystemMasterClientPool = new FileSystemMasterClientPool(mParentSubject, mMasterInquireClient); mBlockMasterClientPool = new BlockMasterClientPool(mParentSubject, mMasterInquireClient); } Do we need to guard this?

Target:
private synchronized void init() { mMasterInquireClient = MasterInquireClient.Factory.create(); mFileSystemMasterClientPool = new FileSystemMasterClientPool(mParentSubject, mMasterInquireClient); mBlockMasterClientPool = new BlockMasterClientPool(mParentSubject, mMasterInquireClient); }
Source:
public String getDescription() { START END return mDescription != null ? mDescription : "N/A"; } NIT: remove the empty line

Target:
public String getDescription() { return mDescription; }
Source:
public void tailFileWithUserSpecifiedBytesWithUnit() throws Exception { FileSystemTestUtils.createByteFile(mFileSystem, "/testFile", WriteType.MUST_CACHE, 10000); mFsShell.run("tail", "-c", "2KB", "/testFile"); START byte[] expect = BufferUtils.getIncreasingByteArray(0, 2048); END Assert.assertArrayEquals(expect, mOutput.toByteArray()); } will this work? `tail` command show the last 2048 byte here, I think it should be ```java byte[] expect = BufferUtils.getIncreasingByteArray(10000 - 2048, 2048); ```

Target:
public void tailFileWithUserSpecifiedBytesWithUnit() throws Exception { FileSystemTestUtils.createByteFile(mFileSystem, "/testFile", WriteType.MUST_CACHE, 10000); mFsShell.run("tail", "-c", "2KB", "/testFile"); byte[] expect = BufferUtils.getIncreasingByteArray(10000 - 2048, 2048); Assert.assertArrayEquals(expect, mOutput.toByteArray()); }
Source:
public LineageMaster create(MasterRegistry registry, JournalFactory journalFactory) { Preconditions.checkArgument(journalFactory != null, "journal factory may not be null"); LOG.info("Creating ", DefaultLineageMaster.class.getName()); FileSystemMaster fileSystemMaster = registry.get(FileSystemMaster.class); LineageMaster lineageMaster = new DefaultLineageMaster(fileSystemMaster, journalFactory); START registry.add(DefaultLineageMaster.class, lineageMaster); END return lineageMaster; } `registry.add(LineageMaster.class, lineageMaster);` Here we register implementations based on its type (interface)

Target:
public LineageMaster create(MasterRegistry registry, JournalFactory journalFactory) { Preconditions.checkArgument(journalFactory != null, "journal factory may not be null"); LOG.info("Creating ", LineageMaster.class.getName()); FileSystemMaster fileSystemMaster = registry.get(FileSystemMaster.class); LineageMaster lineageMaster = new DefaultLineageMaster(fileSystemMaster, journalFactory); registry.add(LineageMaster.class, lineageMaster); return lineageMaster; }
Source:
static PropertyKey create(String name, Object defaultValue, String[] aliases) { PropertyKey key = new PropertyKey(name); START for (String alias : aliases) { END DEFAULT_KEYS_MAP.put(alias, key); } DEFAULT_KEYS_MAP.put(name, key); DEFAULT_VALUES.put(key, defaultValue); return key; } Better check if `alias` is null or not.

Target:
static PropertyKey create(String name, Object defaultValue, String[] aliases) { PropertyKey key = create(name, defaultValue); if (aliases != null) { for (String alias : aliases) { DEFAULT_KEYS_MAP.put(alias, key); } } return key; }
Source:
public static void createFile(String filePath) throws IOException { Path storagePath = Paths.get(filePath); Files.createDirectories(storagePath.getParent()); try { Files.createFile(storagePath); START } catch (FileAlreadyExistsException e) { END throw new IOException("File already exist " + filePath); } } why we need this? `FileAlreadyExistsException` is already a subclass of `IOException`

Target:
public static void createFile(String filePath) throws IOException { Path storagePath = Paths.get(filePath); Files.createDirectories(storagePath.getParent()); Files.createFile(storagePath); }
Source:
public static void createDir(String path) throws IOException { try { Files.createDirectories(Paths.get(path)); START } catch (AccessDeniedException e) { END throw new IOException("Fail to create folder " + path); } } same here, why we need to convert `AccessDeniedException` to `IOException`? it is already a subclass of `IOException`

Target:
public static void createDir(String path) throws IOException { Files.createDirectories(Paths.get(path)); }
Source:
public void start(Boolean isLeader) throws IOException { super.start(isLeader); mGlobalStorageTierAssoc = new MasterStorageTierAssoc(); if (isLeader) { START LOG.info("I am blockmaster. I have blocks", mBlocks.size()); END mLostWorkerDetectionService = getExecutorService().submit(new HeartbeatThread( HeartbeatContext.MASTER_LOST_WORKER_DETECTION, new LostWorkerDetectionHeartbeatExecutor(), (int) Configuration.getMs(PropertyKey.MASTER_HEARTBEAT_INTERVAL_MS))); } } `debug` level or remove?

Target:
public void start(Boolean isLeader) throws IOException { super.start(isLeader); mGlobalStorageTierAssoc = new MasterStorageTierAssoc(); if (isLeader) { mLostWorkerDetectionService = getExecutorService().submit(new HeartbeatThread( HeartbeatContext.MASTER_LOST_WORKER_DETECTION, new LostWorkerDetectionHeartbeatExecutor(), (int) Configuration.getMs(PropertyKey.MASTER_HEARTBEAT_INTERVAL_MS))); } }
Source:
private ObjectListing getObjectListingChunkV1(ListObjectsRequest request) { ObjectListing result; try { // Query S3 for the next batch of objects result = mClient.listObjects(request); // Advance the request continuation token to the next set of objects request.setMarker(result.getNextMarker()); } catch (AmazonClientException e) { START LOG.error("Failed to list path {}", request.getPrefix(), e); END result = null; } return result; } This should be `warn` and with only `e.getMessage()` logged.

Target:
private ObjectListing getObjectListingChunkV1(ListObjectsRequest request) throws IOException { ObjectListing result; try { // Query S3 for the next batch of objects result = mClient.listObjects(request); // Advance the request continuation token to the next set of objects request.setMarker(result.getNextMarker()); } catch (AmazonClientException e) { throw new IOException(e); } return result; }
Source:
S3AObjectListingChunkV1(ListObjectsRequest request, ObjectListing result) START throws IOException { END Preconditions.checkNotNull(result, "result"); mRequest = request; mResult = result; } This no longer throws `IOException`

Target:
S3AObjectListingChunkV1(ListObjectsRequest request, ObjectListing result) { Preconditions.checkNotNull(result, "result"); mRequest = request; mResult = result; }
Source:
private ListObjectsV2Result getObjectListingChunk(ListObjectsV2Request request) throws IOException { ListObjectsV2Result result; try { // Query S3 for the next batch of objects result = mClient.listObjectsV2(request); // Advance the request continuation token to the next set of objects request.setContinuationToken(result.getNextContinuationToken()); } catch (AmazonClientException e) { START throw new IOException(e.getMessage()); END } return result; } `IOException(e)` so that the original cause is preserved

Target:
private ListObjectsV2Result getObjectListingChunk(ListObjectsV2Request request) throws IOException { ListObjectsV2Result result; try { // Query S3 for the next batch of objects result = mClient.listObjectsV2(request); // Advance the request continuation token to the next set of objects request.setContinuationToken(result.getNextContinuationToken()); } catch (AmazonClientException e) { throw new IOException(e); } return result; }
Source:
public void cancel() { if (mClosed) { return; } mClosed = true; mOutStream.cancel(); START mOutStream.close(); END } Its inconsistent that `BlockOutStream` only requires `cancel` or `close` to be called while `PacketOutStream` requires `close` to be called. Not required for this PR.

Target:
public void cancel() throws IOException { if (mClosed) { return; } mClosed = true; mOutStream.cancel(); }
Source:
START public HdfsUnderFileSystem(AlluxioURI ufsUri, UnderFileSystemConfiguration conf, END Configuration hdfsConf) { super(ufsUri); mUfsConf = conf; Path path = new Path(ufsUri.toString()); try { // Set Hadoop UGI configuration to ensure UGI can be initialized by the shaded classes for // group service. UserGroupInformation.setConfiguration(hdfsConf); mFileSystem = path.getFileSystem(hdfsConf); } catch (IOException e) { LOG.warn("Exception thrown when trying to get FileSystem for : {}", ufsUri, e.getMessage()); throw new RuntimeException("Failed to create Hadoop FileSystem", e); } } optional: could this be package private?

Target:
HdfsUnderFileSystem(AlluxioURI ufsUri, UnderFileSystemConfiguration conf, Configuration hdfsConf) { super(ufsUri); mUfsConf = conf; Path path = new Path(ufsUri.toString()); try { // Set Hadoop UGI configuration to ensure UGI can be initialized by the shaded classes for // group service. UserGroupInformation.setConfiguration(hdfsConf); mFileSystem = path.getFileSystem(hdfsConf); } catch (IOException e) { LOG.warn("Exception thrown when trying to get FileSystem for : {}", ufsUri, e.getMessage()); throw new RuntimeException("Failed to create Hadoop FileSystem", e); } }
Source:
public void channelRead(ChannelHandlerContext ctx, Object msg) { if (!acceptMessage(msg)) { ctx.fireChannelRead(msg); return; } ProtoMessage message = ((RPCProtoMessage) msg).getMessage(); if (message.isLocalBlockOpenRequest()) { handleBlockOpenRequest(ctx, message.asLocalBlockOpenRequest()); START } else { END Preconditions.checkState(message.isLocalBlockCloseRequest()); handleBlockCloseRequest(ctx, message.asLocalBlockCloseRequest()); } } explicitly check for `isLocalBlockCloseRequest()`, and add a last `else` block for error handling.

Target:
public void channelRead(ChannelHandlerContext ctx, Object msg) { if (!(msg instanceof RPCProtoMessage)) { ctx.fireChannelRead(msg); return; } ProtoMessage message = ((RPCProtoMessage) msg).getMessage(); if (message.isLocalBlockOpenRequest()) { handleBlockOpenRequest(ctx, message.asLocalBlockOpenRequest()); } else if (message.isLocalBlockCloseRequest()) { handleBlockCloseRequest(ctx, message.asLocalBlockCloseRequest()); } else { ctx.fireChannelRead(msg); } }
Source:
public DataBuffer readPacket() { if (mPos >= mEnd) { return null; } START initIfNot(); END ByteBuffer buffer = mReader.read(mPos, Math.min(LOCAL_READ_PACKET_SIZE, mEnd - mPos)); DataBuffer dataBuffer = new DataByteBuffer(buffer, buffer.remaining()); mPos += dataBuffer.getLength(); return dataBuffer; } Consider putting init in the constructor? Otherwise the block is not guaranteed to be available even if reader is successfully created.

Target:
public DataBuffer readPacket() { if (mPos >= mEnd) { return null; } ByteBuffer buffer = mReader.read(mPos, Math.min(LOCAL_READ_PACKET_SIZE, mEnd - mPos)); DataBuffer dataBuffer = new DataByteBuffer(buffer, buffer.remaining()); mPos += dataBuffer.getLength(); return dataBuffer; }
Source:
private CompleteUfsFileOptions() { START if (SecurityUtils.isSecurityEnabled()) { END mOwner = SecurityUtils.getOwnerFromLoginModule(); mGroup = SecurityUtils.getGroupFromLoginModule(); } else { mOwner = ""; mGroup = ""; } mMode = Mode.defaults().applyFileUMask(); // TODO(chaomin): set permission based on the alluxio file. Not needed for now since the // file is always created with default permission. } would it make sense to push the if logic into the utility method? I would expect that this pattern will be true for every caller at which point it makes sense to encapsulate it

Target:
private CompleteUfsFileOptions() { mOwner = SecurityUtils.getOwnerFromLoginModule(); mGroup = SecurityUtils.getGroupFromLoginModule(); mMode = Mode.defaults().applyFileUMask(); // TODO(chaomin): set permission based on the alluxio file. Not needed for now since the // file is always created with default permission. }
Source:
protected void stopServing() throws Exception { START LOG.info("Alluxio master version stop serving @ (was serving: {})", END RuntimeConstants.VERSION, mRpcAddress, mIsServing); if (mThriftServer != null) { mThriftServer.stop(); mThriftServer = null; } if (mWebServer != null) { mWebServer.stop(); mWebServer = null; } MetricsSystem.stopSinks(); mIsServing = false; } Are these messages duplicates?

Target:
protected void stopServing() throws Exception { if (mThriftServer != null) { mThriftServer.stop(); mThriftServer = null; } if (mWebServer != null) { mWebServer.stop(); mWebServer = null; } MetricsSystem.stopSinks(); mIsServing = false; }
Source:
public final void after() throws Exception { START if (HadoopClientTestUtils.isHadoop1x()) { END return; } mMultiMasterLocalAlluxioCluster.stop(); } I think we can replace all of the hadoop-1 checking with ```java @BeforeClass public static void beforeClass() { Assume.assumeFalse(HadoopClientTestUtils.isHadoop1x()); } ```

Target:
public final void after() throws Exception { mMultiMasterLocalAlluxioCluster.stop(); }
Source:
public void start() throws Exception { START LOG.info("Starting Alluxio master @{}", mRpcAddress); END startMasters(true); startServing(); } Is this logging necessary, I think we are already handling it in `ProcessUtils` (though that might not work for unit tests)

Target:
public void start() throws Exception { startMasters(true); startServing(); }
Source:
public static void run(Process process) { try { LOG.info("Starting {}.", process); process.start(); System.exit(0); } catch (Exception e) { LOG.error("Uncaught exception while running {}, stopping it and exiting.", process, e); try { START LOG.info("Stopping {}.", process); END process.stop(); } catch (Exception e2) { // continue to exit LOG.error("Uncaught exception while stopping {}, simply exiting.", process, e2); } System.exit(-1); } } The previous error level log already says we are stopping the process

Target:
public static void run(Process process) { try { LOG.info("Starting {}.", process); process.start(); LOG.info("Stopping {}.", process); System.exit(0); } catch (Exception e) { LOG.error("Uncaught exception while running {}, stopping it and exiting.", process, e); try { process.stop(); } catch (Exception e2) { // continue to exit LOG.error("Uncaught exception while stopping {}, simply exiting.", process, e2); } System.exit(-1); } }
Source:
public void release(T resource) { if (resource != null) { mResources.add(resource); START mCurrentCapacity.incrementAndGet(); END try (LockResource r = new LockResource(mTakeLock)) { mNotEmpty.signal(); } } } `mCurrentCapacity` is the total number of objects in the pool, whether acquired or still available. A method should never decrease it.

Target:
public void release(T resource) { if (resource != null) { mResources.add(resource); try (LockResource r = new LockResource(mTakeLock)) { mNotEmpty.signal(); } } }
Source:
public void run() { FileSystemMasterClient client = null; START try { END client = FileSystemContext.INSTANCE.acquireMasterClient(); } catch (IOException e) { Assert.fail("Failed to acquire a master client due to interruption occured."); } finally { FileSystemContext.INSTANCE.releaseMasterClient(client); } } use `try-with-resource` pattern?

Target:
public void run() { FileSystemMasterClient client = FileSystemContext.INSTANCE.acquireMasterClient(); FileSystemContext.INSTANCE.releaseMasterClient(client); }
Source:
public T acquire() throws IOException { START return acquire(WAIT_INDEFINITELY, null); END } I would prefer some really large value here instead of introducing "-1" which just adds complexity unnecessarily. You can keep it consistent with what we are doing in DynamicResourcePool. (simpler is better). `acquire(100, TimeUnit.DAYS) `

Target:
public T acquire() { return acquire(WAIT_INDEFINITELY, null); }
Source:
public DataBuffer readPacket() throws IOException { if (mPos >= mEnd) { return null; } ByteBuffer buffer = START ByteBuffer.wrap(mData, (int) mPos, (int) (Math.min(mPacketSize, mEnd) - mPos)); END DataBuffer dataBuffer = new DataByteBuffer(buffer, buffer.remaining()); mPos += dataBuffer.getLength(); return dataBuffer; } Should the third argument be `Math.min(mEnd - mPos, mPacketSize)`?

Target:
public DataBuffer readPacket() throws IOException { if (mPos >= mEnd) { return null; } ByteBuffer buffer = ByteBuffer.wrap(mData, (int) mPos, (int) (Math.min(mPacketSize, mEnd - mPos))); DataBuffer dataBuffer = new DataByteBuffer(buffer, buffer.remaining()); mPos += dataBuffer.getLength(); return dataBuffer; }
Source:
public void equalsTest() throws Exception { Assert.assertEquals(PropertyKey.Template.MASTER_MOUNT_TABLE_ENTRY_ALLUXIO.format("foo"), PropertyKey.Template.MASTER_MOUNT_TABLE_ENTRY_ALLUXIO.format("foo")); START Assert.assertNotEquals(PropertyKey.HOME, PropertyKey.HOME); END } Why are property keys not equal but formatted templates are?

Target:
public void equalsTest() throws Exception { Assert.assertEquals(PropertyKey.Template.MASTER_MOUNT_TABLE_ENTRY_ALLUXIO.format("foo"), PropertyKey.Template.MASTER_MOUNT_TABLE_ENTRY_ALLUXIO.format("foo")); Assert.assertEquals(PropertyKey.HOME, PropertyKey.HOME); }
Source:
public void fields() { START Random random = new Random(); END boolean isPrimary = random.nextBoolean(); long sequenceNumber = random.nextLong(); JournalReaderOptions options = JournalReaderOptions.defaults(); options.setPrimary(isPrimary); Assert.assertEquals(isPrimary, options.isPrimary()); options.setNextSequenceNumber(sequenceNumber); Assert.assertEquals(sequenceNumber, options.getNextSequenceNumber()); } `Random random = new Random(CommonUtils.getCurrentMs());`

Target:
public void fields() throws Exception { Random random = new Random(); boolean isPrimary = random.nextBoolean(); long sequenceNumber = random.nextLong(); JournalReaderOptions options = JournalReaderOptions.defaults(); options.setPrimary(isPrimary); Assert.assertEquals(isPrimary, options.isPrimary()); options.setNextSequenceNumber(sequenceNumber); Assert.assertEquals(sequenceNumber, options.getNextSequenceNumber()); }
Source:
public void run() { try { runInternal(); } catch (RuntimeException e) { LOG.error("{}: Failed to run journal checkpoint thread, crashing.", mMaster.getName(), e); START System.exit(-1); END } finally { if (mJournalReader != null) { try { mJournalReader.close(); } catch (IOException e) { LOG.warn("{}: Failed to close the journal reader with error {}.", mMaster.getName(), e.getMessage()); } } } } The finally block will not be executed?

Target:
public void run() { try { runInternal(); } catch (RuntimeException e) { LOG.error("{}: Failed to run journal checkpoint thread, crashing.", mMaster.getName(), e); throw e; } }
Source:
public JournalReader getReader(JournalReaderOptions options) { if (options.getLocation() != null) { return new UfsJournalFileReader(options); } else { return new UfsJournalReader(this, options); } START } END `UfsJournalReader` and `UfsJournalFileReader` are two separate concepts, they shouldn't be obtained through the same `getReader` call

Target:
public JournalReader getReader(JournalReaderOptions options) { return new UfsJournalReader(this, options); }
Source:
public Master create(MasterRegistry registry, JournalFactory journalFactory) { Preconditions.checkArgument(journalFactory != null, "journal factory may not be null"); LOG.info("Creating ", FileSystemMaster.class.getName()); START return new DefaultFileSystemMaster(registry, journalFactory); END } Should this return a `FileSystemMaster` instead of just a `Master`?

Target:
public FileSystemMaster create(MasterRegistry registry, JournalFactory journalFactory) { Preconditions.checkArgument(journalFactory != null, "journal factory may not be null"); LOG.info("Creating ", FileSystemMaster.class.getName()); return new DefaultFileSystemMaster(registry, journalFactory); }
Source:
protected File generateRelativeFileContent(String path, byte[] toWrite) throws IOException, FileNotFoundException { START File testFile = new File(System.getProperty("user.dir") + path); END testFile.createNewFile(); FileOutputStream fos = new FileOutputStream(testFile); fos.write(toWrite); fos.close(); return testFile; } Does this work the same without including `System.getProperty("user.dir")`?

Target:
protected File generateRelativeFileContent(String path, byte[] toWrite) throws IOException, FileNotFoundException { File testFile = new File(path); testFile.createNewFile(); FileOutputStream fos = new FileOutputStream(testFile); fos.write(toWrite); fos.close(); return testFile; }
Source:
public String getDescription() { return "Displays information for all files and directories directly under the specified path." + " Specify -R to display files and directories recursively." + " Specify -d to list directories as plain files." + " Specify -f to force loading files in the directory." START + " Specify -raw to print raw sizes." END + " Specify -p to list all the pinned files."; } keep options sorted alphabetically

Target:
public String getDescription() { return "Displays information for all files and directories directly under the specified path." + " Specify -d to list directories as plain files." + " Specify -f to force loading files in the directory." + " Specify -p to list all the pinned files." + " Specify -R to display files and directories recursively." + " Specify -raw to print raw sizes."; }
Source:
START public Collection<Master> getMasters() { END List<Map.Entry<Class<?>, Master>> entries = new ArrayList<>(mRegistry.entrySet()); Collections.sort(entries, new DependencyComparator()); List<Master> masters = new ArrayList<>(); for (Map.Entry<Class<?>, Master> entry : entries) { masters.add(entry.getValue()); } return masters; } since the order matters for these, it would make more sense to return a List

Target:
public List<Master> getMasters() { List<Master> masters = new ArrayList<>(mRegistry.values()); Collections.sort(masters, new DependencyComparator()); return masters; }
Source:
public void processJournalCheckpoint(boolean applyToMaster) throws IOException { // Load the checkpoint. LOG.info("{}: Loading checkpoint.", mMaster.getName()); // The checkpoint stream must be retrieved before retrieving any log streams, because the // journal reader verifies that the checkpoint was read before the log streams. START JournalInputStream is = mReader.getCheckpointInputStream(); END if (applyToMaster) { // Only apply the checkpoint to the master, if specified. mMaster.processJournalCheckpoint(is); } // update the latest sequence number seen. mLatestSequenceNumber = is.getLatestSequenceNumber(); is.close(); } given `JournalInputStream` becomes closable, shall we use try-with-resource for safety?

Target:
public void processJournalCheckpoint(boolean applyToMaster) throws IOException { // Load the checkpoint. LOG.info("{}: Loading checkpoint.", mMaster.getName()); // The checkpoint stream must be retrieved before retrieving any log streams, because the // journal reader verifies that the checkpoint was read before the log streams. try (JournalInputStream is = mReader.getCheckpointInputStream()) { if (applyToMaster) { // Only apply the checkpoint to the master, if specified. mMaster.processJournalCheckpoint(is); } // update the latest sequence number seen. mLatestSequenceNumber = is.getLatestSequenceNumber(); } }
Source:
public void unknownException() { try { final String testMessage = "testMessage"; AlluxioTException tException = new AlluxioTException("testType", testMessage, "testClass"); AlluxioException exception = AlluxioException.fromThrift(tException); Assert.assertEquals(testMessage, exception.getMessage()); START } catch (Exception e) { END // this should never happen Assert.fail("unexpected exception" + e.getMessage()); } } why are we using try-catch here?

Target:
public void unknownException() { final String testMessage = "testMessage"; AlluxioTException tException = new AlluxioTException("testType", testMessage, "testClass"); AlluxioException exception = AlluxioException.fromThrift(tException); Assert.assertEquals(testMessage, exception.getMessage()); }
Source:
public UfsBlockReadRequestInternal(Protocol.ReadRequest request) throws Exception { mBlockReader = mWorker .readUfsBlock(request.getSessionId(), request.getId(), request.getOffset(), request.getNoCache()); mId = request.getId(); mStart = request.getOffset(); START mEnd = mStart + request.getLength(); END // Note that we do not need to seek to offset since the block worker is created at the offset. } Use these values when creating the `BlockReader`?

Target:
public UfsBlockReadRequestInternal(Protocol.ReadRequest request) throws Exception { mId = request.getId(); mStart = request.getOffset(); mEnd = mStart + request.getLength(); mBlockReader = mWorker.readUfsBlock(request.getSessionId(), mId, mStart, request.getNoCache()); // Note that we do not need to seek to offset since the block worker is created at the offset. }
Source:
START private void createBlockFile(String blockPath) throws IOException { END FileUtils.createBlockPath(blockPath); FileUtils.createFile(blockPath); FileUtils.changeLocalFileToFullPermission(blockPath); LOG.debug("Created new file block, block path: {}", blockPath); } should this be a static method?

Target:
private static void createBlockFile(String blockPath) throws IOException { FileUtils.createBlockPath(blockPath); FileUtils.createFile(blockPath); FileUtils.changeLocalFileToFullPermission(blockPath); LOG.debug("Created new file block, block path: {}", blockPath); }
Source:
private BlockInfo getBlockInfo(long sessionId, long blockId) throws BlockDoesNotExistException { Key key = new Key(sessionId, blockId); BlockInfo blockInfo = mBlocks.get(key); if (blockInfo == null) { START try { END throw new BlockDoesNotExistException(ExceptionMessage.UFS_BLOCK_DOES_NOT_EXIST_FOR_SESSION, blockId, sessionId); } catch (Throwable e) { LOG.error("UFS Block does not exist.", e); throw e; } } return blockInfo; } please fix @peisun1115

Target:
private BlockInfo getBlockInfo(long sessionId, long blockId) throws BlockDoesNotExistException { Key key = new Key(sessionId, blockId); BlockInfo blockInfo = mBlocks.get(key); if (blockInfo == null) { throw new BlockDoesNotExistException(ExceptionMessage.UFS_BLOCK_DOES_NOT_EXIST_FOR_SESSION, blockId, sessionId); } return blockInfo; }
Source:
public String toString() { return Objects.toStringHelper(this) START .add("ufsPath", mUfsPath) END .add("offset", mOffset) .add("blockSize", mBlockSize) .add("maxUfsReadConcurrency", mMaxUfsReadConcurrency).toString(); } nit: sort fileds alphabetically

Target:
public String toString() { return Objects.toStringHelper(this) .add("blockSize", mBlockSize) .add("maxUfsReadConcurrency", mMaxUfsReadConcurrency) .add("offset", mOffset) .add("ufsPath", mUfsPath).toString(); }
Source:
public long getServiceVersion() { LOG.debug("Enter GetServiceVersion."); long ret = Constants.FILE_SYSTEM_MASTER_CLIENT_SERVICE_VERSION; LOG.debug("Exit GetServiceVersion."); START return ret; END } shall we remove this then?

Target:
public long getServiceVersion() { return Constants.FILE_SYSTEM_MASTER_CLIENT_SERVICE_VERSION; }
Source:
START public static BlockMasterClient create(InetSocketAddress masterAddress) { END return new RetryHandlingBlockMasterClient(null, masterAddress); } Would it be possible to use the factory throughout and make the constructors private? Its unclear when one should be used over the other

Target:
public static BlockMasterClient create(InetSocketAddress masterAddress) { return create(null, masterAddress); }
Source:
protected FileSystemMasterClient createNewResource() { FileSystemMasterClient client = START new RetryHandlingFileSystemMasterClient(mSubject, mMasterAddress); END mClientList.add(client); return client; } Is it possible to make this use the factory?

Target:
protected FileSystemMasterClient createNewResource() { FileSystemMasterClient client = RetryHandlingFileSystemMasterClient.create(mSubject, mMasterAddress); mClientList.add(client); return client; }
Source:
public void workerReRegister() throws Exception { AlluxioBlockStore store = AlluxioBlockStore.create(); Assert.assertEquals(WORKER_CAPACITY_BYTES, store.getCapacityBytes()); for (int kills = 0; kills < MASTERS - 1; kills++) { Assert.assertTrue(mMultiMasterLocalAlluxioCluster.stopLeader()); mMultiMasterLocalAlluxioCluster.waitForNewMaster(CLUSTER_WAIT_TIMEOUT_MS); START waitForWorkerRegistration(store, 1, Constants.SECOND_MS); END // If worker is successfully re-registered, the capacity bytes should not change. Assert.assertEquals(WORKER_CAPACITY_BYTES, store.getCapacityBytes()); } } 5 seconds might be better to weather interference from other builds

Target:
public void workerReRegister() throws Exception { AlluxioBlockStore store = AlluxioBlockStore.create(); Assert.assertEquals(WORKER_CAPACITY_BYTES, store.getCapacityBytes()); for (int kills = 0; kills < MASTERS - 1; kills++) { Assert.assertTrue(mMultiMasterLocalAlluxioCluster.stopLeader()); mMultiMasterLocalAlluxioCluster.waitForNewMaster(CLUSTER_WAIT_TIMEOUT_MS); waitForWorkerRegistration(store, 1, 5 * Constants.SECOND_MS); // If worker is successfully re-registered, the capacity bytes should not change. Assert.assertEquals(WORKER_CAPACITY_BYTES, store.getCapacityBytes()); } }
Source:
START public void equalsTest() throws Exception { END CommonTestUtils.testEquals(RenameOptions.class, "mOperationTimeMs"); } NIT: `equals` instead of `equalsTest`?

Target:
public void equalsTest() throws Exception { CommonTestUtils.testEquals(RenameOptions.class); }
Source:
private JournalContext() { START mFlushCounter = AsyncJournalWriter.INVALID_FLUSH_COUNTER; END } NIT: I guess we could make `AsyncJournalWriter.INVALID_FLUSH_COUNTER` private now since it becomes completely an internal state. Up to you

Target:
private JournalContext() { mFlushCounter = INVALID_FLUSH_COUNTER; }
Source:
START public long getAutoSavePrefs() END { int delay = preferences.getInt(UIConstants.Preferences.AUTO_SAVE_FILE, 15); if (delay > 0) { long delayInMilliseconds = 1000 * 60 * delay; return delayInMilliseconds; } return 0L; } Die Methode muss nicht ```public``` sein, oder?

Target:
private long getAutoSavePrefs() { int delay = preferences.getInt(UIConstants.Preferences.AUTO_SAVE_FILE, 15); if (delay > 0) { long delayInMilliseconds = 1000 * 60 * delay; return delayInMilliseconds; } return 0L; }
Source:
public String getOriginalFilePath() { Object path = tuples.get(FILE_PATH_LABEL); return path != null ? path.toString() : PATH_DEFAULT; START } END Not sure we want a path value of "path" in the rest json. It just adds noise and data to the network transfer.

Target:
public String getOriginalFilePath() { Object path = tuples.get(FILE_PATH_LABEL); return path != null ? path.toString() : null; }
Source:
public int getVersion() { Object version = tuples.get(VERSION_LABEL); return version != null ? Integer.parseInt(version.toString()) : VERSION_DEFAULT; START } END Same as original path for these values. If the item is null then its not included in the json content so the network transfer is smaller.

Target:
public int getVersion() { Object version = tuples.get(VERSION_LABEL); return version != null ? Integer.parseInt(version.toString()) : 1; }
Source:
public final void setPrimaryType( final UnitOfWork uow, final String typeName ) throws UnsupportedOperationException { START throw new UnsupportedOperationException(); END } Why is this throwing an UOE? UOE is a runtime exception so does not need a throws clause. Also, the fact it does not need a throws clauses means it catching is undetermined. Can we replace it with a normal exception if it should be throwing an exception.

Target:
public final void setPrimaryType( final UnitOfWork uow, final String typeName ) { throw new UnsupportedOperationException(); }
Source:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Package that = (Package) o; if (!name.equals(that.name)) return false; return true; START } END Only very few parts of this function is tested, I think thats why codecov bails out. Are all these checks really needed? Specifically, the check for class equality will cause problems in case someone subclasses `Package`, right? Also the last two statements can just be written as return name.equals(that.name); To avoid a branch that would otherwise need to be tested.

Target:
public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Package)) return false; Package that = (Package) o; return name.equals(that.name); }
Source:
START public Component(Package pkg, String component){ END mPackage = pkg; mComponent = component; } Space before `{`

Target:
public Component(Package pkg, String component) { this.pkg = pkg; this.component = component; }
Source:
public void remove(RemoteFile file) throws IOException, JadbException { InputStream s = device.executeShell("rm", "-f", Bash.quote(file.getPath())); Stream.flushRead(s); START s.close(); END } Nice :+1: To make it even better, use try-with-resource idiom.

Target:
public void remove(RemoteFile file) throws IOException, JadbException { try (InputStream stream = device.executeShell("rm", "-f", Bash.quote(file.getPath()))) { Stream.flushRead(stream); } }
Source:
public void launch(Package name) throws IOException, JadbException { InputStream s = device.executeShell("monkey", "-p", name.toString(), "-c", "android.intent.category.LAUNCHER", "1"); START Stream.flushRead(s); END s.close(); } Why is this needed?

Target:
public void launch(Package name) throws IOException, JadbException { try (InputStream stream = device.executeShell("monkey", "-p", name.toString(), "-c", "android.intent.category.LAUNCHER", "1")) { Stream.flushRead(stream); } }
Source:
public void close() throws IOException { super.close(); transport.close(); START } END Remember to revert this file, it should know about the transport class.

Target:
public void close() throws IOException { super.close(); }
Source:
START public int getMode(File file) { END //noinspection OctalInteger return 0664; } This does not need to be public, let's keep private

Target:
private int getMode(File file) { //noinspection OctalInteger return 0664; }
Source:
public void sendEvent(InputEvent event) throws JadbException { try (InputStream is = device.executeShell("input", event.buildArgs())) { Stream.flushRead(is); } catch (IOException e) { START throw new JadbException(e.getMessage()); END } } Here the important inner exception gets lost, please pass e to `JadbException` constructor.

Target:
public void sendEvent(InputEvent event) throws JadbException { try (InputStream is = device.executeShell("input", event.buildArgs())) { Stream.flushRead(is); } catch (IOException e) { throw new JadbException(e); } }
Source:
public void remove(RemoteFile file) throws IOException, JadbException { try (InputStream stream = device.executeShell("rm", "-f", Bash.quote(file.getPath()))) { Stream.flushRead(stream); START stream.close(); END } } Close should not be needed here as you use try-with-resource? What's wring with the `readAll` method? I feel the name is clearer.

Target:
public void remove(RemoteFile file) throws IOException, JadbException { try (InputStream stream = device.executeShell("rm", "-f", Bash.quote(file.getPath()))) { Stream.flushRead(stream); } }
Source:
public void launch(Package name) throws IOException, JadbException { try (InputStream stream = device.executeShell("monkey", "-p", name.toString(), "-c", "android.intent.category.LAUNCHER", "1")) { Stream.flushRead(stream); START stream.close(); END } } Close should not be needed here as you use try-with-resource? What's wring with the `readAll` method? I feel the name is clearer.

Target:
public void launch(Package name) throws IOException, JadbException { try (InputStream stream = device.executeShell("monkey", "-p", name.toString(), "-c", "android.intent.category.LAUNCHER", "1")) { Stream.flushRead(stream); } }
Source:
public Map<String, String> getprop() throws IOException, JadbException { BufferedReader bufferedReader = null; START try { END bufferedReader = new BufferedReader(new InputStreamReader(device.executeShell("getprop"))); return parseProp(bufferedReader); } finally { if (bufferedReader != null) { bufferedReader.close(); } } } Use `try-with-resources` please!

Target:
public Map<String, String> getprop() throws IOException, JadbException { try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(device.executeShell("getprop")))) { return parseProp(bufferedReader); } }
Source:
private String findAdbExecutable() { String android_home = System.getenv("ANDROID_HOME"); START return android_home != null && !android_home.equals("")?android_home + "/platform-tools/adb":"adb"; END } I feel this one liner hurt readability, please use the previous syntax for clarity.

Target:
private String findAdbExecutable() { String android_home = System.getenv("ANDROID_HOME"); if (android_home == null || android_home.equals("")) { return "adb"; } return android_home + "/platform-tools/adb"; }
Source:
public String getVoxelId() { START return voxelState.getId(); END } Qualify with `this.` Same goes everywhere.

Target:
public String getVoxelId() { return this.voxelState.getId(); }
Source:
public List<EntryDTO> getNotificationsBySourceAndCustomAttribute(String source, String attributeName, String attributeValue) { Validate.notBlank(source, "Argument 'source' cannot be blank"); START Validate.notBlank(source, "Argument 'attributeName' cannot be blank"); END // Does it make sense to allow blank attributeValue? logger.debug("Invoking getNotificationsBySourceAndCustomAttribute with " + "source='{}', attributeName='{}', attributeValue='{}'", source, attributeName, attributeValue); final List<JpaEntry> entries = notificationDao.getNotificationsBySourceAndCustomAttribute(source, attributeName, attributeValue); logger.debug("Found the following entries: {}", entries.size(), entries); return notificationMapper.toEntryList(entries); } Should line 89 be ``` java Validate.notBlank(attributeName, "Argument 'attributeName' cannot be blank"); ``` ?

Target:
public List<EntryDTO> getNotificationsBySourceAndCustomAttribute(String source, String attributeName, String attributeValue) { Validate.notBlank(source, "Argument 'source' cannot be blank"); Validate.notBlank(attributeName, "Argument 'attributeName' cannot be blank"); // Does it make sense to allow blank attributeValue? logger.debug("Invoking getNotificationsBySourceAndCustomAttribute with " + "source='{}', attributeName='{}', attributeValue='{}'", source, attributeName, attributeValue); final List<JpaEntry> entries = notificationDao.getNotificationsBySourceAndCustomAttribute(source, attributeName, attributeValue); logger.debug("Found the following entries: {}", entries.size(), entries); return notificationMapper.toEntryList(entries); }
Source:
public Response reliableRequest(final Request request, final int[] retryCodes, int retries, final long delayMillis) { Response response = null; while (retries > 0) { response = makeRequest(request); if (!shouldRetry(response, retryCodes)) { break; } try { Thread.sleep(delayMillis); } catch (final InterruptedException e) { // Delay failed, continue } // Decrement retries retries--; } START lastRequest = request; END lastResponse = response; return response; } lastRequest should probably be set before we make the request too.

Target:
public Response reliableRequest(final Request request, final int[] retryCodes, int retries, final long delayMillis) { lastRequest = request; Response response = null; while (retries > 0) { response = makeRequest(request); if (!shouldRetry(response, retryCodes)) { break; } try { Thread.sleep(delayMillis); } catch (final InterruptedException e) { // Delay failed, continue } // Decrement retries retries--; } lastResponse = response; return response; }