auphong2707/dl4se-code-review-dataset huggingface dataset:
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(); aspectRatio.setValue(Objects.firstNonNull(encoding.getVideoAspectRatio(), DEFAULT_ASPECT_RATIO)); videoAttributes.getAspectRatio().add(aspectRatio); return videoAttributes; }

Target:
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.
Source:
private Function<Version, Iterable<Broadcast>> toBroadcasts() { return new Function<Version, Iterable<Broadcast>>() { @Override public Iterable<Broadcast> apply(Version input) { return input.getBroadcasts(); } }; }

Target:
Can these 2 functions be constants? So we don't need to create new instances every time these methods are called
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); super.onBindDialogView(view); }

Target:
Should this be done first in the method?
Source:
public void copyCurrentSelectionToClipboard() { terminalTextViewOverlay.copyCurrentSelectionToClipboard(); }

Target:
This could be `null`, but is this even used anymore?
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 && getIntent().getAction() == DISCONNECT_ACTION) { Log.d(TAG, "Got disconnect all request"); disconnectAll(); } // Still close on disconnect if waiting for a disconnect. closeOnDisconnectAll = waitingForDisconnectAll && closeOnDisconnectAll; }

Target:
DISCONNECT_ACTION.equals(getIntent().getAction())
Source:
public PluginConfig(String className) { requireNonNull(className); this.className = className; }

Target:
```suggestion this.className = requireNonNull(className); ```
Source:
protected String getLockID() { return lockID; }

Target:
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.
Source:
protected void acquireRecoveryMemory(KeyExtent extent) { if (!extent.isMeta()) { recoveryLock.lock(); } }

Target:
```suggestion void acquireRecoveryMemory(KeyExtent extent) { ```
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; return Objects.equals(usage, diskUsage.usage); }

Target:
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.
Source:
public Builder addOptions(Map<String,String> options) { options.forEach((key, value) -> addOption(key, value)); return this; }

Target:
You can even go a step further with this one: ```suggestion options.forEach(this::addOption); ```
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); } return path; }

Target:
Did we want to have this normalize the path also by returning the normalized version from `Path`?
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 } System.out.println(); listTable(Ample.DataLevel.METADATA, context); System.out.println(); listTable(Ample.DataLevel.USER, context); }

Target:
I see. Yeah I would at least print there are no volumes, that would be helpful.
Source:
public SeekableByteArrayInputStream(byte[] buf, int maxOffset) { Objects.requireNonNull(buf, "bug argument was null"); this.buffer = buf; this.cur = 0; this.max = maxOffset; }

Target:
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.
Source:
Collection<String> asNames(List<Path> recoveryLogs) { return Collections2.transform(recoveryLogs, input -> input.getName()); }

Target:
```suggestion return Collections2.transform(recoveryLogs, input::getName); ```
Source:
private static boolean checkNoCrypto(byte[] params) { byte[] noCryptoBytes = NO_CRYPTO_VERSION.getBytes(StandardCharsets.UTF_8); return Arrays.equals(params, noCryptoBytes); }

Target:
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.
Source:
String getTraceId(HttpServletRequest req) { final String stringValue = getStringParameter(req, "id", null); return TRACE_ID_PATTERN.matcher(stringValue).matches() ? stringValue : null; }

Target:
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; ```
Source:
protected void prepareMetrics() { metricsValuesLock.lock(); try { long now = System.currentTimeMillis(); if ((lastUpdate + minimumRefreshDelay) < now) { metricValues = updateFromZookeeper(); lastUpdate = now; } recordValues(); } finally { metricsValuesLock.unlock(); } }

Target:
If metricValues is the same as the last time recordValues() was called will calling it have an effect?
Source:
RowLock(ReentrantLock rlock, ByteSequence rowSeq) { this.rlock = rlock; this.count = new AtomicInteger(1); this.rowSeq = rowSeq; }

Target:
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.
Source:
private void returnRowLock(RowLock lock) { rowLocks.compute(lock.rowSeq, (key, value) -> { Objects.requireNonNull(value); Preconditions.checkState(value.count.intValue() > 0); final int newCount = value.count.decrementAndGet(); return (newCount > 0) ? value : null; }); }

Target:
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; }); } ```
Source:
public static boolean isValidBooleanPropertyKey(String key) { return validProperties.contains(key) && getPropertyByKey(key).getType().equals(PropertyType.BOOLEAN); }

