auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public ObjectListingChunk getNextChunk() throws IOException { if (mResult.isTruncated()) { String nextMarker = mResult.getNextMarker(); mRequest.setMarker(nextMarker); ObjectListing nextResult = mClient.listObjects(mRequest); if (nextResult != null) { return new OSSObjectListingChunk(mRequest, nextResult); } } return null; }

Target:
Could you inline the first call? `mRequest.setMarker(mResult.getNextMarker())`
Source:
public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final LoopDetectionCriteria that = (LoopDetectionCriteria) o; return seen.equals(that.seen); }

Target:
Is there a particular reason why `getClass()` is used instead of `instanceof`. `instanceof` is less restrictive and may be the better choice.
Source:
public void testBool() { final Arbitrary<Boolean> arbBooleanR = arbitrary(arbBoolean.gen); final Property p = property(arbBooleanR, arbBooleanR, (m1, m2) -> bool(m1.equals(m2)) .implies(new BoolTestClass(m1).getBoolean() == new BoolTestClass(m2).getBoolean())); PropertyAssert.assertResult(p); }

Target:
What is the purpose of wrapping the Boolean in a class and getting the boolean back out, rather than a direct `m1 == m2` expression?
Source:
private void update() { // OK to ignore calls to update() if already busy updating if (busy.compareAndSet(false, true)) { try { PollingResponse response = reader.call(); if (response.hasData()) { current = response.getToAdd(); notifyConfigUpdated(this); } } catch (Exception e) { try { notifyError(e, this); } catch (Exception e2) { LOG.warn("Failed to notify error observer"); } } finally { busy.set(false); } } }

Target:
Shouldn't this pass the exception to the logger so the user will know what the failure was?
Source:
public javax.ws.rs.core.Response toResponse(InvalidValueException e) { Fault fault = new Fault(); fault.setReason("Invalid Value"); fault.setDetail(e.getMessage()); return Response.status(Response.Status.BAD_REQUEST).entity(fault).build(); }

Target:
Do you need the fully qualified class name here?
Source:
static long calculateDirSizeAndSave(final File dir) throws IOException { final Path path = Paths.get(dir.getPath(), FlowPreparer.PROJECT_DIR_SIZE_FILE_NAME); if (!Files.exists(path)) { final long sizeInByte = FileUtils.sizeOfDirectory(dir); FileIOUtils.dumpNumberToFile(path, sizeInByte); } return FileIOUtils.readNumberFromFile(path); }

Target:
Return sizeInByte instead, if available.
Source:
public void initFromPage(int valueCount, ByteBufferInputStream inputStream) throws IOException { int bitWidth = BytesUtils.readIntLittleEndianOnOneByte(inputStream); decoder = new RunLengthBitPackingHybridDecoder(bitWidth, inputStream); }

Target:
static import `readIntLittleEndianOnOneByte`.
Source:
@Override public boolean onCreate() { Picasso.setSingletonInstance(new Picasso.Builder(getContext()).build()); return true; }

Target:
if you want to override the singleton instance, then, you need to remove the ContentProvider from the manifest, right? or is there another way?
Source:
public long getDelayBetweenSyncs(@NonNull TimeUnit unit) { return TimeUnit.MILLISECONDS.convert(this.getDelayBetweenSyncs(), unit); }

Target:
No, this one was correct... 😈 We want to convert the internal delay (expressed in milliseconds) to whatever unit the client asked.
Source:
public CompositeCodec(Map<Class<?>, Codec> delegates, Codec defaultCodec) { Assert.notNull(defaultCodec, "'defaultCodec' cannot be null"); this.defaultCodec = defaultCodec; this.delegates = delegates; }

Target:
`new HashMap(delegates)` - don't keep a reference to the caller's map - he might change it.
Source:
public T get() { return getOr(defaultValue); }

Target:
final?
Source:
private void updateNics(List<NetworkInterfaceModel> nics) { nicList.clear(); Collections.sort(nics); List<NetworkGroup> groups = new ArrayList<>(); for (NetworkInterfaceModel nic : nics) { groups.add(new NetworkGroup(nic, eventBus, style)); } nicList.addAll(groups, !rendered); nicGroups = groups; }

Target:
if you are going to assign the local variable to the field, why not skip the local variable and use the field in the method?
Source:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; RpcOptions options = (RpcOptions) o; if (timeout != options.timeout) return false; if (deliverOrder != options.deliverOrder) return false; return unit == options.unit; }

Target:
nitpick: replace `if` with `&&` ```suggestion return timeout == options.timeout && deliverOrder == options.deliverOrder && unit == options.unit; ```
Source:
protected abstract OutputStream getOutputStreamInternal(RepositoryPath repositoryPath) throws IOException; protected final RepositoryOutputStream decorate(RepositoryPath repositoryPath, OutputStream os) throws IOException { if (os == null || os instanceof RepositoryOutputStream) { return (RepositoryOutputStream) os; } String path = RepositoryFiles.stringValue(repositoryPath); return RepositoryOutputStream.of(repositoryPath.getRepository(), path, os).with(this); }

Target:
Why is it necessary to rename these methods?
Source:
public MatchAttributeWithValue(String attributeName, String attributeRegex) { super("match attribute"); this.attributeName = attributeName; this.attributeRegex = Pattern.compile(attributeRegex, DOTALL); }

Target:
Why DOTALL? As I know, it's needed to support multiline Strings, which hardly can happen to attribute values.
Source:
public void tearDown() throws Exception { if (executor != null) executor.shutdownNow(); if (app != null) Entities.destroyAll(app.getManagementContext()); if (exampleEntity != null) Entities.destroyAll(exampleEntity.getApplication().getManagementContext()); }

Target:
saw NPE here - change to `if (exampleEntity != null && exampleEntity.getApplication() != null)` (happened when `ExampleAppInFile.groovy` was not on my classpath due to annoying Eclipse behaviour).
Source:
public void refreshJobInfo(JobInfo info) { GroupInfo group = info.getGroupInfo(); if (group != null) { refreshGroup(group); } Object[] listenersArray = listeners.getListeners(); for (Object element : listenersArray) { IJobProgressManagerListener listener = (IJobProgressManagerListener) element; if (!isCurrentDisplaying(info.getJob(), listener.showsDebug())) { listener.refreshJobInfo(info); } } }

