auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void zookeeper() throws Exception { mCluster = MultiProcessCluster.newBuilder() .setClusterName("zookeeper") .addProperty(PropertyKey.ZOOKEEPER_ENABLED, "true") .setNumMasters(3) .setNumWorkers(2) .build(); boolean success = false; try { mCluster.start(); FileSystem fs = mCluster.getFileSystemClient(); createAndOpenFile(fs); mSuccess = true; } finally { cleanup(); } }

Target:
is this var ever used any where?
Source:
public JvmPauseMonitor reset() { mJvmMonitorThread = null; mThreadStarted = true; return this; }

Target:
the thread is not started, since it's set to null above,right?
Source:
private boolean shouldCachePartiallyReadBlock() throws IOException { return mShouldCache && mCachePartiallyReadBlock; }

Target:
Does this throw `IOException`?
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(); Assert.fail("get a non-existing bucket should fail"); } catch (AssertionError e) { // expected } }

Target:
this will throw AssertionError too, then if the test fails, there is no way to detect the error
Source:
private UserLimitValidationTask(String name, String command, Integer lowerBound, Integer upperBound) { mName = name; mCommand = new String[] {"bash", "-c", command}; mLowerBound = lowerBound; mUpperBound = upperBound; }

Target:
`mCommand` can be a string as input. Add `bash -c` to the place when you call it.
Source:
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."); System.exit(0); } } }); }

Target:
include the error message
Source:
public void stop() { synchronized (this) { if (!mStopped) { mLoggingWorkerThread.interrupt(); try { mLoggingWorkerThread.join(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { mStopped = true; mLoggingWorkerThread = null; LOG.info("AsyncUserAccessAuditLogWriter thread stopped."); } } } }

Target:
This just synchronizes the entire method? If so, you can just define the method as: `public synchronized void stop()`
Source:
public synchronized Inode getLastExistingInode() { Inode<?> inode = mInodes.get(mInodes.size() - 1); return inode; }

Target:
NIT: extra space
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; } // 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; }

Target:
Put these two conditions together?
Source:
private void init() { mMasterInquireClient = MasterInquireClient.Factory.create(); mFileSystemMasterClientPool = new FileSystemMasterClientPool(mParentSubject, mMasterInquireClient); mBlockMasterClientPool = new BlockMasterClientPool(mParentSubject, mMasterInquireClient); }

Target:
Do we need to guard this?
Source:
public String getDescription() { return mDescription != null ? mDescription : "N/A"; }

Target:
NIT: remove the empty line
Source:
public void tailFileWithUserSpecifiedBytesWithUnit() throws Exception { FileSystemTestUtils.createByteFile(mFileSystem, "/testFile", WriteType.MUST_CACHE, 10000); mFsShell.run("tail", "-c", "2KB", "/testFile"); byte[] expect = BufferUtils.getIncreasingByteArray(0, 2048); Assert.assertArrayEquals(expect, mOutput.toByteArray()); }

Target:
will this work? `tail` command show the last 2048 byte here, I think it should be ```java byte[] expect = BufferUtils.getIncreasingByteArray(10000 - 2048, 2048); ```
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); registry.add(DefaultLineageMaster.class, lineageMaster); return lineageMaster; }

Target:
`registry.add(LineageMaster.class, lineageMaster);` Here we register implementations based on its type (interface)
Source:
static PropertyKey create(String name, Object defaultValue, String[] aliases) { PropertyKey key = new PropertyKey(name); for (String alias : aliases) { DEFAULT_KEYS_MAP.put(alias, key); } DEFAULT_KEYS_MAP.put(name, key); DEFAULT_VALUES.put(key, defaultValue); return key; }

Target:
Better check if `alias` is null or not.
Source:
public static void createFile(String filePath) throws IOException { Path storagePath = Paths.get(filePath); Files.createDirectories(storagePath.getParent()); try { Files.createFile(storagePath); } catch (FileAlreadyExistsException e) { throw new IOException("File already exist " + filePath); } }

Target:
why we need this? `FileAlreadyExistsException` is already a subclass of `IOException`
Source:
public static void createDir(String path) throws IOException { try { Files.createDirectories(Paths.get(path)); } catch (AccessDeniedException e) { throw new IOException("Fail to create folder " + path); } }

Target:
same here, why we need to convert `AccessDeniedException` to `IOException`? it is already a subclass of `IOException`
Source:
public void start(Boolean isLeader) throws IOException { super.start(isLeader); mGlobalStorageTierAssoc = new MasterStorageTierAssoc(); if (isLeader) { LOG.info("I am blockmaster. I have blocks", mBlocks.size()); mLostWorkerDetectionService = getExecutorService().submit(new HeartbeatThread( HeartbeatContext.MASTER_LOST_WORKER_DETECTION, new LostWorkerDetectionHeartbeatExecutor(), (int) Configuration.getMs(PropertyKey.MASTER_HEARTBEAT_INTERVAL_MS))); } }