Target:
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; ```
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 return GSON.toJson(gd).replaceAll(" ", " "); }

Target:
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.
Source:
public String getMessage() { StringBuilder message = new StringBuilder(); message.append("Error ").append(errorCode); message.append(" for user ").append(user); if (!tableInfo.isEmpty()) { message.append(" on table ").append(tableInfo); } message.append(" - ").append(super.getMessage()); return message.toString(); }

Target:
These aren't equivalent. The `StringUtils` version checks for `null` and `""` in one call.
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"); if (!table.isBlank()) { model.put("table", table); } return model; }

Target:
This could be null, I think.
Source:
public Ample.TabletMutator putBulkFile(Ample.FileMeta bulkref, long tid) { Preconditions.checkState(updatesEnabled, "Cannot make updates after calling mutate."); Value tidBytes = new Value(Long.toString(tid).getBytes()); mutation.put(TabletsSection.BulkFileColumnFamily.NAME, bulkref.meta(), tidBytes); return this; }

Target:
Should use the Value constructor that takes String
Source:
public SummarizerConfiguration build() { return new SummarizerConfiguration(className, configId, Collections.unmodifiableMap(imBuilder)); }

Target:
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
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(); assertEquals(executionHints.toString(), hints.toString()); }

Target:
In an asserts statement, the expected values is the first argument. Please switch the order of the arguments.
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"); profileNameOpt = new Option("pn", "profile-name", true, "only include rows from that iterator profile"); opts.addOption(numThreadsOpt); opts.addOption(negateOpt); opts.addOption(profileNameOpt); return opts; }

Target:
Not completely sure, but I think the earlier call to `super.getOptions();` may already add a profile option.
Source:
public void useRetry() { if (!canRetry()) { throw new IllegalStateException("No retries left"); } retriesDone++; firstRetry = false; }

Target:
This is redundant. retriesDone already tells us whether we've done any retries or not.
Source:
private TNonblockingTransport getTransport(FrameBuffer frameBuffer) { try { return (TNonblockingTransport) fbTansportField.get(frameBuffer); } catch (IllegalArgumentException | IllegalAccessException e) { throw new RuntimeException(e); } }

Target:
I know this is copied from Thrift, but still seems unnecessary to wrap an RTE with a new RTE.
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 (RuntimeException e1) { throw new RuntimeException(e1); } }

Target:
This catch block could probably be removed.
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) { throw new UnsupportedOperationException(e1); } }

Target:
I'm confused by this. Why not just let e1 get thrown all the way through?
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}; assertArrayEquals(errorBytes, ByteUtils.unescape(errorBytes)); }

Target:
Is it expected that `ByteUtils.unescape(errorBytes)` will throw an exception? If so, why check the return value?
Source:
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); return result; } catch (ThriftSecurityException ex) { audit(c, ex, CAN_DELETE_TABLE_AUDIT_TEMPLATE, tableName); throw ex; } }

Target:
Why drop the tableId here?
Source:
public Configuration getConfiguration() { return new ConfigurationImpl(srvCtx.getConfiguration()); }

Target:
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?
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); aconf = getCluster().getServerContext().getConfiguration(); fs = getCluster().getFileSystem(); rootPath = cluster.getTemporaryPath().toString(); testSingleTabletSingleFile(client, false, true); } }

Target:
Seems like there is no need to set `aconf`, `fs`, and `rootPath` here as these will be set by the `@Before` method.
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); tableConfigMap.get(currentTable).setIterators(new ArrayList<>(this.iterators.values())); return this; }

Target:
The way `this.iterators` is used seems a bit odd. Dropping `this.iterators` and doing `tableConfigMap.get(currentTable).addIterator(cfg)` might clean this up.
Source:
public T build() { return builderFunction.build(this); }

Target:
If using `Function<ClientBuilderImpl, T>` for the build function type, instead of a custom interface, this method becomes `return builderFunction.apply(this);`
Source:
public InputInfoBuilder.TableParams clientInfo(ClientInfo clientInfo) { Objects.requireNonNull(clientInfo, "ClientInfo must not be null"); this.clientInfo = clientInfo; return this; }

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

Target:
Could do `iterators.values()`
Source:
private void ensureOpen() { Preconditions.checkState(!closed, "This client was closed."); }

Target:
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.
Source:
public boolean createIfNotExists(String tableName, NewTableConfiguration ntc) throws AccumuloException, AccumuloSecurityException { try { if (!exists(tableName)) { create(tableName, ntc); return true; } else { return false; } } catch (TableExistsException e) { // should not happen throw new AssertionError(e); } }

Target:
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 } ```
Source:
public synchronized String getPropertiesPath() { if (propsPath == null) { URL propLocation = SiteConfiguration.getAccumuloPropsLocation(); propsPath = propLocation.getFile(); } return propsPath; }

