auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public ProbeStatus run() { if (Framework.getRuntime() != null && Framework.getRuntime().isStarted()) { return ProbeStatus.newSuccess("Runtime started"); START } END return ProbeStatus.newFailure("Runtime not started"); } Put the second return in an `else` statement

Target:
public ProbeStatus run() { if (Framework.getRuntime() != null && Framework.getRuntime().isStarted()) { return ProbeStatus.newSuccess("Runtime started"); } else { return ProbeStatus.newFailure("Runtime not started"); } }
Source:
protected HealthCheckResult getOrRunHealthCheck(String probe) { ProbeManager pm = Framework.getService(ProbeManager.class); if (StringUtils.isEmpty(probe)) { // run all healthCheck probes return pm.getOrRunHealthChecks(); } START return pm.getOrRunHealthCheck(probe); END } Put the second return in an `else` block for symmetry.

Target:
protected HealthCheckResult getOrRunHealthCheck(String probe) { ProbeManager pm = Framework.getService(ProbeManager.class); if (StringUtils.isEmpty(probe)) { // run all healthCheck probes return pm.getOrRunHealthChecks(); } else { return pm.getOrRunHealthCheck(probe); } }
Source:
public static List<Throwable> getThrowableList(Throwable throwable) { START final List<Throwable> list = new ArrayList<Throwable>(); END while (throwable != null && list.contains(throwable) == false) { list.add(throwable); throwable = getCause(throwable); } return list; } `List<Throwable> list = new ArrayList<>();`

Target:
public static List<Throwable> getThrowableList(Throwable throwable) { final List<Throwable> list = new ArrayList<>(); while (throwable != null && list.contains(throwable) == false) { list.add(throwable); throwable = getCause(throwable); } return list; }
Source:
protected void logSearchRequest(SearchRequest request, NxQueryBuilder query, SearchType searchType) { if (log.isDebugEnabled()) { String scroll = ""; if (request.scroll() != null) { scroll = "&scroll=" + request.scroll().toString(); START } END 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())); } } 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;

Target:
protected void logSearchRequest(SearchRequest request, NxQueryBuilder query, SearchType searchType) { if (log.isDebugEnabled()) { String scroll = request.scroll() != null ? "&scroll=" + request.scroll() : ""; 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())); } }
Source:
protected String getIndexesAsString(String[] indexNames) { String indexes = ""; if (indexNames != null && indexNames.length > 0) { indexes = String.join(",", indexNames); START } END return indexes; } 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);

Target:
protected String getIndexesAsString(String[] indexNames) { return indexNames == null ? "" : String.join(",", indexNames); }
Source:
public boolean isEmbedded() { START return (embeddedServer != null); END } Remove extra parentheses

Target:
public boolean isEmbedded() { return embeddedServer != null; }
Source:
protected void setSystemProperty(String key, String newValue) { String originValue = System.getProperty(key); originSystemProps.put(key, originValue); START System.setProperty(key, newValue); END } `@since 9.3` `originSystemProps.put(key, System.setProperty(key, newValue));`

Target:
protected void setSystemProperty(String key, String newValue) { originSystemProps.put(key, System.setProperty(key, newValue)); }
Source:
public void transientFilesWorkAreCleaned() throws Exception { START LogFactory.getLog(WorkManagerTest.class).fatal("\"default\" is processing=" + service.isProcessingEnabled("default")); END final File file = feature.resolveAndCreate(new File("pfouh")); service.schedule(new CreateFile(file)); service.awaitCompletion(5, TimeUnit.SECONDS); } Do you really want to keep this `log.fatal`?

Target:
public void transientFilesWorkAreCleaned() throws Exception { final File file = feature.resolveAndCreate(new File("pfouh")); service.schedule(new CreateFile(file)); service.awaitCompletion(5, TimeUnit.SECONDS); }
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()); START response.close(); END } A try/finally would be better here.