Target:
`debug` level or remove?
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) { LOG.error("Failed to list path {}", request.getPrefix(), e); result = null; } return result; }

Target:
This should be `warn` and with only `e.getMessage()` logged.
Source:
S3AObjectListingChunkV1(ListObjectsRequest request, ObjectListing result) throws IOException { Preconditions.checkNotNull(result, "result"); mRequest = request; mResult = result; }

Target:
This no longer throws `IOException`
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) { throw new IOException(e.getMessage()); } return result; }

Target:
`IOException(e)` so that the original cause is preserved
Source:
public void cancel() { if (mClosed) { return; } mClosed = true; mOutStream.cancel(); mOutStream.close(); }

Target:
Its inconsistent that `BlockOutStream` only requires `cancel` or `close` to be called while `PacketOutStream` requires `close` to be called. Not required for this PR.
Source:
public 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); } }

Target:
optional: could this be package private?
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()); } else { Preconditions.checkState(message.isLocalBlockCloseRequest()); handleBlockCloseRequest(ctx, message.asLocalBlockCloseRequest()); } }

Target:
explicitly check for `isLocalBlockCloseRequest()`, and add a last `else` block for error handling.
Source:
public DataBuffer readPacket() { if (mPos >= mEnd) { return null; } initIfNot(); 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; }

Target:
Consider putting init in the constructor? Otherwise the block is not guaranteed to be available even if reader is successfully created.
Source:
private CompleteUfsFileOptions() { if (SecurityUtils.isSecurityEnabled()) { 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. }

Target:
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
Source:
protected void stopServing() throws Exception { LOG.info("Alluxio master version stop serving @ (was serving: {})", RuntimeConstants.VERSION, mRpcAddress, mIsServing); if (mThriftServer != null) { mThriftServer.stop(); mThriftServer = null; } if (mWebServer != null) { mWebServer.stop(); mWebServer = null; } MetricsSystem.stopSinks(); mIsServing = false; }

Target:
Are these messages duplicates?
Source:
public final void after() throws Exception { if (HadoopClientTestUtils.isHadoop1x()) { return; } mMultiMasterLocalAlluxioCluster.stop(); }

Target:
I think we can replace all of the hadoop-1 checking with ```java @BeforeClass public static void beforeClass() { Assume.assumeFalse(HadoopClientTestUtils.isHadoop1x()); } ```
Source:
public void start() throws Exception { LOG.info("Starting Alluxio master @{}", mRpcAddress); startMasters(true); startServing(); }

Target:
Is this logging necessary, I think we are already handling it in `ProcessUtils` (though that might not work for unit tests)
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 { LOG.info("Stopping {}.", process); process.stop(); } catch (Exception e2) { // continue to exit LOG.error("Uncaught exception while stopping {}, simply exiting.", process, e2); } System.exit(-1); } }

Target:
The previous error level log already says we are stopping the process
Source:
public void release(T resource) { if (resource != null) { mResources.add(resource); mCurrentCapacity.incrementAndGet(); try (LockResource r = new LockResource(mTakeLock)) { mNotEmpty.signal(); } } }

Target:
`mCurrentCapacity` is the total number of objects in the pool, whether acquired or still available. A method should never decrease it.
Source:
public void run() { FileSystemMasterClient client = null; try { client = FileSystemContext.INSTANCE.acquireMasterClient(); } catch (IOException e) { Assert.fail("Failed to acquire a master client due to interruption occured."); } finally { FileSystemContext.INSTANCE.releaseMasterClient(client); } }

Target:
use `try-with-resource` pattern?
Source:
public T acquire() throws IOException { return acquire(WAIT_INDEFINITELY, null); }

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

Target:
Should the third argument be `Math.min(mEnd - mPos, mPacketSize)`?
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")); Assert.assertNotEquals(PropertyKey.HOME, PropertyKey.HOME); }

Target:
Why are property keys not equal but formatted templates are?
Source:
public void fields() { 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()); }

Target:
`Random random = new Random(CommonUtils.getCurrentMs());`
Source:
public void run() { try { runInternal(); } catch (RuntimeException e) { LOG.error("{}: Failed to run journal checkpoint thread, crashing.", mMaster.getName(), e); System.exit(-1); } finally { if (mJournalReader != null) { try { mJournalReader.close(); } catch (IOException e) { LOG.warn("{}: Failed to close the journal reader with error {}.", mMaster.getName(), e.getMessage()); } } } }

Target:
The finally block will not be executed?
Source:
public JournalReader getReader(JournalReaderOptions options) { if (options.getLocation() != null) { return new UfsJournalFileReader(options); } else { return new UfsJournalReader(this, options); } }

Target:
`UfsJournalReader` and `UfsJournalFileReader` are two separate concepts, they shouldn't be obtained through the same `getReader` call
Source:
public Master 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); }