Target:
```java propsPath = SiteConfiguration.getAccumuloPropsLocation().getFile();
Source:
public Connector getConnector(String user, String passwd) throws AccumuloException, AccumuloSecurityException { return (Connector) impl.getAccumuloClient(user, new PasswordToken(passwd)); }

Target:
Would be a bit cleaner to use `Connector.from()` here.
Source:
private static URL toURL(File f) { try { return f.toURI().toURL(); } catch (MalformedURLException e) { throw new IllegalStateException(e); } }

Target:
If it's a malformed URL, then it's an illegal argument to the method, rather than an illegal state.
Source:
public void turnCryptoOnInSiteConfig() { SiteConfiguration.clearInstance(); SiteConfiguration siteConfig = SiteConfiguration.getInstance(); 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(); }

Target:
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.
Source:
public VolumeChooserEnvironment(Table.ID tableId, ServerContext context) { this.scope = ChooserScope.TABLE; this.context = context; this.tableId = Objects.requireNonNull(tableId); tabletId = null; }

Target:
I do not think we need this method. I believe it was removed from the master branch. Might be useful to rebase yours.
Source:
synchronized public Instance getInstance() { if (cachedInstance == null) { if (mock) { cachedInstance = DeprecationUtil.makeMockInstance(instance); } else { try { cachedInstance = getConnector().getInstance(); } catch (AccumuloSecurityException | AccumuloException e) { throw new RuntimeException(e); } } } return cachedInstance; }

Target:
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.
Source:
public void setBaseOptions(Options options) { setPriorityOptions(options); setNameOptions(options); setIteratorTypeOptions(options); }

Target:
I this refactoring, very nice. Could make this method protected.
Source:
private void put(byte b[], int length) { buffer.writeVLong(length); buffer.add(b, 0, length); estimatedSize += length + SERIALIZATION_OVERHEAD; }

Target:
seems like this will double count some data
Source:
public long getUpdateCount() { return Math.max(parent.getUpdateCount(), getPropCacheAccessor().getZooCache().getUpdateCount()); }

Target:
This should be sum of parent and self, not max.
Source:
public QualifierStep family(byte[] colFam, int colFamLength) { columnFamily = colFam; columnFamilyLength = colFamLength; return this; }

Target:
should add `@Override` annotation here and to all other methods. Eclipse can automatically do this.
Source:
int count(String tableName, Connector conn) throws Exception { Scanner s = conn.createScanner(tableName, Authorizations.EMPTY); s.close(); return Iterators.size(s.iterator()); }

Target:
This shouldn't be closed before it is used.
Source:
public NewTableConfiguration attachIterator(IteratorSetting setting) throws AccumuloException { return attachIterator(setting, EnumSet.allOf(IteratorScope.class)); }

Target:
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.
Source:
public String marshal(AbstractId id) { return id.canonicalID(); }

Target:
Should guard against NPE here. Serialization shouldn't break if ID is null.
Source:
private static void incrementIV(byte[] iv, int i) { iv[i]++; if (iv[i] == 0) { if (i != 0) { incrementIV(iv, i - 1); } else return; } }

Target:
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`)
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); assert (result.equals(1)); }

Target:
should use assertTrue or assertEquals
Source:
public static String get(Property property) { if (config.containsKey(property.getKey())) { return config.get(property.getKey()); } return null; }

Target:
Why do the containsKey check? If its not in the map, then get() will return null.
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): "); return optionalWarning.toString(); }

Target:
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!
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); if (indexBlockSize > Integer.MAX_VALUE || indexBlockSize < 0) { throw new IllegalArgumentException("table.file.compress.blocksize.index must be greater than 0 and no more than " + Integer.MAX_VALUE); } }

Target:
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.
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."); } obuffer = cipher.update(b, off, len); if (obuffer != null) { output.write(obuffer); obuffer = null; } }

Target:
can you call super.write here?
Source:
TableConfWatcher(Instance instance) { this.instance = instance; tablesPrefix = ZooUtil.getRoot(instance) + Constants.ZTABLES + "/"; tablesPrefixLength = tablesPrefix.length(); scf = new ServerConfigurationFactory(instance); }

Target:
Why store the length?
Source:
public GarbageCollectorCycle() { started = finished = candidates = inUse = deleted = errors = 0l; }

