auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void writeProperty(JsonGenerator jg, Property prop) throws IOException { if (prop.isScalar()) { writeScalarProperty(jg, prop); } else if (prop.isList()) { writeListProperty(jg, prop); } else if (prop.isComplex()) { writeComplexProperty(jg, prop); } else if (prop instanceof BlobProperty) { // a blob writeBlobProperty(jg, prop); } else if (prop.isPhantom()) { jg.writeNull(); } }

Target:
Because a `BlobProperty` is also a complex property, this check should come before `prop.isComplex()`. In my local tests I got a `NuxeoException` with `Trying to access a member of a null object: mime-type` when trying to write a blob property, which was treated as a complex.
Source:
public ProbeStatus run() { if (Framework.getRuntime().isStarted()) { return ProbeStatus.newSuccess("Runtime started"); } return ProbeStatus.newFailure("Runtime not started"); }

Target:
You should also check first `Framework.getRuntime() != null` just in case.
Source:
public ProbeStatus run() { if (Framework.getRuntime() != null && Framework.getRuntime().isStarted()) { return ProbeStatus.newSuccess("Runtime started"); } return ProbeStatus.newFailure("Runtime not started"); }

Target:
Put the second return in an `else` statement
Source:
protected HealthCheckResult getOrRunHealthCheck(String probe) { ProbeManager pm = Framework.getService(ProbeManager.class); if (StringUtils.isEmpty(probe)) { // run all healthCheck probes return pm.getOrRunHealthChecks(); } return pm.getOrRunHealthCheck(probe); }

Target:
Put the second return in an `else` block for symmetry.
Source:
public static List<Throwable> getThrowableList(Throwable throwable) { final List<Throwable> list = new ArrayList<Throwable>(); while (throwable != null && list.contains(throwable) == false) { list.add(throwable); throwable = getCause(throwable); } return list; }

Target:
`List<Throwable> list = new ArrayList<>();`
Source:
protected void logSearchRequest(SearchRequest request, NxQueryBuilder query, SearchType searchType) { if (log.isDebugEnabled()) { String scroll = ""; if (request.scroll() != null) { scroll = "&scroll=" + request.scroll().toString(); } log.debug(String.format( "Search query: curl -XGET 'http://localhost:9200/%s/%s/_search?pretty&search_type=%s%s' -d '%s'", getSearchIndexesAsString(query), DOC_TYPE, searchType.toString().toLowerCase(), scroll, request.source().toString())); } }

Target:
Double assignment to `scroll` is bad style, and the `toString` is implicit when concatenating to a String. Just use: IDontKnowTheType requestScroll = request.scroll(); String scroll = requestScroll == null ? null : "&scroll=" + requestScroll;
Source:
protected String getIndexesAsString(String[] indexNames) { String indexes = ""; if (indexNames != null && indexNames.length > 0) { indexes = String.join(",", indexNames); } return indexes; }

Target:
Don't do double assignment, and no need for "return at end of method", and the case `indexNames.length == 0` is already dealt with by `String.join`, so just do: return indexNames == null ? "" : String.join(",", indexNames);
Source:
public boolean isEmbedded() { return (embeddedServer != null); }

Target:
Remove extra parentheses
Source:
protected void setSystemProperty(String key, String newValue) { String originValue = System.getProperty(key); originSystemProps.put(key, originValue); System.setProperty(key, newValue); }

Target:
`@since 9.3` `originSystemProps.put(key, System.setProperty(key, newValue));`
Source:
public void transientFilesWorkAreCleaned() throws Exception { LogFactory.getLog(WorkManagerTest.class).fatal("\"default\" is processing=" + service.isProcessingEnabled("default")); final File file = feature.resolveAndCreate(new File("pfouh")); service.schedule(new CreateFile(file)); service.awaitCompletion(5, TimeUnit.SECONDS); }

Target:
Do you really want to keep this `log.fatal`?
Source:
public void testRetryPostEnabled() throws Exception { // Enable POST retry enableSunHttpClientRetryPostProp(); sendInitialGetRequest(); // POST retry is enabled, the call should succeed ClientResponse response = webResource.post(ClientResponse.class); assertEquals(200, response.getStatus()); response.close(); }

Target:
A try/finally would be better here.
Source:
ApacheHttpClientBuilder() { this.socketTimeout = DEFAULT_CONNECTION_TIMEOUT; this.connectTimeout = DEFAULT_CONNECTION_TIMEOUT; this.connectionRequestTimeout = DEFAULT_CONNECTION_TIMEOUT; }

Target:
`public` ?
Source:
public DocumentModel run(DocumentModel doc) throws ConcurrentUpdateException, IOException { if (changeToken != null) { // Check for dirty update save = true; doc.putContextData(CoreSession.CHANGE_TOKEN, changeToken); } DocumentHelper.setProperties(session, doc, properties); if (save) { doc = session.saveDocument(doc); // may throw ConcurrentUpdateException if bad change token } return doc; }

Target:
Maybe could be stated in the `changeToken` parameter description that it forces the session to be saved, even if the `save` parameter was set to false?
Source:
public long getMaxResultWindow() { if (maxResultWindow == null) { ConfigurationService cs = Framework.getService(ConfigurationService.class); String maxResultWindowStr = cs.getProperty(ES_MAX_RESULT_WINDOW_PROPERTY, DEFAULT_ES_MAX_RESULT_WINDOW_VALUE); try { maxResultWindow = Long.valueOf(maxResultWindowStr); } catch (NumberFormatException e) { log.warn(String.format( "Invalid maxResultWindow property value: %s for page provider: %s, fallback to default.", maxResultWindow, getName())); maxResultWindow = Long.valueOf(DEFAULT_ES_MAX_RESULT_WINDOW_VALUE); } } return maxResultWindow; }

Target:
maxResultWindow -> maxResultWindowStr
Source:
public boolean shouldIgnore() { return coreFeature.getStorageConfiguration().isVCS() // MySQL fulltext is funky with respect to what words it finds in small databases // so don't bother testing on MySQL, this is mostly a configuration test anyway || coreFeature.getStorageConfiguration().isVCSMySQL(); }

Target:
Here you changed the logic. Previously the test ran if it was on VCS and not on MySQL. Now you ignore if it's VCS or MySQL. That's not the same.
Source:
protected void postSetUp() throws Exception { EventService service = Framework.getService(EventService.class); serviceImpl = (EventServiceImpl) service; }

Target:
Put the cast on the same line
Source:
void assertSetEquals(List<String> expected, List<String> actual) { assertEquals(new HashSet<String>(expected), new HashSet<String>(actual)); }

Target:
Can we inject this feature directly ?
Source:
protected Stream<URL> listBundleComponents(Bundle bundle) { String list = OSGiRuntimeService.getComponentsList(bundle); String name = bundle.getSymbolicName(); log.debug("PartialBundle: " + name + " components: " + list); if (list == null) { return null; } return Arrays.stream(list.split("[, \t\n\r\f]")).map(s -> bundle.getEntry((String) s)).filter(Objects::nonNull); }

Target:
Not needed, `s` is already a `String`
Source:
public void refresh() { if (parent != null) parent.refresh(); }

Target:
Format
Source:
public void addLinks(String sourceId, List<String> targetIds, Session session) throws DirectoryException { if (readOnly) { return; } checkDualReference(); dualReference.addLinks(sourceId, targetIds, session); }

Target:
Shouldn't this be `addLinks(targetIds, sourceId, session)`? So we'd need the symmetrical `addLinks(List<String> sourceIds, String targetId, Session session)` method in the `Reference` interface too, no?
Source:
public OAuth2ServiceProvider getProvider(String serviceName) { DocumentModel model = getProviderDocModel(serviceName); return model != null ? buildProvider(model): null; }

Target:
I prefer `model == null ? null : buildProvider(model)` to avoid negations. Also please make sure of having a space left and right of the `:`.
Source:
public List<OAuth2ServiceProvider> getProviders() { List<DocumentModel> providers = queryProviders(Collections.emptyMap(), 0); return providers.stream().map(provider -> buildProvider(provider)).collect(Collectors.toList()); }

Target:
`provider -> buildProvider(provider)` -> `this::buildProvider`
Source:
Registration with(MBeanServer server) { this.server = server; return this; }

Target:
`protected` instead of package protected
Source:
Registration register() throws JMException { instance = server.registerMBean(StandbyCommand.this, ObjectNameFactory.getObjectName(StandbyCommand.class.getName())); return this; }

Target:
`protected` instead of package protected
Source:
void unregister() throws JMException { try { server.unregisterMBean(instance.getObjectName()); } finally { instance = null; } }

Target:
`protected` instead of package protected
Source:
public void expandAll() { List<WebElement> expanders = getItemExpanderInPublishTreeForm(); if (expanders.size() == 0) { return; } else { for (WebElement expander : expanders) { Locator.waitUntilEnabledAndClick(expander); } } }

Target:
`expanders.isEmpty()`
Source:
private void checkUserExistence(String username) { UserManager userManager = Framework.getService(UserManager.class); if (userManager.getUserModel(username) == null && userManager.getGroupModel(username) == null) { String errorMsg = "User or group name '" + username + "' does not exist. Please provide a valid name."; throw new NuxeoException(errorMsg); } }

Target:
`protected` to allow subclassing.
Source:
public File getDataDir() { if (StringUtils.isBlank(path)) { File transienStoreHome = new File(Environment.getDefault().getData(), "transientstores"); return new File(transienStoreHome, getName()); } else { return new File(path); } }

Target:
Don't put any logic in the descriptor, it should be pure data. Do everything in the caller.
Source:
protected HashMap<String, String> evalDynamicProperties() throws ConfigurationException { HashMap<String, String> newParametersToSave = new HashMap<>(); evalEnvironmentVariables(); evalLoopbackURL(); evalServerStatusKey(newParametersToSave); return newParametersToSave; }

Target:
use `newParametersToSave`
Source:
public static JSONPropertyWriter create() { JSONPropertyWriter writer = new JSONPropertyWriter(); writer.dateTimeFormat = DateTimeFormat.W3C; return writer; }

Target:
Why not put this as field default like `writeEmpty` and `writeNull`?
Source:
public JSONPropertyWriter dateTimeFormat(DateTimeFormat dateTimeFormat) { JSONPropertyWriter writer = new JSONPropertyWriter(this); writer.dateTimeFormat = dateTimeFormat; return writer; }

Target:
Do you really need to return a new one each time? Fluent style doesn't necessarily imply that, and it would be faster without. I'd modify the existing one in place.
Source:
private String[] getIndexNames() { List<String> repositoryNames = getRepositoryNames(); String indices[] = new String[this.repositoryNames.size()]; int i = 0; for (String repo : repositoryNames) { indices[i++] = esa.getIndexNameForRepository(repo); } return indices; }

Target:
The `this` is surprising here, I'd remove it.
Source:
public synchronized void registerPropertyDeprecation(PropertyDeprecationDescriptor descriptor) { Map<String, Map<String, String>> properties = removedProperties; if (descriptor.isDeprecated()) { properties = deprecatedProperties; } properties.computeIfAbsent(descriptor.getSchema(), key -> new HashMap<>()).put(descriptor.getName(), descriptor.getFallback()); log.info("Registered property deprecation: " + descriptor); }

Target:
`Map<String, Map<String, String>> properties = descriptor.isDeprecated() ? deprecatedProperties : removedProperties`
Source:
protected String getPDFConversionURL(Blob blob) { BlobManager blobManager = Framework.getService(BlobManager.class); try { URI uri = blobManager.getAvailableConversions(blob, UsageHint.DOWNLOAD).get(MimetypeRegistry.PDF_MIMETYPE); if (uri != null) { return uri.toString(); } } catch (IOException e) { log.error("Failed to retrieve available conversions", e); } return null; }

Target:
You can `import static org.nuxeo.ecm.platform.mimetype.interfaces.MimetypeRegistry.PDF_MIMETYPE` for this type of constant.
Source:
public ElasticSearchAdminImpl(ElasticSearchLocalConfig localConfig, ElasticSearchRemoteConfig remoteConfig, Map<String, ElasticSearchIndexConfig> indexConfig) { this.remoteConfig = remoteConfig; this.localConfig = localConfig; this.indexConfig = indexConfig; this.clientInitService = null; connect(); initializeIndexes(); }

Target:
Don't repeat this code, make it call the new constructor passing `null` as an argument for `clientInitService`.
Source:
public static String getEntryContentAsString(File file, String entryName) throws IOException { InputStream resultStream = getEntryContentAsStream(file, entryName); // resultStream has been closed by FileUtils call return IOUtils.toString(resultStream, Charsets.UTF_8); }

Target:
Also the various `IOUtils` utilities like `toString` do **not** close the stream, so it must be closed afterwards (usually using a `try-with-resources` block).
Source:
@Test public void testToAscii() throws UnsupportedEncodingException { String s = "h\u00E9h\u00E9"; assertEquals("hehe", StringUtils.toAscii(s)); }

Target:
Please put `@Test` on the line above, not on the same line.
Source:
public boolean hasPreview(String xpath) { String srcMT = getMimeType(xpath); if (!Framework.getService(ConfigurationService.class).isBooleanPropertyTrue(ALLOW_ZIP_PREVIEW) && "application/zip".equals(srcMT)) { return false; } MimeTypePreviewer mtPreviewer = getPreviewManager().getPreviewer(srcMT); return mtPreviewer != null || getConversionService().getConverterName(srcMT, "text/html") != null; }

Target:
Put `"application/zip".equals(srcMT)` first before the `&&` as it's cheaper to evaluate.
Source:
public Type getType(String id) { Type type = types.get(id); if (type == null) { return null; } else { Map<String, SubType> allowedSubTypes = getCoreAllowedSubtypes(type); Type newType = type.clone(); newType.setAllowedSubTypes(allowedSubTypes); // do not need to add denied subtypes because allowed subtypes already come filtered from core newType.setDeniedSubTypes(new String[0]); return newType; } }

Target:
This is early exit, so you can move the `else` part unindented below.
Source:
public static SharedPackageListingsSettings instance() { RequestResolver resolver = resolvers.values() .stream() .filter(RequestResolver::isActive) .findFirst() .orElse(null); if (resolver != null) { return instance(resolver.resolve()); } return null; }

Target:
Here maybe you could use .map(RequestResolver::resolve).map(this::instance).orElse(null);
Source:
protected Blob getContentBlob(Blob original, DocumentModel doc) { if (doc.getProperty(PICTURE_VIEWS_PROPERTY) != null) { MultiviewPicture multiviewPicture = doc.getAdapter(MultiviewPicture.class); for (PictureView view : multiviewPicture.getViews()) { if (view.getTitle().equals("FullHD") && view.getBlob() != null) { return view.getBlob(); } } } return original; }

Target:
you shouldn't need the previous check. Normally you use doc.getAdapter() and check if it's null
Source:
public boolean waitForCompletion(long timeoutMillis) throws InterruptedException { WorkManager workManager = getWorkManager(); if (workManager!=null) { return workManager.awaitCompletion(timeoutMillis, TimeUnit.MILLISECONDS); } else { return false; } }

Target:
Space before/after `!=`. Prefer the early-exit idiom: ``` if (workManager == null) { return false; } return workManager.await... ```
Source:
public void init() { asyncExec.init(); EventDispatcherDescriptor dispatcherDescriptor = dispatchers.getDispatcherDescriptor(); if (dispatcherDescriptor != null) { List<EventPipeDescriptor> pipes = registeredPipes.getPipes(); if (pipes.size() > 0) { pipeDispatcher = dispatcherDescriptor.getInstance(); pipeDispatcher.init(pipes, dispatcherDescriptor.getParameters()); } } }

Target:
`if (!pipes.isEmpty())`
Source:
public void sendEventBundle(EventBundle events) { events = filterBundle(events); if (events.size() == 0) { return; } preProcessBundle(events); send(marshall(events)); }

Target:
`events.isEmpty()`
Source:
public EventDispatcherDescriptor getDispatcherDescriptor() { int nbd = contribs.size(); if (nbd > 0) { return contribs.get(nbd - 1); } else { return null; } }

Target:
`return contribs.isEmpty() ? null : contribs.get(contribs.size() - 1)`
Source:
public void sendEventBundle(EventBundle events) { if (events.size() == 0) { return; } for (EventBundlePipe pipe : pipes) { pipe.sendEventBundle(events); } }

Target:
isEmpty
Source:
public boolean waitForCompletion(long timeoutMillis) throws InterruptedException { boolean res = true; for (EventBundlePipe pipe : pipes) { res = res && pipe.waitForCompletion(timeoutMillis); } return res; }

Target:
IMPORTANT `res = pipe.waitForCompletion(timeoutMillis) && res` otherwise after the first fails to complete the boolean expression will short-circuit and the other waits won't get executed..
Source:
public String getVocabularyLabel(String voc, String key) { try (Session session = getDirService().open(voc)) { if (!session.hasEntry(key)) { log.warn("Unable to find the key '" + key + "' in the vocabulary '" + voc + "'."); return key; } DocumentModel doc = session.getEntry(key); // TODO: which is the best method to get "label" property when not // knowing vocabulary schema? // AT: the best is to accept it as a parameter of the method, and // fallback on "label" when not given DataModel dm = doc.getDataModels().values().iterator().next(); return (String) dm.getData("label"); } }

Target:
Not sure we want a WARN here, this could spam the logs and the server admin can't do much about it. I'd do just DEBUG.
Source:
public DocumentModel toFields(DocumentModel inDoc, HashMap<String, String> inMapping, boolean inSave, CoreSession inSession) { // Parse if needed run(); HashMap<String, String> values = toHashMap(); for (String inXPath : inMapping.keySet()) { String value = values.get(inMapping.get(inXPath)); inDoc.setPropertyValue(inXPath, value); } if (inSave) { inDoc = inSession.saveDocument(inDoc); } return inDoc; }

Target:
`Map<String, String>`
Source:
public String getAllExtractedLines() throws NuxeoException { if (extractedAllAsString == null) { PDDocument pdfDoc = null; try { pdfDoc = PDFUtils.load(pdfBlob, password); PDFTextStripper stripper = new PDFTextStripper(); extractedAllAsString = stripper.getText(pdfDoc); } catch (IOException e) { throw new NuxeoException("Failed to handle the pdf", e); } finally { PDFUtils.closeSilently(pdfDoc); } } return extractedAllAsString; }

Target:
try with resource
Source:
public ArrayList<LinkInfo> getRemoteGoToLinks() throws IOException { if (remoteGoToLinks == null) { loadAndPreflightPdf(); remoteGoToLinks = parseForLinks(PDActionRemoteGoTo.SUB_TYPE); } return remoteGoToLinks; }

Target:
`List<LinkInfo>` (check below for other method signatures)
Source:
public void setCurrentContentViewName(String contentViewName) { currentContentViewName = contentViewName; }

Target:
Is it needed to remove 'this' ?
Source:
protected void resetCurrentContentViewWorkingList() { if (currentContentViewName != null) { ContentView contentView = contentViewActions.getContentView(currentContentViewName); if(contentView != null){ String selectionListName = contentView.getSelectionListName(); documentsListsManager.resetWorkingList(selectionListName); } } }

Target:
format there's a space between if and (
Source:
public DocumentModel run(DocumentModel input) { IdRef idRef = new IdRef(input.getId()); DocumentModel lastVersion = session.getLastDocumentVersion(idRef); return lastVersion; }

Target:
just return this
Source:
public DocumentModel run(DocumentModel input) { DocumentModelList proxies = session.getProxies(input.getRef(), null); for (DocumentModel proxy : proxies) { session.removeDocument(proxy.getRef()); } session.save(); return null; }

Target:
Guess return type should be `void`
Source:
private void resetSchemaProperties(DocumentModel target) throws OperationException { if (xpath != null) { target.setPropertyValue(xpath, null); } else if (schema != null) { for (Map.Entry<String, Object> entry : target.getProperties(schema).entrySet()) { target.setProperty(schema, entry.getKey(), null); } } else { throw new OperationException("No schema or xpath was provided"); } }

Target:
use .keySet() since we only use the key anyway
Source:
public boolean documentExists(CoreSession session, String idOrPath) { DocumentRef documentRef; if (idOrPath.startsWith("/")) { documentRef = new PathRef(idOrPath); } else { documentRef = new IdRef(idOrPath); } try { // we do not need the variable, just check if the document exists /*DocumentModel doc = */session.getDocument(documentRef); } catch (DocumentNotFoundException exception) { return false; } return true; }

Target:
Ternary operator `idOrPath.startsWith("/") ? new PathRef(idOrPath) : new IdRef(idOrPath)`
Source:
public DocumentModel run(DocumentModel input) { // we ignore the result /*boolean result = */ input.addFacet(facet); session.saveDocument(input); return input; }

Target:
For such small method (next one in next file too) having extra blank lines doesn't bring anything.
Source:
protected void createDocumentVersions(DocumentModel doc, VersioningOption vo, int nrVersions) { // create a document with major versions for (int i = 1; i <= nrVersions; i++) { doc.setPropertyValue("dc:description", "" + i); doc.putContextData(VersioningService.VERSIONING_OPTION, vo); session.saveDocument(doc); } session.save(); }

Target:
`String.valueOf(i)`
Source:
public void run() { Map<String, List<String>> sourceIdToRenditionRefs = computeLiveDocumentRefsToRenditionRefs(); List<String> sourceIds = new ArrayList<>(sourceIdToRenditionRefs.keySet()); removeStoredRenditions(sourceIdToRenditionRefs, sourceIds); }

Target:
If you rework `removeStoredRenditions` as a simple iterative method you don't need to do the copy.
Source:
public SavedSearch getSavedSearch(CoreSession session, String id) { DocumentRef docRef = new IdRef(id); DocumentModel savedSearchDoc = session.getDocument(docRef); if (savedSearchDoc != null) { SavedSearch search = savedSearchDoc.getAdapter(SavedSearch.class); if (search != null) { return search; } } return null; }

Target:
You can return that directly here.
Source:
public void toggleJoypad(Key key, boolean state) { if (key.name == MojamComponent.instance.keys.joy_click.name) { MouseButtons mb = MojamComponent.instance.mouseButtons; MojamComponent.instance.mouseButtons.nextState[1] = (!mb.nextState2[1])?state:mb.nextState[1]; return; } key.nextState = (!key.nextState2)?state:key.nextState; }

Target:
shouldn't it be key.name.equals( ... ); ? I always get confused about checking equality on immutable objects.
Source:
public void render(){ System.out.println("Rendering Path "+toString()); for(Node n:nodes){ MojamComponent.screen.alphaFill((int)n.pos.x, (int)n.pos.y, Tile.WIDTH, Tile.HEIGHT, 0x00ccff, 0x10); } }

Target:
This debug output should be deleted
Source:
protected void upgradeComplete() { health += 10; maxHealth += 10; radius = upgradeRadius[upgradeLevel]; capacity = upgradeCapacities[upgradeLevel]; }

Target:
this can cause some conflicts.. best thing to do is put this after that the maxHealth is upgraded, and then just health = maxHealth (like stated before by @Borsty)
Source:
private static boolean responseOk(final int status) { switch (status) { case HttpStatus.SC_CREATED: case HttpStatus.SC_OK: return true; default: return false; } }

Target:
Is it relevant to maybbe rewrite this to the `status / 100 == 2` trick, as in https://github.com/digipost/digipost-useragreements-api-client-java/blob/master/src/main/java/no/digipost/api/useragreements/client/response/ResponseUtils.java#L198-L200
Source:
@Test public void connectWithIdnUrl() throws MalformedURLException { URL url = new URL("https://тест.рф"); Connection con = HttpConnection.connect(url, true); String expectedUrl = url.getProtocol() + "://" + IDN.toASCII(url.getHost()) + url.getPath(); assertEquals(expectedUrl, con.request().url().toExternalForm()); }

Target:
Need to make sure we have test for redirects to IDNs, and for finding IDN in HTML and following.
Source:
public String getWholeText(){ final StringBuilder accum = new StringBuilder(); new NodeTraversor(new NodeVisitor() { public void head(Node node, int depth) { if (node instanceof TextNode) { TextNode textNode = (TextNode) node; accum.append(textNode.getWholeText()); } } public void tail(Node node, int depth) { } }).traverse(this); return accum.toString().trim(); }

Target:
why `trim()`? if we use `<p> Hello\nthere </p>`, wouldn't I want everything inside `<p>` that is not an html node?
Source:
public OutputSettings charset(Charset charset) { if( document != null ) { Element meta = document.select("meta[charset]").first(); if( meta != null ) { meta.attr("charset", charset.displayName()); } } this.charset = charset; charsetEncoder = charset.newEncoder(); return this; }

Target:
What about the other forms of this? `meta name=charset value=`, and `meta htt-equiv contenttype`? There's code in DataUtils for that, should be able to reuse.
Source:
public Builder keyValueSeparator(char keyValueSeparator) { if (keyValueSeparator == 0) throw new IllegalArgumentException("keyValueSeparator == 0"); if (keyValueSeparator == entrySeparator) { throw new IllegalArgumentException("keyValueSeparator == entrySeparator"); } this.keyValueSeparator = keyValueSeparator; return this; }

Target:
Validating in the setter is nicer but I guess it means we should default the values to `0` and replace with the actual defaults in `build`. Otherwise, it requires hoops to do the horrible, but not inconceivable, using `=` as entry separator and `,` as keyvalue separator.
Source:
@Override public void onClose(Status status, Metadata trailers) { Throwable error = null; try (Scope scope = currentTraceContext.maybeScope(invocationContext)) { delegate().onClose(status, trailers); } catch (Throwable e) { error = e; throw e; } finally { GrpcClientResponse response = new GrpcClientResponse(request, status, trailers, error); finish(response, spanRef.getAndSet(null)); } }

Target:
Not sure but I think this would only happen if there is an error in the business logic on the client side when processing the closure, even if the request itself succeeded. So this might not warrant marking the span as error.
Source:
@Override public void close(Status status, Metadata trailers) { Throwable error = null; try (Scope scope = currentTraceContext.maybeScope(context)) { delegate().close(status, trailers); } catch (Throwable e) { error = e; throw e; } finally { GrpcServerResponse response = new GrpcServerResponse(request, status, trailers, error); finish(response, spanRef.getAndSet(null)); } }

Target:
I'm less clear about this one since closure on the server side is handled by the framework, so an error may or may not indicate the response failed. Ideally, our interceptor is in a location where the only possibility of an exception here is a grpc-java bug.
Source:
@Override public void onReady() { Scope scope = currentTraceContext.maybeScope(invocationContext); try { delegate().onReady(); } finally { scope.close(); } }

Target:
Not sure if gRPC being Java 8 means we would prefer try/resources here but just in case
Source:
@Override public Throwable error() { if (caught != null || request == null) return caught; return request.maybeError(); }

Target:
I had to do a doubletake here, it's an extra line but this could help readers ```java if (caught != null) return caught; if (request == null) return null; return request.maybeError(); ```
Source:
static String getSpanName(String commandName, @Nullable String collectionName) { return commandName + (collectionName == null ? "" : (" " + collectionName)); }

Target:
Just return `commandName` if collection is null. I'm not sure but don't expect the JVM to optimize the stringbuilder away for this pattern.
Source:
Builder(MongoDBTracing mongoDBTracing) { this(mongoDBTracing.tracing); maxAbbreviatedCommandLength(mongoDBTracing.maxAbbreviatedCommandLength); clearCommandsWithCollectionName(); addAllCommandsWithCollectionName(mongoDBTracing.commandsWithCollectionName); }

Target:
I'd just set `maxAbbreviatedCommandLength = t.maxAbbreviated...` since we never need to validate values from a built object.
Source:
@Nullable public final String tag(I input, @Nullable TraceContext context, SpanCustomizer span) { if (input == null) throw new NullPointerException("input == null"); if (span == null) throw new NullPointerException("span == null"); if (span == NoopSpanCustomizer.INSTANCE) return null; return tag(span, input, context); }

Target:
It's compatible with source compilation, but I'm pretty sure it's ABI incompatible, meaning if two libraries target different Brave and use this method, one gets `NoSuchMethodError`.
Source:
public TracingP6SpyOptions(P6OptionsRepository optionsRepository) { super(TracingP6SpyOptionsMBean.class, false); logLoadableOptions = new P6LogOptions(optionsRepository); this.optionsRepository = optionsRepository; }

Target:
revert public here. note: please use the format on all files changed as I notice some missing or too many spaces around. if you look at the diff you can notice.
Source:
protected CurrentTraceContext(Builder<?> builder) { this.scopeDecorators = (List<ScopeDecorator>) builder.scopeDecorators.clone(); }

Target:
I personally haven't seen `clone()` for copying anything other than an array. `new ArrayList<ScopeDecorator>(builder.scopeDecorators)`?
Source:
protected Scope decorateScope(@Nullable TraceContext currentSpan, Scope scope) { int length = scopeDecorators.size(); if (length == 0) return scope; for (int i = 0; i < length; i++) { scope = scopeDecorators.get(i).decorateScope(currentSpan, scope); } return scope; }

Target:
I think the for loop duplicates this check so it doesn't really speed up the `0` case.
Source:
public void finish(TraceContext context, long finishTimestamp) { if (noop.get()) return; MutableSpan span = spanMap.remove(context); if (span == null || noop.get()) return; synchronized (span) { span.finish(finishTimestamp); reporter.report(V2SpanConverter.toSpan(span.toSpan())); } }

Target:
for these down, you don't want to early return as they remove data from the map (we want that data removed even in noop in case a span started before the tracing component was set to noop status)
Source:
private void handleConsumed(ConsumerRecord record) { Span span = startAndFinishConsumerSpan(record); // remove propagation headers from the record tracing.propagation().keys().forEach(key -> record.headers().remove(key)); // Inject new propagation headers tracing.propagation().injector(injector) .inject(span.context(), record); }

Target:
save some overhead by declaring injector as a field and reusing it. `injector = tracing.propagation().injector(injector)`
Source:
public <T> T trace(String component, String operation, Callable<T> callable) throws RuntimeException { try { startNewSpan(component, operation); return callable.call(); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } finally { finishSpan(); } }

Target:
if something throws an exception, you should probably propagate it vs wrap
Source:
public void trace(String component, String operation, Runnable runable) throws RuntimeException { try { startNewSpan(component, operation); runable.run(); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } finally { finishSpan(); } }

Target:
iirc Runnable doesn't have declared exceptions, so this will just wrap runtime exceptions in another runtime exception?
Source:
private void internalFinishSpan(Span span, long duration) { synchronized (span) { span.setDuration(duration); reporter().report(span.toZipkin()); } spanAndEndpoint().state().setCurrentLocalSpan(null); }

Target:
Is it worth moving the reporting out of the synchronized block (though I wouldn't expect convention on that span)?
Source:
synchronized Long startTick(Span span) { return span.startTick; }

Target:
Should this be synchronizing on the span rather than `this`?
Source:
public URI getUri() { return getRequest().url().uri(); }

Target:
It's wasteful to be calling `getRequest()` in these methods. Consider taking in the original `Request` and storing it in a field alongside the mutable result of `newBuilder()`
Source:
public SVGReadParam() { super(); allowExternalResources = true; }

Target:
Same here, just remove all this, and leave the value as `false`.
Source:
private void decodeRowType2() throws IOException { if(optionByteAligned) resetBuffer(); decode1D(); }

Target:
Code style: Always use curly brackets, and space after `if`.
Source:
private void decodeRowType4() throws IOException { if(optionByteAligned) resetBuffer(); eof: while (true) { // read till next EOL code Node n = eolOnlyTree.root; while (true) { n = n.walk(readBit()); if (n == null) { continue eof; } if (n.isLeaf) { break eof; } } } if (!optionG32D || readBit()) { decode1D(); } else { decode2D(); } }

Target:
Code style: Always use curly brackets, and space after `if`.
Source:
private ImmutableList<Dimension> createDimensions(Iterable<Map<String, Object>> dimensions) { if (dimensions == null) { return ImmutableList.of(); } return FluentIterable.from(dimensions).transform(MAP_ENTRY_TO_DIMENSION).toList(); }

Target:
Please handle the nullity in the constructor
Source:
public String getAlias() { if (alias == null) { return null; } return alias; }

Target:
No need to check whether alias is null
Source:
private void doMain() throws Exception { // Start the process start(); while (true) { // look for some terminator // attempt to read off queue // process message // TODO : Make something here, maybe watch for files? try { Thread.sleep(5); } catch (Exception e) { log.info("shutting down", e); break; } } unregisterMBeans(); }

Target:
There are many unneeded changes, mostly code style, in this PR. Removing `this.` is not needed and adds unnecessary noise to this PR. Maybe move this to another PR.
Source:
public void internalWrite(Server server, Query query, ImmutableList<Result> results) throws Exception { LogWriter logwriter = new LogWriter(logger,delimiter); graphiteWriter.write(logwriter, server, query, results); }

Target:
This logwriter could be a field, no need to instantiate a new one for each message.
Source:
protected void after() { System.setOut(originalOut); System.setErr(originalErr); // I guess it's useful to print this after completion System.out.println("What was captured:"); System.out.println(out); }

Target:
I would disagree... It is the job of the client of OutputCapture to print stuff if it make sense. In most cases, it probably does not. And even if it does, it should be sent to a logger.
Source:
public void close() throws IOException { markedAsDestroyed = true; if (connector != null) { executor.submit(new Runnable() { public void run() { if (connector != null) { try { connector.close(); } catch (IOException e) { logger.error("Error occurred during close connection {}", this, e); } } } }); } }

Target:
Why delegate the closing to an executor?
Source:
public JMXConnection(@Nullable JMXConnector connector, @Nonnull MBeanServerConnection mBeanServerConnection) { this.connector = connector; this.mBeanServerConnection = mBeanServerConnection; this.markedAsDestroyed = false; executor = Executors.newSingleThreadExecutor(); }

Target:
We should probably extract that executor at least as high as `MBeanServerConnectionFactory` and share it between connections. Keeping a single thread executor is probably fine for this case (if we have enough servers in trouble to saturate the single thread executor, we probably want to apply some back pressure to the connection pool anyway, we can tune that in the future if need be). This would also allow the use of a sameThreadExecutor in the test, slightly simpler.
Source:
public OpenTSDBWriter build() throws LifecycleException, UnknownHostException { return new OpenTSDBWriter( typeNames.build(), booleanAsNumber, debugEnabled, host, port, tags.build(), tagName, mergeTypeNamesTags, metricNamingExpression, (addHostnameTag == null) ? true : addHostnameTag, null ); }

Target:
Damn autoboxing... A `firstNonNull()` would make findbugs happy. And cleaner still, as `addHostnameTag` is a Boolean object, `true` should be as well (so `Boolean.TRUE` in this case).
Source:
public void stop() throws LifecycleException { try { target.stop(); } catch (LifecycleException ex) { throw(ex); } }

Target:
Catching an Exception and just rethrowing it as-is is equivalent to not catching it at all. So the implementation of this method should be just `target.stop();`, with no exception management at all (much simpler!).
Source:
private Boolean isHeartBeating() throws Exception { Stat stat = this.clClient.checkExists().forPath(clConfig.getWorkerNodePath()); return (null != stat); }

Target:
this should be `boolean` (with a small `b`).
Source:
private Boolean hasAffinityForJvm(){ return this.clConfig.getWorkerAlias().equals(this.affinity); }

Target:
`boolean`with small `b`
Source:
public void setup() { openTSDBMessageFormatter = Mockito.mock(OpenTSDBMessageFormatter.class); writer = new OpenTSDBWriter2(openTSDBMessageFormatter); outputWriter = Mockito.mock(Writer.class); result = Mockito.mock(Result.class); }

Target:
Just for fun ... I'd fid it more readable to have a static import of `Mockito.mock()` (this is a complete detail, feel free to ignore).
Source:
public String getPid() { if(this.pid == null) { return null; } return this.pid; }

Target:
This `if` is useless, if you remove it you will get the exact same behaviour.
Source:
public void testValidationWithoutSettings() throws ValidationException { CloudWatchWriter writer = createCloudWatchWriter(); Query query = Query.builder() .setObj("test") .build(); Server server = Server.builder().setHost("localhost").setPort("123").build(); writer.validateSetup(server, query); System.out.println("I got here"); }

Target:
Remove this. =)
Source:
public void toggleFlagDown() { if (flagdown == true) { flagdown = false; } if (flagdown == false) { flagdown = true; } }

Target:
This won´t work this way. Maybe u meant: `flagdown = !flagdown`?
Source:
public boolean getFlagDown() { if (flagdown == true) { return true; } else{ return false; } }

Target:
return flagdown; ?
Source:
public DroolsAbstractPMMLTest() { super(); Properties props = System.getProperties(); props.setProperty("drools.dump.dir", "/home/gcardosi/NotBackedUp/old_pmml_dump_dir"); }

Target:
To be removed or at least moved to a different path :)
Source:
public Optional<KiePMMLModel> getModel(String modelName) { logger.trace("getModel {}", modelName); return KnowledgeBaseUtils.getModel(knowledgeBase, modelName); }

Target:
Can you please add `isTraceEnabled` check?
Source:
private String fieldTypeUnwrapped() { if (fieldDMNType.isCollection()) { String typeName = index.asJava(fieldDMNType.getBaseType()); return typeName; } throw new IllegalArgumentException(); }

Target:
here we rather 1) inline the whole statement 2) split into significant different statements (`index.asJava` and `fieldDMNType.getBaseType`)
Source:
private List getListFromSerializableCollection(Collection<?> objects) { List serializableItems = new ArrayList<>(objects.size()); Iterator<? extends Object> iterator = objects.iterator(); while (iterator.hasNext()) { Object o = iterator.next(); serializableItems.add(o); } return serializableItems; }

Target:
You can use ``` serializableItems.addAll(objects); ``` instead of iterating the collection.
Source:
public static Properties getConfiguration(String filename) { Properties props = new Properties(); InputStream in = null; try { in = ClientUtils.class.getClassLoader().getResourceAsStream(filename); } catch (Exception e) { } finally { try { props.load(in); if(in != null) { in.close(); } } catch (IOException ioe) { } } return props; }

Target:
You can use try with resources here so the Input stream is closed automatically.
Source:
protected <Z extends ScesimDataWithIndex> List<Z> toScesimDataWithIndex(BiFunction<Integer, T, Z> producer) { List<Z> toReturn = new ArrayList<>(); List<T> data = getUnmodifiableData(); for (int index = 0; index < data.size(); index += 1) { toReturn.add(producer.apply(index + 1, data.get(index))); } return toReturn; }

Target:
@danielezonca I think `<Z extends ScesimDataWithIndex<T>> `
Source:
private boolean isjPMMLAvailableToClassLoader(ClassLoader classLoader) { try { classLoader.loadClass("org.kie.dmn.jpmml.DMNjPMMLInvocationEvaluator"); return true; } catch (ClassNotFoundException e) { } return false; }

Target:
Please handle this exception. Either rethrow or handle other way.
Source:
public static Document getDocument(String xml) throws ParserConfigurationException, IOException, SAXException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); DocumentBuilder dBuilder = factory.newDocumentBuilder(); InputStream inputStream = new ByteArrayInputStream(xml.getBytes()); return dBuilder.parse(inputStream); }

Target:
We do not close this stream nowhere, or am I missing something?
Source:
protected Object createObject(String className, List<String> genericClasses) { if (ScenarioSimulationSharedUtils.isMap(className)) { return new HashMap(); } else { try { if (SIMPLE_TYPES_LIST.contains(className)) { return null; } return classLoader.loadClass(className).newInstance(); } catch (Exception e) { throw new IllegalArgumentException("Impossible to instantiate " + className, e); } } }

Target:
Can be the `className` null? If not I would maybe rewrite as [1], what do you think? My point is to not nesting expression into try catch, if an exception can not be thrown. [1] ```java if (ScenarioSimulationSharedUtils.isMap(className)) { return new HashMap(); } else if (SIMPLE_TYPES_LIST.contains(className)) { return null; } else { try { return classLoader.loadClass(className).newInstance(); } catch (Exception e) { throw new IllegalArgumentException("Impossible to instantiate " + className, e); } } ```
Source:
public boolean isThereANeedToSetDefaultType(final InterpolationVariable newVar, final InterpolationVariable oldVar) { if (newVar.getDataType().equals(oldVar.getDataType()) && Objects.equals(newVar.getFactType(), oldVar.getFactType()) && Objects.equals(newVar.getFactField(), oldVar.getFactField())) { return false; } else { return true; } }

Target:
I'm surprised @jomarko didn't report this! It'd be more consistent to use `Objects.equals(...)` on all three checks.
Source:
public synchronized long getTimeToNextJob() { TimerJobInstance item = (TimerJobInstance) queue.peek(); return (item != null && item.getTrigger().hasNextFireTime() != null) ? item.getTrigger().hasNextFireTime().getTime() - this.timer.get() : -1; }

Target:
This should also never happen.
Source:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; org.drools.constraint.parser.JavaToken javaToken = (org.drools.constraint.parser.JavaToken) o; if (kind != javaToken.kind) return false; if (!text.equals(javaToken.text)) return false; return true; }

Target:
I know that this is a generated code, however please include curly braces for the ifs. Without them, the code could be misinterpreted more easily.
Source:
public NullSafeFieldAccessExpr setName(final SimpleName name) { assertNotNull(name); if (name == this.name) { return (NullSafeFieldAccessExpr) this; } notifyPropertyChange(ObservableProperty.NAME, this.name, name); if (this.name != null) this.name.setParentNode(null); this.name = name; setAsParentNodeOf(name); return this; }

Target:
Please add curly bracers here. Also please check other places, because I saw it also on more other places. You could use IDEA formatting highlights for that.
Source:
public Object get(String name) { return getCurrentEntries().get( EvalHelper.normalizeVariableName( name ) ); }

Target:
If the variable name is normalized on the set() method, is it necessary to normalize on the get() as well?
Source:
protected void initOutputClauses(CompilerContext feelctx, Map<String, CompiledFEELExpression> compilationCache) { logger.info("Reading " + outputs.size() + " outputs from class loader"); iterateOverOutputClauses((output, defaultValue) -> output.compiledDefault = (CompiledFEELExpression) readFieldWithRuntimeCheck(instanceName(getOutputName(defaultValue)))); }

Target:
Can you please change these to `debug` ?
Source:
protected List<ExternalBeanDefinition> getExternalMiningClasses() { List<ExternalBeanDefinition> list = null; if (externalMiningFields != null && !externalMiningFields.isEmpty()) { list = externalMiningFields.stream() .map(ref -> ref.getBeanDefinition()) .distinct() .collect(Collectors.toList()); } return list != null ? list : new ArrayList<>(); }

Target:
The fix proposed here may address some issue, but it does not address the issue that I have seen with drools-scorecards; mainly that there are some tests that periodically fail. I have applied the fixes from this PR to my local machine and I still get the intermittent errors in the ScorecardReasonCodeTest. Please see https://issues.jboss.org/browse/DROOLS-2592 to see my latest notes and results from my testing.
Source:
public static String normalizeVariableName(String name) { if (normalizationCache.containsKey(name)){ return normalizationCache.get(name); } String normalized = SPACES_PATTERN.matcher( name.trim() ).replaceAll( " " ); normalizationCache.put(name, normalized); return normalized; }

Target:
Are we caching the result of the application of a regular expression to a String here? Unless there are very good reason to do this, and we can demonstrate it with a benchmark, this seems really a bad idea.
Source:
public ExternalBeanDefinition(String beanInfo) throws Exception { if (beanInfo == null || beanInfo.isEmpty()) { throw new Exception("External type name missing"); } int lastPos = beanInfo.lastIndexOf("."); if (lastPos >= 0) { this.beanPackageName = beanInfo.substring(0, lastPos); this.beanName = beanInfo.substring(lastPos + 1); } else { this.beanPackageName = DEFAULT_BEAN_PKG; this.beanName = beanInfo; } }

Target:
Please don't use general Exception type for throwing exceptions. This makes handling of such exceptions very hard, because the type of the exception is hidden. For this, IllegalArgumentException can be used - it makes the exception specific - Illegal value for beanInfo argument was provided. Minor edit: please reformat the throw line, it is off to the right by 4 spaces.
Source:
public ExternalBeanRef(String modelFieldName, String beanInfo, ModelUsage usage) throws Exception { this.modelFieldName = modelFieldName; this.usage = usage; try { this.beanDefinition = new ExternalBeanDefinition(beanInfo); } catch (Exception e) { throw new Exception("Unable to construct ExternalBeanRef. ", e); } }

Target:
Please reformat this try-catch.
Source:
protected void initFieldMaps() { try { initMiningFieldMap(); initOutputFieldMap(); } catch(Exception e) { logger.error(e.getMessage()); } }

Target:
Please don't catch general Exception class, this could catch also exceptions that we don't want to be catched. E.g. NullPointerException.
Source:
static FEEL newInstance() { return new FEELImpl(Thread.currentThread().getContextClassLoader()); }

Target:
Same here, better to wrap the classloader creation inside a method.
Source:
public JPAPlaceholderResolverStrategy(String persistenceUnit, ClassLoader cl) { ClassLoader tccl = Thread.currentThread().getContextClassLoader(); try { // override tccl so persistence unit can be found from within given class loader - e.g. kjar Thread.currentThread().setContextClassLoader(cl); this.emf = Persistence.createEntityManagerFactory(persistenceUnit); initializeManagedClasses(); this.closeEmf = true; } finally { Thread.currentThread().setContextClassLoader(tccl); } this.classLoader = cl; this.name += ":" + persistenceUnit; }

Target:
I believe this is breaking backward compatibility as it will register itself with different name then it was persisted before this change so I think we should make it via additional cunstructor so we won't break existing sessions
Source:
public void testCopy() { final DSLVariableValue original = new DSLVariableValue("value"); final DSLVariableValue copy = original.copy(); assertEquals(original, copy); assertNotSame(original, copy); }

Target:
You could possibly check values too (but I guess, if the ```equals()``` method is broken we're really screwed!)
Source:
public XStreamMarshaller (List<DMNExtensionRegister> extensionRegisters) { this.extensionRegisters = new ArrayList<DMNExtensionRegister>(); this.extensionRegisters.addAll(extensionRegisters); }

Target:
`new ArrayList<>(extensionRegisters)` will do the same thing, with the additional benefit of properly sizing the list.