Target:
Should this return a `FileSystemMaster` instead of just a `Master`?
Source:
protected File generateRelativeFileContent(String path, byte[] toWrite) throws IOException, FileNotFoundException { File testFile = new File(System.getProperty("user.dir") + path); testFile.createNewFile(); FileOutputStream fos = new FileOutputStream(testFile); fos.write(toWrite); fos.close(); return testFile; }

Target:
Does this work the same without including `System.getProperty("user.dir")`?
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." + " Specify -raw to print raw sizes." + " Specify -p to list all the pinned files."; }

Target:
keep options sorted alphabetically
Source:
public Collection<Master> getMasters() { 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; }

Target:
since the order matters for these, it would make more sense to return a List
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. 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(); is.close(); }

Target:
given `JournalInputStream` becomes closable, shall we use try-with-resource for safety?
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()); } catch (Exception e) { // this should never happen Assert.fail("unexpected exception" + e.getMessage()); } }

Target:
why are we using try-catch here?
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(); mEnd = mStart + request.getLength(); // Note that we do not need to seek to offset since the block worker is created at the offset. }

Target:
Use these values when creating the `BlockReader`?
Source:
private void createBlockFile(String blockPath) throws IOException { FileUtils.createBlockPath(blockPath); FileUtils.createFile(blockPath); FileUtils.changeLocalFileToFullPermission(blockPath); LOG.debug("Created new file block, block path: {}", blockPath); }

Target:
should this be a static method?
Source:
private BlockInfo getBlockInfo(long sessionId, long blockId) throws BlockDoesNotExistException { Key key = new Key(sessionId, blockId); BlockInfo blockInfo = mBlocks.get(key); if (blockInfo == null) { try { 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; }

Target:
please fix @peisun1115
Source:
public String toString() { return Objects.toStringHelper(this) .add("ufsPath", mUfsPath) .add("offset", mOffset) .add("blockSize", mBlockSize) .add("maxUfsReadConcurrency", mMaxUfsReadConcurrency).toString(); }

Target:
nit: sort fileds alphabetically
Source:
public long getServiceVersion() { LOG.debug("Enter GetServiceVersion."); long ret = Constants.FILE_SYSTEM_MASTER_CLIENT_SERVICE_VERSION; LOG.debug("Exit GetServiceVersion."); return ret; }

Target:
shall we remove this then?
Source:
public static BlockMasterClient create(InetSocketAddress masterAddress) { return new RetryHandlingBlockMasterClient(null, masterAddress); }

Target:
Would it be possible to use the factory throughout and make the constructors private? Its unclear when one should be used over the other
Source:
protected FileSystemMasterClient createNewResource() { FileSystemMasterClient client = new RetryHandlingFileSystemMasterClient(mSubject, mMasterAddress); mClientList.add(client); return client; }

Target:
Is it possible to make this use the factory?
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); waitForWorkerRegistration(store, 1, Constants.SECOND_MS); // If worker is successfully re-registered, the capacity bytes should not change. Assert.assertEquals(WORKER_CAPACITY_BYTES, store.getCapacityBytes()); } }

Target:
5 seconds might be better to weather interference from other builds
Source:
public void equalsTest() throws Exception { CommonTestUtils.testEquals(RenameOptions.class, "mOperationTimeMs"); }

Target:
NIT: `equals` instead of `equalsTest`?
Source:
private JournalContext() { mFlushCounter = AsyncJournalWriter.INVALID_FLUSH_COUNTER; }

Target:
NIT: I guess we could make `AsyncJournalWriter.INVALID_FLUSH_COUNTER` private now since it becomes completely an internal state. Up to you
Source:
public long getAutoSavePrefs() { int delay = preferences.getInt(UIConstants.Preferences.AUTO_SAVE_FILE, 15); if (delay > 0) { long delayInMilliseconds = 1000 * 60 * delay; return delayInMilliseconds; } return 0L; }

Target:
Die Methode muss nicht ```public``` sein, oder?
Source:
public String getOriginalFilePath() { Object path = tuples.get(FILE_PATH_LABEL); return path != null ? path.toString() : PATH_DEFAULT; }

Target:
Not sure we want a path value of "path" in the rest json. It just adds noise and data to the network transfer.
Source:
public int getVersion() { Object version = tuples.get(VERSION_LABEL); return version != null ? Integer.parseInt(version.toString()) : VERSION_DEFAULT; }

Target:
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.
Source:
public final void setPrimaryType( final UnitOfWork uow, final String typeName ) throws UnsupportedOperationException { throw new UnsupportedOperationException(); }

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

Target:
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.
Source:
public Component(Package pkg, String component){ mPackage = pkg; mComponent = component; }

Target:
Space before `{`
Source:
public void remove(RemoteFile file) throws IOException, JadbException { InputStream s = device.executeShell("rm", "-f", Bash.quote(file.getPath())); Stream.flushRead(s); s.close(); }

Target:
Nice :+1: To make it even better, use try-with-resource idiom.
Source:
public void launch(Package name) throws IOException, JadbException { InputStream s = device.executeShell("monkey", "-p", name.toString(), "-c", "android.intent.category.LAUNCHER", "1"); Stream.flushRead(s); s.close(); }

Target:
Why is this needed?
Source:
public void close() throws IOException { super.close(); transport.close(); }

Target:
Remember to revert this file, it should know about the transport class.
Source:
public int getMode(File file) { //noinspection OctalInteger return 0664; }

Target:
This does not need to be public, let's keep private
Source:
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.getMessage()); } }