Target:
Each on their own line, or do this when you declare the variables and remove the default constructor. This doesn't match existing style.
Source:
public Builder addOption(String key, long value) { return addOption(key, value + ""); }

Target:
`Integer.toString(value)`
Source:
protected String getNamespaceId() { try { return Tables.getNamespaceId(inst, tableId); } catch (TableNotFoundException e) { return null; } }

Target:
why return null here?
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) { throw new IOException(e); } iter = source.iterator(); return true; } return false; }

Target:
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.
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) { throw new RuntimeException(e); } } return this; }

Target:
I think this can be changed to : ``` java } catch (IOException e) { throw new UncheckedIOException(e) } ```
Source:
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) { init(row, rOff, rLen, cf, cfOff, cfLen, cq, cqOff, cqLen, cv, cvOff, cvLen, ts, deleted, copy); }

Target:
This should be package-private.
Source:
public int available() throws IOException { final FSDataInputStream inLocal = in; synchronized (inLocal) { int avail = in.available(); if (pos + avail > end) { avail = (int) (end - pos); } return avail; } }

Target:
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?
Source:
public int available() throws IOException { final FSDataInputStream inLocal = in; synchronized (inLocal) { int avail = inLocal.available(); if (pos + avail > end) { avail = (int) (end - pos); } return avail; } }

Target:
It seems like the method should seek before calling available. Like the following : ``` java synchronized (inLocal) { inLocal.seek(pos); int avail = inLocal.available(); . . . } ```
Source:
public void finish() throws IOException { if (!closed) { synchronized (in) { if (!closed) { try { in.close(); } finally { closed = true; if (decompressor != null) { try { compressAlgo.returnDecompressor(decompressor); } finally { decompressor = null; } } } } } } }

Target:
Whats the purpose of this double check? Is it an optimization to avoid sync? I suspect that in the majority of cases where this is called, closed will be false. Therefore this double check will usually result in an extra round trip to memory (reading closed twice from main memory) in the majority of cases. So this may slow down the majority case.
Source:
public Shell() throws IOException

Target:
Can remove the `throws IOException` as it won't affect callers at all. They were already expecting the IOException -- if we don't throw that anymore, that's fine.
Source:
static Key sanityCheck(Key prev, Key current, Key shortened) { if (prev.compareTo(shortened) >= 0) { LoggerFactory.getLogger(KeyShortener.class).warn("Bug in key shortening code, please open an issue " + prev + " >= " + shortened); return null; } if (current.compareTo(shortened) <= 0) { LoggerFactory.getLogger(KeyShortener.class).warn("Bug in key shortening code, please open an issue " + current + " <= " + shortened); return null; } return shortened; }

Target:
Make one Logger instance?
Source:
private List getUniqKVCount(List<MemKey> memKeys) { List<Integer> kvCounts = new ArrayList<Integer>(); for (MemKey m : memKeys) { kvCounts.add(m.getKVCount()); } return ImmutableSet.copyOf(kvCounts).asList(); }

Target:
Was this intended to be a `Set<Integer>`?
Source:
private Durability getMincEventDurability(KeyExtent extent) { TableConfiguration conf; if (extent.isMeta() || extent.isRootTablet()) { conf = confFactory.getTableConfiguration(RootTable.ID); } else { conf = confFactory.getTableConfiguration(MetadataTable.ID); } Durability durability = DurabilityImpl.fromString(conf.get(Property.TABLE_DURABILITY)); return durability; }

Target:
This check is a bit confusing. To me it reads "If the extent is for the metadata table or the root tablet, use the root tablet's configuration. Otherwise, use the metadata configuration." Is there some other setting for user tables that's more appropriate? `KeyExtent#isMeta` already returns whether or not it's for the metadata table or the root tablet, so the `|| extent.isRootTablet()` is redundant. However, I think refactoring `KeyExtent#isMeta` is more appropriate to make it more clear about what it is checking.
Source:
private SamplerConfiguration getIteratorSamplerConfigurationInternal() { SamplerConfiguration scannerSamplerConfig = getSamplerConfiguration(); if (scannerSamplerConfig != null) { if (iteratorSamplerConfig != null && !new SamplerConfigurationImpl(iteratorSamplerConfig).equals(new SamplerConfigurationImpl(scannerSamplerConfig))) { throw new IllegalStateException("Scanner and iterator sampler configuration differ"); } return scannerSamplerConfig; } return iteratorSamplerConfig; }

