auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public DataSink<T> writeAsCsv(String filePath, String rowDelimiter, String fieldDelimiter) { START return internalWriteAsCsv(new Path(filePath), rowDelimiter, fieldDelimiter, FileOutputFormat.getDefaultWriteMode()); END } No sure, if we should do it this way. If no write mode is explicitly specified, the system default write mode will be used. If we decide to introduce something like a client option to set the write mode for a session, this would be overwritten by the system default. Why not having two internalWriteAsCsv methods, one with explicit write mode and one without?

Target:
public DataSink<T> writeAsCsv(String filePath, String rowDelimiter, String fieldDelimiter) { return internalWriteAsCsv(new Path(filePath), rowDelimiter, fieldDelimiter, null); }
Source:
public boolean isConverged(int iteration, LongValue value) { if ( value.getValue() > 3 ) { return true; } START else END return false; } checkstyle will complain here, missing {}.

Target:
public boolean isConverged(int iteration, LongValue value) { return value.getValue() > 3; }
Source:
public static final int compare(MemorySegment seg1, MemorySegment seg2, int offset1, int offset2, int len) { final byte[] b1 = seg1.memory; final byte[] b2 = seg2.memory; int val = 0; for (int pos = 0; pos < len && (val = (b1[offset1 + pos] & 0xff) - (b2[offset2 + pos] & 0xff)) == 0; pos++) { START ; END } return val; } But this would mean that we deactivate the rule globally. I rather suggest to disable the rule for this specific code block: http://stackoverflow.com/questions/2640110/how-can-you-suppress-checkstyle-checks-within-a-block-of-code-only-for-specific

Target:
public static final int compare(MemorySegment seg1, MemorySegment seg2, int offset1, int offset2, int len) { final byte[] b1 = seg1.memory; final byte[] b2 = seg2.memory; int val = 0; for (int pos = 0; pos < len && (val = (b1[offset1 + pos] & 0xff) - (b2[offset2 + pos] & 0xff)) == 0; pos++) { } return val; }
Source:
public static void writeObjectToConfig(Object o, Configuration config, String key) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(o); byte[] bytes = baos.toByteArray(); config.setBytes(key, bytes); START oos.close(); END } I think this should be after `oos.writeObject(o);`, in case there is buffered data. In any case, before obtaining the `byte[]` result.

Target:
public static void writeObjectToConfig(Object o, Configuration config, String key) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(o); byte[] bytes = baos.toByteArray(); config.setBytes(key, bytes); }
Source:
public int compareTo(BlockLocation o) { START return (new Long(offset)).compareTo(o.getOffset()); END } Why are you creating a new Long here? I think a cast should suffice

Target:
public int compareTo(BlockLocation o) { return ((Long) (offset)).compareTo(o.getOffset()); }
Source:
public Path getWorkingDirectory() { START return new Path(pathToString(workingDirectory)); END } Why can't you just return `this.workingDirectory` ?

Target:
public Path getWorkingDirectory() { return workingDirectory; }
Source:
public void initialize(){ ScheduleExpression scheduleExpression = new ScheduleExpression(); START scheduleExpression.hour("*"); END scheduleExpression.minute("*"); scheduleExpression.second("*/5"); TimerConfig timerConfig = new TimerConfig(); timerConfig.setInfo("Every 5 second timer"); timerService.createCalendarTimer(scheduleExpression, timerConfig); } It might be a little cleaner to use the builder pattern.

