auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
START public void removeResultGroupRelations(PerunSession sess, Group resultGroup) { END jdbc.update("DELETE FROM groups_groups WHERE result_gid = ?", resultGroup.getId()); jdbc.update("DELETE FROM groups_members WHERE group_id = ? AND membership_type != ?", resultGroup.getId(), MembershipType.DIRECT.getCode()); } In redmine 2630.

Target:
public void removeResultGroupRelations(PerunSession sess, Group resultGroup) { jdbc.update("DELETE FROM groups_groups WHERE result_gid = ?", resultGroup.getId()); }
Source:
public void checkAttributeValue(PerunSessionImpl sess, User user, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException { String attributeValue = null; START Matcher emailMatcher = Utils.emailPattern.matcher(attributeValue); END if (!emailMatcher.find()) { throw new WrongAttributeValueException(attribute, user, "Email is not in correct form."); } } Variable attributeValue always contains null (see line 24), therefore this matcher will never match.

Target:
public void checkAttributeValue(PerunSessionImpl sess, User user, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException { String attributeValue = (String) attribute.getValue(); Matcher emailMatcher = Utils.emailPattern.matcher(attributeValue); if (!emailMatcher.find()) { throw new WrongAttributeValueException(attribute, user, "Email is not in correct form."); } }
Source:
public void checkAttributeValue(PerunSessionImpl perunSession, Facility facility, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException, WrongAttributeAssignmentException { //Null is ok, it means use default permissions in script (probably 0700) if(attribute.getValue() == null) return; String attrValue = (String) attribute.getValue(); START Pattern pattern = Pattern.compile("^[01234567]?[01234567]{3}$"); END Matcher match = pattern.matcher(attrValue); if(!match.matches()) throw new WrongAttributeValueException(attribute, facility, "Bad format of attribute, (expected something like '750' or '0700')."); } Pattern should be compiled only once. Please move it outside from method.

Target:
public void checkAttributeValue(PerunSessionImpl perunSession, Facility facility, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException, WrongAttributeAssignmentException { //Null is ok, it means use default permissions in script (probably 0700) if(attribute.getValue() == null) return; String attrValue = (String) attribute.getValue(); Matcher match = pattern.matcher(attrValue); if(!match.matches()) throw new WrongAttributeValueException(attribute, facility, "Bad format of attribute, (expected something like '750' or '0700')."); }
Source:
public List<RichGroup> convertGroupsToRichGroupsWithAttributes(PerunSession sess, List<Group> groups) throws InternalErrorException { List<RichGroup> richGroups = new ArrayList<>(); START for(Group group: groups) END richGroups.add(new RichGroup(group, this.getPerunBl().getAttributesManagerBl().getAttributes(sess, group))); return richGroups; } Even if there is only 1 row in "for cyclus" i prefer using '{' and '}' for better reading.

Target:
public List<RichGroup> convertGroupsToRichGroupsWithAttributes(PerunSession sess, List<Group> groups) throws InternalErrorException { List<RichGroup> richGroups = new ArrayList<>(); for(Group group: groups) { richGroups.add(new RichGroup(group, this.getPerunBl().getAttributesManagerBl().getAttributes(sess, group))); } return richGroups; }
Source:
public void checkAttributeValue(PerunSessionImpl perunSession, Facility facility, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException { //Null means the same like 0 (not enabled) if(attribute.getValue() == null) return; Integer quotaEnabled = (Integer) attribute.getValue(); START if(quotaEnabled > 1 || quotaEnabled < 0) throw new WrongAttributeValueException(attribute, "Attribute has only two possible options for quota: 0 - means not enabled, 1 - means enabled."); END } Please add attribute holder to the exception parameters.

Target:
public void checkAttributeValue(PerunSessionImpl perunSession, Facility facility, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException { //Null means the same like 0 (not enabled) if(attribute.getValue() == null) return; Integer quotaEnabled = (Integer) attribute.getValue(); if(quotaEnabled > 1 || quotaEnabled < 0) throw new WrongAttributeValueException(attribute, facility, null, "Attribute has only two possible options for quota: 0 - means not enabled, 1 - means enabled."); }
Source:
public void checkFormatOfShell(String shell, Attribute attribute) throws WrongAttributeValueException { //previous regex ^/[-a-zA-Z0-9_/]*$" Pattern pattern = Pattern.compile("^(/[-_a-zA-Z0-9]+)+$"); Matcher match = pattern.matcher(shell); if (!match.matches()) { throw new WrongAttributeValueException(attribute, "Bad shell attribute format " + shell); } START if(!shell.startsWith("/")) { END throw new WrongAttributeValueException(attribute, "Shell " + shell + " doesnt start with /"); } } This is already covered on line 524, isn't it?

Target:
public void checkFormatOfShell(String shell, Attribute attribute) throws WrongAttributeValueException { //previous regex ^/[-a-zA-Z0-9_/]*$" Pattern pattern = Pattern.compile("^(/[-_a-zA-Z0-9]+)+$"); Matcher match = pattern.matcher(shell); if (!match.matches()) { throw new WrongAttributeValueException(attribute, "Bad shell attribute format " + shell); } }
Source:
public VehicleLocationRecordBean getVehicleLocationRecordForVehicleId( AgencyAndId vehicleId, long targetTime) { TargetTime target = new TargetTime(targetTime, targetTime); START if (_blockLocationService == null) { END _log.error("blocklocationservice is null"); return null; } BlockLocation blockLocation = _blockLocationService.getLocationForVehicleAndTime( vehicleId, target); if (blockLocation == null) return null; return getBlockLocationAsVehicleLocationRecord(blockLocation); } Now that you've added the setBlockLocationService(...) with @Autowired you can probably remove this null check, since it shouldn't ever be null.

Target:
public VehicleLocationRecordBean getVehicleLocationRecordForVehicleId( AgencyAndId vehicleId, long targetTime) { TargetTime target = new TargetTime(targetTime, targetTime); BlockLocation blockLocation = _blockLocationService.getLocationForVehicleAndTime( vehicleId, target); if (blockLocation == null) return null; return getBlockLocationAsVehicleLocationRecord(blockLocation); }
Source:
public OutputStream openOutputStream(String filePath) throws IOException { try { DistributedLogManager dlm = namespace.openLog( filePath); LedgerMetadata metadata = new LedgerMetadata(); metadata.setApplication(Constants.LEDGER_METADATA_APPLICATION_STREAM_STORAGE); START metadata.setComponent("checkpoint-store"); END AsyncLogWriter writer = Utils.ioResult(dlm.openAsyncLogWriter()); return new BufferedOutputStream( new DLOutputStream(dlm, writer), 128 * 1024); } catch (LogNotFoundException le) { throw new FileNotFoundException(filePath); } } this looks like a dead store, you are not using this variable

Target:
public OutputStream openOutputStream(String filePath) throws IOException { try { DistributedLogManager dlm = namespace.openLog( filePath); LedgerMetadata metadata = new LedgerMetadata(); metadata.setApplication(Constants.LEDGER_METADATA_APPLICATION_STREAM_STORAGE); metadata.setComponent("checkpoint-store"); AsyncLogWriter writer = Utils.ioResult(dlm.openAsyncLogWriter(metadata)); return new BufferedOutputStream( new DLOutputStream(dlm, writer), 128 * 1024); } catch (LogNotFoundException le) { throw new FileNotFoundException(filePath); } }
Source:
public void process(int journalVersion, long offset, ByteBuffer entry) throws IOException { if (!printJournalVersion) { START System.out.println("Journal Version : " + journalVersion); END printJournalVersion = true; } } Use Logger please

Target:
public void process(int journalVersion, long offset, ByteBuffer entry) throws IOException { LOG.warn("Journal Version : " + journalVersion); }
Source:
public CRC32CDigestManager(long ledgerId, boolean useV2Protocol, ByteBufAllocator allocator) { super(ledgerId, useV2Protocol, allocator); if (!Sse42Crc32C.isSupported() && !nonSupportedMessagePrinted) { START log.error("Sse42Crc32C is not supported, will use a slower CRC32C implementation."); END nonSupportedMessagePrinted = true; } } Can we still make this logging statement to `warn`?

Target:
public CRC32CDigestManager(long ledgerId, boolean useV2Protocol, ByteBufAllocator allocator) { super(ledgerId, useV2Protocol, allocator); if (!Sse42Crc32C.isSupported() && !nonSupportedMessagePrinted) { log.warn("Sse42Crc32C is not supported, will use a slower CRC32C implementation."); nonSupportedMessagePrinted = true; } }
Source:
public long getLastStoredEntryId() { START Long lastEntry = LedgerHandle.INVALID_ENTRY_ID; END for (int bookieIndex : bookieIndexes) { Long lastStoredEntryIdForBookie = getLastStoredEntryId(bookieIndex); if (lastStoredEntryIdForBookie != LedgerHandle.INVALID_ENTRY_ID) { if (lastEntry == LedgerHandle.INVALID_ENTRY_ID) { lastEntry = lastStoredEntryIdForBookie; } else { lastEntry = Math.max(lastEntry, lastStoredEntryIdForBookie); } } } return lastEntry; } this can be 'long' instead of 'Long'

Target:
public long getLastStoredEntryId() { long lastEntry = LedgerHandle.INVALID_ENTRY_ID; for (int bookieIndex : bookieIndexes) { Long lastStoredEntryIdForBookie = getLastStoredEntryId(bookieIndex); if (lastStoredEntryIdForBookie != LedgerHandle.INVALID_ENTRY_ID) { if (lastEntry == LedgerHandle.INVALID_ENTRY_ID) { lastEntry = lastStoredEntryIdForBookie; } else { lastEntry = Math.max(lastEntry, lastStoredEntryIdForBookie); } } } return lastEntry; }
Source:
protected void doStart() { try { this.server.start(); } catch (Throwable exc) { LOG.error("Got unexpected exception while starting BookieServer", exc); if (uncaughtExceptionHandler != null) { START LOG.error("Calling uncaughtExceptionHandler"); END uncaughtExceptionHandler.uncaughtException(Thread.currentThread(), exc); } else { throw new RuntimeException("Failed to start bookie server", exc); } } } nit: add more details to this log line?

Target:
protected void doStart() { try { this.server.start(); } catch (InterruptedException exc) { throw new RuntimeException("Failed to start bookie server", exc); } }
Source:
protected void doStart() { try { this.main.start(); } catch (Throwable exc) { START LOG.error("Got unexpected exception while starting AutoRecoveryMain", exc); END if (uncaughtExceptionHandler != null) { LOG.error("Calling uncaughtExceptionHandler"); uncaughtExceptionHandler.uncaughtException(Thread.currentThread(), exc); } else { throw new RuntimeException("Failed to start AutoRecoveryMain", exc); } } } Lets move this to AbstractLifecycle#start() method, since exceptions can happen in any component start.

Target:
protected void doStart() { this.main.start(); }
Source:
public long getTLSCertFilesRefreshDurationSeconds() { START return getLong(TLS_CERT_FILES_REFRESH_DURATION_SECONDS, 300); END } It should be disabled by default

Target:
public long getTLSCertFilesRefreshDurationSeconds() { return getLong(TLS_CERT_FILES_REFRESH_DURATION_SECONDS, 0); }
Source:
Future<?> triggerGC(final boolean force, final boolean suspendMajor, final boolean suspendMinor) { return gcExecutor.submit(() -> { try { runWithFlags(force, suspendMajor, suspendMinor); } catch (Exception e) { LOG.warn("Failed to complete gc {}", e.getMessage(), e); } START }); END } it would be better not to reformat code, as this changes makes the diff harder to review. Can you revert the formatting ? as soon as checkstyle is happy we are okay

Target:
Future<?> triggerGC(final boolean force, final boolean suspendMajor, final boolean suspendMinor) { return gcExecutor.submit(() -> { runWithFlags(force, suspendMajor, suspendMinor); }); }
Source:
public void safeRun() { boolean force = forceGarbageCollection.get(); boolean suspendMajor = suspendMajorCompaction.get(); boolean suspendMinor = suspendMinorCompaction.get(); try { runWithFlags(force, suspendMajor, suspendMinor); } catch (Exception e) { START LOG.warn("Failed to complete gc {}", e.getMessage(), e); END } if (force) { // only set force to false if it had been true when the garbage // collection cycle started forceGarbageCollection.set(false); } } if we are catching "Exception" any time you call runWithFlags.... why don't catch the error inside runWithFlags and leave the previous signature ? catch (Exception) is a code smell, do we really need it ?

Target:
public void safeRun() { boolean force = forceGarbageCollection.get(); boolean suspendMajor = suspendMajorCompaction.get(); boolean suspendMinor = suspendMinorCompaction.get(); runWithFlags(force, suspendMajor, suspendMinor); if (force) { // only set force to false if it had been true when the garbage // collection cycle started forceGarbageCollection.set(false); } }
Source:
START public PlacementResult(T result, boolean adhering) { END this.result = result; this.adhering = adhering; } I am fine with either approach.

Target:
private PlacementResult(T result, boolean adhering) { this.result = result; this.adhering = adhering; }
Source:
public long getCtime() { START return ctime.orElse(metadataStoreCtime.orElse(-1L)); END } isn't this a behavior change?

Target:
public long getCtime() { return ctime; }
Source:
public void setExceptionHandler(UncaughtExceptionHandler exceptionHandler) { this.uncaughtExceptionHandler = exceptionHandler; START this.bookie.setExceptionHandler(exceptionHandler); END } nit: since bookie is not final, there can be possibility `bookie` is null if these methods are not called in correct order. can we add `final` modifier to `bookie` field?

Target:
public void setExceptionHandler(UncaughtExceptionHandler exceptionHandler) { this.uncaughtExceptionHandler = exceptionHandler; }
Source:
public void close() throws IOException { START IOUtils.close(log, activeLogChannel); END } unrelated note. With current method definition ```java public static void close(Logger log, java.io.Closeable... closeables) { ``` java will create new Object[] for single closeable that is passed to the method. We'll benefit from a variant that takes only one parameter. Do we ever use this method with more than one closeable?

Target:
public void close() throws IOException { if (activeLogChannel != null) { activeLogChannel.close(); } }
Source:
START protected synchronized void closeLedgerManagerFactory() { END LedgerManagerFactory lmToClose; synchronized (this) { lmToClose = lmFactory; lmFactory = null; } if (null != lmToClose) { try { lmToClose.close(); } catch (IOException e) { log.warn("Failed to close zookeeper based ledger manager", e); } } } you already synchronized at line 261, do we still need this?

Target:
protected void closeLedgerManagerFactory() { LedgerManagerFactory lmToClose; synchronized (this) { lmToClose = lmFactory; lmFactory = null; } if (null != lmToClose) { try { lmToClose.close(); } catch (IOException e) { log.warn("Failed to close zookeeper based ledger manager", e); } } }
Source:
static BookKeeper createBookKeeperClient(ServerConfiguration conf) throws InterruptedException, IOException { ClientConfiguration clientConfiguration = new ClientConfiguration(conf); clientConfiguration.setClientRole(ClientConfiguration.CLIENT_ROLE_SYSTEM); START LOG.info("AuthProvider used by the Auditor is {}", END clientConfiguration.getClientAuthProviderFactoryClass()); try { return BookKeeper.forConfig(clientConfiguration).build(); } catch (BKException e) { throw new IOException("Failed to create bookkeeper client", e); } } I think this logging doesn't belong to this method. it should be kept at `initialize` method.

Target:
static BookKeeper createBookKeeperClient(ServerConfiguration conf) throws InterruptedException, IOException { ClientConfiguration clientConfiguration = new ClientConfiguration(conf); clientConfiguration.setClientRole(ClientConfiguration.CLIENT_ROLE_SYSTEM); try { return BookKeeper.forConfig(clientConfiguration).build(); } catch (BKException e) { throw new IOException("Failed to create bookkeeper client", e); } }
Source:
public SettableFuture<Boolean> fenceLedger(long ledgerId, byte[] masterKey) START throws IOException, BookieException, InterruptedException { END LedgerDescriptor handle = handles.getHandle(ledgerId, masterKey); return handle.fenceAndLogInJournal(getJournal(ledgerId)); } Same problem here

Target:
public SettableFuture<Boolean> fenceLedger(long ledgerId, byte[] masterKey) throws IOException, BookieException { LedgerDescriptor handle = handles.getHandle(ledgerId, masterKey); return handle.fenceAndLogInJournal(getJournal(ledgerId)); }
Source:
void maybeHandleDelayedWriteBookieFailure() { synchronized (metadataLock) { if (delayedWriteFailedBookies.isEmpty()) { return; } START Map<Integer, BookieSocketAddress> toReplace = new HashMap<>(); END toReplace.putAll(delayedWriteFailedBookies); delayedWriteFailedBookies.clear(); // Original intent of this change is to do a best-effort ensemble change. // But this is not possible until the local metadata is completely immutable. // Until the feature "Make LedgerMetadata Immutable #610" Is complete we will use // handleBookieFailure() to handle delayed writes as regular bookie failures. handleBookieFailure(toReplace); } } the existing code to construct the hashmap from `delayedWriteFailedBookies`. it is one line code. any reason why do you split into 2 lines?

Target:
void maybeHandleDelayedWriteBookieFailure() { synchronized (metadataLock) { if (delayedWriteFailedBookies.isEmpty()) { return; } Map<Integer, BookieSocketAddress> toReplace = new HashMap<>(delayedWriteFailedBookies); delayedWriteFailedBookies.clear(); // Original intent of this change is to do a best-effort ensemble change. // But this is not possible until the local metadata is completely immutable. // Until the feature "Make LedgerMetadata Immutable #610" Is complete we will use // handleBookieFailure() to handle delayed writes as regular bookie failures. handleBookieFailure(toReplace); } }
Source:
START ConcurrentHashMap<Long, LedgerData> getBookieData(BookieSocketAddress addr) { END return data.computeIfAbsent(addr, (key) -> new ConcurrentHashMap<>()); } "public" or "private" ?

Target:
private ConcurrentHashMap<Long, LedgerData> getBookieData(BookieSocketAddress addr) { return data.computeIfAbsent(addr, (key) -> new ConcurrentHashMap<>()); }
Source:
public void close() throws IOException { Set<BufferedLogChannelWithDirInfo> copyOfCurrentLogsWithDirInfo = getCopyOfCurrentLogs(); for (BufferedLogChannelWithDirInfo currentLogWithDirInfo : copyOfCurrentLogsWithDirInfo) { START IOUtils.close(log, currentLogWithDirInfo.getLogChannel()); END } } any reason why "IOUtils.close" is called instead of "currentLogWithDirInfo.getLogChannel().close()"

Target:
public void close() throws IOException { Set<BufferedLogChannelWithDirInfo> copyOfCurrentLogsWithDirInfo = getCopyOfCurrentLogs(); for (BufferedLogChannelWithDirInfo currentLogWithDirInfo : copyOfCurrentLogsWithDirInfo) { if (currentLogWithDirInfo.getLogChannel() != null) { currentLogWithDirInfo.getLogChannel().close(); } } }
Source:
public synchronized void close() throws IOException { if (writeBuffer != null) { ReferenceCountUtil.safeRelease(writeBuffer); START writeBuffer = null; END } fileChannel.close(); } Thanks @merlimat calling twice is an issue and we should address that. :)

Target:
public synchronized void close() throws IOException { ReferenceCountUtil.safeRelease(writeBuffer); fileChannel.close(); }
Source:
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException { START checkQueue(); END return super.invokeAll(tasks); } Shouldn't you pass something like the size of the list? checkQueue assumes you are going to add 1 item. I mean something like checkQueue(tasks.size())

Target:
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException { checkQueue(tasks.size()); return super.invokeAll(tasks); }
Source:
private TransientLedgerInfo getOrAddLedgerInfo(long ledgerId) { TransientLedgerInfo tli = transientLedgerInfoCache.get(ledgerId); if (tli != null) { return tli; } else { TransientLedgerInfo newTli = new TransientLedgerInfo(ledgerId, ledgerIndex); tli = transientLedgerInfoCache.putIfAbsent(ledgerId, newTli); START return tli != null ? tli : newTli; END } } better to close `newTli`?

Target:
private TransientLedgerInfo getOrAddLedgerInfo(long ledgerId) { TransientLedgerInfo tli = transientLedgerInfoCache.get(ledgerId); if (tli != null) { return tli; } else { TransientLedgerInfo newTli = new TransientLedgerInfo(ledgerId, ledgerIndex); tli = transientLedgerInfoCache.putIfAbsent(ledgerId, newTli); if (tli != null) { newTli.close(); return tli; } else { return newTli; } } }
Source:
START public ClientConfiguration getConf() { END return conf; } This is not good. Unfortunately this object is mutable. You can you Whitebox in tests

Target:
protected ClientConfiguration getConf() { return conf; }
Source:
public long getWaitTimeoutOnBackpressureMillis() { START return getLong(WAIT_TIMEOUT_ON_BACKPRESSURE, 500); END } I think we should make this default value as -1, util we have benchmarks show 500 is in general good for most of applications.

Target:
public long getWaitTimeoutOnBackpressureMillis() { return getLong(WAIT_TIMEOUT_ON_BACKPRESSURE, -1); }
Source:
public long getAuditorLedgerVerificationPercentage() { START return getLong(AUDITOR_LEDGER_VERIFICATION_PERCENTAGE, 100); END } shall we make the default value as `0`, which by default this feature is not enabled.

Target:
public long getAuditorLedgerVerificationPercentage() { return getLong(AUDITOR_LEDGER_VERIFICATION_PERCENTAGE, 0); }
Source:
public static ByteBuf generatePacket(long ledgerId, long entryId, long lastAddConfirmed, long length, byte[] data, int offset, int len) { DigestManager dm = null; try { // CRC32 need not password, and is support definitely currently. dm = DigestManager.instantiate(ledgerId, new byte[2], CRC32); } catch (GeneralSecurityException gse) { START END } return dm.computeDigestAndPackageForSending(entryId, lastAddConfirmed, length, Unpooled.wrappedBuffer(data, offset, len)); } Rethrow or at least log

Target:
public static ByteBuf generatePacket(long ledgerId, long entryId, long lastAddConfirmed, long length, byte[] data, int offset, int len) throws GeneralSecurityException { DigestManager dm = DigestManager.instantiate(ledgerId, new byte[2], CRC32); return dm.computeDigestAndPackageForSending(entryId, lastAddConfirmed, length, Unpooled.wrappedBuffer(data, offset, len)); }
Source:
private void handleLedgerEviction(RemovalNotification<Long, CachedFileInfo> notification) { CachedFileInfo fileInfo = notification.getValue(); Long ledgerId = notification.getKey(); if (null == fileInfo || null == notification.getKey()) { return; } if (notification.wasEvicted()) { evictedLedgersCounter.inc(); } START fileInfo.release(); END } This is the same extreme situation that could happen in https://github.com/apache/bookkeeper/pull/513, if you think it's unlikely to happen then we can ignore it.

Target:
private void handleLedgerEviction(RemovalNotification<Long, CachedFileInfo> notification) { CachedFileInfo fileInfo = notification.getValue(); if (null == fileInfo || null == notification.getKey()) { return; } if (notification.wasEvicted()) { evictedLedgersCounter.inc(); } fileInfo.release(); }
Source:
START private Set<String> getNetworkLocations(Set<Node> bookieNodes) { END Set<String> networkLocs = new HashSet<String>(); for (Node bookieNode : bookieNodes) { networkLocs.add(bookieNode.getNetworkLocation()); } return networkLocs; } static ?

Target:
private static Set<String> getNetworkLocations(Set<Node> bookieNodes) { Set<String> networkLocs = new HashSet<>(); for (Node bookieNode : bookieNodes) { networkLocs.add(bookieNode.getNetworkLocation()); } return networkLocs; }
Source:
BookieStateManager(ServerConfiguration conf, RegistrationManager registrationManager) throws IOException { this.conf = conf; this.registrationManager = registrationManager; START this.statsLogger = null; END this.ledgerDirsManager = new LedgerDirsManager(conf, conf.getLedgerDirs(), new DiskChecker(conf.getDiskUsageThreshold(), conf.getDiskUsageWarnThreshold()), NullStatsLogger.INSTANCE); // ZK ephemeral node for this Bookie. this.bookieId = getMyId(); } use NullStatsLogger.INSTANCE rather than plain `null` Also I think this constructor use this other constructor ``` this(conf, NullStatsLogger.INSTANCE, registrationManager, new LedgerDirsManager(...)); ```

Target:
BookieStateManager(ServerConfiguration conf, RegistrationManager registrationManager) throws IOException { this(conf, NullStatsLogger.INSTANCE, registrationManager, new LedgerDirsManager(conf, conf.getLedgerDirs(), new DiskChecker(conf.getDiskUsageThreshold(), conf.getDiskUsageWarnThreshold()), NullStatsLogger.INSTANCE)); }
Source:
public void keySmallerThanTotalSize() { try { new ArrayGroupSort(3, 2); fail("should have failed"); START } catch (IllegalArgumentException e) { END // ok } } Nit: This can be put in @Test(expected=IllegalArgumentException.class) Same for below checks

Target:
public void keySmallerThanTotalSize() { new ArrayGroupSort(3, 2); }
Source:
START void monitorPendingAddOps() { END int timedOut = 0; for (PendingAddOp op : pendingAddOps) { if (op.maybeTimeout()) { timedOut++; } } LOG.info("Timed out add ops", timedOut); } make this private if it is not used outside.

Target:
private void monitorPendingAddOps() { int timedOut = 0; for (PendingAddOp op : pendingAddOps) { if (op.maybeTimeout()) { timedOut++; } } if (timedOut > 0) { LOG.info("Timed out add ops", timedOut); } }
Source:
public void monitorPendingOperations() { START for (PerChannelBookieClientPool clientPool : channels.values()) { END clientPool.checkTimeoutOnPendingOperations(); } } channels.values().forEach ?

Target:
private void monitorPendingOperations() { for (PerChannelBookieClientPool clientPool : channels.values()) { clientPool.checkTimeoutOnPendingOperations(); } }
Source:
START protected EntryLoggerAllocator getEntryLoggerAllocator() { END return entryLoggerAllocator; } nit: you can remove `protected` to make this method package private, because the test and class are in the same package.

Target:
EntryLoggerAllocator getEntryLoggerAllocator() { return entryLoggerAllocator; }
Source:
public void testGetWriteFlagsNone() { START assertEquals(EnumSet.noneOf(WriteFlag.class), WriteFlag.getWriteFlags(0)); END } give a meaningful name for value `0`

Target:
public void testGetWriteFlagsNone() { assertEquals(EnumSet.noneOf(WriteFlag.class), WriteFlag.getWriteFlags(NONE)); }
Source:
public LedgerEntryImpl duplicate() { START LedgerEntryImpl other = RECYCLER.get(); END other.ledgerId = ledgerId; other.entryId = entryId; other.length = length; other.entryBuf = entryBuf.retainedSlice(); return other; } this can be simplified with ``` return duplicate(this); ```

Target:
public LedgerEntryImpl duplicate() { return duplicate(this); }
Source:
private void releaseByteBuf() { if (entries != null) { START for (LedgerEntry entry : entries) { END entry.getEntryBuffer().release(1); } } } entries.forEach(LedgerEntry::close()); entries.clear(); entries = null;

Target:
private void releaseByteBuf() { if (entries != null) { entries.forEach(LedgerEntry::close); entries.clear(); entries = null; } }
Source:
public void onRotateEntryLog() { // for interleaved ledger storage, we request a checkpoint when rotating a entry log file. // the checkpoint represent the point that all the entries added before this point are already // in ledger storage and ready to be synced to disk. // TODO: we could consider remove checkpointSource and checkpointSouce#newCheckpoint // later if we provide kind of LSN (Log/Journal Squeuence Number) // mechanism when adding entry. {@link https://github.com/apache/bookkeeper/issues/279} START if (null != checkpointer) { END Checkpoint checkpoint = checkpointSource.newCheckpoint(); checkpointer.startCheckpoint(checkpoint); } } in which case it can be null? and is it ok to be null?

Target:
public void onRotateEntryLog() { // for interleaved ledger storage, we request a checkpoint when rotating a entry log file. // the checkpoint represent the point that all the entries added before this point are already // in ledger storage and ready to be synced to disk. // TODO: we could consider remove checkpointSource and checkpointSouce#newCheckpoint // later if we provide kind of LSN (Log/Journal Squeuence Number) // mechanism when adding entry. {@link https://github.com/apache/bookkeeper/issues/279} Checkpoint checkpoint = checkpointSource.newCheckpoint(); checkpointer.startCheckpoint(checkpoint); }
Source:
START public void start() throws IOException, UnavailableException, InterruptedException, KeeperException, BKException { END this.bookie.start(); // fail fast, when bookie startup is not successful if (!this.bookie.isRunning()) { exitCode = bookie.getExitCode(); return; } this.nettyServer.start(); running = true; deathWatcher = new DeathWatcher(conf); deathWatcher.start(); } can we remove `KeeperException` here?

Target:
public void start() throws IOException, UnavailableException, InterruptedException, BKException { this.bookie.start(); // fail fast, when bookie startup is not successful if (!this.bookie.isRunning()) { exitCode = bookie.getExitCode(); return; } this.nettyServer.start(); running = true; deathWatcher = new DeathWatcher(conf); deathWatcher.start(); }
Source:
public void setUp() throws Exception { super.setUp(); START LOG.info("setUp"); END zkUtil.createBKEnsemble("/" + runtime.getMethodName()); rm = new ZKRegistrationManager(); } remove this?

Target:
public void setUp() throws Exception { super.setUp(); zkUtil.createBKEnsemble("/" + runtime.getMethodName()); rm = new ZKRegistrationManager(); }
Source:
START private String requestToString(Object request) { END if (request instanceof BookkeeperProtocol.Request) { BookkeeperProtocol.BKPacketHeader header = ((BookkeeperProtocol.Request)request).getHeader(); return String.format("Req(txnId=%d,op=%s,version=%s)", header.getTxnId(), header.getOperation(), header.getVersion()); } else { return request.toString(); } } nit: static ?

Target:
private static String requestToString(Object request) { if (request instanceof BookkeeperProtocol.Request) { BookkeeperProtocol.BKPacketHeader header = ((BookkeeperProtocol.Request)request).getHeader(); return String.format("Req(txnId=%d,op=%s,version=%s)", header.getTxnId(), header.getOperation(), header.getVersion()); } else { return request.toString(); } }
Source:
public static <T> T fromJson(String jsonStr, Class<T> valueType) throws ParseJsonException { try { return mapper.readValue(jsonStr, valueType); } catch (Exception e) { START e.printStackTrace(); END throw new ParseJsonException("Failed to deserialize Object from Json string"); } } remove

Target:
public static <T> T fromJson(String jsonStr, Class<T> valueType) throws ParseJsonException { try { return mapper.readValue(jsonStr, valueType); } catch (Exception e) { throw new ParseJsonException("Failed to deserialize Object from Json string"); } }
Source:
START public BookKeeper.DigestType getDigestType() { END if (digestType.equals(LedgerMetadataFormat.DigestType.HMAC)) { return BookKeeper.DigestType.MAC; } else { return BookKeeper.DigestType.CRC32; } } why is this made public?

Target:
BookKeeper.DigestType getDigestType() { if (digestType.equals(LedgerMetadataFormat.DigestType.HMAC)) { return BookKeeper.DigestType.MAC; } else { return BookKeeper.DigestType.CRC32; } }
Source:
START public CreateAdvBuilder makeAdv() { END if(advBuilder == null) { advBuilder = new CreateAdvBuilderImpl(this); } return advBuilder; } why do we need separate advbuilder? cannt we just assume / implement the logic as if it is advbuilder if ledger id is provided

Target:
public CreateAdvBuilder makeAdv() { return new CreateAdvBuilderImpl(this); }
Source:
public BookieNode selectFromNetworkLocation( String networkLoc, Set<Node> excludeBookies, Predicate<BookieNode> predicate, Ensemble<BookieNode> ensemble) throws BKNotEnoughBookiesException { // select one from local rack try { return selectRandomFromRack(networkLoc, excludeBookies, predicate, ensemble); } catch (BKNotEnoughBookiesException e) { LOG.warn("Failed to choose a bookie from : " + "excluded {}, fallback to choose bookie randomly from the cluster.", networkLoc, excludeBookies); START LOG.warn("Predicate Ensemble {}", predicate, ensemble); END // randomly choose one from whole cluster, ignore the provided predicate. return selectRandom(1, excludeBookies, predicate, ensemble).get(0); } } This line doesn't give any useful information for debugging, isn't it?

Target:
public BookieNode selectFromNetworkLocation( String networkLoc, Set<Node> excludeBookies, Predicate<BookieNode> predicate, Ensemble<BookieNode> ensemble) throws BKNotEnoughBookiesException { // select one from local rack try { return selectRandomFromRack(networkLoc, excludeBookies, predicate, ensemble); } catch (BKNotEnoughBookiesException e) { LOG.warn("Failed to choose a bookie from : " + "excluded {}, fallback to choose bookie randomly from the cluster.", networkLoc, excludeBookies); // randomly choose one from whole cluster, ignore the provided predicate. return selectRandom(1, excludeBookies, predicate, ensemble).get(0); } }
Source:
HttpServer.Method convertMethod(HttpServerRequest request) { switch (request.method()) { case GET: return HttpServer.Method.GET; case POST: return HttpServer.Method.POST; case DELETE: return HttpServer.Method.DELETE; case PUT: return HttpServer.Method.PUT; START default: END return HttpServer.Method.GET; } } Could just omit first case GET and let it default.

Target:
HttpServer.Method convertMethod(HttpServerRequest request) { switch (request.method()) { case POST: return HttpServer.Method.POST; case DELETE: return HttpServer.Method.DELETE; case PUT: return HttpServer.Method.PUT; default: return HttpServer.Method.GET; } }
Source:
private void writeToFile(File file, String body) throws IOException { START FileOutputStream fos = new FileOutputStream(file); END BufferedWriter bw = null; try { bw = new BufferedWriter(new OutputStreamWriter(fos, UTF_8)); bw.write(body); } finally { if (bw != null) { bw.close(); } fos.close(); } } it is better to use try(FileOutputStream ....)

Target:
private static void writeToFile(File file, String body) throws IOException { FileOutputStream fos = new FileOutputStream(file); BufferedWriter bw = null; try { bw = new BufferedWriter(new OutputStreamWriter(fos, UTF_8)); bw.write(body); } finally { if (bw != null) { bw.close(); } fos.close(); } }
Source:
private BookieStatus readFromFile(File file) throws IOException, IllegalArgumentException { if (!file.exists()) { return null; } START BufferedReader reader = new BufferedReader( END new InputStreamReader(new FileInputStream(file), UTF_8)); try { return parse(reader); } finally { reader.close(); } } we can use try(BufferedReader...)

Target:
private BookieStatus readFromFile(File file) throws IOException, IllegalArgumentException { if (!file.exists()) { return null; } try (BufferedReader reader = new BufferedReader( new InputStreamReader(new FileInputStream(file), UTF_8))) { return parse(reader); } }
Source:
public ClientAuthProvider newProvider(ClientConnectionPeer connection, AuthCallbacks.GenericCallback<Void> completeCb) { return new ClientAuthProvider() { @Override public void process(AuthToken m, AuthCallbacks.GenericCallback<AuthToken> cb) { } @Override public void close() { closeCountersOnConnections.incrementAndGet(); } START END public void init(AuthCallbacks.GenericCallback<AuthToken> cb) { initCountersOnConnections.incrementAndGet(); completeCb.operationComplete(BKException.Code.OK, null); } }; } do we need '@Override' here?

Target:
public ClientAuthProvider newProvider(ClientConnectionPeer connection, AuthCallbacks.GenericCallback<Void> completeCb) { return new ClientAuthProvider() { @Override public void process(AuthToken m, AuthCallbacks.GenericCallback<AuthToken> cb) { } @Override public void close() { closeCountersOnConnections.incrementAndGet(); } @Override public void init(AuthCallbacks.GenericCallback<AuthToken> cb) { initCountersOnConnections.incrementAndGet(); completeCb.operationComplete(BKException.Code.OK, null); } }; }
Source:
public BookKeeper build() throws IOException, InterruptedException, KeeperException { Preconditions.checkNotNull(statsLogger, "No stats logger provided"); if (eventLoopGroup == null) { START eventLoopGroup = getDefaultEventLoopGroup(); END } return new BookKeeper(conf, zk, eventLoopGroup, statsLogger, dnsResolver, requestTimer, featureProvider); } This will cause the eventLoopGroup to leak. We need to be sure that ownChanelFactory (or ownEventLoopGroup) is set to true when we are the ones that create the eventLoopGroup.

Target:
public BookKeeper build() throws IOException, InterruptedException, KeeperException { Preconditions.checkNotNull(statsLogger, "No stats logger provided"); return new BookKeeper(conf, zk, eventLoopGroup, statsLogger, dnsResolver, requestTimer, featureProvider); }
Source:
public void operationComplete(int rc, Void v) { if (rc == BKException.Code.OK) { authenticated = true; START LOG.error("Authentication success on server side"); END } else { LOG.debug("Authentication failed on server side"); } } 'info'?

Target:
public void operationComplete(int rc, Void v) { if (rc == BKException.Code.OK) { authenticated = true; LOG.info("Authentication success on server side"); } else { LOG.debug("Authentication failed on server side"); } }
Source:
public ArrayList<BookieSocketAddress> newEnsemble(int ensembleSize, int writeQuorumSize) throws BKNotEnoughBookiesException { try { // we try to only get from the healthy bookies first START return placementPolicy.newEnsemble(ensembleSize, writeQuorumSize, quarantinedBookies.asMap().keySet()); END } catch (BKNotEnoughBookiesException e) { if (logger.isDebugEnabled()) { logger.debug("Not enough healthy bookies available, using quarantined bookies"); } return placementPolicy.newEnsemble(ensembleSize, writeQuorumSize, EMPTY_SET); } } the key set will be modified in #newEnsembel(). It seems to me you have to create a new set from current quarantinedBookies's key set

Target:
public ArrayList<BookieSocketAddress> newEnsemble(int ensembleSize, int writeQuorumSize) throws BKNotEnoughBookiesException { try { // we try to only get from the healthy bookies first return placementPolicy.newEnsemble(ensembleSize, writeQuorumSize, new HashSet<BookieSocketAddress>( quarantinedBookies.asMap().keySet())); } catch (BKNotEnoughBookiesException e) { if (logger.isDebugEnabled()) { logger.debug("Not enough healthy bookies available, using quarantined bookies"); } return placementPolicy.newEnsemble(ensembleSize, writeQuorumSize, EMPTY_SET); } }
Source:
START public RevTree getTree(ObjectId id) { END return getIfPresent(id, RevTree.class); } all the type specific getters should call get instead of getIfPresent, as they're supposed to fail if the object is not found, instead of returning null

Target:
public RevTree getTree(ObjectId id) { return get(id, RevTree.class); }
Source:
START public void add(DiffObjectCount toAdd) { END treesCount += toAdd.getTreesCount(); featuresCount += toAdd.getFeaturesCount(); } This class should ideally be immutable. I see the convenience in having these add\* methods while computing the sizes, but can you at least make them package private in order to reduce the class' public interface to the immutable part?

Target:
void add(DiffObjectCount toAdd) { treesCount += toAdd.getTreesCount(); featuresCount += toAdd.getFeaturesCount(); }
Source:
public void addRecentPage(int page) { START BookmarksWidget.updateWidget(context); END addRecentPage(page, true); } take a look at `BookmarkPresenter` i think - there's an rx observable there. we can just subscribe to it and refresh then - not sure what the right place to subscribe is, but in worst case, some object that subscribes whenever there is at least one active widget

Target:
public void addRecentPage(int page) { addRecentPage(page, true); }
Source:
public void onPause() { START scrollPosition = translationView.findFirstCompletelyVisibleItemPosition(); END ayahTrackerPresenter.unbind(this); presenter.unbind(this); super.onPause(); } can we move this into `onSaveInstanceState`?

Target:
public void onPause() { ayahTrackerPresenter.unbind(this); presenter.unbind(this); super.onPause(); }
Source:
public String getTranslatorName() { final String result; if (this.translatorForeign != null) { START result = this.translator; END } else if (this.translator != null) { result = this.translator; } else { result = this.name; } return result; } You probably wanted to put `result = this.translatorForeign;`?

Target:
public String getTranslatorName() { final String result; if (this.translatorForeign != null) { result = this.translatorForeign; } else if (this.translator != null) { result = this.translator; } else { result = this.name; } return result; }
Source:
public void testLongParseDefaultSuccess() { START Long num = NumberParser.parseLong("Non Long", 1L); END assertTrue(num == 1L); num = NumberParser.parseLong("0", 1L); assertTrue(num == 0L); } This method returns primitive `long`, no need for boxing. Same for the other method like this.

Target:
public void testLongParseDefaultSuccess() { long num = NumberParser.parseLong("Non Long", 1L); assertEquals(1L, num); }
Source:
protected RequestBuilder applyAuth(RequestBuilder request) throws NexmoClientException { AuthMethod authMethod = getAuthMethod(getAcceptableAuthMethods()); START if (isUseBasicAuth()) { END return authMethod.applyAsBasicAuth(request); } return authMethod.apply(request); } I think overiding `applyAuth` in `RedactMethod` is probably a better approach. I think that kind of thing was why I implemented it.

Target:
protected RequestBuilder applyAuth(RequestBuilder request) throws NexmoClientException { return getAuthMethod(getAcceptableAuthMethods()).apply(request); }
Source:
private void attachedFile() throws ApiError { this.deliveriesBackend.attach(delivery, fileName, in); assertEquals(1, delivery.getAttachments().size()); // Because a simple get did not return the correct deliveryAttachment, we had to do it the fancy way. START assertEquals(1, delivery.getAttachments().stream() END .map((attachment) -> attachment.getFileName().equals(fileName) ).count()); } assertEquals(fileName, delivery.getAttachments().iterator().next().getFileName()) did not do the trick? Or `assertThat(delivery.getAttachments(), Matchers.contains(attachment))`? (Don't know what the `equals()` for attachment currently checks for though, and it might require that you instantiate it manually instead of mocking it)

Target:
private void attachedFile() throws ApiError { this.deliveriesBackend.attach(delivery, fileName, in); assertEquals(1, delivery.getAttachments().size()); assertEquals(fileName, delivery.getAttachments().iterator().next().getFileName()); }
Source:
public boolean exists( String fileSystem, String path ) { PathMap pathMap = getPathMap( fileSystem, path ); if ( pathMap != null ) { return true; } START return false; END } nitpick. Just single one statement is enough: return getPathMap(fileSystem, path)!=null

Target:
public boolean exists( String fileSystem, String path ) { return getPathMap( fileSystem, path ) != null; }
Source:
public SpecialPathInfo getSpecialPathInfo( Transfer transfer, String pkgType ) { if ( transfer != null ) { START return getSpecialPathInfo( transfer.getLocation(), transfer.getStoragePath(), pkgType ); END } // TODO: Return SpecialPathConstants.DEFAULT_FILE or SpecialPathConstants.DEFAULT_DIR or something non-null? return null; } This looks like it will result in getPathInfo(..) executing and calculating the storage path of this storage path...I think we need to pass in the logical path here (the getPath() output).

Target:
public SpecialPathInfo getSpecialPathInfo( Transfer transfer, String pkgType ) { if ( transfer != null ) { return getSpecialPathInfo( transfer.getLocation(), transfer.getPath(), pkgType ); } // TODO: Return SpecialPathConstants.DEFAULT_FILE or SpecialPathConstants.DEFAULT_DIR or something non-null? return null; }
Source:
public void copyFrom( final Transfer f ) throws IOException { provider.waitForWriteUnlock( resource ); provider.lockWrite( resource ); try { if ( decorator != null ) { START decorator.decorateCopyFrom( f, this, new EventMetadata( ) ); END } provider.copy( f.getResource(), resource ); } finally { provider.unlockWrite( resource ); } } another place where a variant of `copyFrom()` may need event metadata eventually

Target:
public void copyFrom( final Transfer f ) throws IOException { copyFrom( f, new EventMetadata( ) ); }
Source:
public void registerSpecialPathInfo( SpecialPathInfo pathInfo, final String pkgType ) { START for ( Map.Entry<String, SpecialPathSet> entry : pkgtypes.entrySet() ) END { if ( pkgType.equals( entry.getKey() ) ) { entry.getValue().registerSpecialPathInfo( pathInfo ); } } } Can you just do `pkgtypes.get(pkgType)` here?

Target:
public void registerSpecialPathInfo( SpecialPathInfo pathInfo, final String pkgType ) { pkgtypes.get(pkgType).registerSpecialPathInfo( pathInfo ); }
Source:
public void deregisterSpecialPathInfo( SpecialPathInfo pathInfo, String pkgType ) { START for ( Map.Entry<String, SpecialPathSet> entry : pkgtypes.entrySet() ) END { if ( pkgType.equals( entry.getKey() ) ) { entry.getValue().deregisterSpecialPathInfo( pathInfo ); } } } `pkgtypes.get(pkgType)`...

Target:
public void deregisterSpecialPathInfo( SpecialPathInfo pathInfo, String pkgType ) { pkgtypes.get(pkgType).deregisterSpecialPathInfo( pathInfo ); }
Source:
START public void deregesterSpecialPathSet( SpecialPathSet pathSet ) END { if ( !pkgtypes.containsKey( pathSet.getPackageType() ) ) { logger.warn( "[Galley] The package does not contain the path set for this package type {}, no deregister operation there", pathSet.getPackageType() ); } pkgtypes.remove( pathSet.getPackageType() ); } IMO we should return the removed SpecialPathSet. It's similar to Map semantics, and if people don't need the return value they can just discard it.

Target:
public SpecialPathSet deregesterSpecialPathSet( SpecialPathSet pathSet ) { if ( !pkgtypes.containsKey( pathSet.getPackageType() ) ) { logger.warn( "[Galley] The package does not contain the path set for this package type {}, no deregister operation there", pathSet.getPackageType() ); } return pkgtypes.remove( pathSet.getPackageType() ); }
Source:
public String resolveExpressions( final String value, final String... activeProfileIds ) { if ( !containsExpression( value ) ) { return value; } START List<String> prefixs = new ArrayList<>(); END prefixs.add( PrefixAwareRecursionInterceptor.DEFAULT_START_TOKEN ); PrefixAwareRecursionInterceptor ri = new PrefixAwareRecursionInterceptor( prefixs ); return resolveExpressions( value, ri, activeProfileIds ); } Since you have to do the null check in `resolveExpressions(String, RecursionInterceptor, String...)` anyway, you could probably move this down to that method, and call with a null `ri` here...

Target:
public String resolveExpressions( final String value, final String... activeProfileIds ) { if ( !containsExpression( value ) ) { return value; } return resolveExpressions( value, null, activeProfileIds ); }
Source:
START public String get(String name, ParcelableProxy proxy) throws QueryFailedException { END throw new UnsupportedOperationException("Returning armored key from Web Key Directory not supported"); } why here you still want to return an empty entry array?

Target:
public String get(String name, ParcelableProxy proxy) { throw new UnsupportedOperationException("Returning armored key from Web Key Directory not supported"); }