Target:
inline listeners.getListeners()
Source:
public ConnectorHandle(ConnectorLocator locator, Class<? extends StoragePluginConfig> configClass) { this.locator = locator; this.configClass = configClass; this.isIntrinsic = false; }

Target:
Is it obvious if we pass config class so it is not intrinsic but if StoragePlugin instance it is? Maybe it's better to have this done using static methods for better readability? For example: We'll have only one constructor and two static methods: ``` private ConnectorHandle(ConnectorLocator locator, Class<? extends StoragePluginConfig> configClass, boolean isIntrinsic) { this.locator = locator; this.configClass = configClass; this.isIntrinsic = isIntrinsic; } public static ConnectorHandle initIntrinsic(ConnectorLocator locator, Class<? extends StoragePluginConfig> configClass) { return new ConnectorHandle(...); } public static ConnectorHandle initNonIntrinsic(ConnectorLocator locator, Class<? extends StoragePluginConfig> configClass) { return new ConnectorHandle(...); } ```
Source:
public void testReconfigureServer() { api().reconfigureServer(serverId, 4, CpuSpeed.HIGHPERFORMANCE.name(), 1); waitForServerState(api(), serverId, State.PENDING_CHANGE, 30 * 60 * 1000, "Error"); waitForServerState(api(), serverId, State.NORMAL, 30 * 60 * 1000, "Error"); }

Target:
Is it possible that the reconfigure operation is fast enough that we don't actually see this state? Does it really make sense to wait for intermediate states?
Source:
public void run() { try { log.info("Running reporting task: " + getClass().getSimpleName()); currentSession = sessionFactory.getHibernateSessionFactory().getCurrentSession(); executeTask(); log.info("Completed reporting task: " + getClass().getSimpleName()); } catch (Exception e) { log.error("An error occurred while running reporting task: " + getClass(), e); } }

Target:
Revert back to sessionFactory.getCurrentSession()
Source:
public static final boolean isStorageWritable() { return Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED; }

Target:
This should imho be implemented with an equals since you are comparing Strings and to make it null safe I would suggest: `return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());`
Source:
public ModuleMetadataResource toResource(ModuleMetadata entity) { return createResourceWithId(entity.getName(), entity); }

Target:
I foresee clashes here. Should at least use <type> + "/" + <name>
Source:
private void bindFrontendInfrastructure() { bind(Frontend.class).in(Singleton.class); requestStaticInjection(Frontend.InstanceHolder.class); requestStaticInjection(AssetProvider.class); bind(VdcOperationManager.class).in(Singleton.class); bind(OperationProcessor.class).in(Singleton.class); bind(CommunicationProvider.class).to(GWTRPCCommunicationProvider.class).in(Singleton.class); }