Target:
public void initialize() { ScheduleExpression scheduleExpression = new ScheduleExpression() .hour("*") .minute("*") .second("*/5"); TimerConfig timerConfig = new TimerConfig(); timerConfig.setInfo("Every 5 second timer"); timerService.createCalendarTimer(scheduleExpression, timerConfig); }
Source:
public static String javaVersion(final String def) { final String javaVersionProperty = SafePropertyAccessor.getProperty("java.version", def); START if (javaVersionProperty.equals("0")) return "1.7.0"; // Android END return javaVersionProperty; } makes it no longer null-safe (as it was before) - could you please swap the equals comparison, just in case

Target:
public static String javaVersion(final String def) { final String javaVersionProperty = SafePropertyAccessor.getProperty("java.version", def); if ("0".equals(javaVersionProperty)) return "1.7.0"; // Android return javaVersionProperty; }
Source:
public MongoFeedStatisticsStore build() { START return new MongoFeedStatisticsStore(mongo, taskStore, clock, destinationType); END } same, pass the builder object in

Target:
public MongoFeedStatisticsStore build() { return new MongoFeedStatisticsStore(this); }
Source:
private static Predicate<Location> isYouViewPlatform() { return new Predicate<Location>() { @Override public boolean apply(Location input) { Policy policy = input.getPolicy(); START if (policy == null) { END return false; } return Platform.YOUVIEW_IPLAYER.equals(policy.getPlatform()); } }; } `return policy != null && Platform.YOUVIEW_IPLAYER.equals(policy.getPlatform())`

Target:
private static Predicate<Location> isYouViewPlatform() { return new Predicate<Location>() { @Override public boolean apply(Location input) { Policy policy = input.getPolicy(); return policy != null && Platform.YOUVIEW_IPLAYER.equals(policy.getPlatform()); } }; }
Source:
public String generateVersionCrid(Item item, Version version) { String versionCrid = delegate.generateVersionCrid(item, version); Optional<String> value = idMappingStore.getValueFor(version.getCanonicalUri()); if (!value.isPresent() || !versionCrid.equals(value.get())) { START idMappingStore.storeMapping(version.getCanonicalUri(), versionCrid); END } return versionCrid; } This is something that should be private to the store itself. It's a mongo thing we need to protect writes, so a user of it shouldn't need to care.

Target:
public String generateVersionCrid(Item item, Version version) { String versionCrid = delegate.generateVersionCrid(item, version); idMappingStore.storeMapping(version.getCanonicalUri(), versionCrid); return versionCrid; }
Source:
private VideoAttributesType generateVideoAttributes(Encoding encoding) { VideoAttributesType videoAttributes = new VideoAttributesType(); videoAttributes.setHorizontalSize(Optional.fromNullable(encoding.getVideoHorizontalSize()) .or(DEFAULT_HORIZONTAL_SIZE)); videoAttributes.setVerticalSize(Optional.fromNullable(encoding.getVideoVerticalSize()) .or(DEFAULT_VERTICAL_SIZE)); AspectRatioType aspectRatio = new AspectRatioType(); START aspectRatio.setValue(Objects.firstNonNull(encoding.getVideoAspectRatio(), DEFAULT_ASPECT_RATIO)); END videoAttributes.getAspectRatio().add(aspectRatio); return videoAttributes; } Why do one as `Objects.firstNonNull( [field], [default] )` and t'other as `Optional.fromNullable( [field] ).or( [default] )`? I'd pick one and stick to it.

Target:
private VideoAttributesType generateVideoAttributes(Encoding encoding) { VideoAttributesType videoAttributes = new VideoAttributesType(); videoAttributes.setHorizontalSize(Objects.firstNonNull(encoding.getVideoHorizontalSize(), DEFAULT_HORIZONTAL_SIZE)); videoAttributes.setVerticalSize(Objects.firstNonNull(encoding.getVideoVerticalSize(), DEFAULT_VERTICAL_SIZE)); AspectRatioType aspectRatio = new AspectRatioType(); aspectRatio.setValue(Objects.firstNonNull(encoding.getVideoAspectRatio(), DEFAULT_ASPECT_RATIO)); videoAttributes.getAspectRatio().add(aspectRatio); return videoAttributes; }
Source:
START private Function<Version, Iterable<Broadcast>> toBroadcasts() { END return new Function<Version, Iterable<Broadcast>>() { @Override public Iterable<Broadcast> apply(Version input) { return input.getBroadcasts(); } }; } Can these 2 functions be constants? So we don't need to create new instances every time these methods are called

Target:
private static Function<Version, Iterable<Broadcast>> toBroadcasts() { return new Function<Version, Iterable<Broadcast>>() { @Override public Iterable<Broadcast> apply(Version input) { return input.getBroadcasts(); } }; }
Source:
protected void onBindDialogView(View view) { SeekBar volumeBar = (SeekBar) view.findViewById(R.id.volume_bar); volumeBar.setProgress((int) (getPersistedFloat( PreferenceConstants.DEFAULT_BELL_VOLUME) * 100)); volumeBar.setOnSeekBarChangeListener(this); START super.onBindDialogView(view); END } Should this be done first in the method?

Target:
protected void onBindDialogView(View view) { super.onBindDialogView(view); SeekBar volumeBar = (SeekBar) view.findViewById(R.id.volume_bar); volumeBar.setProgress((int) (getPersistedFloat( PreferenceConstants.DEFAULT_BELL_VOLUME) * 100)); volumeBar.setOnSeekBarChangeListener(this); }
Source:
public void copyCurrentSelectionToClipboard() { START terminalTextViewOverlay.copyCurrentSelectionToClipboard(); END } This could be `null`, but is this even used anymore?

Target:
public void copyCurrentSelectionToClipboard() { if (terminalTextViewOverlay != null) { terminalTextViewOverlay.copyCurrentSelectionToClipboard(); } }
Source:
public void onResume() { super.onResume(); // Must disconnectAll before setting closeOnDisconnectAll to know whether to keep the // activity open after disconnecting. if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == 0 && START getIntent().getAction() == DISCONNECT_ACTION) { END Log.d(TAG, "Got disconnect all request"); disconnectAll(); } // Still close on disconnect if waiting for a disconnect. closeOnDisconnectAll = waitingForDisconnectAll && closeOnDisconnectAll; } DISCONNECT_ACTION.equals(getIntent().getAction())

Target:
public void onResume() { super.onResume(); // Must disconnectAll before setting closeOnDisconnectAll to know whether to keep the // activity open after disconnecting. if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == 0 && DISCONNECT_ACTION.equals(getIntent().getAction())) { Log.d(TAG, "Got disconnect all request"); disconnectAll(); } // Still close on disconnect if waiting for a disconnect. closeOnDisconnectAll = waitingForDisconnectAll && closeOnDisconnectAll; }
Source:
public PluginConfig(String className) { START requireNonNull(className); this.className = className; END } ```suggestion this.className = requireNonNull(className); ```

Target:
public PluginConfig(String className) { this.className = requireNonNull(className); this.options = Map.of(); }
Source:
START protected String getLockID() { return lockID; } END I think most of the other new 'getter' methods can be removed in favor of package-private visibility on the field. Keeping the field access simple, rather than creating all these new methods, will help future code changes by minimizing the call stack one has to follow to understand what is going on. However, I think this one should stay, because it provides access to a non-final field, whereas most of the others are final already. It should be package-private, though, instead of protected, because they don't need access by subclasses.

Target:
String getLockID() { return lockID; }
Source:
START protected void acquireRecoveryMemory(KeyExtent extent) { END if (!extent.isMeta()) { recoveryLock.lock(); } } ```suggestion void acquireRecoveryMemory(KeyExtent extent) { ```

Target:
void acquireRecoveryMemory(KeyExtent extent) { if (!extent.isMeta()) { recoveryLock.lock(); } }
Source:
public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof DiskUsage)) return false; DiskUsage diskUsage = (DiskUsage) o; if (!Objects.equals(tables, diskUsage.tables)) return false; START return Objects.equals(usage, diskUsage.usage); END } This could be reduced further using AND, something like: `return Objects.equals(tables, diskUsage.tables) && Objects.equals(usage, diskUsage.usage);` Also, any thought to replacing hashCode at the same time to use Objects.hash(tables, usage); - that might help with the constraint that equals and hashCode are consistent.

Target:
public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof DiskUsage)) return false; DiskUsage diskUsage = (DiskUsage) o; return Objects.equals(tables, diskUsage.tables) && Objects.equals(usage, diskUsage.usage); }
Source:
public Builder addOptions(Map<String,String> options) { START options.forEach((key, value) -> addOption(key, value)); END return this; } You can even go a step further with this one: ```suggestion options.forEach(this::addOption); ```