Target:
Can the instantiation of the objects in the equals method be broken out of the if condition? There's a lot going on for a simple equality check that would be easier to follow if the impls are instantiated earlier IMO
Source:
public TabletIteratorEnvironment(IteratorScope scope, AccumuloConfiguration config) { if (scope == IteratorScope.majc) throw new IllegalArgumentException("must set if compaction is full"); this.scope = scope; this.trm = null; this.config = config; this.fullMajorCompaction = false; this.authorizations = Authorizations.EMPTY; this.topLevelIterators = new ArrayList<SortedKeyValueIterator<Key,Value>>(); }

Target:
Unnecessary SKVI<K,V> parameterization?
Source:
protected static boolean isBatchScan(JobContext context) { return InputConfigurator.isIsolated(CLASS, context.getConfiguration()); }

Target:
Why JobContext here? And why not public?
Source:
private List<String> getJavaBuildPathLibraries(PropertyDialog pd) { pd.select("Java Build Path"); BuildPathsPropertyPage bppp = new BuildPathsPropertyPage(pd); bppp.activateLibrariesTab(); List<String> libs = new ArrayList<String>(); libs.addAll(bppp.getLibraries()); log.debug("Libraries found after conversion:"); for (String i : libs) { log.debug(" " + i); } return libs; }

Target:
Instead of this use something similar with select, see https://github.com/eclipse/reddeer/blob/5791383f991e4b2503988d5db59cc85b93055cfc/tests/org.eclipse.reddeer.eclipse.test/src/org/eclipse/reddeer/eclipse/test/jdt/ui/preferences/BuildPathsPropertyPageTest.java#L81 (to hide "Java Build Path" string in reddeer)
Source:
public static void setup() { WorkbenchPreferenceDialog preferenceDialog = new WorkbenchPreferenceDialog(); preferenceDialog.open(); MavenSettingsPreferencePage prefPage = new MavenSettingsPreferencePage(preferenceDialog); preferenceDialog.select(prefPage); preferenceDialog.ok(); new DefaultToolItem(new WorkbenchShell(), CENTRAL_LABEL).click(); // activate central editor new DefaultEditor(CENTRAL_LABEL); }

Target:
@zcervink lines 60-64 were related to setting settings.xml in preferences, and now this code is useless, so please remove it.
Source:
private AddIfSystemPropertyDialog invokeDefaultAddIfSystemPropertyDialog(String property){ new ContextMenu().getItem("Add System Property").select(); new WaitUntil(new ShellIsAvailable("Add If System Property")); new DefaultShell("Add If System Property"); return new AddIfSystemPropertyDialog(); }

Target:
no need for the wait
Source:
public boolean matches(Object item) { AbstractTableItem ti = (AbstractTableItem) item; for (int i = 0; i < 7; i++) { if (ti.getText(i).contains(text)) { return true; } } return false; }

Target:
What is 7 in this context?
Source:
public String toString() { return "Account{" + "id=" + id + ", description='" + description + '\'' + ", creationDate='" + creationDate + '\'' + ", limits=" + limits + ", blurb=" + blurb.stream().map(Arrays::toString).collect(Collectors.toList()) + ", unknownFieldSet='" + unknownFieldSet + '\'' + ", currencies='" + Arrays.toString(currencies) + '\'' + '}'; }

Target:
I'd prefer to have the unknownFieldSet as the last printed stuff.
Source:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Descriptor that = (Descriptor) o; return fullName.equals(that.fullName) && name.equals(that.name); }

Target:
Why include the name in the comparison? fullName should be enough.
Source:
public PoolConfig() { maxIdleTimeMillis = DEFAULT_MAX_IDLE_TIME_MILLIS; idleConnCleanupTicker = Observable.interval(maxIdleTimeMillis, TimeUnit.MILLISECONDS); idleConnectionsHolder = new FIFOIdleConnectionsHolder<>(); limitDeterminationStrategy = UnboundedPoolLimitDeterminationStrategy.INSTANCE; }

Target:
Sorry, one more. This should have an initial delay so that it doesn't try to clean up immediately. It's less important on creation, but if there are errors it will keep emitting right after each failure. This means a failure will keep triggering as fast as it can instead of just every `maxIdleTimeMillis`. ``` idleConnCleanupTicker = Observable.interval(maxIdleTimeMillis, maxIdleTimeMillis, TimeUnit.MILLISECONDS); ```
Source:
public static void addSortedParams(UriBuilder uriBuilder, DataMap params) { convertRawProjectionFieldsToMaskTree(params); Map<String, String> map = dataMapToQueryParams(params); addSortedParams(uriBuilder, map); }