Target:
Hm, this method was meant to contain GIN bindings for "frontend communication infra" classes, so I'd rather put AssetProvider binding elsewhere, e.g. at the end of bindCommonInfrastructure method?
Source:
public Subscriber<Observable<? extends T>> call(final Subscriber<? super T> child) { MergeSubscriber<T> subscriber = new MergeSubscriber<T>(child, delayErrors, maxConcurrent); MergeProducer<T> producer = new MergeProducer<T>(subscriber); subscriber.producer = producer; producer.lazySet(0); // make sure subscriber.producer is visible child.add(subscriber); child.setProducer(producer); return subscriber; }

Target:
What is this lazySet about? What about visibility would not work if this wasn't done?
Source:
public void getRadiologyOrders_shouldReturnAllRadiologyOrdersForGivenUrgency() throws Exception { Patient patient = patientService.getPatient(PATIENT_ID_WITH_ONE_VOIDED_AND_TWO_NON_VOIDED_RADIOLOGY_ORDERS); RadiologyOrderSearchCriteria radiologyOrderSearchCriteria = new RadiologyOrderSearchCriteria.Builder().withPatient(patient) .withUrgency(Urgency.STAT) .build(); List<RadiologyOrder> radiologyOrders = radiologyOrderService.getRadiologyOrders(radiologyOrderSearchCriteria); assertThat(radiologyOrders.size(), is(2)); for (RadiologyOrder radiologyOrder : radiologyOrders) { assertThat(radiologyOrder.getUrgency(), is(Urgency.STAT)); } }

Target:
@bgeVam why did you add patient ?
Source:
static FeignException errorReading(Request request, Response ignored, IOException cause) { return new FeignException( format("%s reading %s %s", cause.getMessage(), request.httpMethod().name(), request.url()), cause); }

Target:
`format` should be able to deal with `Enum`s just fine. no need to call `name()`
Source:
protected WrappedByteBuf(ByteBuf buf) { ObjectUtil.checkNotNull(buf, "buf"); this.buf = buf; }

Target:
nit: you can merge both lines above as `checkNotNull` will return the given argument
Source:
public boolean isFull() { return chunks.size() == chunks.get(0).getObject().getAtomicUpdateGroupSize(); }

Target:
Should this check that chunks.get(0) exists?
Source:
public String me() { return "" + state + ME_SEPARATOR; }

Target:
private
Source:
public int findWikiIndex(String wikiCode) { int index = ArrayUtils.indexOf(getWikiCodes(), wikiCode); if (index == ArrayUtils.INDEX_NOT_FOUND) { // FIXME: Instrument this with EL to find out what is happening on places where there is a lang we can't find // In the meantime, just fall back to en. See https://bugzilla.wikimedia.org/show_bug.cgi?id=66140 return findWikiIndex(FALLBACK_WIKI_LANG_CODE); } return index; }

Target:
Couldn't we just use Arrays.asList(getWikiCodes).indexOf(wikiCode) instead of importing a whole new library?
Source:
public void testRayCasting(){ final double[][] platform = {{ 59.8925348, 10.5242855}, { 59.8927012, 10.524743}, { 59.8926397, 10.5248089}, {59.8924888, 10.5243485}}; double[] testPointInside = { 59.8926474, 10.524729}; double[] testPointOutside = { 59.8925344, 10.5249007}; assert(PlatformLinker.contains(platform, testPointInside)); assert(!PlatformLinker.contains(platform, testPointOutside)); }

Target:
nit: I would prefer to use the junit assertion functions.
Source:
public void init() { try { eventBus.registerSubscriber(this); // Must set the initial status currentStatus.compareAndSet(InstanceInfo.InstanceStatus.UNKNOWN, client.getInstanceRemoteStatus()); } catch (InvalidSubscriberException e) { LOG.error("Error registring for discovery status change events.", e); } }

Target:
@PostConstruct would not be called concurrently, rite? Do we need the current status as AtomicRef?
Source:
public static void insertPageProlog(StringBuilder buffer, int position) { StringBuilder pageProlog= new StringBuilder(60); pageProlog.append("<html>"); //$NON-NLS-1$ buffer.append("<head>"); //$NON-NLS-1$ appendStyleSheetWithBodyColorRules(pageProlog, FG_COLOR_RGB, BG_COLOR_RGB); buffer.append("</head>"); //$NON-NLS-1$ buffer.insert(position, pageProlog.toString()); }

Target:
Shouldn't this be appended to pageProlog?
Source:
private void verifyCertificateChain(final List<X509Certificate> certificates) throws GeneralSecurityException, AuthenticationException { // create certificate chain, find the self signed cert first and chain all the way back // to the signer cert. Also perform certificate signing validation when chaining them back. X509Certificate issuerCert = getSelfSignedCert(certificates); final TrustAnchor trustAnchor = new TrustAnchor(issuerCert, null); PKIXParameters pkixParameters = new PKIXParameters(Collections.singleton(trustAnchor)); pkixParameters.setRevocationEnabled(false); final CertPath certPath = CertificateFactory.getInstance("X.509") .generateCertPath(certificates); final CertPathValidator certPathValidator = CertPathValidator.getInstance("PKIX"); certPathValidator.validate(certPath, pkixParameters); }

Target:
final?
Source:
public Set<Class<?>> getClasses() { final Set<Class<?>> classes = new HashSet<>(); classes.add(HelloResource.class); classes.add(PureProxyEndPoint.class); classes.add(HelloBadResource.class); classes.add(HelloSometimesBadResource.class); return classes; }

Target:
This change causes regression of JaxrsRuntimeNameTestCase. JaxrsRuntimeNameTestCase uses HelloApplication.java as well, but HelloBadResource is not added to the deployment from JaxrsRuntimeNameTestCase. So JaxrsRuntimeNameTestCase fails.
Source:
private void reconnectExceptionally(final String message) throws DatabaseEngineException { try { getConnection(); } catch (final Exception e) { throw new DatabaseEngineException(message, e); } }

Target:
Subclasses are also doing this. The method should be _protected_, and the same code should be replaced by a call to this method in the subclasses.
Source:
public Aggregator factorize(ColumnSelectorFactory metricFactory) { return new LongLastAggregator( name, metricFactory.makeLongColumnSelector(fieldName), metricFactory.makeLongColumnSelector(Column.TIME_COLUMN_NAME) ); }

Target:
minor nit: can we pass time column selector before field selector to be consistent with buffered aggregator ?
Source:
protected void logToAudit(){ super.logToAudit(); if (isPolicyResetMessage(getReturnStatus().message)) { return; } AuditLogableBase auditLogableBase = new AuditLogableBase(vds.getId()); auditLogableBase.setVds(vds); auditLogableBase.addCustomValue("message", getReturnStatus().message); auditLogDirector.log(auditLogableBase, AuditLogType.VDS_BROKER_COMMAND_FAILURE); }

Target:
This won't do what you think. The base class should probably have a sholdLog() method, and the caller should implement protected final void logToAudit() { if (shouldLog()) { realLogToAudit()); } }
Source:
protected String gtk_rgba_to_css_string (GdkRGBA rgba) { String color = "rgba(" + (int)(rgba.red * 255) + "," + (int)(rgba.green * 255) + "," + (int)(rgba.blue * 255) + "," + (int)(rgba.alpha * 255) + ")"; return color; }

Target:
This should not be protected but package.
Source:
public FileMode getMode(File f, FS.Attributes attributes) { if (attributes.isSymbolicLink()) return FileMode.SYMLINK; else if (attributes.isDirectory()) { if (new File(f, Constants.DOT_GIT).exists()) return FileMode.GITLINK; else return FileMode.TREE; } else if (attributes.isExecutable()) return FileMode.EXECUTABLE_FILE; else return FileMode.REGULAR_FILE; }

Target:
style nit: missing braces, the style guide was changed a while back since then we use braces around single line blocks
Source:
public Map<String, Set<ExecutableElement>> setters() { return Maps.transformValues(setters.asMap(), Sets::newHashSet); }

Target:
Move to constructor? We already do a defensive copy might as well front-load this work instead.
Source:
public void sendBannerChange(Location location, CompoundTag nbt) throws NullPointerException { sendBlockEntityChange(location, nbt, GlowBlockEntity.BANNER); }

Target:
throws is not required
Source:
public VfsFileChooserHelper( Shell shell, VfsFileChooserDialog fileChooserDialog, VariableSpace variableSpace, FileSystemOptions fileSystemOptions ) { this.fileChooserDialog = fileChooserDialog; this.shell = shell; this.variableSpace = variableSpace; this.fileSystemOptions = fileSystemOptions; this.schemeRestrictions = new String[1]; }

Target:
@e-cuellar is the reason this is set to 1 because of line number 133? If so, I'd prefer this to be String[0], and add some safety on getSchemeRestriction() to check array length (because it could be 0, as set by setSchemeRestrictions). Looks like setSchemeRestriction needs to be a little smarter too. I'd suggest that if the API call setSchemeRestriction that we wipe the schemeRestriction and stuff it only with the incoming schemeRestriction.
Source:
public static int getCurrentCounterValue() { return COUNTER.intValue(); }

Target:
Default access (no modifier) suffices.
Source:
private void setCharset(String charsetName) { try { if (charsetName == null) { this.charset = Charset.defaultCharset(); } else { this.charset = Charset.forName(charsetName); } logger.debug("Serial port '{}' charset '{}' set.", this.port, charsetName); } catch (IllegalCharsetNameException e) { logger.error("Serial port '{}' charset '{}' not found.", this.port, charsetName); } }

Target:
Should eliminate the extraneous use of `this.` throughout.
Source:
void prepareView(final String type, final String constraintValue, final ConstraintType constraintType) { getView().setType(type); if (!isEmpty(constraintValue)) { getView().loadComponent(constraintType); } else { getView().setupEmptyContainer(); } }

Target:
Now that we have the `constraintType `, we need change this to something like this: ```suggestion if (!isEmpty(constraintValue) || constraintType != null) { ``` Otherwise, when the user selects the "Expression" type and leaves the expression blank, the _Expression component_ wont be loaded.
Source:
public boolean shutdown() { }

Target:
I do not know much about databases but whether this method is properly constructed? My Eclipse returns "This method must return a result of type boolean" and I can add return for firstRun of false.
Source:
public String getTitle() { return Context.getMessageSourceService().getMessage("emrapi.title"); }

Target:
Why not just return "emrapi.title"?
Source:
public static String resolveName(Object context, String path) { Preconditions.checkNotNull(path, "path must not be null"); if (path==null || path.startsWith("/") || Urls.isUrlWithProtocol(path)) return path; Preconditions.checkNotNull(context, "context must not be null when path is relative"); return packagePath(context)+path; }

Target:
Unnecessary null check for path; trivial; ignoring.
Source:
private void sendCancelCommand(IntSet cancelledSegments) { Address origin = rpcManager.getAddress(); CacheRpcCommand cmd = commandsFactory.buildStateTransferCancelCommand(topologyId, cancelledSegments); try { rpcManager.sendTo(source, cmd, DeliverOrder.NONE); } catch (Exception e) { // Ignore exceptions here, the worst that can happen is that the provider will send some extra state log.debugf("Caught an exception while cancelling state transfer from node %s for segments %s", source, cancelledSegments); } }

Target:
can be removed.
Source:
public void heartbeat() { // Sync the pin list before attempting to reserve space mBlockWorker.syncPinList(); reserveSpace(); }

Target:
This might be too expensive to call on every eviction attempt. We want to keep the eviction loop fast and without dependencies on external services.
Source:
private final void decrementResponseOrExpired() { int decrementedValue = responsesAndExpirations.decrementAndGet(); if (decrementedValue == 0) { // The condition being signaled is a valid proxy for the CL being achieved // Only mark it as failed if the requested CL was achieved. if (!condition.isSignaled() & requestedCLAchieved) { replicaPlan.keyspace().metric.writeFailedIdealCL.inc(); } else { replicaPlan.keyspace().metric.idealCLWriteLatency.addNano(System.nanoTime() - queryStartNanoTime); } } }

Target:
Is this intentionally a bitwise AND?
Source:
public List<Attribute> getRequiredAttributes(PerunSession sess, List<Service> services, Resource resource, Group group, boolean withGroupAttributes) throws GroupResourceMismatchException { this.checkGroupIsFromTheSameVoLikeResource(sess, group, resource); List<Attribute> attributes = new ArrayList<>(); attributes.addAll(getAttributesManagerImpl().getRequiredAttributes(sess, services, resource, group)); if (withGroupAttributes) { attributes.addAll(getAttributesManagerImpl().getRequiredAttributes(sess, services, group)); } return attributes; }

Target:
You can use parameterized constructor call instead of addAll()
Source:
private boolean extractZsetIncrementHeader(Message<?> message) { if (message.getHeaders().containsKey(RedisHeaders.ZSET_INCREMENT_SCORE)) { return this.zsetIncrementScoreExpression.getValue(this.evaluationContext, message, Boolean.class); } return false; }

Target:
If we open up the expression for user specification, this if test would have to go inside the default `FunctionExpression`.
Source:
public void shouldGetDiagnosisById() { int diagnosisId = 1; Diagnosis diagnosis = diagnosisDAO.getDiagnosisById(diagnosisId); assertEquals("4e663d66-6b78-11e0-93c3-18a905e044dc", diagnosis.getUuid()); }

Target:
We can get rid of the above variable
Source:
public Operator createOperator(DriverContext driverContext) { checkState(!closed, "Factory is already closed"); OperatorContext operatorContext = driverContext.addOperatorContext(operatorId, planNodeId, HashBuilderOperator.class.getSimpleName()); return new SpatialJoinOperator(operatorContext, getTypes(), probeTypes, probeOutputChannels, probeGeometryChannel, pagesSpatialIndexFactory.createPagesSpatialIndex(), spatialRelationshipTest); }

Target:
split lines
Source:
private IssuesRecorder enableWarningsForNewFixedOutstandingTest(final FreeStyleProject job, IssuesRecorder oldPublisher, String pattern) { if(oldPublisher != null) { job.getPublishersList().remove(oldPublisher); } IssuesRecorder publisher = new IssuesRecorder(); publisher.setTools(Collections.singletonList(new ToolConfiguration(pattern, new Eclipse()))); job.getPublishersList().add(publisher); return publisher; }

Target:
Evtl. geht auch `clear()` dann braucht man gar keinen Parameter...
Source:
public boolean isMember(User user) { if (user == null || user.getPerson() == null) { return false; } return new ActivePhdProcessesGroup().isMember(user) || (user.getPerson().getStudent() != null && user.getPerson() .getStudent().hasActiveRegistrations()); }

Target:
There are more non PHD students than there are PHD students, thus switching the order of the || will probably improve performance.
Source:
public ListenableFuture<?> waitForWriting() { if (isFinished()) { return NOT_BLOCKED; } return exchanger.getNotFullFuture(); }

Target:
maybe you could rename this `getNotFullFuture` to `waitForWriting`?
Source:
public Map<String, TransportConfiguration> getConnectors() { return Collections.unmodifiableMap(connectors); }

Target:
What's the relation between this change and WFLY-19339?
Source:
public void setEntries(IRuntimeClasspathEntry[] entries) { model.removeAll(); IRuntimeClasspathEntry entry; for (IRuntimeClasspathEntry entrie : entries) { entry = entrie; switch (entry.getClasspathProperty()) { case IRuntimeClasspathEntry.USER_CLASSES: model.addEntry(ClasspathModel.USER, entry); break; default: model.addEntry(ClasspathModel.BOOTSTRAP, entry); break; } } refresh(); }

Target:
rename to entry
Source:
public static String getGerritJarPluginName(File srcFile) throws IOException { JarFile jarFile = new JarFile(srcFile); try { return jarFile.getManifest().getMainAttributes() .getValue("Gerrit-PluginName"); } finally { jarFile.close(); } }

Target:
This is not a new code, you just mved it, but consider to use Java7 try-with-resources statement: try (JarFile jarFile = new JarFile(srcFile)) { return jarFile.getManifest().getMainAttributes() .getValue("Gerrit-PluginName"); }
Source:
protected String getContextId(String name) { boolean includeHostName = camelContext != null && camelContext.getManagementStrategy().getManagementAgent().getIncludeHostName(); if (includeHostName != null && includeHostName) { return hostName + "/" + (name != null ? name : VALUE_UNKNOWN); } else { return name != null ? name : VALUE_UNKNOWN; } }

Target:
primitive boolean cannot be compared with null.
Source:
public boolean getChecked(Object element) { if (fObjects.containsKey(element)) { return fObjects.get(element); } return fCheckboxTreeViewer.getChecked(element); }

Target:
If it's possible for an element to be checked in the viewer but not in the map, then other code is wrong, e.g. getCheckedElements(). If it's not possible, then you can just return false here.
Source:
private void putPreferred(String email) throws RestApiException, OrmException { List<EmailInfo> emails = getEmails.apply(rsrc); for (EmailInfo e : emails) { if (e.email.equals(email)) { putPreferred.apply(new AccountResource.Email(user, email), null); } } }

Target:
Should we swallow typo-case without even issue a warning? Delete email method above doesn't really matter, because if a mail doesn't exist, all is fine. Here someone rellies on this command to change something, yet when she spelled email wrong, it should fail, i think.
Source:
private void cancel(Job[] jobs) { for (Job job : jobs) { job.cancel(); } }

Target:
The "brackets for single statements" cleanup in this file should be done in a separate commit, as we should not mix unrelated changes.
Source:
static private long toMillis(String seconds) { if (seconds.contains(".")) { float value = Float.parseFloat(seconds); float millis = value % 1; return SECONDS.toMillis((long) value) + (long) (millis * 1000); } else { return SECONDS.toMillis(Long.parseLong(seconds)); } }

Target:
Please swap the order to `private static` like in the [google code style guide](https://google.github.io/styleguide/javaguide.html#s4.8.7-modifiers)
Source:
public synchronized void addSegmentChangeRequests(List<DataSegmentChangeRequest> requests) { for (DataSegmentChangeRequest request : requests) { if (changes.size() >= maxSize) { changes.remove(0); } changes.add(new Holder(request, getLastCounter().inc())); } singleThreadedExecutor.execute(resolveWaitingFuturesRunnable); }

Target:
This might be pre-mature optimization, but I worry about how this data structure is being used. One option would be to view the list as a revolving buffer and essentially maintain an index of the oldest "valid" item. You can replace and increment that on `add` and start your search from there wrapping back around.
Source:
static boolean checkStartObject(JsonParser parser, boolean shouldThrow) throws IOException { try { JsonToken currentToken = parser.currentToken(); // The parser may not be at a token, yet. If that's the case advance. if (currentToken == null) currentToken = parser.nextToken(); // If we are still not at the expected token, we could be an another or an empty body. if (currentToken == JsonToken.START_OBJECT) return true; if (shouldThrow) { throw new IllegalArgumentException("Expected start object, was " + currentToken); } return false; } catch (JsonParseException e) { // likely not json if (shouldThrow) throw e; return false; } }

Target:
catch `Throwable`? When methods shouldn't throw, like where `shouldThrow` is `false` here, it's easy to end up with a hang because an exception type changed.
Source:
public VdsIdVDSCommandBase(P parameters, boolean newHost) { super(parameters); if (!newHost) { _vdsManager = Injector.get(ResourceManager.class).getVdsManager(parameters.getVdsId()); } }

Target:
It seems that we can get rid from this injection by moving the initialization of the _vdsManager from the c'tor to the executeVDSCommand() method. we actually can just keep the newHost as a member and use it from the executeVDSCommand() by referring to the already initialized ResourceManager to obtain the vdsManager associated with the host.
Source:
public DRCatalogDiffEngine(Catalog localCatalog, Catalog remoteCatalog) { super(localCatalog, remoteCatalog); localCatalog.getClusters().get("cluster").getDrclusterid(); }

Target:
This seems not needed.
Source:
public List<@NonNull Integer> getSubAttributes(int quark, boolean recursive) throws AttributeNotFoundException { return getAttributeTree().getSubAttributes(quark, recursive); }

Target:
If you annotate the interface methods you don't need to repeat them here (we have to setting to inherit annotations).
Source:
private String getLsRegisterOutput() throws Exception { if (lsRegisterOutput != null) { return lsRegisterOutput; } long beforeCallLsRegister = System.currentTimeMillis(); lsRegisterOutput = processExecutor.execute(LSREGISTER, DUMP); long afterCallLsRegister = System.currentTimeMillis(); System.out.println("Call to lsregister took :" + (afterCallLsRegister - beforeCallLsRegister)); //$NON-NLS-1$ return lsRegisterOutput; }

Target:
this.lsRegisterOutput
Source:
public static String masterInbox(Map conf) throws IOException { String ret = masterLocalDir(conf) + FILE_SEPARATOR + "inbox"; try { FileUtils.forceMkdir(new File(ret)); } catch (IOException e) { LOG.error("Failed to create dir " + ret, e); throw e; } return ret; }

Target:
Again lets remove the try/catch/log/rethrow
Source:
public MockReplicaId(String storeId, long capacity, String filePath) { this.storeId = storeId; this.capacity = capacity; this.filePath = filePath; partitionId = mock(PartitionId.class); when(partitionId.toString()).thenReturn(storeId); }

Target:
not public
Source:
public static void main(String[] args) { LOG.info("Validating configuration."); try { Configuration.validate(); LOG.info("Configuration is valid."); } catch (IllegalStateException e) { LOG.warn("Configuration is invalid: {}", e.getMessage()); System.exit(-1); } System.exit(0); }

Target:
Log this at error level? I don't think we should put the stack trace, but the end result is crashing the system which seems to be more of an issue than warn.
Source:
private boolean isConstantFilterFunction(FilterFunction filter, Block[] constantBlocks) { return Arrays.stream(filter.getInputChannels()).allMatch(channel -> constantBlocks[channel] != null); }

Target:
static
Source:
public void testDefaults() { assertRecordedDefaults(ConfigAssertions.recordDefaults(FileSessionPropertyManagerConfig.class) .setConfigFile(null)); }

Target:
Nit: static import `recordDefaults`
Source:
public int hashCode() { return Objects.hash(storageDomainId, imageGroupId, baseImageId, topImageId, baseImageGeneration, baseImage, topImage); }

Target:
Let's break up this line please
Source:
public boolean isApplicable(Class<? extends Item> itemClass) { if (itemClass.isAssignableFrom(MavenModule.class) || itemClass.isAssignableFrom(MavenModuleSet.class)) { return true; } else { return false; } }

Target:
`return itemClass.isAssignableFrom(MavenModule.class) || itemClass.isAssignableFrom(MavenModuleSet.class)`.
Source:
public void TestWikiaLogoInGlobalNav_001_centralWikiExists(String wikiName, String expectedCentralUrl) { HomePageObject homePage = new HomePageObject(driver); homePage.getUrl(urlBuilder.getUrlForWiki(wikiName)); VenusGlobalNavPageObject globalNav = homePage.getVenusGlobalNav(); globalNav.waitForCorrectUrl(config.getEnv()); globalNav.clickWikiaLogo(); Assertion.assertStringContains(urlBuilder.getUrlForWiki(expectedCentralUrl), driver.getCurrentUrl()); }

Target:
Use fluent interface in here
Source:
public void execute(WorkflowExecutor workflowExecutor) throws IOException { if (!isComplete()) throw new IllegalArgumentException("Workflow is not complete"); Pool pool = step1.getInput(); pool.setConcentration((double) step0.getInput()); workflowExecutor.save(pool); }

Target:
There's no issue with the argument (`workflowExecutor`), so an `IllegalStateException` makes more sense here
Source:
public void should_return_null_when_encountering_parsing_issue() { logTester.setLevel(LoggerLevel.DEBUG); assertThat(XmlParser.parseXML(new File("src/test/files/xml/parsing-issue.xml"))).isNull(); assertThat(logTester.logs(LoggerLevel.ERROR)).contains("Unable to parse xml file: src/test/files/xml/parsing-issue.xml"); System.out.println(logTester.logs(LoggerLevel.DEBUG)); assertThat(logTester.logs(LoggerLevel.DEBUG)).hasSize(1).allSatisfy(s -> s.startsWith("XML file parsing failed because of : org.xml.sax.SAXParseException; systemId: file: ")); }

Target:
Please remove this `System.out.println`
Source:
boolean getHl7PrefixProperty() { try { return PropertyAccessor.getInstance().getPropertyBoolean(NhincConstants.GATEWAY_PROPERTY_FILE, NhincConstants.HL7_PREFIX_FOR_ATTR_PROPERTY); } catch (final PropertyAccessException ex) { LOG.warn(ex.getLocalizedMessage()); LOG.trace("Get HL7 Prefix Property exception: {}", ex.getLocalizedMessage(), ex); } return false; }

Target:
Remove log.warn since we already cover in log.trace
Source:
public void followPeergos() throws Exception { UserContext u1 = PeergosNetworkUtils.ensureSignedUp("peergos", "testpassword", network, crypto); UserContext u2 = PeergosNetworkUtils.ensureSignedUp("w", "w", network, crypto); u2.sendFollowRequest(u1.username, SymmetricKey.random()).get(); List<FollowRequestWithCipherText> u1Requests = u1.processFollowRequests().get(); assertTrue("Receive a follow request", u1Requests.size() > 0); }

Target:
this shouldn't be here. Users automatically friend "peergos" during signup
Source:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { requireNonNull(contextThreadLocalSupplier, "httpClientContextSupplier should not be null"); try { contextThreadLocalSupplier.addContext(getRequestHeadersMap(request), getQueryParamsMap(request)); chain.doFilter(request, response); } catch (IllegalArgumentException e) { ((HttpServletResponse) response).sendError(HttpServletResponse.SC_BAD_REQUEST); } finally { contextThreadLocalSupplier.clear(); } }

Target:
тут ты ловишь и то, что вылетит из `chain.doFilter()`. надо более узкий `try` - только на `getRequestHeadersMap()` и `getQueryParamsMap()`
Source:
public CtPath getPath() { try { return new CtElementPathBuilder().fromElement(this, getParent(CtModelImpl.CtRootPackage.class)); } catch (CtPathException e) { throw new SpoonException(); } }

Target:
`throw new SpoonException(e);` ... the orgin exception should be used as cause of the SpoonException
Source:
public void instrument(final InputStream input, final OutputStream output, final String name) throws IOException { final byte[] bytes; try { bytes = Java9Support.readFully(input); } catch (final IOException e) { throw instrumentError(name, e); } output.write(instrument(bytes, name)); }

Target:
I think we can delegate to the overloaded method here: public void instrument(final InputStream input, final OutputStream output, final String name) throws IOException { output.write(instrument(input, name)); }
Source:
public WorkQueue.Executor getBatchQueue() { System.out.println("Job scheduled in batch Queue"); return batchExecutor; }

Target:
Drop the println. :-)
Source:
protected void tearDown() { boolean removed = api().deleteRole(roleName); assertTrue(removed); }

Target:
This will fail if the `testCreateRole` test fails. Better leave the assertions for the tests, not the tearDown methods.
Source:
public void itDoesntWritePassword() throws Exception { // When I call JSON for user1 JsonNode node = getResponseAsJson(RequestType.GET, "/user/user1"); // Then it doesn't contain the password at all assertNull("", node.get("properties").get("password")); }

Target:
No need for an empty message here `assertNull(node.get("properties").get("password"));`
Source:
protected void demandUnload(SynchronizedResourceSet resourceSet, Resource resource, IProgressMonitor monitor) { lock.lock(); try { unloadingPool.execute(new ResourceUnloader(resourceSet, resource, monitor)); } finally { lock.unlock(); } }

Target:
why do you need to lock this code? ExecutorService.execute is thread safe, isn't it ?
Source:
private void checkSigOps() throws VerificationException { // Check there aren't too many signature verifications in the block. This is an anti-DoS measure, see the // comments for MAX_BLOCK_SIGOPS. int sigOps = 0; for (Transaction tx : transactions) { sigOps += tx.getSigOpCount(); } if (sigOps > MAX_BLOCK_SIGOPS) { throw new VerificationException("Block had too many Signature Operations"); } }

Target:
This is an unrelated change snuck in. Sorry for bitching, but it makes reviewing harder for big refactorings like this one.
Source:
public static Expression filterConjuncts(Expression expression, Predicate<Expression> predicate) { List<Expression> conjuncts = extractConjuncts(expression).stream() .filter(predicate) .collect(toList()); return combineConjuncts(conjuncts); }

Target:
There are no conjuncts in the API (no `List`, just an `expression`). Make it `private`.
Source:
public void createPartControl(Composite parent) { String name = getViewSite().getSecondaryId(); if (name != null) { name = TmfViewFactory.getBaseSecId(name); } if (name != null) { /* must initialize view info before calling super */ fViewInfo.setName(name); } fPresentationProvider = new XmlPresentationProvider(name); TimeGraphViewer timeGraphViewer = getTimeGraphViewer(); timeGraphViewer.getTimeGraphControl().colorSettingsChanged(timeGraphViewer.getTimeGraphProvider().getStateTable()); super.createPartControl(parent); }

Target:
NPE: timeGraphViewer is null before super is called. But I don't think the next line is necessary.
Source:
public ProtocolVersion protocolVersion() { return protocolVersion; }

Target:
Let's not change this signature. Maybe add a separate method
Source:
public Matrix removeRow(int i) { return removeRow(i, this.factory); }

Target:
Please, do not use `this` when it's unnecessary. You can write just `factory`.
Source:
public void testBracketsInGroup() throws Exception { createFiles("[", "]", "[]", "][", "[[]", "[]]", "[[]]"); writeTrashFile(".gitattributes", "[[]] bar1\n"); writeTrashFile(".gitattributes", "[\\[]] bar2\n"); writeTrashFile(".gitattributes", "[[\\]] bar3\n"); writeTrashFile(".gitattributes", "[\\[\\]] bar4\n"); assertSameAsCGit(); }

Target:
I presume you want to have all those line in .gitattributes? I think you need to do a single writeTrashFile with the four lines: writeTrashFile(".gitattributes", "[[]] bar\n" + "[\\[]] bar2\n" + ... );
Source:
public void notIgnoredAfterOnCreateView() { assertFalse(myListFragment.didExecute); LayoutInflater inflater = mock(LayoutInflater.class); ViewGroup viewGroup = mock(ViewGroup.class); Bundle bundle = mock(Bundle.class); myListFragment.onCreateView(inflater, viewGroup, bundle); assertFalse(myListFragment.didExecute); myListFragment.ignoreWhenViewDestroyed(); assertTrue(myListFragment.didExecute); }

Target:
We could just pass `null` to every parameter here, there is no need for mocking in this case.
Source:
private static String checkSitePathToken(Site site, String pattern) { if (site.getRequestScheme().hasPathToken()) { StringBuilder modified = new StringBuilder(pattern.length() + 8); modified.append("/*"); if (!pattern.isEmpty() && !pattern.startsWith("/")) { modified.append('/'); } modified.append(pattern); return modified.toString(); } else { return pattern; } }

Target:
why `8`?
Source:
public JSONObject getSnapshot() { JSONObject snapshot = new JSONObject(); DataNodeId dataNodeId = getDataNodeId(); snapshot.put(REPLICA_NODE, dataNodeId.getHostname() + ":" + dataNodeId.getPort()); snapshot.put(REPLICA_PARTITION, getPartitionId().toPathString()); snapshot.put(REPLICA_PATH, getReplicaPath()); snapshot.put(CAPACITY_BYTES, getCapacityInBytes()); return snapshot; }

Target:
Minor: don't really need to call getDataNodeId() since it's a class member.
Source:
protected String createPassFile(String value) throws IOException { File temp = File.createTempFile("ovirt", ".tmp"); String filePath = temp.getAbsolutePath(); temp.setReadable(true, true); temp.setWritable(true, true); temp.setExecutable(false); BufferedWriter out = new BufferedWriter(new FileWriter(temp)); out.write(value); out.close(); return filePath; }

Target:
This doesn't work. These Java 6 enhancements only help if you want to *add* permissions to the file, not if you wan't to remove them.
Source:
public void retireIdentifierSource_shouldRetireAnIdentifierSourceFromTheSystem() throws Exception { IdentifierSource identifierSource = identifierSourceService.getIdentifierSource(1); Assert.assertFalse(identifierSourceService.getIdentifierSource(1).isRetired()); identifierSourceService.retireIdentifierSource(identifierSource, "testing"); Assert.assertTrue(identifierSourceService.getIdentifierSource(1).isRetired()); }

Target:
Can you avoid repeating 1 in several places?
Source:
public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final LinkedSpan<T> other = (LinkedSpan<T>) obj; return Objects.equals(this.linkedEntries, other.linkedEntries) && this.sentenceid == other.sentenceid && Objects.equals(this.searchTerm, other.searchTerm); }

Target:
Can you remove this? OPENNLP-922 changes that in one style across all equals and hashCode implementations.
Source:
private Expression simplifyExpression(Session session, Expression predicate, TypeProvider types) { Map<NodeRef<Expression>, Type> expressionTypes = getExpressionTypes(session, predicate, types); ExpressionInterpreter interpreter = ExpressionInterpreter.expressionOptimizer(predicate, metadata, session, expressionTypes); Object value = interpreter.optimize(NoOpSymbolResolver.INSTANCE); if (value instanceof Expression) { return (Expression) value; } if (value == null) { // expression evaluates to SQL null, which in Filter is equivalent to false value = false; } return literalEncoder.toExpression(value, BOOLEAN); }

Target:
`literalEncoder.toExpression()` already returns the Expression if the value is an instanceof Expression, and a NullLiteral if it equals null. I would get rid of the if statements and always return `literalEncoder.toExpression(value,BOOLEAN)`. And add a `visitNullLiteral` to FilterExpressionStatsCalculatingVisitor.
Source:
public boolean post(String topic, Object data) { Event event = constructEvent(topic, data); EventAdmin eventAdmin = Activator.getDefault().getEventAdmin(); if (eventAdmin == null && logger != null) { logger.error(NLS.bind(ServiceMessages.NO_EVENT_ADMIN, event.toString())); return false; } eventAdmin.postEvent(event); return true; }

Target:
That is incorrect, in case the logger and eventAdmin is null we get a NPE
Source:
public void testTypeAccessInLambdaNoClassPath() { final Launcher runLaunch = new Launcher(); runLaunch.getEnvironment().setNoClasspath(true); runLaunch.addInputResource("./src/test/resources/noclasspath/lambdas/TypeAccessInLambda.java"); runLaunch.buildModel(); assertEquals("The token 'Strings' has not been parsed as CtTypeAccess", runLaunch.getModel().getElements(new Filter<CtTypeAccess>() { @Override public boolean matches(final CtTypeAccess element) { return element.getAccessedType().getSimpleName().equals("Strings"); } }).size(), 1); }

Target:
The expected value (1) must be the second parameter of `assertEquals`
Source:
public RecipientListRouter rlRouter() { RecipientListRouter router = new RecipientListRouter(); router.setChannels(Arrays.asList(new MessageChannel[] { barChannel(), bazChannel() })); router.setDefaultOutputChannel(discards()); return router; }

Target:
![redundantarraycreation](https://cloud.githubusercontent.com/assets/1071590/15787201/e1d4932a-298e-11e6-9dc8-243abf4e1f9f.jpg)
Source:
protected List<MetricFamilySamples> familySamplesList(Collector.Type type, List<MetricFamilySamples.Sample> samples) { MetricFamilySamples mfs = new MetricFamilySamples(fullname, type, help, samples); List<MetricFamilySamples> mfsList = new ArrayList<MetricFamilySamples>(1); mfsList.add(mfs); return mfsList; }

Target:
This should probably be package rather than protected
Source:
private VmTemplate createVmTemplate() { VmTemplate template = new VmTemplate(); template.setname("test-template"); template.setorigin(OriginType.OVIRT); template.setId(new Guid()); template.setdescription("test-description"); template.setDbGeneration(2L); return template; }

Target:
should be static
Source:
private static IType getDeclType(ICPPASTSimpleDeclSpecifier spec) { IASTExpression expr = spec.getDeclTypeExpression(); if (expr == null) { return null; } int specifierType = spec.getType(); if (specifierType == IASTSimpleDeclSpecifier.t_decltype || specifierType == IASTSimpleDeclSpecifier.t_decltype_auto) { return getDeclType(expr); } return expr.getExpressionType(); }

Target:
Why handle t_decltype_auto here? We should never get in here for decltype(auto) because getDeclTypeExpression() will be null.
Source:
public Number getLineMiterLimit() { if (paint.get("line-miter_limit") != null) { return (Number) paint.get("line-miter-limit"); } else { return 2; } }

Target:
I think the underscore should be a dash
Source:
public void start() { if (started.compareAndSet(false, true)) { register(); scheduler = Utils.newScheduler(1, false); scheduler.scheduleAtFixedRate(new NettyMetricCollector(), 0, config.nettyMetricsRefreshIntervalSeconds, TimeUnit.SECONDS); logger.trace("Schedule netty metric collector"); } }

Target:
change this to INFO level
Source:
public String getFile(@PathVariable("id") final String id, final HttpServletRequest request) { String encodedId; try { // When forwarding, the downstream ApplicationContext will perform URL decoding. // If the job ID contains special characters (such as '+'), they will be interpreted as url-encoded and // decoded, resulting in an invalid job ID that cannot be found. // To prevent this, always perform URL encoding on the ID before forwarding. encodedId = URLEncoder.encode(id, "UTF-8"); } catch (UnsupportedEncodingException e) { log.warn("Failed to encode id: {}", id, e); encodedId = id; } final String path = "/api/v3/jobs/" + encodedId + "/" + ControllerUtils.getRemainingPath(request); return "forward:" + path; }

Target:
At this point any reason we wouldn't throw the exception up and return error to client?
Source:
private Integer deserializeValue(Map<String, Object> entry, String curveKey, int conversionRate) { Map<String, Double> parameters = (Map<String, Double>) entry.get(curveKey); if (parameters == null) { return null; } Double average = parameters.get(VdsProperties.HOST_QOS_AVERAGE); return (average == null) ? null : (int) (average / conversionRate); }

Target:
How is it possible to get a non-integer value? Is there a way to set the value via the host? If there is, it would be more accurate to save the qos parameters on HostNetworkQos as doubles. Or even saving it as integer but in bits and just displaying it to the user in Mb. I don't understand the benefit of sending/receiving bits as doubles through the api with vdsm.
Source:
public NotifyingFuture<V> attachListener(final FutureListener<V> listener) { future.whenComplete((value, throwable) -> { if (throwable == null) { listener.futureDone(this); } else { listener.futureDone(this); } }); return this; }

Target:
Seems this if else block here can just be replaced by `listener.futureDone(this);`