Target:
public Builder addOptions(Map<String,String> options) { options.forEach(this::addOption); return this; }
Source:
public static String validate(String path) { Path p = new Path(path); if (p.toUri().getScheme() == null) { throw new IllegalArgumentException("Invalid path provided, no scheme in " + path); } START return path; END } Did we want to have this normalize the path also by returning the normalized version from `Path`?

Target:
public static String validate(String path) { Path p = new Path(path); if (p.toUri().getScheme() == null) { throw new IllegalArgumentException("Invalid path provided, no scheme in " + path); } return p.toString(); }
Source:
public static void listVolumes(ServerContext context) throws Exception { try { listTable(Ample.DataLevel.ROOT, context); } catch (UnsupportedOperationException ex) { // print nothing if no table name exists START } END System.out.println(); listTable(Ample.DataLevel.METADATA, context); System.out.println(); listTable(Ample.DataLevel.USER, context); } I see. Yeah I would at least print there are no volumes, that would be helpful.

Target:
public static void listVolumes(ServerContext context) throws Exception { listTable(Ample.DataLevel.ROOT, context); System.out.println(); listTable(Ample.DataLevel.METADATA, context); System.out.println(); listTable(Ample.DataLevel.USER, context); }
Source:
public SeekableByteArrayInputStream(byte[] buf, int maxOffset) { START Objects.requireNonNull(buf, "bug argument was null"); this.buffer = buf; END this.cur = 0; this.max = maxOffset; } These are more readable if they are inline'd into the assignment. I'm not sure if this worked for Guava Preconditions, but the Java requireNonNull returns the reference, so it does work for that. Example: ```java this.buffer = Objects.requireNonNull(buf, "buf argument was null"); ``` But, we should stick with whatever minimal change merges to master easiest.

Target:
public SeekableByteArrayInputStream(byte[] buf, int maxOffset) { requireNonNull(buf, "bug argument was null"); this.buffer = buf; this.cur = 0; this.max = maxOffset; }
Source:
Collection<String> asNames(List<Path> recoveryLogs) { START return Collections2.transform(recoveryLogs, input -> input.getName()); END } ```suggestion return Collections2.transform(recoveryLogs, input::getName); ```

Target:
Collection<String> asNames(List<Path> recoveryLogs) { return Collections2.transform(recoveryLogs, Path::getName); }
Source:
private static boolean checkNoCrypto(byte[] params) { START byte[] noCryptoBytes = NO_CRYPTO_VERSION.getBytes(StandardCharsets.UTF_8); END return Arrays.equals(params, noCryptoBytes); } Many places in the codebase that use this constant statically import it. Like https://github.com/apache/accumulo/blob/3c37cc97c12cc3abeb27882fa2f79a64ca32a9f9/core/src/main/java/org/apache/accumulo/core/iteratorsImpl/conf/ColumnSet.java#L19 It would be nice to do that for consistency with other code.

Target:
private static boolean checkNoCrypto(byte[] params) { byte[] noCryptoBytes = NO_CRYPTO_VERSION.getBytes(UTF_8); return Arrays.equals(params, noCryptoBytes); }
Source:
String getTraceId(HttpServletRequest req) { final String stringValue = getStringParameter(req, "id", null); START return TRACE_ID_PATTERN.matcher(stringValue).matches() ? stringValue : null; END } This looks like it could produce an NPE from the matcher if `stringValue` is null. We probably want to add a check for that: ```suggestion if (stringValue == null) { return null; } return TRACE_ID_PATTERN.matcher(stringValue).matches() ? stringValue : null; ```

Target:
String getTraceId(HttpServletRequest req) { final String stringValue = getStringParameter(req, "id", null); if (stringValue == null) { return null; } return TRACE_ID_PATTERN.matcher(stringValue).matches() ? stringValue : null; }
Source:
protected void prepareMetrics() { metricsValuesLock.lock(); try { long now = System.currentTimeMillis(); if ((lastUpdate + minimumRefreshDelay) < now) { metricValues = updateFromZookeeper(); lastUpdate = now; } START recordValues(); END } finally { metricsValuesLock.unlock(); } } If metricValues is the same as the last time recordValues() was called will calling it have an effect?

Target:
protected void prepareMetrics() { metricsValuesLock.lock(); try { long now = System.currentTimeMillis(); if ((lastUpdate + minimumRefreshDelay) < now) { metricValues = updateFromZookeeper(); lastUpdate = now; recordValues(); } } finally { metricsValuesLock.unlock(); } }
Source:
RowLock(ReentrantLock rlock, ByteSequence rowSeq) { this.rlock = rlock; START this.count = new AtomicInteger(1); END this.rowSeq = rowSeq; } Since this count is only accessed in by lambdas running in Map.compute(), I do not think it needs to be an atomic integer. The atomic integer may force unneeded round trips to main memory. The lock held by Map.compute should ensure consistency with main memory at the end of the sync block within Map.compute() and ensure mutually exclusive access.

Target:
RowLock(ReentrantLock rlock, ByteSequence rowSeq) { this.rlock = rlock; this.count = 1; this.rowSeq = rowSeq; }
Source:
private void returnRowLock(RowLock lock) { rowLocks.compute(lock.rowSeq, (key, value) -> { START Objects.requireNonNull(value); END Preconditions.checkState(value.count.intValue() > 0); final int newCount = value.count.decrementAndGet(); return (newCount > 0) ? value : null; }); } At the point in the code I would expect that `lock == value`. I think it may be worth adding a sanity check for that. Could do something like the following. ```java private void returnRowLock(RowLock lock) { Objects.requireNonNull(lock); rowLocks.compute(lock.rowSeq, (key, value) -> { Preconditions.checkState(value == lock); Preconditions.checkState(value.count.intValue() > 0); final int newCount = value.count.decrementAndGet(); ￼ return (newCount > 0) ? value : null; }); } ```

Target:
private void returnRowLock(RowLock lock) { Objects.requireNonNull(lock); rowLocks.compute(lock.rowSeq, (key, value) -> { Preconditions.checkState(value == lock); Preconditions.checkState(value.count > 0); final int newCount = --value.count; return (newCount > 0) ? value : null; }); }
Source:
public static boolean isValidBooleanPropertyKey(String key) { return validProperties.contains(key) START && getPropertyByKey(key).getType().equals(PropertyType.BOOLEAN); END } Should use `==` to compare enums (such as PropertyType), because `equals()` accepts `Object`, but `==` forces the compiler to check that both sides are the same type, so it's easier to catch coding mistakes. Enums instances in Java are JVM-wide singletons, so there's none of the typical risks you get with `==` comparing sameness instead of equality. For enums equality implies sameness. ```suggestion && getPropertyByKey(key).getType() == PropertyType.BOOLEAN; ```

Target:
public static boolean isValidBooleanPropertyKey(String key) { return validProperties.contains(key) && getPropertyByKey(key).getType() == PropertyType.BOOLEAN; }
Source:
public String toJson() { GSonData gd = new GSonData(); gd.candidates = candidates; // replace two space indentation with one space to save bytes in ZK while still leaving it human // readable START return GSON.toJson(gd).replaceAll(" ", " "); END } I think tweaking the pretty-print is error prone... this could affect values. We should either store minimized (my preference; can use jq or pretty print on display), or store pretty-print without modifications. Gson may also have an option to change the indent depth for its pretty-printer... which gets you the best of both. Could also just make this less error prone by replacing only spaces at the beginning of the line... but I don't know if that might still have issues on wrapped strings in JSON.

Target:
public String toJson() { GSonData gd = new GSonData(); gd.candidates = candidates; return GSON.toJson(gd); }
Source:
public String getMessage() { StringBuilder message = new StringBuilder(); message.append("Error ").append(errorCode); message.append(" for user ").append(user); START if (!tableInfo.isEmpty()) { END message.append(" on table ").append(tableInfo); } message.append(" - ").append(super.getMessage()); return message.toString(); } These aren't equivalent. The `StringUtils` version checks for `null` and `""` in one call.

Target:
public String getMessage() { StringBuilder message = new StringBuilder(); message.append("Error ").append(errorCode); message.append(" for user ").append(user); if (!StringUtils.isEmpty(tableInfo)) { message.append(" on table ").append(tableInfo); } message.append(" - ").append(super.getMessage()); return message.toString(); }
Source:
getProblems(@QueryParam("table") @Pattern(regexp = ALPHA_NUM_REGEX_BLANK_OK) String table) { Map<String,Object> model = getModel(); model.put("title", "Per-Table Problem Report"); model.put("template", "problems.ftl"); model.put("js", "problems.js"); START if (!table.isBlank()) { END model.put("table", table); } return model; } This could be null, I think.

Target:
getProblems(@QueryParam("table") @Pattern(regexp = ALPHA_NUM_REGEX_BLANK_OK) String table) { Map<String,Object> model = getModel(); model.put("title", "Per-Table Problem Report"); model.put("template", "problems.ftl"); model.put("js", "problems.js"); if (table != null && !table.isBlank()) { model.put("table", table); } return model; }
Source:
public Ample.TabletMutator putBulkFile(Ample.FileMeta bulkref, long tid) { Preconditions.checkState(updatesEnabled, "Cannot make updates after calling mutate."); START Value tidBytes = new Value(Long.toString(tid).getBytes()); END mutation.put(TabletsSection.BulkFileColumnFamily.NAME, bulkref.meta(), tidBytes); return this; } Should use the Value constructor that takes String

Target:
public Ample.TabletMutator putBulkFile(Ample.FileMeta bulkref, long tid) { Preconditions.checkState(updatesEnabled, "Cannot make updates after calling mutate."); mutation.put(TabletsSection.BulkFileColumnFamily.NAME, bulkref.meta(), new Value(Long.toString(tid))); return this; }
Source:
public SummarizerConfiguration build() { return new SummarizerConfiguration(className, configId, START Collections.unmodifiableMap(imBuilder)); END } This does not have the same behavior. If someone calls addOption on the builder after calling build it would modify the map. Could set imBuilder to null to prevent future use. Or could call Map.copyOf

Target:
public SummarizerConfiguration build() { return new SummarizerConfiguration(className, configId, imBuilder.build()); }
Source:
public void testInputFormatBuilderImplTest_ExecuteHints() { SortedMap<String,String> hints = new TreeMap<>(); hints.put("key1", "value1"); hints.put("key2", "value2"); hints.put("key3", "value3"); formatBuilderTest.executionHints(hints); SortedMap<String,String> executionHints = formatBuilderTest.getExecutionHints(); START assertEquals(executionHints.toString(), hints.toString()); END } In an asserts statement, the expected values is the first argument. Please switch the order of the arguments.

Target:
public void testInputFormatBuilderImplTest_ExecuteHints() { SortedMap<String,String> hints = new TreeMap<>(); hints.put("key1", "value1"); hints.put("key2", "value2"); hints.put("key3", "value3"); formatBuilderTest.executionHints(hints); SortedMap<String,String> executionHints = formatBuilderTest.getExecutionHints(); assertEquals(hints.toString(), executionHints.toString()); }
Source:
public Options getOptions() { final Options opts = super.getOptions(); numThreadsOpt = new Option("nt", "num-threads", true, "number of threads to use"); negateOpt = new Option("v", "negate", false, "only include rows without search term"); START profileNameOpt = new Option("pn", "profile-name", true, END "only include rows from that iterator profile"); opts.addOption(numThreadsOpt); opts.addOption(negateOpt); opts.addOption(profileNameOpt); return opts; } Not completely sure, but I think the earlier call to `super.getOptions();` may already add a profile option.

Target:
public Options getOptions() { final Options opts = super.getOptions(); numThreadsOpt = new Option("nt", "num-threads", true, "number of threads to use"); negateOpt = new Option("v", "negate", false, "only include rows without search term"); opts.addOption(numThreadsOpt); opts.addOption(negateOpt); return opts; }
Source:
public void useRetry() { if (!canRetry()) { throw new IllegalStateException("No retries left"); } retriesDone++; START firstRetry = false; END } This is redundant. retriesDone already tells us whether we've done any retries or not.

Target:
public void useRetry() { if (!canRetry()) { throw new IllegalStateException("No retries left"); } retriesDone++; }
Source:
private TNonblockingTransport getTransport(FrameBuffer frameBuffer) { try { return (TNonblockingTransport) fbTansportField.get(frameBuffer); } catch (IllegalArgumentException | IllegalAccessException e) { START throw new RuntimeException(e); END } } I know this is copied from Thrift, but still seems unnecessary to wrap an RTE with a new RTE.

Target:
private TNonblockingTransport getTransport(FrameBuffer frameBuffer) { try { return (TNonblockingTransport) fbTansportField.get(frameBuffer); } catch (IllegalAccessException e) { throw new RuntimeException(e); } }
Source:
public void close() { try { for (RFileSource source : opts.in.getSources()) { source.getInputStream().close(); } } catch (IOException e) { throw new RuntimeException(e); } try { if (this.blockCacheManager != null) { this.blockCacheManager.stop(); } START } catch (RuntimeException e1) { END throw new RuntimeException(e1); } } This catch block could probably be removed.

Target:
public void close() { try { for (RFileSource source : opts.in.getSources()) { source.getInputStream().close(); } } catch (IOException e) { throw new RuntimeException(e); } if (this.blockCacheManager != null) { this.blockCacheManager.stop(); } }
Source:
public void close() { try { for (RFileSource source : opts.in.getSources()) { source.getInputStream().close(); } } catch (IOException e) { throw new RuntimeException(e); } try { if (this.blockCacheManager != null) { this.blockCacheManager.stop(); } } catch (UnsupportedOperationException e1) { START throw new UnsupportedOperationException(e1); END } } I'm confused by this. Why not just let e1 get thrown all the way through?

Target:
public void close() { try { for (RFileSource source : opts.in.getSources()) { source.getInputStream().close(); } } catch (IOException e) { throw new RuntimeException(e); } if (this.blockCacheManager != null) { this.blockCacheManager.stop(); } }
Source:
public void testEscape() { byte[] bytes = {0x00, 0x01}; byte[] escaped = ByteUtils.escape(bytes); assertArrayEquals(bytes, ByteUtils.unescape(escaped)); // no escaped bytes found so returns the input byte[] notEscaped = {0x02, 0x02, 0x02}; assertArrayEquals(notEscaped, ByteUtils.unescape(notEscaped)); // incomplete bytes would cause an ArrayIndexOutOfBounds in the past exception.expect(IllegalArgumentException.class); byte[] errorBytes = {0x01}; START assertArrayEquals(errorBytes, ByteUtils.unescape(errorBytes)); END } Is it expected that `ByteUtils.unescape(errorBytes)` will throw an exception? If so, why check the return value?

Target:
public void testEscape() { byte[] bytes = {0x00, 0x01}; byte[] escaped = ByteUtils.escape(bytes); assertArrayEquals(bytes, ByteUtils.unescape(escaped)); // no escaped bytes found so returns the input byte[] notEscaped = {0x02, 0x02, 0x02}; assertArrayEquals(notEscaped, ByteUtils.unescape(notEscaped)); }
Source:
public boolean canDeleteTable(TCredentials c, TableId tableId, NamespaceId namespaceId) throws ThriftSecurityException { String tableName = getTableName(tableId); try { boolean result = super.canDeleteTable(c, tableId, namespaceId); START audit(c, result, CAN_DELETE_TABLE_AUDIT_TEMPLATE, tableName); END return result; } catch (ThriftSecurityException ex) { audit(c, ex, CAN_DELETE_TABLE_AUDIT_TEMPLATE, tableName); throw ex; } } Why drop the tableId here?

Target:
public boolean canDeleteTable(TCredentials c, TableId tableId, NamespaceId namespaceId) throws ThriftSecurityException { String tableName = getTableName(tableId); try { boolean result = super.canDeleteTable(c, tableId, namespaceId); audit(c, result, CAN_DELETE_TABLE_AUDIT_TEMPLATE, tableName, tableId); return result; } catch (ThriftSecurityException ex) { audit(c, ex, CAN_DELETE_TABLE_AUDIT_TEMPLATE, tableName, tableId); throw ex; } }
Source:
public Configuration getConfiguration() { START return new ConfigurationImpl(srvCtx.getConfiguration()); END } Do we want to create a new object when getConfiguration() methods are called? I am thinking of the use case where user code passes around the ServiceEnv and calls getConfiguration().get() frequently would create too many objects. Shouldn't we create a single ConfigurationImpl object in the ServiceEnvironment constructor?

Target:
public Configuration getConfiguration() { return conf; }
Source:
public void testSetTime() throws Exception { try (AccumuloClient client = createAccumuloClient()) { tableName = "testSetTime_table1"; NewTableConfiguration newTableConf = new NewTableConfiguration(); // set logical time type so we can set time on bulk import newTableConf.setTimeType(TimeType.LOGICAL); client.tableOperations().create(tableName, newTableConf); START aconf = getCluster().getServerContext().getConfiguration(); END fs = getCluster().getFileSystem(); rootPath = cluster.getTemporaryPath().toString(); testSingleTabletSingleFile(client, false, true); } } Seems like there is no need to set `aconf`, `fs`, and `rootPath` here as these will be set by the `@Before` method.

Target:
public void testSetTime() throws Exception { try (AccumuloClient client = createAccumuloClient()) { tableName = "testSetTime_table1"; NewTableConfiguration newTableConf = new NewTableConfiguration(); // set logical time type so we can set time on bulk import newTableConf.setTimeType(TimeType.LOGICAL); client.tableOperations().create(tableName, newTableConf); testSingleTabletSingleFile(client, false, true); } }
Source:
public InputFormatBuilder.InputFormatOptions<T> addIterator(IteratorSetting cfg) { // store iterators by name to prevent duplicates Objects.requireNonNull(cfg, "IteratorSetting must not be null."); this.iterators.put(cfg.getName(), cfg); START tableConfigMap.get(currentTable).setIterators(new ArrayList<>(this.iterators.values())); END return this; } The way `this.iterators` is used seems a bit odd. Dropping `this.iterators` and doing `tableConfigMap.get(currentTable).addIterator(cfg)` might clean this up.

Target:
public InputFormatBuilder.InputFormatOptions<T> addIterator(IteratorSetting cfg) { // store iterators by name to prevent duplicates Objects.requireNonNull(cfg, "IteratorSetting must not be null."); tableConfigMap.get(currentTable).addIterator(cfg); return this; }
Source:
public T build() { START return builderFunction.build(this); END } If using `Function<ClientBuilderImpl, T>` for the build function type, instead of a custom interface, this method becomes `return builderFunction.apply(this);`

Target:
public T build() { return builderFunction.apply(this); }
Source:
public InputInfoBuilder.TableParams clientInfo(ClientInfo clientInfo) { START Objects.requireNonNull(clientInfo, "ClientInfo must not be null"); END this.clientInfo = clientInfo; return this; } ```java this.clientInfo = Objects.requireNonNull(clientInfo, "ClientInfo must not be null"); ```

Target:
public InputInfoBuilder.TableParams clientInfo(ClientInfo clientInfo) { this.clientInfo = Objects.requireNonNull(clientInfo, "ClientInfo must not be null"); return this; }
Source:
public Collection<IteratorSetting> getIterators() { START return iterators.entrySet().stream().map(Map.Entry::getValue).collect(Collectors.toSet()); END } Could do `iterators.values()`

Target:
public Collection<IteratorSetting> getIterators() { return iterators.values(); }
Source:
private void ensureOpen() { START Preconditions.checkState(!closed, "This client was closed."); END } Since this check is already isolated to its own method, I'm not we benefit much by the depenency on the third party utility. We could just inline the if statement. That way, it's one less place where we depend on Guava.

Target:
private void ensureOpen() { if (closed) { throw new IllegalStateException("This client was closed."); } }
Source:
public boolean createIfNotExists(String tableName, NewTableConfiguration ntc) throws AccumuloException, AccumuloSecurityException { try { START if (!exists(tableName)) { END create(tableName, ntc); return true; } else { return false; } } catch (TableExistsException e) { // should not happen throw new AssertionError(e); } } This code has a race condition. Its possible that another thread creates a table between `exists()` and `create()`. The following avoids the race condition. ```java try{ create(tableName, ntc); ￼ return true; } catch (TableExistsException e) { return false } ```

Target:
public boolean createIfNotExists(String tableName, NewTableConfiguration ntc) throws AccumuloException, AccumuloSecurityException { try { create(tableName, ntc); return true; } catch (TableExistsException e) { return false; } }
Source:
public synchronized String getPropertiesPath() { if (propsPath == null) { START URL propLocation = SiteConfiguration.getAccumuloPropsLocation(); END propsPath = propLocation.getFile(); } return propsPath; } ```java propsPath = SiteConfiguration.getAccumuloPropsLocation().getFile();

Target:
public synchronized String getPropertiesPath() { if (propsPath == null) { propsPath = SiteConfiguration.getAccumuloPropsLocation().getFile(); } return propsPath; }
Source:
public Connector getConnector(String user, String passwd) throws AccumuloException, AccumuloSecurityException { START return (Connector) impl.getAccumuloClient(user, new PasswordToken(passwd)); END } Would be a bit cleaner to use `Connector.from()` here.

Target:
public Connector getConnector(String user, String passwd) throws AccumuloException, AccumuloSecurityException { return Connector.from(impl.getAccumuloClient(user, new PasswordToken(passwd))); }
Source:
private static URL toURL(File f) { try { return f.toURI().toURL(); } catch (MalformedURLException e) { START throw new IllegalStateException(e); END } } If it's a malformed URL, then it's an illegal argument to the method, rather than an illegal state.

Target:
private static URL toURL(File f) { try { return f.toURI().toURL(); } catch (MalformedURLException e) { throw new IllegalArgumentException(e); } }
Source:
public void turnCryptoOnInSiteConfig() { SiteConfiguration.clearInstance(); SiteConfiguration siteConfig = SiteConfiguration.getInstance(); START siteConfig.set(Property.INSTANCE_CRYPTO_SERVICE, AESCryptoService.class.getName()); END siteConfig.set("instance.crypto.opts.kekId", "file:///tmp/testAESFile"); siteConfig.set("instance.crypto.opts.keyManager", "uri"); CryptoServiceFactory.resetInstance(); } Site configuration should be immutable. It represents the state of a configuration file. We typically put stuff in a "CopyConfiguration" (or is it "ConfigurationCopy"?) to modify it. This setter seems out of place here.

Target:
public void turnCryptoOnInSiteConfig() { SiteConfiguration.clearInstance(); SiteConfiguration siteConfig = SiteConfiguration.create(); siteConfig.set(Property.INSTANCE_CRYPTO_SERVICE, AESCryptoService.class.getName()); siteConfig.set("instance.crypto.opts.kekId", "file:///tmp/testAESFile"); siteConfig.set("instance.crypto.opts.keyManager", "uri"); CryptoServiceFactory.resetInstance(); }
Source:
public VolumeChooserEnvironment(Table.ID tableId, ServerContext context) { this.scope = ChooserScope.TABLE; START this.context = context; END this.tableId = Objects.requireNonNull(tableId); tabletId = null; } I do not think we need this method. I believe it was removed from the master branch. Might be useful to rebase yours.

Target:
public VolumeChooserEnvironment(Table.ID tableId, ServerContext context) { this(tableId, null, context); }
Source:
synchronized public Instance getInstance() { if (cachedInstance == null) { if (mock) { START cachedInstance = DeprecationUtil.makeMockInstance(instance); END } else { try { cachedInstance = getConnector().getInstance(); } catch (AccumuloSecurityException | AccumuloException e) { throw new RuntimeException(e); } } } return cachedInstance; } Mock is deprecated. If we're changing this code anyway, it's probably better to go ahead and phase it out, if it isn't going to add too many complications.

Target:
synchronized public Instance getInstance() { if (cachedInstance == null) { try { cachedInstance = getConnector().getInstance(); } catch (AccumuloSecurityException | AccumuloException e) { throw new IllegalStateException(e); } } return cachedInstance; }
Source:
START public void setBaseOptions(Options options) { END setPriorityOptions(options); setNameOptions(options); setIteratorTypeOptions(options); } I this refactoring, very nice. Could make this method protected.

Target:
protected void setBaseOptions(Options options) { setPriorityOptions(options); setNameOptions(options); setIteratorTypeOptions(options); }
Source:
private void put(byte b[], int length) { buffer.writeVLong(length); buffer.add(b, 0, length); START estimatedSize += length + SERIALIZATION_OVERHEAD; END } seems like this will double count some data

Target:
private void put(byte b[], int length) { buffer.writeVLong(length); buffer.add(b, 0, length); }
Source:
public long getUpdateCount() { START return Math.max(parent.getUpdateCount(), getPropCacheAccessor().getZooCache().getUpdateCount()); END } This should be sum of parent and self, not max.

Target:
public long getUpdateCount() { return parent.getUpdateCount() + getPropCacheAccessor().getZooCache().getUpdateCount(); }
Source:
START public QualifierStep family(byte[] colFam, int colFamLength) { END columnFamily = colFam; columnFamilyLength = colFamLength; return this; } should add `@Override` annotation here and to all other methods. Eclipse can automatically do this.

Target:
private QualifierStep family(byte[] colFam, int colFamLength) { columnFamily = colFam; columnFamilyLength = colFamLength; return this; }
Source:
int count(String tableName, Connector conn) throws Exception { Scanner s = conn.createScanner(tableName, Authorizations.EMPTY); START s.close(); END return Iterators.size(s.iterator()); } This shouldn't be closed before it is used.

Target:
int count(String tableName, Connector conn) throws Exception { try (Scanner s = conn.createScanner(tableName, Authorizations.EMPTY)) { return Iterators.size(s.iterator()); } }
Source:
START public NewTableConfiguration attachIterator(IteratorSetting setting) throws AccumuloException { END return attachIterator(setting, EnumSet.allOf(IteratorScope.class)); } I don't think that these methods need to throw a checked `AccumuloException`. It might be preferable for them to just throw an `IllegalArgumentException`, since the problem is with the bad argument to the method, and not a problem with Accumulo itself.

Target:
public NewTableConfiguration attachIterator(IteratorSetting setting) { return attachIterator(setting, EnumSet.allOf(IteratorScope.class)); }
Source:
public String marshal(AbstractId id) { START return id.canonicalID(); END } Should guard against NPE here. Serialization shouldn't break if ID is null.

Target:
public String marshal(AbstractId id) { if (id != null) return id.canonicalID(); else return null; }
Source:
START private static void incrementIV(byte[] iv, int i) { END iv[i]++; if (iv[i] == 0) { if (i != 0) { incrementIV(iv, i - 1); } else return; } } This implementation looks correct to me, but I think it should have its own unit test, to be sure, and to prevent regressions. I think testing all the boundary cases for arrays of length 1, 2, and 3, would be sufficient to cover all possible cases. (`i == 0, i == a.len-1, and 0 < i < a.len-1`)

Target:
static void incrementIV(byte[] iv, int i) { iv[i]++; if (iv[i] == 0) { if (i != 0) { incrementIV(iv, i - 1); } else return; } }
Source:
public void AESGCM_Encryption_Test_Correct_Encryption_And_Decryption() throws IOException, AEADBadTagException { AccumuloConfiguration conf = setAndGetAccumuloConfig(CRYPTO_ON_CONF); byte[] encryptedBytes = testEncryption(conf, new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20}); Integer result = testDecryption(conf, encryptedBytes); START assert (result.equals(1)); END } should use assertTrue or assertEquals

Target:
public void AESGCM_Encryption_Test_Correct_Encryption_And_Decryption() throws IOException, AEADBadTagException { AccumuloConfiguration conf = setAndGetAccumuloConfig(CRYPTO_ON_CONF); byte[] encryptedBytes = testEncryption(conf, new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20}); Integer result = testDecryption(conf, encryptedBytes); assertEquals(result, Integer.valueOf(1)); }
Source:
public static String get(Property property) { START if (config.containsKey(property.getKey())) { END return config.get(property.getKey()); } return null; } Why do the containsKey check? If its not in the map, then get() will return null.

Target:
public static String get(Property property) { return config.get(property.getKey()); }
Source:
private String getInitialPasswordWarning() { StringBuilder optionalWarning = new StringBuilder(); Property authenticatorProperty = Property.INSTANCE_SECURITY_AUTHENTICATOR; if (SiteConfiguration.getInstance().get(authenticatorProperty).equals(authenticatorProperty.getDefaultValue())) optionalWarning.append(": "); else optionalWarning.append(" (this may not be applicable for your security setup): "); START return optionalWarning.toString(); END } Can probably avoid use of StringBuilder here, since there is only a single string to return in each case, and it's not being concatenated with anything else until outside the method. Other than that, this change looks good to me. Thanks for the contribution!

Target:
private String getInitialPasswordWarning() { String optionalWarning; Property authenticatorProperty = Property.INSTANCE_SECURITY_AUTHENTICATOR; if (SiteConfiguration.getInstance().get(authenticatorProperty).equals(authenticatorProperty.getDefaultValue())) optionalWarning = ": "; else optionalWarning = " (this may not be applicable for your security setup): "; return optionalWarning; }
Source:
public Writer(BlockFileWriter bfw, int blockSize) throws IOException { this(bfw, blockSize, (int) DefaultConfiguration.getInstance().getAsBytes(Property.TABLE_FILE_COMPRESSED_BLOCK_SIZE_INDEX), null, null); long indexBlockSize = DefaultConfiguration.getInstance().getAsBytes(Property.TABLE_FILE_COMPRESSED_BLOCK_SIZE_INDEX); START if (indexBlockSize > Integer.MAX_VALUE || indexBlockSize < 0) { END throw new IllegalArgumentException("table.file.compress.blocksize.index must be greater than 0 and no more than " + Integer.MAX_VALUE); } } This appears to only be checking the default value... which is hard-coded. A check in the unit test for Property could ensure we don't make a stupid mistake for the default. I think we may have a validate method in Property.java, also, which might be used to do a quick verification that a value is good when a user sets it or when the process starts up and reads the config for the first time.

Target:
public Writer(BlockFileWriter bfw, int blockSize) throws IOException { this(bfw, blockSize, (int) DefaultConfiguration.getInstance().getAsBytes(Property.TABLE_FILE_COMPRESSED_BLOCK_SIZE_INDEX), null, null); }
Source:
public void write(byte b[], int off, int len) throws IOException { count += len; if (count > maxOutputSize) { throw new IOException("Attempt to write " + count + " bytes was made. A maximum of " + maxOutputSize + " is allowed for an encryption stream."); } START obuffer = cipher.update(b, off, len); END if (obuffer != null) { output.write(obuffer); obuffer = null; } } can you call super.write here?

Target:
public void write(byte b[], int off, int len) throws IOException { count += len; if (count > maxOutputSize) { throw new IOException("Attempt to write " + count + " bytes was made. A maximum of " + maxOutputSize + " is allowed for an encryption stream."); } super.write(b, off, len); }
Source:
TableConfWatcher(Instance instance) { this.instance = instance; tablesPrefix = ZooUtil.getRoot(instance) + Constants.ZTABLES + "/"; START tablesPrefixLength = tablesPrefix.length(); END scf = new ServerConfigurationFactory(instance); } Why store the length?

Target:
TableConfWatcher(Instance instance) { this.instance = instance; tablesPrefix = ZooUtil.getRoot(instance) + Constants.ZTABLES + "/"; scf = new ServerConfigurationFactory(instance); }
Source:
public GarbageCollectorCycle() { START started = finished = candidates = inUse = deleted = errors = 0l; END } Each on their own line, or do this when you declare the variables and remove the default constructor. This doesn't match existing style.

Target:
public GarbageCollectorCycle()
Source:
public Builder addOption(String key, long value) { START return addOption(key, value + ""); END } `Integer.toString(value)`

Target:
public Builder addOption(String key, long value) { return addOption(key, Long.toString(value)); }
Source:
protected String getNamespaceId() { try { return Tables.getNamespaceId(inst, tableId); } catch (TableNotFoundException e) { START return null; END } } why return null here?

Target:
protected String getNamespaceId() { try { return Tables.getNamespaceId(inst, tableId); } catch (TableNotFoundException e) { throw new RuntimeException(e); } }
Source:
private boolean switchSource() throws IOException { if (!source.isCurrent()) { source = source.getNewDataSource(); // if our source actually changed, then attempt to close the previous iterator try { if (iter != null) { iter.close(); } } catch (Exception e) { START throw new IOException(e); END } iter = source.iterator(); return true; } return false; } This is a private method. Do we need to wrap exceptions here, or should we handle it in the caller? It seems we might be converting them to IOExceptions here, only to have them converted back to RuntimeExceptions later.

Target:
private boolean switchSource() throws IOException { if (!source.isCurrent()) { source = source.getNewDataSource(); iter = source.iterator(); return true; } return false; }
Source:
public DataSource getNewDataSource() { if (switched) throw new IllegalStateException(); if (!isCurrent()) { switched = true; try { if (iter != null) { iter.close(); } iter = null; // ensure files are referenced even if iterator was never seeked before iterator(); } catch (Exception e) { START throw new RuntimeException(e); END } } return this; } I think this can be changed to : ``` java } catch (IOException e) { throw new UncheckedIOException(e) } ```

Target:
public DataSource getNewDataSource() { if (switched) throw new IllegalStateException(); if (!isCurrent()) { switched = true; iter = null; try { // ensure files are referenced even if iterator was never seeked before iterator(); } catch (IOException e) { throw new RuntimeException(); } } return this; }
Source:
START public Key(byte row[], int rOff, int rLen, byte cf[], int cfOff, int cfLen, byte cq[], int cqOff, int cqLen, byte cv[], int cvOff, int cvLen, long ts, boolean deleted, boolean copy) { END init(row, rOff, rLen, cf, cfOff, cfLen, cq, cqOff, cqLen, cv, cvOff, cvLen, ts, deleted, copy); } This should be package-private.

Target:
Key(byte row[], int rOff, int rLen, byte cf[], int cfOff, int cfLen, byte cq[], int cqOff, int cqLen, byte cv[], int cvOff, int cvLen, long ts, boolean deleted, boolean copy) { init(row, rOff, rLen, cf, cfOff, cfLen, cq, cqOff, cqLen, cv, cvOff, cvLen, ts, deleted, copy); }
Source:
public int available() throws IOException { final FSDataInputStream inLocal = in; synchronized (inLocal) { START int avail = in.available(); END if (pos + avail > end) { avail = (int) (end - pos); } return avail; } } The input stream doesn't change. Why can't this be computed by using the offset of the last read minus what was available when it was passed in?

Target:
public int available() throws IOException { return (int) (end - pos); }