Target:
Agree with Evan, also the projection parameters are already available as MaskTree in resourContext. So a better fix would be to update the `buildCriteriaURI()` method in BatchFinderResponseBuilder to replace the projection params with masktree objects.
Source:
protected static URI buildCriteriaURI(ResourceContextImpl resourceContext, RecordTemplate criteria, String batchParameterName, URI uri) throws CloneNotSupportedException { DataList criteriaList = new DataList(1); criteriaList.add(criteria.data()); DataMap queryParams = extractQueryParamsFromResourceContext(resourceContext); return URIParamUtils.replaceQueryParam(uri, batchParameterName, criteriaList, queryParams, resourceContext.getRestliProtocolVersion()); }

Target:
I'd suggest making private methods package-private if they need to be accessed by a unit test. Making it protected opens the access too much and implies an intended inheritance relationship.
Source:
public void testBuildCriteriaURI(ResourceContextImpl resourceContext, RecordTemplate criteria, String batchParameterName, URI uri, URI expectedURI) throws CloneNotSupportedException { URI generatedURI = BatchFinderResponseBuilder.buildCriteriaURI(resourceContext, criteria, batchParameterName, uri); Assert.assertEquals(generatedURI.toString(), expectedURI.toString()); }

Target:
remove CloneNotSupportedException
Source:
private Token finishToken(Token token) { _currentToken = token; if (_currentToken == START_OBJECT) { if (_currComplexObjTokenSize > 0) { _complexObjTokenSizeStack.push(_currComplexObjTokenSize); } _currComplexObjTokenSize = _intValue << 1; } else if (_currentToken == START_ARRAY) { if (_currComplexObjTokenSize > 0) { _complexObjTokenSizeStack.push(_currComplexObjTokenSize); } _currComplexObjTokenSize = _intValue; } else if (_currentToken != NOT_AVAILABLE) { _currComplexObjTokenSize--; } return _currentToken; }

Target:
switch instead of if else here?
Source:
public JacksonTraverseCallback(JsonGenerator generator) { this(generator, false); }

Target:
Why did we make this public?
Source:
protected void writeObject(Object object, JsonGenerator generator) throws IOException { try (Data.TraverseCallback callback = createTraverseCallback(generator)) { Data.traverse(object, callback); generator.flush(); } }

Target:
My point is about consistency between different codecs. Protobuf codec assumes the callback handles the flush, while this code has to call it explicitly. We should make it consistent and set the expectation that the traverse callback should handle flushing/closing the generator. Then the codec's would just close the traverse callback.
Source:
public ClasspathResourceDataSchemaResolver(ClassLoader classLoader) { for (DataSchemaParserFactory parserForFormat: BUILTIN_FORMAT_PARSER_FACTORIES) { SingleFormatClasspathSchemaResolver resolver = new SingleFormatClasspathSchemaResolver(parserForFormat); resolver.setExtension("." + parserForFormat.getLanguageExtension()); addResolver(resolver); } _classLoader = classLoader; }

Target:
why do we need this setter exposed? Should constructor handle this automatically?
Source:
public boolean handleRequest(RestRequest originalRequest, RestRequest darkRequest, RequestContext requestContext) { int numRequestDuplicates = getNumDuplicateRequests(_random.nextFloat()); return _baseDarkClusterDispatcher.sendRequest(originalRequest, darkRequest, requestContext, numRequestDuplicates); }

Target:
no need to include _random as an argument since it's already an instance variable.
Source:
protected Data.TraverseCallback createTraverseCallback(JsonGenerator generator, boolean traverseMapBySortedKeyOrder) { return traverseMapBySortedKeyOrder? new JacksonTraverseCallbackMapKeyOrdered(generator): new JacksonTraverseCallback(generator); }