Target:
public void testRetryPostEnabled() throws Exception { // Enable POST retry enableSunHttpClientRetryPostProp(); sendInitialGetRequest(); // POST retry is enabled, the call should succeed ClientResponse response = null; try { response = webResource.post(ClientResponse.class); assertEquals(200, response.getStatus()); } finally { if (response != null) { response.close(); } } }
Source:
START ApacheHttpClientBuilder() { END this.socketTimeout = DEFAULT_CONNECTION_TIMEOUT; this.connectTimeout = DEFAULT_CONNECTION_TIMEOUT; this.connectionRequestTimeout = DEFAULT_CONNECTION_TIMEOUT; } `public` ?

Target:
protected ApacheHttpClientBuilder() { this.socketTimeout = DEFAULT_CONNECTION_TIMEOUT; this.connectTimeout = DEFAULT_CONNECTION_TIMEOUT; this.connectionRequestTimeout = DEFAULT_CONNECTION_TIMEOUT; }
Source:
public DocumentModel run(DocumentModel doc) throws ConcurrentUpdateException, IOException { if (changeToken != null) { // Check for dirty update START save = true; END 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; } 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?

Target:
public DocumentModel run(DocumentModel doc) throws ConcurrentUpdateException, IOException { if (changeToken != null) { // Check for dirty update 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; }
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.", START maxResultWindow, getName())); END maxResultWindow = Long.valueOf(DEFAULT_ES_MAX_RESULT_WINDOW_VALUE); } } return maxResultWindow; } maxResultWindow -> maxResultWindowStr

Target:
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.", maxResultWindowStr, getName())); maxResultWindow = Long.valueOf(DEFAULT_ES_MAX_RESULT_WINDOW_VALUE); } } return maxResultWindow; }
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 START || coreFeature.getStorageConfiguration().isVCSMySQL(); END } 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.

Target:
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(); }
Source:
protected void postSetUp() throws Exception { EventService service = Framework.getService(EventService.class); START serviceImpl = (EventServiceImpl) service; END } Put the cast on the same line

Target:
protected void postSetUp() throws Exception { serviceImpl = (EventServiceImpl) Framework.getService(EventService.class); }
Source:
START void assertSetEquals(List<String> expected, List<String> actual) { END assertEquals(new HashSet<String>(expected), new HashSet<String>(actual)); } Can we inject this feature directly ?

Target:
void assertSetEquals(List<String> expected, List<String> actual) { assertEquals(new HashSet<>(expected), new HashSet<>(actual)); }
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; } START return Arrays.stream(list.split("[, \t\n\r\f]")).map(s -> bundle.getEntry((String) s)).filter(Objects::nonNull); END } Not needed, `s` is already a `String`

Target:
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(bundle::getEntry).filter(Objects::nonNull); }
Source:
public void refresh() { START if (parent != null) parent.refresh(); END } Format

Target:
public void refresh() { if (parent != null) { parent.refresh(); } }
Source:
public void addLinks(String sourceId, List<String> targetIds, Session session) throws DirectoryException { if (readOnly) { return; } checkDualReference(); START dualReference.addLinks(sourceId, targetIds, session); END } 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?

Target:
public void addLinks(String sourceId, List<String> targetIds, Session session) throws DirectoryException { if (readOnly) { return; } checkDualReference(); dualReference.addLinks(targetIds, sourceId, session); }
Source:
public OAuth2ServiceProvider getProvider(String serviceName) { DocumentModel model = getProviderDocModel(serviceName); START return model != null ? buildProvider(model): null; END } I prefer `model == null ? null : buildProvider(model)` to avoid negations. Also please make sure of having a space left and right of the `:`.

Target:
public OAuth2ServiceProvider getProvider(String serviceName) { DocumentModel model = getProviderDocModel(serviceName); return model == null ? null : buildProvider(model); }
Source:
public List<OAuth2ServiceProvider> getProviders() { List<DocumentModel> providers = queryProviders(Collections.emptyMap(), 0); START return providers.stream().map(provider -> buildProvider(provider)).collect(Collectors.toList()); END } `provider -> buildProvider(provider)` -> `this::buildProvider`

Target:
public List<OAuth2ServiceProvider> getProviders() { List<DocumentModel> providers = queryProviders(Collections.emptyMap(), 0); return providers.stream().map(this::buildProvider).collect(Collectors.toList()); }
Source:
START Registration with(MBeanServer server) { END this.server = server; return this; } `protected` instead of package protected

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

Target:
protected Registration register() throws JMException { instance = server.registerMBean(StandbyCommand.this, ObjectNameFactory.getObjectName(StandbyCommand.class.getName())); return this; }
Source:
START void unregister() throws JMException { END try { server.unregisterMBean(instance.getObjectName()); } finally { instance = null; } } `protected` instead of package protected

Target:
protected void unregister() throws JMException { try { server.unregisterMBean(instance.getObjectName()); } finally { instance = null; } }
Source:
public void expandAll() { List<WebElement> expanders = getItemExpanderInPublishTreeForm(); START if (expanders.size() == 0) { END return; } else { for (WebElement expander : expanders) { Locator.waitUntilEnabledAndClick(expander); } } } `expanders.isEmpty()`