Target:
Here the important inner exception gets lost, please pass e to `JadbException` constructor.
Source:
public void remove(RemoteFile file) throws IOException, JadbException { try (InputStream stream = device.executeShell("rm", "-f", Bash.quote(file.getPath()))) { Stream.flushRead(stream); stream.close(); } }

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

Target:
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.
Source:
public Map<String, String> getprop() throws IOException, JadbException { BufferedReader bufferedReader = null; try { bufferedReader = new BufferedReader(new InputStreamReader(device.executeShell("getprop"))); return parseProp(bufferedReader); } finally { if (bufferedReader != null) { bufferedReader.close(); } } }

Target:
Use `try-with-resources` please!
Source:
private String findAdbExecutable() { String android_home = System.getenv("ANDROID_HOME"); return android_home != null && !android_home.equals("")?android_home + "/platform-tools/adb":"adb"; }

Target:
I feel this one liner hurt readability, please use the previous syntax for clarity.
Source:
public String getVoxelId() { return voxelState.getId(); }

Target:
Qualify with `this.` Same goes everywhere.
Source:
public List<EntryDTO> getNotificationsBySourceAndCustomAttribute(String source, String attributeName, String attributeValue) { Validate.notBlank(source, "Argument 'source' cannot be blank"); Validate.notBlank(source, "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); }

Target:
Should line 89 be ``` java Validate.notBlank(attributeName, "Argument 'attributeName' cannot be blank"); ``` ?
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--; } lastRequest = request; lastResponse = response; return response; }

Target:
lastRequest should probably be set before we make the request too.
Source:
public Map<String, Integer> getTasksByPriority() { Map<String, Object> tasksByPriority = (Map<String, Object>) getRealtime().get(TASKS_BY_PRIORITY_PROPERTY); Map<String, Integer> tasksByPriorityMap = new HashMap<String, Integer>(); for (String priorityKey : tasksByPriority.keySet()) { tasksByPriorityMap.put(priorityKey, (Integer) tasksByPriority.get(priorityKey)); } return tasksByPriorityMap; }

Target:
you can use `tasksByPriority.entrySet()` here
Source:
private boolean checkPermission(String permission) { int res = this.ctx.checkCallingOrSelfPermission(permission); return (res == PackageManager.PERMISSION_GRANTED); }

Target:
// nitpick-mode-on Can you change `this.ctx` to `ctx`? // nitpick-mode-off
Source:
public Map<String, Object> getLocals() { if (locals == null || locals.length == 0) { return Collections.emptyMap(); } Map<String, Object> localsMap = null; for (Frame.LocalVariable localVariable : locals) { if (localVariable != null) { if (localsMap == null) { localsMap = new HashMap<>(); } localsMap.put(localVariable.getName(), localVariable.getValue()); } } return localsMap; }

Target:
Why is this instantiated here rather than on L47?
Source:
protected Collection<String> getInAppFrames(Dsn dsn) { if (dsn.getOptions().containsKey(IN_APP_FRAMES_OPTION)) { ArrayList<String> inAppPackages = new ArrayList<>(); for (String inAppPackage : dsn.getOptions().get(IN_APP_FRAMES_OPTION).split(",")) { if (!inAppPackage.trim().equals("")) { inAppPackages.add(inAppPackage); } } return inAppPackages; } return Collections.emptyList(); }

Target:
Stylistic nitpick: usually, in this case, I'd invert the conditional at the top and return the empty value immediately at the top of the function, rather than wrapping the bulk of the "real" code in the conditional block. (Is this not idomatic Java style?)
Source:
public static int parseInteger(String value, int defaultValue) { if (isNullOrEmpty(value)) { return defaultValue; } try { return Integer.parseInt(value); } catch (NumberFormatException e) { return defaultValue; } }