Target:
space before ?
Source:
private static DataSchema backfillSchemaIfPossible(Class<?> type) { // These are all the classes used for type specs that are "schema-less". if (type == CompoundKey.class || type == ComplexResourceKey.class || type == Void.class || (!DataSchemaUtil.isPrimitiveClass(type) && DataTemplateUtil.hasCoercer(type))) { return null; } try { return DataTemplateUtil.getSchema(type); // could be a primitive, DataTemplate, TyperefInfo, or enum } catch (TemplateRuntimeException e) { // can happen in case of custom types return null; } }

Target:
Why don't you just keep track of registered custom classes in `Custom.java`? I think that would be simpler
Source:
public void testPattern() { DateTime dateTime = new DateTime().withDate(1995, 7, 4).withTime(14, 32, 12, 0); try { shouldCompileTo("{{jodaPatternHelper this \"y-MMM-d H:m:s\"}}", dateTime, "1995-Jul-4 14:32:12"); } catch (IOException e) { Assert.fail("IOException thrown"); } }

Target:
you don't need the `try/catch` for valid tests. The test will fail anyway when an exception occurs
Source:
public MethodCall(String methodName, Object[] args, Map<String, String> metaData, List<String> classes) { super(); init(methodName, args, classes, metaData); }

Target:
Why would this make sense? Just because of the order?
Source:
private String checkStage(EDBStage stage) { if (stage != null) { return stage.getStageId(); } return null; }

Target:
just write return stage != null ? stage.getStageId() : null; spare some lines : )
Source:
public void testConstructorWithUnparseablePath() throws IOException { Path unparseablePath = (new File(".")).toPath().resolve("UnparseableTagFolderName"); try { Tag tag = new ConfigurationTag(unparseablePath); } catch (ParseException e) { //This exception is expected to be thrown; Assert.assertTrue(true); return; } Assert.assertTrue("Error: ParseException has not been thrown!", false); }

Target:
y not use @Test (expected...)
Source:
public void start(BundleContext bc) throws Exception { if (webDavHandler == null) { webDavHandler = WebDavHandler.getInstance(); } webDavHandler.setBundleContext(bc); webDavHandler.start(); }

Target:
the if here is'nt too useful, is it?
Source:
public AdvancedModelWrapper(OpenEngSBModel model) { super(model); }

Target:
I think a static method for construction might still fit better
Source:
public Boolean connectorExists(String id) { try { List<ConnectorConfiguration> list = configPersistence.load(ImmutableMap.of(Constants.CONNECTOR_PERSISTENT_ID, id)); if (list.isEmpty()) { return false; } return true; } catch (PersistenceException e) { throw new RuntimeException(e); } }

Target:
you could just return here !list.isEmpty() to save the branching :)
Source:
public void init() { registry = ModelRegistryService.getInstance(null); graph = mock(ModelGraph.class); registry.setEkbClassLoader(new EKBTestClassLoader()); registry.setGraphDb(graph); }

Target:
use a constant instead of null to make the code easier to read at this place pls
Source:
private Boolean shouldHandleEvent(BundleEvent event) { if (event.getType() != BundleEvent.STARTED && event.getType() != BundleEvent.STOPPED) { return false; } String symbolicName = event.getBundle().getSymbolicName(); if (symbolicName.equals("org.apache.servicemix.bundles.xmlbeans")) { return false; } if (symbolicName.equals("org.ops4j.pax.wicket.service")) { return false; } return true; }

Target:
I don't like it; we need a better way to handle optional imports; a more general one; there could be always others more libs
Source:
public void openSite_shouldShowAuditLog() { tester.debugComponentTrees(); tester.assertVisible("auditsContainer:audits"); tester.assertVisible("auditsContainer:audits:0:audit"); tester.assertVisible("auditsContainer:audits:1:audit"); int i = 0; for (Event event : domain.getAllAudits()) { tester.assertLabel("auditsContainer:audits:" + i + ":audit", event.getName()); i++; } }

Target:
remove that one from commit again
Source:
public void testToExecuteNotInstalledCommand_shouldThrowException() throws Exception { CommandProcessor cp = getOsgiService(CommandProcessor.class); CommandSession cs = cp.createSession(System.in, System.out, System.err); cs.execute("failing-command"); fail("Exception should be thrown that the command does not exist"); cs.close(); }

Target:
maybe the CommandSession should be closed before the call of fail?
Source:
static List<EntryElement> makeEntryElementList(Object... value) { List<EntryElement> valueElements = new ArrayList<EntryElement>(); for (Object o : value) { Class<?> type = ClassUtils.primitiveToWrapper(o.getClass()); EntryElement entryElement = new EntryElement(type.getName(), o.toString()); valueElements.add(entryElement); } return valueElements; }

Target:
why not public?
Source:
static <T> Collection<T> convertAllBeanDataToObjects(Collection<? extends BeanData> data) { return Collections2.transform(data, new BeanDataToObjectFunction<T>()); }

Target:
why not public
Source:
public ConfigPersistenceService getPersistence() { return OpenEngSBCoreServices .getConfigPersistenceService("WORKFLOW"); }

Target:
do you really want to make this public?
Source:
public void testWorkflowRepresentationMarshalling_shouldMarshallWorkflowCorrectly() throws SAXException, IOException, JAXBException { WorkflowRepresentation representation = createWorkflow(); WorkflowRepresentationConverter workflowRepresentationMarshaller = new WorkflowRepresentationConverter(); String converted = workflowRepresentationMarshaller.marshallWorkflow(representation); WorkflowRepresentation rep = workflowRepresentationMarshaller.unmarshallWorkflow(converted); compareActionRepresentation(representation.getRoot(), rep.getRoot()); }

Target:
throws exception?
Source:
public <T> List<T> listServices(Class<T> clazz, String filterString) throws InvalidSyntaxException { Filter filter = makeFilter(clazz, filterString); ServiceTracker tracker = new ServiceTracker(bundleContext, filter, null); return getListFromTracker(tracker); }

Target:
one backspace too much
Source:
public LocalizableString mockLocalizeableString(String value) { LocalizableString mock2 = mock(LocalizableString.class); when(mock2.getString(any(Locale.class))).thenReturn(value); return mock2; }

Target:
isn't protected sufficient for this method?
Source:
public static String shorten(String s, int len) { s = s.trim(); if (s.length() > 12) { s = s.substring(0, len - 3).trim() + "..."; } return s; }

Target:
Do you mean `s.length() > len`?
Source:
public static String amountToDollars(int n){ String s = "$ " + (n / 100) + "."; if (((n % 100) / 10) == 0) { s += "0"; } s += (n % 100); return s; }

Target:
Wouldn't this be clearer with the condition being `if ((n % 100) < 10)`?
Source:
void shouldReturnEmptyPropertyString() { final Issues<Issue> issues = new Issues<>(); IssueBuilder builder = new IssueBuilder(); PropertyStatistics statistics = new PropertyStatistics(issues, "", Function.identity()); String actualProperty = statistics.getProperty(); assertThat(actualProperty).isEmpty(); }

Target:
Der Fall "" bietet keinen Mehrwert zu "category", oder? Test entfernen oder alternativ (dann gibt es kein Duplizieren): ``` @ParameterizedTest(name = "[{index}] Category name = {0}") @ValueSource(strings = {"category", ""}) ```
Source:
void shouldReturnEmptyDisplayNameString() { final Issues<Issue> issues = new Issues<>(); IssueBuilder builder = new IssueBuilder(); PropertyStatistics statistics = new PropertyStatistics(issues, "category", Function.identity()); String actualDisplayName = statistics.getDisplayName(""); assertThat(actualDisplayName).isEmpty(); }

Target:
Hier wäre noch ein Test schön, wo nicht identify verwendet wird.
Source:
void shouldReturnCountEmpty() { //Given final Issues<Issue> issues = new Issues<>(); IssueBuilder builder = new IssueBuilder(); PropertyStatistics statistics = new PropertyStatistics(issues, "category", Function.identity()); assertThrows(NullPointerException.class, ()->statistics.getCount("key")); }

Target:
Das ist eigentlich ein "Bug". Schöner wäre, wenn da eine `NoSuchElementException` mit passender Meldung fliegt. Wenn Sie wollen, dürfen Sie das SUT auch abändern.
Source:
void shouldReturnUnmodifiedOutputForEmptyInput() { final EnvironmentResolver environmentResolver = new EnvironmentResolver(); final String expanded = environmentResolver.expandEnvironmentVariables(new EnvVars(), ""); assertThat(expanded).isEmpty(); }

Target:
final für locals kann entfallen
Source:
void shouldReturnAdjustedOutputForAGivenInputBasedOnDollarSigns() { final EnvironmentResolver environmentResolver = new EnvironmentResolver(); final EnvVars envVars = new EnvVars(); envVars.put(KEY, VALUE); final String previous = "$$Test$$Testing$TestString$$Testing$Test"; final String expanded = environmentResolver.expandEnvironmentVariables(envVars, previous); final String expected = "$Test$Testing$TestString$Testing$Test"; assertThat(expanded).isEqualTo(expected); }

Target:
Das war mit gar nicht bewusst, dass $$ durch $ ersetzt wird. (Das ist ja auch ein Feature der aufgerufenen Methode in Jenkins Core). Wäre es in unserem Fall nicht leichter zu verstehen, wenn 1. "Test" so bleib wie es ist 2. "$KEY" durch "$VALUE" ersetzt wird. "$VALUE" aber nicht weiter 3. "$KEY" durch "$VALUE" ersetzt wird und dann "$VALUE" durch was weiteres Ergibt drei Tests...