Target:
public void expandAll() { List<WebElement> expanders = getItemExpanderInPublishTreeForm(); if (expanders.isEmpty()) { return; } else { for (WebElement expander : expanders) { Locator.waitUntilEnabledAndClick(expander); } } }
Source:
START private void checkUserExistence(String username) { END 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); } } `protected` to allow subclassing.

Target:
protected 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); } }
Source:
public File getDataDir() { if (StringUtils.isBlank(path)) { File transienStoreHome = new File(Environment.getDefault().getData(), "transientstores"); START return new File(transienStoreHome, getName()); END } else { return new File(path); } } Don't put any logic in the descriptor, it should be pure data. Do everything in the caller.

Target:
public String getDataDir() { return path; }
Source:
protected HashMap<String, String> evalDynamicProperties() throws ConfigurationException { HashMap<String, String> newParametersToSave = new HashMap<>(); START evalEnvironmentVariables(); END evalLoopbackURL(); evalServerStatusKey(newParametersToSave); return newParametersToSave; } use `newParametersToSave`

Target:
protected HashMap<String, String> evalDynamicProperties() throws ConfigurationException { HashMap<String, String> newParametersToSave = new HashMap<>(); evalEnvironmentVariables(newParametersToSave); evalLoopbackURL(); evalServerStatusKey(newParametersToSave); return newParametersToSave; }
Source:
public static JSONPropertyWriter create() { JSONPropertyWriter writer = new JSONPropertyWriter(); START writer.dateTimeFormat = DateTimeFormat.W3C; END return writer; } Why not put this as field default like `writeEmpty` and `writeNull`?

Target:
public static JSONPropertyWriter create() { return new JSONPropertyWriter(); }
Source:
public JSONPropertyWriter dateTimeFormat(DateTimeFormat dateTimeFormat) { START JSONPropertyWriter writer = new JSONPropertyWriter(this); END writer.dateTimeFormat = dateTimeFormat; return writer; } 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.

Target:
public JSONPropertyWriter dateTimeFormat(DateTimeFormat dateTimeFormat) { this.dateTimeFormat = dateTimeFormat; return this; }
Source:
private String[] getIndexNames() { List<String> repositoryNames = getRepositoryNames(); START String indices[] = new String[this.repositoryNames.size()]; END int i = 0; for (String repo : repositoryNames) { indices[i++] = esa.getIndexNameForRepository(repo); } return indices; } The `this` is surprising here, I'd remove it.

Target:
private String[] getIndexNames() { List<String> repositoryNames = getRepositoryNames(); String indices[] = new String[repositoryNames.size()]; int i = 0; for (String repo : repositoryNames) { indices[i++] = esa.getIndexNameForRepository(repo); } return indices; }
Source:
public synchronized void registerPropertyDeprecation(PropertyDeprecationDescriptor descriptor) { Map<String, Map<String, String>> properties = removedProperties; if (descriptor.isDeprecated()) { properties = deprecatedProperties; START } END properties.computeIfAbsent(descriptor.getSchema(), key -> new HashMap<>()).put(descriptor.getName(), descriptor.getFallback()); log.info("Registered property deprecation: " + descriptor); } `Map<String, Map<String, String>> properties = descriptor.isDeprecated() ? deprecatedProperties : removedProperties`

Target:
public synchronized void registerPropertyDeprecation(PropertyDeprecationDescriptor descriptor) { Map<String, Map<String, String>> properties = descriptor.isDeprecated() ? deprecatedProperties : removedProperties; properties.computeIfAbsent(descriptor.getSchema(), key -> new HashMap<>()).put(descriptor.getName(), descriptor.getFallback()); log.info("Registered property deprecation: " + descriptor); }
Source:
protected String getPDFConversionURL(Blob blob) { BlobManager blobManager = Framework.getService(BlobManager.class); try { START URI uri = blobManager.getAvailableConversions(blob, UsageHint.DOWNLOAD).get(MimetypeRegistry.PDF_MIMETYPE); END if (uri != null) { return uri.toString(); } } catch (IOException e) { log.error("Failed to retrieve available conversions", e); } return null; } You can `import static org.nuxeo.ecm.platform.mimetype.interfaces.MimetypeRegistry.PDF_MIMETYPE` for this type of constant.

Target:
protected String getPDFConversionURL(Blob blob) { BlobManager blobManager = Framework.getService(BlobManager.class); try { URI uri = blobManager.getAvailableConversions(blob, UsageHint.DOWNLOAD).get(PDF_MIMETYPE); if (uri != null) { return uri.toString(); } } catch (IOException e) { log.error("Failed to retrieve available conversions", e); } return null; }
Source:
public ElasticSearchAdminImpl(ElasticSearchLocalConfig localConfig, ElasticSearchRemoteConfig remoteConfig, Map<String, ElasticSearchIndexConfig> indexConfig) { this.remoteConfig = remoteConfig; this.localConfig = localConfig; this.indexConfig = indexConfig; this.clientInitService = null; connect(); START initializeIndexes(); END } Don't repeat this code, make it call the new constructor passing `null` as an argument for `clientInitService`.