Target:
It'd probably be worth logging if is an invalid value rather than silently ignoring the input value.
Source:
public Raven createRavenInstance(Dsn dsn) { Raven raven = new Raven(); raven.setConnection(createConnection(dsn)); try { // `ServletRequestListener` was added in the Servlet 2.4 API, and // is used as part of the `HttpEventBuilderHelper`, see: // https://tomcat.apache.org/tomcat-5.5-doc/servletapi/ Class.forName("javax.servlet.ServletRequestListener", false, this.getClass().getClassLoader()); raven.addBuilderHelper(new HttpEventBuilderHelper()); raven.addBuilderHelper(new ContextBuilderHelper(raven)); } catch (ClassNotFoundException e) { logger.debug("The current environment doesn't provide access to servlets," + "or provides an unsupported version."); } return raven; }

Target:
I don't think this needs to be in this `try`/`catch` block — shouldn't this be unrelated to the HTTP helper?
Source:
IngestJob(Content dataSource, List<AbstractFile> files, IngestJobSettings settings) { this.id = IngestJob.nextId.getAndIncrement(); this.ingestJobPipelines = new ConcurrentHashMap<>(); this.settings = settings; this.files = files; this.dataSources.add(dataSource); this.ingestMode = Mode.BATCH; incompleteJobsCount = new AtomicInteger(1); cancellationReason = CancellationReason.NOT_CANCELLED; }

Target:
The first two constructors have a lot of duplicated code. Perhaps this can be reduced by having one call the other?
Source:
void addStreamingIngestFiles(List<Long> fileObjIds) { if (stage.equals(Stages.FIRST_STAGE_FILES_ONLY) || stage.equals(Stages.FIRST_STAGE_FILES_AND_DATASOURCE)) { IngestJobPipeline.taskScheduler.scheduleStreamedFileIngestTasks(this, fileObjIds); } else { logErrorMessage(Level.SEVERE, "Adding streaming files to job during stage " + stage.toString() + " not supported"); } }

Target:
Stages.FIRST_STAGE_FILES_AND_DATASOURCE applies here?
Source:
public void add(GeoLocationParseResult<T> toAdd) { this.successfullyParsed = (this.successfullyParsed == false) ? false : toAdd.isSuccessfullyParsed(); this.items.addAll(toAdd.getItems()); }

Target:
I believed Codacy flagged this. I think this could be replaced with this.successfullyParsed &&= toAdd.isSuccessfullyParsed().
Source:
void executeSearch() { Collection<Persona> results = Collections.EMPTY_LIST; try { results = Persona.getPersonaByName(searchField.getText()); } catch (CentralRepoException ex) { Exceptions.printStackTrace(ex); } updateResultsTable(results); }

Target:
this method could be private
Source:
List<String> getTypes() { List<String> types = new ArrayList(counts.keySet()); Collections.sort(types); return types; }

Target:
This method causes several build warning.
Source:
public boolean isSupported() { // get the MIME type String mimeType = file.getMIMEType(); // if it is not present, attempt to use the FileTypeDetector to determine if (StringUtils.isEmpty(mimeType)) { FileTypeDetector fileTypeDetector = null; try { fileTypeDetector = new FileTypeDetector(); } catch (FileTypeDetector.FileTypeDetectorInitException ex) { logger.log(Level.SEVERE, "Unable to create file type detector for determining MIME type."); return false; } mimeType = fileTypeDetector.getMIMEType(file); // if able to determine mime type, if (!StringUtils.isEmpty(mimeType)) file.setMIMEType(mimeType); } return PLAIN_TEXT_MIME_TYPE.equals(mimeType); }

Target:
Let's just remove the call, thanks.
Source:
public WrapLayoutRow(List<Component> components, List<Component> oppositeAligned, int height, int width) { this.components = components; this.oppositeAligned = oppositeAligned; this.height = height; this.width = width; }

Target:
public constructor in private class should be package level constructor.
Source:
protected void addOriginalNameProp(Sheet.Set properties) { if (TextTranslationService.getInstance().hasProvider() && UserPreferences.displayTranslatedFileNames()) { properties.put(new NodeProperty<>( ORIG_NAME_PROP_NAME, ORIG_NAME_PROP_DISPLAY_NAME, "", translatedName != null ? translatedName : "")); if (translatedName == null) { new FileNameTransTask(originalName, this, new NameTranslationListener()).submit(); } } }

Target:
This is the wrong substitution if translatedName is not null.
Source:
public void setAccountId(Long accountId) { this.accountId = accountId; }

Target:
Is a public setter necessary? Can the abstraction be the CentralRepositoryAccount instance itself, rather than the primitive?
Source:
public XRYKeyValuePair(String key, String value, String namespace) { this.key = key.trim(); this.value = value.trim(); this.namespace = namespace.trim(); }

Target:
public constructor in non-public class
Source:
public String getItemType() { return DisplayableItemNode.FILE_PARENT_NODE_KEY; }

Target:
This node can't be a file parent, so it should have its own key.
Source:
public static XRYFileParser get(String reportType) { if (reportType == null) { throw new IllegalArgumentException("Report type cannot be null"); } switch (reportType.toLowerCase()) { case "calls": return new XRYCallsFileParser(); case "contacts/contacts": return new XRYContactsFileParser(); case "device/general information": return new XRYDeviceGenInfoFileParser(); case "messages/sms": return new XRYMessagesFileParser(); case "web/bookmarks": return new XRYWebBookmarksFileParser(); default: throw new IllegalArgumentException(reportType + " not recognized."); } }

Target:
Public methods on package access classes seem a little strange to me.
Source:
static void writeModel(NaiveBayesModel model) throws IOException { ensureTextClassifierFolderExists(); FileWriter fw = new FileWriter(new File(MODEL_PATH)); PlainTextNaiveBayesModelWriter modelWriter; modelWriter = new PlainTextNaiveBayesModelWriter(model, new BufferedWriter(fw)); modelWriter.persist(); fw.close(); }

Target:
When this throws an exception the file writer may not get closed, consider a try with resources.
Source:
public ResultSet runQuery(String queryStr) throws TskCoreException { ResultSet resultSet = null; try { resultSet = statement.executeQuery(queryStr); //NON-NLS } catch (SQLException ex) { throw new TskCoreException("Error running app SQLite query. " + ex.getMessage(), ex); } return resultSet; }

Target:
Why wrap into a TskCoreException? The query is not run on the case database. Furthermore, the client will need to catch a SQLException anyway in order to interact with the ResultSet.
Source:
void nextPage() { currentPage++; DataResultViewerTable.this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); postPageChangeEvent(); DataResultViewerTable.this.setCursor(null); }

Target:
But that has nothing to do with logical imager cancellation and shouldn't be in this PR.
Source:
public void cancel() { if (addLogicalImageTask != null) { thread.interrupt(); addLogicalImageTask.cancelTask(); } }

Target:
Is this still necessary? And saving the thread in general?
Source:
public int size() { return items.size(); }

Target:
does not need to be public in non-public class
Source:
public static String getTextClassifierPath() { return getUserDirectory().getAbsolutePath() + File.separator + TEXT_CLASSIFIERS_SUBDIRECTORY; }

Target:
does not need to be public in non-public class
Source:
public void updateStatusLabel(String statusMessage) { if (status != ReportStatus.CANCELED) { logger.log(Level.INFO, "Report Progress Logger status update: {0}", statusMessage); } }

Target:
I don't think that "Report Progress Logger status update:" will add anything to the logs, which will tell us the call site of the message. Logging the message from the report module should be sufficient.
Source:
public GetSCOTask(WeakReference<AbstractContentNode<?>> weakContentRef, PropertyChangeListener listener) { this.weakNodeRef = weakContentRef; this.listener = listener; }

Target:
public in non-public class, can have public removed
Source:
private void deleteDataSource(Long dsObjId) { String dataSourceId = Long.toString(dsObjId); String deleteQuery = "image_id:" + dataSourceId; try { // Get the first result. UpdateResponse updateResponse = solrCore.deleteByQuery(deleteQuery); } catch (SolrServerException | IOException ex) { logger.log(Level.SEVERE, "Error deleting content from Solr. Solr image id " + dataSourceId, ex); //NON-NLS } }

Target:
As above for the DeleteDataSourceAction, low level classes should propagate exceptions for handling by the top level classes. E.g., here, how does the Server know what the performAction needs to do in its context of a menu selection in the UI by a user? These exceptions should propagate to the public deleteDataSource method above, which should propagate all errors, and so on, up the chain. The exceptions can be wrapped in other exceptions as needed.
Source:
int getZoneId() { int zoneValue = -1; String value = dataMap.get(ZONE_ID); if (value != null) { zoneValue = Integer.parseInt(value); } return zoneValue; }

Target:
ZoneIdentifierInfo is a private inner class so this point is debatable, but codacy suggests all the accessor methods of ZoneIdentifierInfo should also be private.
Source:
public void setFile(AbstractFile file) { WindowManager.getDefault().getMainWindow().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); abstractFile = file; htmlPanel.setHtmlText(getHtmlText(file)); WindowManager.getDefault().getMainWindow().setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); }

Target:
variable named abstractFile does not exist, which prevents pr from building
Source:
private void init() { getRootPane().registerKeyboardAction( action -> { setVisible(false); }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_IN_FOCUSED_WINDOW); multiUserCasesPanel = new OpenMultiUserCasePanel(this); add(multiUserCasesPanel); pack(); setResizable(false); }

Target:
Hitting ESC doesn't seem to do anything for me
Source:
synchronized private void shutDownDBExecutor() { if (dbExecutor != null) { dbExecutor.shutdownNow(); try { dbExecutor.awaitTermination(30, TimeUnit.SECONDS); } catch (InterruptedException ex) { logger.log(Level.WARNING, "Image Gallery failed to shutdown DB Task Executor in a timely fashion.", ex); } dbExecutor = null; } }

Target:
is it necessary to null out dbExecutor? Won't it be garbage collected when the enclosing ImageGalleryController is garbage collected?
Source:
public EventAddedEvent(org.sleuthkit.datamodel.TimelineManager.EventAddedEvent event) { super(Case.Events.EVENT_ADDED.name(), null, event.getAddedEvent().getEventID()); addedEvent = event.getAddedEvent(); addedEventID = addedEvent.getEventID(); }

Target:
It seems like passing the event id to the super class constructor and also making it a field might be a little confusing. Personally, I prefer the approach used in DataSourceAddedEvent where the id of the object is obtained in getNewValue via long id = (Long) super.getNewValue() and the "extra" field is not required. Thoughts?
Source:
private void syncGroupControlsEnabledState(GroupViewState newViewState) { boolean noGroupSelected = newViewState == null || newViewState.getGroup() == null; tagGroupMenuButton.setDisable(noGroupSelected); catGroupMenuButton.setDisable(noGroupSelected); }

Target:
I'd put these booleans into parentheses for easier reading.
Source:
void setTaskCompletionStatus(boolean status) { taskCompletionStatus = status; }

Target:
I think this should be protected, not package access.
Source:
boolean isFlaggedAsZipBomb() { return flaggedAsZipBomb; }

Target:
Are there any multithreading issues here? Can two threads be accessing the same root Archive object?
Source:
Keyword(String searchTerm, boolean isLiteral, boolean isWholeWord) { this.searchTerm = Normalizer.normalize(searchTerm, Normalizer.Form.NFKD);; this.isLiteral = isLiteral; this.isWholeWord = isWholeWord; this.listName = ""; this.originalTerm = searchTerm; }

Target:
Can you have this constructor call the 5 parameter one instead of it assigning the values?
Source:
private AddEditCentralRepoCommentAction(AbstractFile file, String title) throws EamDbException, NoCurrentCaseException, TskCoreException { super(title); this.title = title; correlationAttribute = EamArtifactUtil.getCorrelationAttributeFromContent(file); if (correlationAttribute == null) { addToDatabase = true; correlationAttribute = EamArtifactUtil.makeCorrelationAttributeFromContent(file); } }

Target:
Looking at this again, I don't think anything in here actually throws an exception and you can get rid of the entire "throws" part. This should allow you to remove the exception handling from createAddEditCentralRepoCommentAction, and possibly get rid of the new exception class if it isn't used anywhere else.
Source:
} catch (UnsatisfiedLinkError e) { tempOpenCvLoaded = false; System.out.println("OpenCV native library failed to load " + e.toString()); }

Target:
Leftover debug line - edit not leftover, it's just that the logger is not available. Suggested saving the error string to display when creating the exception a few lines down.
Source:
public void tearDown() { try { Case.closeCurrentCase(); //Seems like we need some time to close the case. try { Thread.sleep(2000); } catch (InterruptedException ex) { } FileUtils.deleteDirectory(CASE_DIR); } catch (CaseActionException | IOException ex) { Exceptions.printStackTrace(ex); } assertFalse(CASE_DIR.exists()); }

Target:
This delete frequently fails (it worked a few times but is failing consistantly now for me) to delete the case dir in User\AppData\Local\Temp causing the test to fail.
Source:
CommonFilesSearchNode(CommonFilesMetaData metaData) { super(Children.create(new CommonFilesChildren(metaData), true), Lookups.singleton(metaData)); children = this.getChildren(); }

Target:
We don't need it.
Source:
public static Case getOpenCase() throws NoCurrentCaseException { try { Case openCase = new Case(currentCase.getCaseType(), currentCase.getCacheDirectory(), new CaseDetails(currentCase.getDisplayName(), currentCase.getNumber(), currentCase.getExaminer(), currentCase.getExaminerPhone(), currentCase.getExaminerEmail(), currentCase.getCaseNotes())); return openCase; } catch (NullPointerException ex) { throw new NoCurrentCaseException(); } }

Target:
For this fix, we should be making a local copy of the reference in currentCase, checking the local reference for null, and finally returning the local reference. This does not prevent another thread from closing the case, but it does make things a bit better because we will at least not risk returning null and violating the contract of the method. Dealing with the possibility of the current case being closed while other objects have a reference to it is a much bigger problem for another story.
Source:
public PListViewer() { // Create an Outlineview and add to the panel outlineView = new org.openide.explorer.view.OutlineView(); initComponents(); outline = outlineView.getOutline(); ((DefaultOutlineModel) outline.getOutlineModel()).setNodesColumnLabel("Key"); Bundle.PListNode_KeyCol(); outlineView.setPropertyColumns( "Type", Bundle.PListNode_TypeCol(), "Value", Bundle.PListNode_ValueCol()); customize(); }

Target:
Looks for me this line is an extra: Bundle.PListNode_KeyCol();
Source:
private ContentViewer getSupportingViewer(String mimeType) { return mimeTypeToViewerMap.containsKey(mimeType) ? mimeTypeToViewerMap.get(mimeType) : null; }

Target:
Map.get(key) already returns null if he key is not contained in the map.
Source:
public synchronized TagName addTagName(String displayName, String description, TagName.HTML_COLOR color) throws TagNameAlreadyExistsException, TskCoreException { TskData.FileKnown knownStatus = TskData.FileKnown.UNKNOWN; if (getNotableTagDisplayNames().contains(displayName)) { knownStatus = TskData.FileKnown.BAD; } return addTagName(displayName, description, color, knownStatus); }

Target:
Let's just go ahead and pass unknown to the four args method, I think it will be a tad simpler.
Source:
public void setup() throws Exception { System.setProperty("java.naming.factory.initial", "org.osjava.sj.SimpleContextFactory"); System.setProperty("org.osjava.sj.root", "file://src/test/resources"); System.setProperty("org.osjava.sj.delimiter", "."); System.setProperty("jndi.syntax.separator", "/"); System.setProperty("org.osjava.sj.space", "java:/comp/env"); this.initContext = new InitialContext(); }

Target:
If we are going to use System properties shouldn't we reset them when the test tears down? We don't want any unexpected side effects when other tests run.
Source:
public int partition(String topic, Object key, byte[] keyBytes, Object value, byte[] valueBytes, Cluster cluster) { if (((String)key).length() % 2 == 0) return 0; return 1; }

Target:
use of braces is generally considered a best practice in this situation, even though not required by the language
Source:
public void whenSerializingJava8DateAndReadingValue_thenCorrect() throws IOException { final String stringDate = "\"2014-12-20\""; final ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new JavaTimeModule()); mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); final String result2 = mapper.readValue(stringDate, LocalDate.class) .toString(); assertThat(result2, containsString("2014-12-20")); }

Target:
This is an odd way to test serialization: load it into an object and then do `toString` on that object. Can we not assert the fields of the LocalDate object? At a glance, this just looks like string processing, even though there's a date object in the middle.
Source:
public Future<Response> apply(Request request, Service<Request, Response> service) { System.out.println("Request host:" + request.host().getOrElse(() -> "")); System.out.println("Request params:"); request.getParams().forEach(entry -> System.out.println("\t" + entry.getKey() + " : " + entry.getValue())); return service.apply(request); }

Target:
if the stdouts are irrelevant let's remove them
Source:
protected void configure(HttpSecurity http) throws Exception { http.httpBasic() .and() .authorizeRequests() .antMatchers(HttpMethod.GET, "/user/**") .hasRole("USER") .and() .logout() .logoutUrl("/user/logout") .addLogoutHandler(logoutHandler) .logoutSuccessHandler((new HttpStatusReturningLogoutSuccessHandler(HttpStatus.OK))) .permitAll() .and() .csrf() .disable() .formLogin() .disable(); }

Target:
Hey @kirill-vlasov - sorry to be picky but seems to be an extra set of brackets here?
Source:
protected IDataSet getDataSet() throws Exception { try (java.io.InputStream resourceAsStream = getClass() .getClassLoader() .getResourceAsStream("dbunit/data.xml")) { return new FlatXmlDataSetBuilder().build(resourceAsStream); } }

Target:
let's use imports on this one and the following
Source:
@Override protected javax.sql.DataSource getDataSource() { JdbcDataSource dataSource = new JdbcDataSource(); dataSource.setURL(JDBC_URL); dataSource.setUser("sa"); dataSource.setPassword(""); return dataSource; }

Target:
why? let's format it properly, it was ok before. annotations and method definitions on different lines
Source:
public void shouldNotTimeout() { try { WebTestClient.ResponseSpec response = webTestClient.get() .uri("/timeout/{timeout}", 1) .exchange(); response.expectStatus() .isOk() .expectBody(String.class) .isEqualTo("OK"); } catch (ReadTimeoutException e) { Assert.fail(); } }

Target:
I would remove this since the exception fails the test, and it's better to have that reported then to hide it
Source:
public void shouldTimeout() { exception.expect(ReadTimeoutException.class); webTestClient.get() .uri("/timeout/{timeout}", 3) .exchange(); Assert.fail(); }

Target:
this can now be removed because if the exception is not thrown, JUnit it will fail it since it was expecting it