Target:
public ElasticSearchAdminImpl(ElasticSearchLocalConfig localConfig, ElasticSearchRemoteConfig remoteConfig, Map<String, ElasticSearchIndexConfig> indexConfig) { this(localConfig, remoteConfig, indexConfig, null); }
Source:
public static String getEntryContentAsString(File file, String entryName) throws IOException { InputStream resultStream = getEntryContentAsStream(file, entryName); // resultStream has been closed by FileUtils call START return IOUtils.toString(resultStream, Charsets.UTF_8); END } 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).

Target:
public static String getEntryContentAsString(File file, String entryName) throws IOException { try (InputStream resultStream = getEntryContentAsStream(file, entryName)) { return IOUtils.toString(resultStream, Charsets.UTF_8); } }
Source:
START @Test public void testToAscii() throws UnsupportedEncodingException { END String s = "h\u00E9h\u00E9"; assertEquals("hehe", StringUtils.toAscii(s)); } Please put `@Test` on the line above, not on the same line.

Target:
public void testToAscii() throws UnsupportedEncodingException { String s = "h\u00E9h\u00E9"; assertEquals("hehe", StringUtils.toAscii(s)); }
Source:
public boolean hasPreview(String xpath) { String srcMT = getMimeType(xpath); if (!Framework.getService(ConfigurationService.class).isBooleanPropertyTrue(ALLOW_ZIP_PREVIEW) START && "application/zip".equals(srcMT)) { END return false; } MimeTypePreviewer mtPreviewer = getPreviewManager().getPreviewer(srcMT); return mtPreviewer != null || getConversionService().getConverterName(srcMT, "text/html") != null; } Put `"application/zip".equals(srcMT)` first before the `&&` as it's cheaper to evaluate.

Target:
public boolean hasPreview(String xpath) { String srcMT = getMimeType(xpath); if ("application/zip".equals(srcMT) && !Framework.getService(ConfigurationService.class).isBooleanPropertyTrue(ALLOW_ZIP_PREVIEW)) { return false; } MimeTypePreviewer mtPreviewer = getPreviewManager().getPreviewer(srcMT); return mtPreviewer != null || getConversionService().getConverterName(srcMT, "text/html") != null; }
Source:
public Type getType(String id) { Type type = types.get(id); if (type == null) { return null; START } else { END 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; } } This is early exit, so you can move the `else` part unindented below.

Target:
public Type getType(String id) { return types.get(id); }
Source:
public static SharedPackageListingsSettings instance() { RequestResolver resolver = resolvers.values() .stream() .filter(RequestResolver::isActive) START .findFirst() END .orElse(null); if (resolver != null) { return instance(resolver.resolve()); } return null; } Here maybe you could use .map(RequestResolver::resolve).map(this::instance).orElse(null);

Target:
public static SharedPackageListingsSettings instance() { return resolvers.values() .stream() .filter(RequestResolver::isActive) .findFirst() .map(RequestResolver::resolve) .map(SharedPackageListingsSettings::instance) .orElse(null); }
Source:
protected Blob getContentBlob(Blob original, DocumentModel doc) { if (doc.getProperty(PICTURE_VIEWS_PROPERTY) != null) { START MultiviewPicture multiviewPicture = doc.getAdapter(MultiviewPicture.class); END for (PictureView view : multiviewPicture.getViews()) { if (view.getTitle().equals("FullHD") && view.getBlob() != null) { return view.getBlob(); } } } return original; } you shouldn't need the previous check. Normally you use doc.getAdapter() and check if it's null

Target:
protected Blob getContentBlob(Blob original, DocumentModel doc) { MultiviewPicture multiviewPicture = doc.getAdapter(MultiviewPicture.class); if (multiviewPicture != null) { for (PictureView view : multiviewPicture.getViews()) { if (view.getTitle().equals("FullHD") && view.getBlob() != null) { return view.getBlob(); } } } return original; }
Source:
public boolean waitForCompletion(long timeoutMillis) throws InterruptedException { WorkManager workManager = getWorkManager(); START if (workManager!=null) { END return workManager.awaitCompletion(timeoutMillis, TimeUnit.MILLISECONDS); } else { return false; } } Space before/after `!=`. Prefer the early-exit idiom: ``` if (workManager == null) { return false; } return workManager.await... ```

Target:
public boolean waitForCompletion(long timeoutMillis) throws InterruptedException { WorkManager workManager = getWorkManager(); if (workManager == null) { return false; } return workManager.awaitCompletion(timeoutMillis, TimeUnit.MILLISECONDS); }
Source:
public void init() { asyncExec.init(); EventDispatcherDescriptor dispatcherDescriptor = dispatchers.getDispatcherDescriptor(); if (dispatcherDescriptor != null) { List<EventPipeDescriptor> pipes = registeredPipes.getPipes(); START if (pipes.size() > 0) { END pipeDispatcher = dispatcherDescriptor.getInstance(); pipeDispatcher.init(pipes, dispatcherDescriptor.getParameters()); } } } `if (!pipes.isEmpty())`

Target:
public void init() { asyncExec.init(); EventDispatcherDescriptor dispatcherDescriptor = dispatchers.getDispatcherDescriptor(); if (dispatcherDescriptor != null) { List<EventPipeDescriptor> pipes = registeredPipes.getPipes(); if (!pipes.isEmpty()) { pipeDispatcher = dispatcherDescriptor.getInstance(); pipeDispatcher.init(pipes, dispatcherDescriptor.getParameters()); } } }
Source:
public void sendEventBundle(EventBundle events) { events = filterBundle(events); START if (events.size() == 0) { END return; } preProcessBundle(events); send(marshall(events)); } `events.isEmpty()`

Target:
public void sendEventBundle(EventBundle events) { events = filterBundle(events); if (events.isEmpty()) { return; } preProcessBundle(events); send(marshall(events)); }
Source:
public EventDispatcherDescriptor getDispatcherDescriptor() { int nbd = contribs.size(); if (nbd > 0) { return contribs.get(nbd - 1); } else { return null; START } END } `return contribs.isEmpty() ? null : contribs.get(contribs.size() - 1)`

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

Target:
public void sendEventBundle(EventBundle events) { if (events.isEmpty()) { return; } for (EventBundlePipe pipe : pipes) { pipe.sendEventBundle(events); } }
Source:
public boolean waitForCompletion(long timeoutMillis) throws InterruptedException { boolean res = true; for (EventBundlePipe pipe : pipes) { START res = res && pipe.waitForCompletion(timeoutMillis); END } return res; } 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..

Target:
public boolean waitForCompletion(long timeoutMillis) throws InterruptedException { boolean res = true; for (EventBundlePipe pipe : pipes) { res = pipe.waitForCompletion(timeoutMillis) && res; } return res; }
Source:
public String getVocabularyLabel(String voc, String key) { try (Session session = getDirService().open(voc)) { if (!session.hasEntry(key)) { START log.warn("Unable to find the key '" + key + "' in the vocabulary '" + voc + "'."); END 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"); } } 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.

Target:
public String getVocabularyLabel(String voc, String key) { try (Session session = getDirService().open(voc)) { if (!session.hasEntry(key)) { log.debug("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"); } }
Source:
public DocumentModel toFields(DocumentModel inDoc, HashMap<String, String> inMapping, boolean inSave, CoreSession inSession) { // Parse if needed run(); START HashMap<String, String> values = toHashMap(); END for (String inXPath : inMapping.keySet()) { String value = values.get(inMapping.get(inXPath)); inDoc.setPropertyValue(inXPath, value); } if (inSave) { inDoc = inSession.saveDocument(inDoc); } return inDoc; } `Map<String, String>`

Target:
public DocumentModel toFields(DocumentModel inDoc, HashMap<String, String> inMapping, boolean inSave, CoreSession inSession) { // Parse if needed run(); Map<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; }
Source:
public String getAllExtractedLines() throws NuxeoException { if (extractedAllAsString == null) { PDDocument pdfDoc = null; START try { END 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; } try with resource

Target:
public String getAllExtractedLines() throws NuxeoException { if (extractedAllAsString == null) { try (PDDocument 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); } } return extractedAllAsString; }
Source:
START public ArrayList<LinkInfo> getRemoteGoToLinks() throws IOException { END if (remoteGoToLinks == null) { loadAndPreflightPdf(); remoteGoToLinks = parseForLinks(PDActionRemoteGoTo.SUB_TYPE); } return remoteGoToLinks; } `List<LinkInfo>` (check below for other method signatures)

Target:
public List<LinkInfo> getRemoteGoToLinks() throws IOException { if (remoteGoToLinks == null) { loadAndPreflightPdf(); remoteGoToLinks = parseForLinks(PDActionRemoteGoTo.SUB_TYPE); } return remoteGoToLinks; }
Source:
public void setCurrentContentViewName(String contentViewName) { START currentContentViewName = contentViewName; END } Is it needed to remove 'this' ?

Target:
public void setCurrentContentViewName(String contentViewName) { this.currentContentViewName = contentViewName; }
Source:
protected void resetCurrentContentViewWorkingList() { if (currentContentViewName != null) { ContentView contentView = contentViewActions.getContentView(currentContentViewName); START if(contentView != null){ END String selectionListName = contentView.getSelectionListName(); documentsListsManager.resetWorkingList(selectionListName); } } } format there's a space between if and (

Target:
protected void resetCurrentContentViewWorkingList() { if (currentContentViewName != null) { ContentView contentView = contentViewActions.getContentView(currentContentViewName); if (contentView != null) { documentsListsManager.resetWorkingList(contentView.getSelectionListName()); } } }
Source:
public DocumentModel run(DocumentModel input) { IdRef idRef = new IdRef(input.getId()); START DocumentModel lastVersion = session.getLastDocumentVersion(idRef); END return lastVersion; } just return this

Target:
public DocumentModel run(DocumentModel input) { IdRef idRef = new IdRef(input.getId()); return session.getLastDocumentVersion(idRef); }
Source:
public DocumentModel run(DocumentModel input) { DocumentModelList proxies = session.getProxies(input.getRef(), null); for (DocumentModel proxy : proxies) { session.removeDocument(proxy.getRef()); } session.save(); START return null; END } Guess return type should be `void`

Target:
public DocumentModel run(DocumentModel input) { DocumentModelList proxies = session.getProxies(input.getRef(), null); for (DocumentModel proxy : proxies) { session.removeDocument(proxy.getRef()); } if (save) { session.save(); } return input; }
Source:
private void resetSchemaProperties(DocumentModel target) throws OperationException { if (xpath != null) { target.setPropertyValue(xpath, null); } else if (schema != null) { START for (Map.Entry<String, Object> entry : target.getProperties(schema).entrySet()) { END target.setProperty(schema, entry.getKey(), null); } } else { throw new OperationException("No schema or xpath was provided"); } } use .keySet() since we only use the key anyway

Target:
private void resetSchemaProperties(DocumentModel target) throws OperationException { if (xpath != null) { target.setPropertyValue(xpath, null); } else if (schema != null) { for (String key : target.getProperties(schema).keySet()) { target.setProperty(schema, key, null); } } else { throw new OperationException("No schema or xpath was provided"); } }
Source:
public boolean documentExists(CoreSession session, String idOrPath) { START DocumentRef documentRef; END 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; } Ternary operator `idOrPath.startsWith("/") ? new PathRef(idOrPath) : new IdRef(idOrPath)`

Target:
public boolean documentExists(CoreSession session, String idOrPath) { DocumentRef documentRef = idOrPath.startsWith("/") ? new PathRef(idOrPath) : new IdRef(idOrPath); return session.exists(documentRef); }
Source:
public DocumentModel run(DocumentModel input) { // we ignore the result /*boolean result = */ input.addFacet(facet); START END session.saveDocument(input); return input; } For such small method (next one in next file too) having extra blank lines doesn't bring anything.

Target:
public DocumentModel run(DocumentModel input) { input.addFacet(facet); input = session.saveDocument(input); return input; }
Source:
protected void createDocumentVersions(DocumentModel doc, VersioningOption vo, int nrVersions) { // create a document with major versions for (int i = 1; i <= nrVersions; i++) { START doc.setPropertyValue("dc:description", "" + i); END doc.putContextData(VersioningService.VERSIONING_OPTION, vo); session.saveDocument(doc); } session.save(); } `String.valueOf(i)`

Target:
protected DocumentModel createDocumentVersions(DocumentModel doc, VersioningOption vo, int nrVersions) { for (int i = 1; i <= nrVersions; i++) { doc.setPropertyValue("dc:description", String.valueOf(i)); doc.putContextData(VersioningService.VERSIONING_OPTION, vo); doc = session.saveDocument(doc); } session.save(); return doc; }
Source:
public void run() { Map<String, List<String>> sourceIdToRenditionRefs = computeLiveDocumentRefsToRenditionRefs(); List<String> sourceIds = new ArrayList<>(sourceIdToRenditionRefs.keySet()); START END removeStoredRenditions(sourceIdToRenditionRefs, sourceIds); } If you rework `removeStoredRenditions` as a simple iterative method you don't need to do the copy.

Target:
public void run() { Map<String, List<String>> sourceIdToRenditionRefs = computeLiveDocumentRefsToRenditionRefs(); removeStoredRenditions(sourceIdToRenditionRefs); }
Source:
public SavedSearch getSavedSearch(CoreSession session, String id) { DocumentRef docRef = new IdRef(id); DocumentModel savedSearchDoc = session.getDocument(docRef); if (savedSearchDoc != null) { START SavedSearch search = savedSearchDoc.getAdapter(SavedSearch.class); END if (search != null) { return search; } } return null; } You can return that directly here.

Target:
public SavedSearch getSavedSearch(CoreSession session, String id) { DocumentRef docRef = new IdRef(id); DocumentModel savedSearchDoc = session.getDocument(docRef); if (savedSearchDoc != null) { return savedSearchDoc.getAdapter(SavedSearch.class); } return null; }
Source:
public void toggleJoypad(Key key, boolean state) { START if (key.name == MojamComponent.instance.keys.joy_click.name) { END 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; } shouldn't it be key.name.equals( ... ); ? I always get confused about checking equality on immutable objects.

Target:
public void toggleJoypad(Key key, boolean state) { if (key.name.equals(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; }
Source:
public void render(){ START System.out.println("Rendering Path "+toString()); END for(Node n:nodes){ MojamComponent.screen.alphaFill((int)n.pos.x, (int)n.pos.y, Tile.WIDTH, Tile.HEIGHT, 0x00ccff, 0x10); } } This debug output should be deleted

Target:
public void render(){ for(Node n:nodes){ MojamComponent.screen.alphaFill((int)n.pos.x, (int)n.pos.y, Tile.WIDTH, Tile.HEIGHT, 0x00ccff, 0x10); } }
Source:
protected void upgradeComplete() { START health += 10; END maxHealth += 10; radius = upgradeRadius[upgradeLevel]; capacity = upgradeCapacities[upgradeLevel]; } 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)

Target:
protected void upgradeComplete() { maxHealth += 10; health = maxHealth; radius = upgradeRadius[upgradeLevel]; capacity = upgradeCapacities[upgradeLevel]; }
Source:
private static boolean responseOk(final int status) { switch (status) { START case HttpStatus.SC_CREATED: END case HttpStatus.SC_OK: return true; default: return false; } } 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

Target:
private static boolean responseOk(final int status) { return status / 100 == 2; //all 2xx is ok }
Source:
@Test public void connectWithIdnUrl() throws MalformedURLException { URL url = new URL("https://тест.рф"); START Connection con = HttpConnection.connect(url, true); END String expectedUrl = url.getProtocol() + "://" + IDN.toASCII(url.getHost()) + url.getPath(); assertEquals(expectedUrl, con.request().url().toExternalForm()); } Need to make sure we have test for redirects to IDNs, and for finding IDN in HTML and following.

Target:
@Test public void connectWithIdnUrl() throws MalformedURLException { URL url = new URL("https://тест.рф"); Connection con = HttpConnection.connect(url); String expectedUrl = url.getProtocol() + "://" + IDN.toASCII(url.getHost()) + url.getPath(); assertEquals(expectedUrl, con.request().url().toExternalForm()); }
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); START return accum.toString().trim(); END } why `trim()`? if we use `<p> Hello\nthere </p>`, wouldn't I want everything inside `<p>` that is not an html node?

Target:
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(); }
Source:
public OutputSettings charset(Charset charset) { if( document != null ) { START Element meta = document.select("meta[charset]").first(); END if( meta != null ) { meta.attr("charset", charset.displayName()); } } this.charset = charset; charsetEncoder = charset.newEncoder(); return this; } 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.

Target:
public OutputSettings charset(Charset charset) { this.charset = charset; charsetEncoder = charset.newEncoder(); return this; }
Source:
public Builder keyValueSeparator(char keyValueSeparator) { if (keyValueSeparator == 0) throw new IllegalArgumentException("keyValueSeparator == 0"); if (keyValueSeparator == entrySeparator) { START throw new IllegalArgumentException("keyValueSeparator == entrySeparator"); END } this.keyValueSeparator = keyValueSeparator; return this; } 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.

Target:
public Builder keyValueSeparator(char keyValueSeparator) { if (keyValueSeparator == 0) throw new IllegalArgumentException("keyValueSeparator == 0"); this.keyValueSeparator = keyValueSeparator; return this; }
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) { START error = e; END throw e; } finally { GrpcClientResponse response = new GrpcClientResponse(request, status, trailers, error); finish(response, spanRef.getAndSet(null)); } } 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.

Target:
@Override public void onClose(Status status, Metadata trailers) { // See /instrumentation/grpc/RATIONALE.md for why we don't catch exceptions from the delegate GrpcClientResponse response = new GrpcClientResponse(request, status, trailers, null); finish(response, spanRef.getAndSet(null)); try (Scope scope = currentTraceContext.maybeScope(invocationContext)) { delegate().onClose(status, trailers); } }
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) { START error = e; END throw e; } finally { GrpcServerResponse response = new GrpcServerResponse(request, status, trailers, error); finish(response, spanRef.getAndSet(null)); } } 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.

Target:
@Override public void close(Status status, Metadata trailers) { // See /instrumentation/grpc/RATIONALE.md for why we don't catch exceptions from the delegate GrpcServerResponse response = new GrpcServerResponse(request, status, trailers, null); finish(response, spanRef.getAndSet(null)); try (Scope scope = currentTraceContext.maybeScope(context)) { delegate().close(status, trailers); } }
Source:
@Override public void onReady() { Scope scope = currentTraceContext.maybeScope(invocationContext); START try { END delegate().onReady(); } finally { scope.close(); } } Not sure if gRPC being Java 8 means we would prefer try/resources here but just in case

Target:
@Override public void onReady() { try (Scope scope = currentTraceContext.maybeScope(invocationContext)) { delegate().onReady(); } }
Source:
@Override public Throwable error() { START if (caught != null || request == null) return caught; END return request.maybeError(); } 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(); ```

Target:
@Override public Throwable error() { if (caught != null) return caught; if (request == null) return null; return request.maybeError(); }
Source:
static String getSpanName(String commandName, @Nullable String collectionName) { START return commandName + (collectionName == null ? "" : (" " + collectionName)); END } 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.

Target:
static String getSpanName(String commandName, @Nullable String collectionName) { if (collectionName == null) return commandName; return commandName + " " + collectionName; }
Source:
Builder(MongoDBTracing mongoDBTracing) { this(mongoDBTracing.tracing); START maxAbbreviatedCommandLength(mongoDBTracing.maxAbbreviatedCommandLength); END clearCommandsWithCollectionName(); addAllCommandsWithCollectionName(mongoDBTracing.commandsWithCollectionName); } I'd just set `maxAbbreviatedCommandLength = t.maxAbbreviated...` since we never need to validate values from a built object.

Target:
Builder(MongoDBTracing mongoDBTracing) { tracing = mongoDBTracing.tracing; }
Source:
START @Nullable public final String tag(I input, @Nullable TraceContext context, SpanCustomizer span) { END 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); } 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`.

Target:
public final void 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; tag(span, input, context); }
Source:
START public TracingP6SpyOptions(P6OptionsRepository optionsRepository) { END super(TracingP6SpyOptionsMBean.class, false); logLoadableOptions = new P6LogOptions(optionsRepository); this.optionsRepository = optionsRepository; } 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.

Target:
TracingP6SpyOptions(P6OptionsRepository optionsRepository) { super(optionsRepository); logLoadableOptions = new P6LogOptions(optionsRepository); this.optionsRepository = optionsRepository; }
Source:
protected CurrentTraceContext(Builder<?> builder) { START this.scopeDecorators = (List<ScopeDecorator>) builder.scopeDecorators.clone(); END } I personally haven't seen `clone()` for copying anything other than an array. `new ArrayList<ScopeDecorator>(builder.scopeDecorators)`?

Target:
protected CurrentTraceContext(Builder<?> builder) { this.scopeDecorators = new ArrayList<>(builder.scopeDecorators); }
Source:
protected Scope decorateScope(@Nullable TraceContext currentSpan, Scope scope) { int length = scopeDecorators.size(); START if (length == 0) return scope; END for (int i = 0; i < length; i++) { scope = scopeDecorators.get(i).decorateScope(currentSpan, scope); } return scope; } I think the for loop duplicates this check so it doesn't really speed up the `0` case.

Target:
protected Scope decorateScope(@Nullable TraceContext currentSpan, Scope scope) { int length = scopeDecorators.size(); for (int i = 0; i < length; i++) { scope = scopeDecorators.get(i).decorateScope(currentSpan, scope); } return scope; }
Source:
public void finish(TraceContext context, long finishTimestamp) { START if (noop.get()) return; END MutableSpan span = spanMap.remove(context); if (span == null || noop.get()) return; synchronized (span) { span.finish(finishTimestamp); reporter.report(V2SpanConverter.toSpan(span.toSpan())); } } 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)

Target:
public void finish(TraceContext context, long finishTimestamp) { MutableSpan span = spanMap.remove(context); if (span == null || noop.get()) return; synchronized (span) { span.finish(finishTimestamp); reporter.report(V2SpanConverter.toSpan(span.toSpan())); } }