auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void validateChain(final List<Certificate> chain, final Certificate cert) { final List<Certificate> certs = new ArrayList<Certificate>(); final Set<TrustAnchor> anchors = new HashSet<TrustAnchor>(); certs.add(cert); certs.addAll(chain); for (final Certificate c : certs) { if (!(c instanceof X509Certificate)) { throw new IllegalArgumentException("Invalid chain format. Expected X509 certificate"); } final X509Certificate xCert = (X509Certificate)c; xCert.getSubjectDN(); xCert.getIssuerDN(); <START> anchors.add(new TrustAnchor(xCert, null)); <END> } final X509CertSelector target = new X509CertSelector(); target.setCertificate((X509Certificate)cert); PKIXBuilderParameters params = null; try { params = new PKIXBuilderParameters(anchors, target); params.setRevocationEnabled(false); params.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(certs))); final CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", "BC"); builder.build(params); } catch (final InvalidAlgorithmParameterException e) { throw new IllegalArgumentException("Invalid certificate chain", e); } catch (final CertPathBuilderException e) { throw new IllegalArgumentException("Invalid certificate chain", e); } catch (final NoSuchAlgorithmException e) { throw new IllegalArgumentException("Invalid certificate chain", e); } catch (final NoSuchProviderException e) { throw new CloudRuntimeException("No provider for certificate validation", e); } }</code><technical_language>Please add a check for return of add method ensure element added anchors</technical_language>

Target:
private void validateChain(final List<Certificate> chain, final Certificate cert) { final List<Certificate> certs = new ArrayList<Certificate>(); final Set<TrustAnchor> anchors = new HashSet<TrustAnchor>(); certs.add(cert); certs.addAll(chain); for (final Certificate c : certs) { if (!(c instanceof X509Certificate)) { throw new IllegalArgumentException("Invalid chain format. Expected X509 certificate"); } final X509Certificate xCert = (X509Certificate)c; anchors.add(new TrustAnchor(xCert, null)); } final X509CertSelector target = new X509CertSelector(); target.setCertificate((X509Certificate)cert); PKIXBuilderParameters params = null; try { params = new PKIXBuilderParameters(anchors, target); params.setRevocationEnabled(false); params.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(certs))); final CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", "BC"); builder.build(params); } catch (final InvalidAlgorithmParameterException | CertPathBuilderException | NoSuchAlgorithmException e) { throw new IllegalStateException("Invalid certificate chain", e); } catch (final NoSuchProviderException e) { throw new CloudRuntimeException("No provider for certificate validation", e); } }
Source:
<code>public void testSkipWithXML() throws Exception { File arquillianXML = new File("target/test-classes/arquillian.xml"); InputStream is = new FileInputStream(arquillianXML); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line; while ((line = br.readLine()) != null) { <START> assertFalse(line.equals(Constants.CONFIGURE_ARQUILLIAN_COMMENT)); <END> } }</code><technical_language>contains method more reliable here, in case some spacing beginning end of line</technical_language>

Target:
public void testSkipWithXML() throws Exception { File arquillianXML = new File("target/test-classes/arquillian.xml"); InputStream is = new FileInputStream(arquillianXML); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line; while ((line = br.readLine()) != null) { assertFalse(line.contains(Constants.CONFIGURE_ARQUILLIAN_COMMENT)); } }
Source:
<code>private static boolean ignoreNetworkInterface(final NetworkInterface networkInterface) { try { return networkInterface == null || networkInterface.isLoopback() || networkInterface.isVirtual() || !networkInterface.isUp(); <START> } catch (SocketException e) { <END> return true; } }</code><technical_language>Please add final for exception, rename e ex</technical_language>

Target:
private static boolean ignoreNetworkInterface(final NetworkInterface networkInterface) { try { return null == networkInterface || networkInterface.isLoopback() || networkInterface.isVirtual() || !networkInterface.isUp(); } catch (final SocketException ex) { return true; } }
Source:
<code><START> private String lookupCacheDirectory(ServletContext servContext) { <END> final String[] typeStrs = { "Java environment variable ", "Servlet context parameter ", "System environment variable " }; final String[] varStrs = { "COMPOSER_CACHE_DIR" }; String cacheDir = null; for (int i = 0; i < varStrs.length && cacheDir == null; i++) { for (int j = 0; j < typeStrs.length && cacheDir == null; j++) { String value = null; String varStr = varStrs[i]; String typeStr = typeStrs[j]; switch (j) { case 0: value = System.getProperty(varStr); break; case 1: value = servContext.getInitParameter(varStr); break; case 2: value = System.getenv(varStr); break; } if (value == null || value.equalsIgnoreCase("")) { LOGGER.finer("Found " + typeStr + varStr + " to be unset"); continue; } if (verifyPath(value, "Found " + typeStr + varStr + " set to " + value)) { cacheDir = value; } } } if(cacheDir == null) { cacheDir = (new GeoServerDataDirectory(catalog.getResourceLoader()).root().getPath()) +File.separator+"composer"; if (verifyPath(cacheDir, "Trying default composer cache directory " + cacheDir)) { LOGGER.info("COMPOSER_CACHE_DIR not set, using default value: " + cacheDir); } } try { File cacheFile = new File(cacheDir); if (!cacheFile.exists()) { cacheFile.mkdirs(); } } catch (Exception e) { LOGGER.log(Level.WARNING, "Could not initilize composer cache directory", e); } return cacheDir; }</code><technical_language>cascading property lookup functionality is provided org.geoserver.platform.GeoServerExtensions</technical_language>

Target:
private String lookupCacheDirectory(ServletContext servContext) { String cacheDir = GeoServerExtensions.getProperty("COMPOSER_CACHE_DIR", servContext); if(cacheDir == null) { cacheDir = (GeoServerExtensions.bean(GeoServerDataDirectory.class).root().getPath()) +File.separator+"composer"; } try { File cacheFile = new File(cacheDir); if (!cacheFile.exists()) { cacheFile.mkdirs(); } } catch (Exception e) { LOGGER.log(Level.WARNING, "Could not initilize composer cache directory", e); } return cacheDir; }
Source:
<code>public Collection<? extends Action> createFor(Job j) { List<Action> actions = new LinkedList<Action>(); <START> if (j.getClass().getCanonicalName().startsWith("org.jenkinsci.plugins.workflow")) <END> { Run r = j.getLastSuccessfulBuild(); if (r != null) { List<HtmlPublisherTarget.HTMLBuildAction> reports = r.getActions(HtmlPublisherTarget.HTMLBuildAction.class); for (HtmlPublisherTarget.HTMLBuildAction report : reports) { actions.add(report.getHTMLTarget().getProjectAction(j)); } } } return actions; }</code><technical_language>easier java if (!(j instanceof AbstractProject)) {</technical_language>

Target:
public Collection<? extends Action> createFor(Job j) { List<Action> actions = new LinkedList<Action>(); if (j.getClass().getCanonicalName().startsWith("org.jenkinsci.plugins.workflow")) { final Run<?,?> r = j.getLastSuccessfulBuild(); if (r != null) { List<HtmlPublisherTarget.HTMLBuildAction> reports = r.getActions(HtmlPublisherTarget.HTMLBuildAction.class); for (HtmlPublisherTarget.HTMLBuildAction report : reports) { actions.add(report.getHTMLTarget().getProjectAction(j)); } List<HtmlPublisherTarget.HTMLPublishedForProjectMarkerAction> projectLevelReports = r.getActions(HtmlPublisherTarget.HTMLPublishedForProjectMarkerAction.class); for (HtmlPublisherTarget.HTMLPublishedForProjectMarkerAction report : projectLevelReports) { actions.add(report.getHTMLTarget().getProjectAction(j)); } } } return actions; }
Source:
<code><START> public void onAddExperienceLevels(int levels, CallbackInfo ci) { <END> recalculateTotalExperience(); }</code><technical_language>injections private ;)</technical_language>

Target:
private void onAddExperienceLevels(int levels, CallbackInfo ci) { recalculateTotalExperience(); }
Source:
<code>protected void configure() { bind(ExecutorLoader.class).to(JdbcExecutorLoader.class).in(Scopes.SINGLETON); bind(ProjectLoader.class).to(JdbcProjectLoader.class).in(Scopes.SINGLETON); bind(Props.class).toInstance(this.config.getProps()); bind(Storage.class).to(resolveStorageClassType()).in(Scopes.SINGLETON); bind(DatabaseOperator.class).to(DatabaseOperatorImpl.class).in(Scopes.SINGLETON); bind(TriggerLoader.class).to(JdbcTriggerImpl.class).in(Scopes.SINGLETON); bind(DataSource.class).to(AzkabanDataSource.class); bind(ExecutorManager.class).in(Scopes.SINGLETON); bind(AlerterHolder.class).in(Scopes.SINGLETON); <START> bind(CommonMetrics.class).in(Scopes.SINGLETON); <END> bind(MetricsManager.class).in(Scopes.SINGLETON); bind(MetricRegistry.class).in(Scopes.SINGLETON); }</code><technical_language>CommonMetrics is annotated singleton already, I need this line here. MetricsManager</technical_language>

Target:
protected void configure() { bind(ExecutorLoader.class).to(JdbcExecutorLoader.class).in(Scopes.SINGLETON); bind(ProjectLoader.class).to(JdbcProjectLoader.class).in(Scopes.SINGLETON); bind(Props.class).toInstance(this.config.getProps()); bind(Storage.class).to(resolveStorageClassType()).in(Scopes.SINGLETON); bind(DatabaseOperator.class).to(DatabaseOperatorImpl.class).in(Scopes.SINGLETON); bind(TriggerLoader.class).to(JdbcTriggerImpl.class).in(Scopes.SINGLETON); bind(DataSource.class).to(AzkabanDataSource.class); bind(ExecutorManager.class).in(Scopes.SINGLETON); bind(AlerterHolder.class).in(Scopes.SINGLETON); bind(MetricRegistry.class).in(Scopes.SINGLETON); }
Source:
<code>public UsbDevice getItem(final int position) { <START> if ((position >= 0) && (position < mList.size())) <END> return mList.get(position); else return null; }</code><technical_language>@guiseco need check validity of position argument here, based getCount() overrode above</technical_language>

Target:
public UsbDevice getItem(final int position) { return mList.get(position); }
Source:
<code>public NodeValue exec(NodeValue nv) { <START> System.out.println(nv); <END> Node n = nv.asNode(); if ( ! n.isNodeTriple() ) throw new ExprEvalException(getClass().getSimpleName()+": Not a triple term: "+nv); Triple t = Node_Triple.triple(n); Node x = function(t); return NodeValue.makeNode(x); }</code><technical_language>Debug left-over</technical_language>

Target:
public NodeValue exec(NodeValue nv) { Node n = nv.asNode(); if ( ! n.isNodeTriple() ) throw new ExprEvalException(getClass().getSimpleName()+": Not a triple term: "+nv); Triple t = Node_Triple.triple(n); Node x = function(t); return NodeValue.makeNode(x); }
Source:
<code>public boolean hasErrors() { <START> return !errors.isEmpty(); <END> }</code><technical_language>Do need || configuration.hasErrors()</technical_language>

Target:
public boolean hasErrors() { return !errors.isEmpty() || configuration.hasErrors(); }
Source:
<code>protected void addTablePartConfig(String tablePartKey, TablePart tablePart, Config jobConfig, Map<String, String> tableConfig) { Map<String, String> tablePartConfig = tablePart.toConfig(jobConfig, new MapConfig(tableConfig)); <START> for (String configKey : tablePartConfig.keySet()) { <END> addTableConfig(String.format("%s.%s", tablePartKey, configKey), tablePartConfig.get(configKey), tableConfig); } }</code><technical_language>tablePart.toConfig(jobConfig, new MapConfig(tableConfig)) .forEach((k, v) -> addTableConfig(String.format("%s.%s", tablePartKey, k), v, tableConfig) );</technical_language>

Target:
protected void addTablePartConfig(String tablePartKey, TablePart tablePart, Config jobConfig, Map<String, String> tableConfig) { tablePart.toConfig(jobConfig, new MapConfig(tableConfig)) .forEach((k, v) -> addTableConfig(String.format("%s.%s", tablePartKey, k), v, tableConfig)); }
Source:
<code>public void setTimeBounds(long beginTime, long endTime) { fBeginTime = beginTime; fEndTime = endTime; fTime0Bound = fBeginTime != SWT.DEFAULT ? fBeginTime : fEndTime; <START> fTime1Bound = fEndTime != SWT.DEFAULT ? fEndTime : fBeginTime; <END> if (fTime0Bound > fTime1Bound) { fBeginTime = endTime; fEndTime = beginTime; fTime0Bound = fBeginTime; fTime1Bound = fEndTime; } adjustHorizontalScrollBar(); }</code><technical_language>recommend parentheses elvis notations: fTime1Bound = (fEndTime != SWT.DEFAULT ? fEndTime : fBeginTime); read code fTime1Bound = fEndtime assigning fEndtime, bad. you</technical_language>

Target:
public void setTimeBounds(long beginTime, long endTime) { fBeginTime = beginTime; fEndTime = endTime; fTime0Bound = (fBeginTime != SWT.DEFAULT ? fBeginTime : fEndTime); fTime1Bound = (fEndTime != SWT.DEFAULT ? fEndTime : fBeginTime); if (fTime0Bound > fTime1Bound) { fBeginTime = endTime; fEndTime = beginTime; fTime0Bound = fBeginTime; fTime1Bound = fEndTime; } adjustHorizontalScrollBar(); }
Source:
<code>protected Void doInBackground(Void... params) { List<Map<String, Object>> blogs; <START> String[] extraFields = {"isHidden", "homeURL", "last_picked_timestamp"}; <END> if (mIsInSearchMode) { blogs = WordPress.wpDB.getBlogsBy(null, extraFields); } else { blogs = getBlogsForCurrentView(extraFields); } SiteList sites = new SiteList(blogs); final long primaryBlogId = AccountHelper.getDefaultAccount().getPrimaryBlogId(); Collections.sort(sites, new Comparator<SiteRecord>() { public int compare(SiteRecord site1, SiteRecord site2) { if (primaryBlogId > 0 && !mIsInSearchMode) { if (site1.blogId == primaryBlogId) { return -1; } else if (site2.blogId == primaryBlogId) { return 1; } } return site1.getBlogNameOrHomeURL().compareToIgnoreCase(site2.getBlogNameOrHomeURL()); } }); if (!mIsInSearchMode && sites.size() >= RECENTLY_PICKED_THRESHOLD) { ArrayList<Integer> pickedIds = AppPrefs.getRecentlyPickedSiteIds(); for (int i = pickedIds.size() - 1; i > -1; i--) { int thisId = pickedIds.get(i); int indexOfSite = sites.indexOfSiteId(thisId); if (indexOfSite > -1) { SiteRecord site = sites.remove(indexOfSite); site.isRecentPick = true; sites.add(0, site); } } } if (mSites == null || !mSites.isSameList(sites)) { mAllSites = (SiteList) sites.clone(); mSites = filteredSitesByTextIfInSearchMode(sites); } return null; }</code><technical_language>This reverted well</technical_language>

Target:
protected Void doInBackground(Void... params) { List<Map<String, Object>> blogs; String[] extraFields = {"isHidden", "homeURL"}; if (mIsInSearchMode) { blogs = WordPress.wpDB.getBlogsBy(null, extraFields); } else { blogs = getBlogsForCurrentView(extraFields); } SiteList sites = new SiteList(blogs); final long primaryBlogId = AccountHelper.getDefaultAccount().getPrimaryBlogId(); Collections.sort(sites, new Comparator<SiteRecord>() { public int compare(SiteRecord site1, SiteRecord site2) { if (primaryBlogId > 0 && !mIsInSearchMode) { if (site1.blogId == primaryBlogId) { return -1; } else if (site2.blogId == primaryBlogId) { return 1; } } return site1.getBlogNameOrHomeURL().compareToIgnoreCase(site2.getBlogNameOrHomeURL()); } }); if (!mIsInSearchMode && sites.size() >= RECENTLY_PICKED_THRESHOLD) { ArrayList<Integer> pickedIds = AppPrefs.getRecentlyPickedSiteIds(); for (int i = pickedIds.size() - 1; i > -1; i--) { int thisId = pickedIds.get(i); int indexOfSite = sites.indexOfSiteId(thisId); if (indexOfSite > -1) { SiteRecord site = sites.remove(indexOfSite); site.isRecentPick = true; sites.add(0, site); } } } if (mSites == null || !mSites.isSameList(sites)) { mAllSites = (SiteList) sites.clone(); mSites = filteredSitesByTextIfInSearchMode(sites); } return null; }
Source:
<code>public synchronized void forceNodeShutdown() { LOGGER.entering(); CloseableHttpClient client = HttpClientBuilder.create().build(); StringBuilder url = new StringBuilder(); url.append("http://"); url.append(machine); url.append(":").append(this.getRemoteHost().getPort()); url.append("/extra/"); url.append(NodeForceRestartServlet.class.getSimpleName()); HttpPost post = new HttpPost(url.toString()); int responseStatusCode = HttpStatus.SC_NOT_FOUND; try { HttpResponse response = client.execute(post); responseStatusCode = response.getStatusLine().getStatusCode(); } catch (IOException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } finally { if (responseStatusCode == HttpStatus.SC_OK) { proxyLogger.info("Node " + machine + " shutdown successfully."); } else { proxyLogger.info("Node " + machine + " did not shutdown. Return code was " + responseStatusCode); } try { client.close(); } catch (IOException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } } stopNodeRecycleThread(); if (responseStatusCode == HttpStatus.SC_OK) { <START> getRegistry().removeIfPresent(this); <END> } LOGGER.exiting(); }</code><technical_language>unregister node in graceful shutdown path well</technical_language>

Target:
public synchronized void forceNodeShutdown() { LOGGER.entering(); CloseableHttpClient client = HttpClientBuilder.create().build(); String url = String.format("http://%s:%d/extra/%s", machine, this.getRemoteHost().getPort(), NodeForceRestartServlet.class.getSimpleName()); HttpPost post = new HttpPost(url); int responseStatusCode = HttpStatus.SC_NOT_FOUND; try { HttpResponse response = client.execute(post); responseStatusCode = response.getStatusLine().getStatusCode(); } catch (IOException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } finally { if (responseStatusCode == HttpStatus.SC_OK) { proxyLogger.info("Node " + machine + " shutdown successfully."); } else { proxyLogger.info("Node " + machine + " did not shutdown. Return code was " + responseStatusCode); } try { client.close(); } catch (IOException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } } stopNodeRecycleThread(); if (responseStatusCode == HttpStatus.SC_OK) { getRegistry().removeIfPresent(this); } LOGGER.exiting(); }
Source:
<code>private void maybeCreateTopic(String topic) { if (!isTopicCreationEnabled || topicCache.contains(topic)) { return; } log.info("The task will send records to topic '{}' for the first time. Checking " + "whether topic exists", topic); Map<String, TopicDescription> existing = admin.describeTopics(topic); if (!existing.isEmpty()) { log.info("Topic '{}' already exists.", topic); topicCache.add(topic); return; } log.info("Creating topic '{}'", topic); NewTopicCreationGroup topicGroup = topicGroups.values().stream() .filter(group -> group.matches(topic)) .findFirst() .orElse(defaultTopicGroup); log.debug("Topic '{}' matched topic creation group: {}", topic, topicGroup); NewTopic newTopic = topicGroup.newTopic(topic); if (admin.createTopic(newTopic)) { topicCache.add(topic); <START> log.info("Created topic '{}'", newTopic); <END> } else { log.warn("Request to create new topic '{}' failed", topic); throw new ConnectException("Task failed to create new topic " + topic + ". Ensure " + "that the task is authorized to create topics or that the topic exists and " + "restart the task"); } }</code><technical_language>WDYT including name of topic creation group (it's included in debug logs far) actual topic settings create topic? like: suggestion log.info("Created topic '{}' creation group '{}' topic settings {}", newTopic, topicGroup, topicGroup.topicSettings()); if NewTopicCreationGroup.toString() method output name only, suggestion log.info("Created topic '{}' creation group {}", newTopic, topicGroup); if NewTopicCreationGroup.toString() method output name topic settings</technical_language>

Target:
private void maybeCreateTopic(String topic) { if (!topicCreation.isTopicCreationRequired(topic)) { return; } log.info("The task will send records to topic '{}' for the first time. Checking " + "whether topic exists", topic); Map<String, TopicDescription> existing = admin.describeTopics(topic); if (!existing.isEmpty()) { log.info("Topic '{}' already exists.", topic); topicCreation.addTopic(topic); return; } log.info("Creating topic '{}'", topic); TopicCreationGroup topicGroup = topicCreation.findFirstGroup(topic); log.debug("Topic '{}' matched topic creation group: {}", topic, topicGroup); NewTopic newTopic = topicGroup.newTopic(topic); if (admin.createTopic(newTopic)) { topicCreation.addTopic(topic); log.info("Created topic '{}' using creation group {}", newTopic, topicGroup); } else { log.warn("Request to create new topic '{}' failed", topic); throw new ConnectException("Task failed to create new topic " + topic + ". Ensure " + "that the task is authorized to create topics or that the topic exists and " + "restart the task"); } }
Source:
<code>private Node tryToFoldArrayConcat(Node n) { checkArgument(n.isCall(), n); if (!isASTNormalized() || !useTypes) { return n; } <START> if (isSafeToRemoveArrayLiteralFromFrontOfConcat(n)) { <END> return removeArrayLiteralFromFrontOfConcat(n); } if (isSafeToFoldConcatChaining(n)) { return foldConcatChaining(n); } return n; }</code><technical_language>good inline logic of isConcatCall() pull n bits need early exit if turns out n a concat call. utility methods do work pieces, check validity of not-very-bright checkArgument() calls etc. This reduces redundant logic improves readability. java Node calleeNode = checkNotNull(n.getFirstChild()); if (!calleeNode.isGetProp()) { return n; // array.concat() call } Node callTargetNode = calleeNode.getFirstChild(); String methodName = calleeNode.getLastChild().getString(); if (!"concat".equals(methodName) { return n; // array.concat() call } // etc</technical_language>

Target:
private Node tryToFoldArrayConcat(Node n) { checkArgument(n.isCall(), n); if (!isASTNormalized() || !useTypes) { return n; } ConcatFunctionCall concatFunctionCall = createConcatFunctionCallForNode(n); if (concatFunctionCall == null) { return n; } concatFunctionCall = tryToRemoveArrayLiteralFromFrontOfConcat(concatFunctionCall); checkNotNull(concatFunctionCall); return tryToFoldConcatChaining(concatFunctionCall); }
Source:
<code>public Optional<UsernamePasswordCredentials> extract(WebContext context) { final Optional<String> username = context.getRequestParameter(this.usernameParameter); final Optional<String> password = context.getRequestParameter(this.passwordParameter); <START> if (username.isPresent() && password.isPresent()) { <END> return Optional.of( new UsernamePasswordCredentials(username.get(), password.get()) ); } return Optional.empty(); }</code><technical_language>advantage of flatmap avoid calling isPresent get</technical_language>

Target:
public Optional<UsernamePasswordCredentials> extract(WebContext context) { final Optional<String> username = context.getRequestParameter(this.usernameParameter); final Optional<String> password = context.getRequestParameter(this.passwordParameter); return username.map( un -> password.isPresent() ? new UsernamePasswordCredentials(un, password.get()) : null ); }
Source:
<code>public static GerritTableView getActiveView() { IViewPart viewPart = null; if (rtv != null) { return rtv; } else { IWorkbench workbench = GerritUi.getDefault().getWorkbench(); IWorkbenchWindow window = workbench.getActiveWorkbenchWindow(); IWorkbenchPage page = null; if (window != null ) { page = workbench.getActiveWorkbenchWindow() .getActivePage(); } if (page != null) { viewPart = page.findView(VIEW_ID); if (viewPart == null) { try { viewPart = page.showView(VIEW_ID, null, org.eclipse.ui.IWorkbenchPage.VIEW_CREATE); } catch (PartInitException e) { <START> StatusHandler.log(new Status(IStatus.WARNING, GerritCorePlugin.PLUGIN_ID, NLS.bind( "PartInitException: ''{0}'' ", e))); <END> } GerritUi.Ftracer.traceWarning("getActiveView() SHOULD (JUST) CREATED A NEW Table:" + viewPart ); } } return (GerritTableView) viewPart; } }</code><technical_language>Sorry, I clear. I meant call 4 argument Status constructor takes exception. putting exception in message do right thing. I write this: StatusHandler.log(new Status(IStatus.WARNING, GerritCorePlugin.PLUGIN_ID, e.getMessage(), e)));</technical_language>

Target:
public static GerritTableView getActiveView() { IViewPart viewPart = null; if (rtv != null) { return rtv; } else { IWorkbench workbench = GerritUi.getDefault().getWorkbench(); IWorkbenchWindow window = workbench.getActiveWorkbenchWindow(); IWorkbenchPage page = null; if (window != null ) { page = workbench.getActiveWorkbenchWindow() .getActivePage(); } if (page != null) { viewPart = page.findView(VIEW_ID); if (viewPart == null) { try { viewPart = page.showView(VIEW_ID, null, org.eclipse.ui.IWorkbenchPage.VIEW_CREATE); } catch (PartInitException e) { StatusHandler.log(new Status(IStatus.WARNING, GerritCorePlugin.PLUGIN_ID, e.getMessage(), e)); } GerritUi.Ftracer.traceWarning("getActiveView() SHOULD (JUST) CREATED A NEW Table:" + viewPart ); } } return (GerritTableView) viewPart; } }
Source:
<code>private Boolean rearrangeColumns(TableView<?> table) { Double tableWidth = getContentWidth(table); List<? extends TableColumnBase<?, ?>> visibleLeafColumns = table.getVisibleLeafColumns(); Double remainingAvailableWidth = tableWidth - getSumMinWidthOfColumns(table); for (TableColumnBase<?, ?> col : visibleLeafColumns) { double share = expansionShare.get(col); double newSize = col.getMinWidth() + share * remainingAvailableWidth; newSize -= 2; newSize = Math.min(newSize, col.getMaxWidth()); <START> col.setPrefWidth(newSize); <END> } return true; }</code><technical_language>I this lead unused space right, of columns a higher preferred width maximum (because redistribute difference other columns)</technical_language>

Target:
private Boolean rearrangeColumns(TableView<?> table) { Double initialContentWidth = getContentWidth(table); LOGGER.debug("initialContentWidth {}", initialContentWidth); for (TableColumnBase<?, ?> col : resizableColumns) { col.setPrefWidth(col.getMinWidth()); } LOGGER.debug("Width after setting min width: {}", getContentWidth(table)); rearrangeColumns(table, resizableColumns); LOGGER.debug("Width after rearranging columns: {}", getContentWidth(table)); return (initialContentWidth - getContentWidth(table)) != 0d; }
Source:
<code>public void startCanTestThread() { if (this.m_pollThread != null) { this.m_pollThread.interrupt(); try { this.m_pollThread.join(100); } catch (InterruptedException e) { } this.m_pollThread = null; } this.m_pollThread = new Thread(new Runnable() { @Override public void run() { <START> if (CanSocketTest.this.m_canConnection != null && !IS_MAC) { <END> while (!CanSocketTest.this.thread_done) { CanSocketTest.this.thread_done = doCanTest(); } } } }); this.m_pollThread.start(); }</code><technical_language>CanSocketTest.this.m_canConnection CanSocketTest.this.thread_done volatile</technical_language>

Target:
public void startCanTestThread() { terminatePollThread(); this.pollThread = new Thread(new Runnable() { @Override public void run() { if (CanSocketTest.this.canConnection != null && !IS_MAC) { boolean threadDone = false; while (!threadDone) { threadDone = doCanTest(); } } } }); this.pollThread.start(); }
Source:
<code>protected void initPingIntervalMilli() { Integer pingIntervalMilliParam = getInitParameter("pingIntervalMilli", Integer.class); <START> setPingIntervalMilli((pingIntervalMilliParam == null) ? DEFAULT_PING_INTERVAL_MILLI : pingIntervalMilliParam); <END> if (isDebug()) { LOGGER.debug("pingIntervalMilli: {}", getPingIntervalMilli()); } }</code><technical_language>If changing this code, relying Optional a good move</technical_language>

Target:
protected void initPingIntervalMilli() { setPingIntervalMilli(Optional.ofNullable(getInitParameter("pingIntervalMilli", Integer.class)).orElse(DEFAULT_PING_INTERVAL_MILLI)); if (isDebug()) { LOGGER.debug("pingIntervalMilli: {}", getPingIntervalMilli()); } }
Source:
<code>public boolean setLayerState(boolean showWidget) { <START> prevWidgetState = showWidget; <END> if (isWidgetVisible() == showWidget) return false; updateQuickActionButton(showWidget); if (settings.DO_NOT_USE_ANIMATIONS.get()) { quickActionsWidget.setVisibility(!showWidget ? View.GONE : View.VISIBLE); } else { animateWidget(showWidget); } mapActivity.updateStatusBarColor(); if (!showWidget) { quitMovingMarker(); quickActionRegistry.setUpdatesListener(null); quickActionsWidget.setSelectionListener(null); } else { enterMovingMode(mapActivity.getMapView().getCurrentRotatedTileBox()); quickActionsWidget.setActions(quickActionRegistry.getFilteredQuickActions()); quickActionRegistry.setUpdatesListener(MapQuickActionLayer.this); quickActionsWidget.setSelectionListener(MapQuickActionLayer.this); } return true; }</code><technical_language>Space</technical_language>

Target:
public boolean setLayerState(boolean showWidget) { currentWidgetState = showWidget; if (isWidgetVisible() == showWidget) return false; updateQuickActionButton(showWidget); if (settings.DO_NOT_USE_ANIMATIONS.get()) { quickActionsWidget.setVisibility(!showWidget ? View.GONE : View.VISIBLE); } else { animateWidget(showWidget); } mapActivity.updateStatusBarColor(); if (!showWidget) { quitMovingMarker(); quickActionRegistry.setUpdatesListener(null); quickActionsWidget.setSelectionListener(null); } else { enterMovingMode(mapActivity.getMapView().getCurrentRotatedTileBox()); quickActionsWidget.setActions(quickActionRegistry.getFilteredQuickActions()); quickActionRegistry.setUpdatesListener(MapQuickActionLayer.this); quickActionsWidget.setSelectionListener(MapQuickActionLayer.this); } return true; }
Source:
<code>public View keys(Object... keys) { <START> this.allDocsKeys = String.format("{%s:%s}", gson.toJson("keys"), getKeyAsJsonElement(keys)); <END> return this; }</code><technical_language>While here, fix this line do sensible: JsonObject e = new JsonObject(); e.add("keys", getKeyAsJsonElement(keys)); this.allDocsKeys = gson.toJson(e);</technical_language>

Target:
public View keys(Object... keys) { JsonObject keysObject = new JsonObject(); keysObject.add("keys", getKeyAsJsonElement(keys)); this.allDocsKeys = gson.toJson(keysObject); return this; }
Source:
<code>public JsonObject findDocument(Integer id) throws DataException { SearchRestClient restClient = initiateRestClient(); String response = restClient.getDocument(id); if (!response.equals("")) { <START> JsonReader jsonReader = Json.createReader(new StringReader(response)); <END> return jsonReader.readObject(); } else { return Json.createObjectBuilder().build(); } }</code><technical_language>here. JsonReader is closeable a try-with-resources statement for closing object is a good idea</technical_language>

Target:
public JsonObject findDocument(Integer id) throws DataException { SearchRestClient restClient = initiateRestClient(); String response = restClient.getDocument(id); if (!response.equals("")) { try (JsonReader jsonReader = Json.createReader(new StringReader(response))) { return jsonReader.readObject(); } } else { return Json.createObjectBuilder().build(); } }
Source:
<code>private void updateParagraph(NotebookSocket conn, Message fromMessage) throws IOException { String paragraphId = (String) fromMessage.get("id"); if (paragraphId == null) { return; } String noteId = getOpenNoteId(conn); if (noteId == null) { noteId = (String) fromMessage.get("noteId"); } <START> NotebookService notebookService = new NotebookService(notebook()); <END> String title = (String) fromMessage.get("title"); String text = (String) fromMessage.get("paragraph"); Map<String, Object> params = (Map<String, Object>) fromMessage.get("params"); Map<String, Object> config = (Map<String, Object>) fromMessage.get("config"); notebookService.updateParagraph(noteId, paragraphId, title, text, params, config, getServiceContext(fromMessage), new WebSocketServiceCallback<Paragraph>(conn) { @Override public void onSuccess(Paragraph p, ServiceContext context) throws IOException { if (p.getNote().isPersonalizedMode()) { Map<String, Paragraph> userParagraphMap = p.getNote().getParagraph(paragraphId).getUserParagraphMap(); broadcastParagraphs(userParagraphMap, p); } else { broadcastParagraph(p.getNote(), p); } } }); }</code><technical_language>this, too</technical_language>

Target:
private void updateParagraph(NotebookSocket conn, Message fromMessage) throws IOException { String paragraphId = (String) fromMessage.get("id"); if (paragraphId == null) { return; } String noteId = getOpenNoteId(conn); if (noteId == null) { noteId = (String) fromMessage.get("noteId"); } String title = (String) fromMessage.get("title"); String text = (String) fromMessage.get("paragraph"); Map<String, Object> params = (Map<String, Object>) fromMessage.get("params"); Map<String, Object> config = (Map<String, Object>) fromMessage.get("config"); getNotebookService().updateParagraph(noteId, paragraphId, title, text, params, config, getServiceContext(fromMessage), new WebSocketServiceCallback<Paragraph>(conn) { @Override public void onSuccess(Paragraph p, ServiceContext context) throws IOException { if (p.getNote().isPersonalizedMode()) { Map<String, Paragraph> userParagraphMap = p.getNote().getParagraph(paragraphId).getUserParagraphMap(); broadcastParagraphs(userParagraphMap, p); } else { broadcastParagraph(p.getNote(), p); } } }); }
Source:
<code>protected void onCommand(final Command c) throws IOException, UnableToExecuteException { String callout = c.getProperty("callout.message"); if (callout != null) { Callout callout1 = new Callout(this.getClass().getCanonicalName(), "info", callout, 0, 0, 0, 0); drawer.createCallout(callout1); } else if (c.getProperty("command") != null && c.getProperty("command").equals("GRAPH-DATA")) { <START> EnvObjectLogic obj = (EnvObjectLogic) getApi().things().findByAddress("harvester", c.getProperty("event.object.address")); <END> if (obj.getBehavior("data") != null) { if (!obj.getBehavior("data").getValueAsString().isEmpty()) { GraphPanel gw = graphs.get(obj.getPojo().getUUID()); if (gw != null) { gw.reDraw(); } else { gw = new GraphPanel(this, obj); graphs.put(obj.getPojo().getUUID(), gw); } } } } else { EventQueue.invokeLater(new Runnable() { @Override public void run() { new Thread(new Runnable() { @Override public void run() { if (c.getProperty("options") != null) { Object[] options = c.getProperty("options").split(";"); int n = JOptionPane.showOptionDialog(window, c.getProperty("question"), "Please reply within " + (int) (c.getReplyTimeout() / 1000) + " seconds", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[2]); c.setProperty("result", options[n].toString()); } reply(c); } }).start(); } }); } }</code><technical_language>@dustinpho another check is ok</technical_language>

Target:
protected void onCommand(final Command c) throws IOException, UnableToExecuteException { String callout = c.getProperty("callout.message"); if (callout != null) { Callout callout1 = new Callout(this.getClass().getCanonicalName(), "info", callout, 0, 0, 0, 0); drawer.createCallout(callout1); } else if (c.getProperty("command") != null && c.getProperty("command").equals("GRAPH-DATA")) { EnvObjectLogic obj = (EnvObjectLogic) getApi().things().findByAddress("harvester", c.getProperty("event.object.address")); if (obj != null && obj.getBehavior("data") != null) { if (!obj.getBehavior("data").getValueAsString().isEmpty()) { GraphPanel gw = graphs.get(obj.getPojo().getUUID()); if (gw != null) { gw.reDraw(); } else { gw = new GraphPanel(this, obj); graphs.put(obj.getPojo().getUUID(), gw); } } } } else { EventQueue.invokeLater(new Runnable() { @Override public void run() { new Thread(new Runnable() { @Override public void run() { if (c.getProperty("options") != null) { Object[] options = c.getProperty("options").split(";"); int n = JOptionPane.showOptionDialog(window, c.getProperty("question"), "Please reply within " + (int) (c.getReplyTimeout() / 1000) + " seconds", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[2]); c.setProperty("result", options[n].toString()); } reply(c); } }).start(); } }); } }
Source:
<code>private static boolean vectorsMatch(VectorValueExpression e1, VectorValueExpression e2) { <START> return e1.getArgs().stream().map(FilterMatcher::asCVE).collect(Collectors.toSet()) <END> .equals(e2.getArgs().stream().map(FilterMatcher::asCVE).collect(Collectors.toSet())); }</code><technical_language>Neat</technical_language>

Target:
private static boolean vectorsMatch(VectorValueExpression e1, VectorValueExpression e2) { final Set<ConstantValueExpression> c1 = new HashSet<>(), c2 = new HashSet<>(); final Set<Integer> tveIndices1 = new HashSet<>(), tveIndices2 = new HashSet<>(); e1.getArgs().forEach(e -> { if (e instanceof ConstantValueExpression || e instanceof ParameterValueExpression) { c1.add(asCVE(e)); } else { assert (e instanceof TupleValueExpression); tveIndices1.add(((TupleValueExpression) e).getColumnIndex()); } }); e2.getArgs().forEach(e -> { if (e instanceof ConstantValueExpression || e instanceof ParameterValueExpression) { c2.add(asCVE(e)); } else { assert (e instanceof TupleValueExpression); tveIndices2.add(((TupleValueExpression) e).getColumnIndex()); } }); return c1.equals(c2) && tveIndices1.equals(tveIndices2); }
Source:
<code>public S indexNullAs(F indexNullAs) { <START> indexNullAsValue = Optional.of( indexNullAs ); <END> return thisAsS(); }</code><technical_language>null is acceptable for indexNullAs. null represent "no selected", need for Optional</technical_language>

Target:
public S indexNullAs(F indexNullAs) { indexNullAsValue = indexNullAs; return thisAsS(); }
Source:
<code>public void testFindAllByOrderByCacheVersionDescVepVersionDescVepVersionOrder() throws Exception { List<AnnotationMetadata> annotationMetadataList = repository.findAllByOrderByCacheVersionDescVepVersionDesc(); AnnotationMetadata prevAnnotationMetadata = annotationMetadataList.get(0); for (AnnotationMetadata curAnnotationMetadata : annotationMetadataList.subList(1, annotationMetadataList.size())) { if (curAnnotationMetadata.getCacheVersion().equals(prevAnnotationMetadata.getCacheVersion())) { assertTrue(Integer.parseInt(curAnnotationMetadata.getCacheVersion()) <START> <= Integer.parseInt(prevAnnotationMetadata.getCacheVersion())); <END> } } }</code><technical_language>I wanted write getVepVersion</technical_language>

Target:
public void testFindAllByOrderByCacheVersionDescVepVersionDescVepVersionOrder() throws Exception { List<AnnotationMetadata> annotationMetadataList = repository.findAllByOrderByCacheVersionDescVepVersionDesc(); AnnotationMetadata prevAnnotationMetadata = annotationMetadataList.get(0); for (AnnotationMetadata curAnnotationMetadata : annotationMetadataList.subList(1, annotationMetadataList.size())) { if (curAnnotationMetadata.getCacheVersion().equals(prevAnnotationMetadata.getCacheVersion())) { assertTrue(curAnnotationMetadata.getCacheVersion().compareTo(prevAnnotationMetadata.getCacheVersion()) <= 0); } } }
Source:
<code>public HtpasswdUserService() { super(); <START> this.htpasswdFile = GitBlit.getFileOrFolder(KEY_HTPASSWD_FILE, DEFAULT_HTPASSWD_FILE); <END> }</code><technical_language>I move this setup() is a setup-related action related IStoredSettings, a Gitblit static method here</technical_language>

Target:
public HtpasswdUserService() { super(); String os = System.getProperty("os.name").toLowerCase(); if (os.startsWith("windows") || os.startsWith("netware")) { SUPPORT_PLAINTEXT_PWD = true; } else { SUPPORT_PLAINTEXT_PWD = false; } }
Source:
<code>public void testSegmentLoading1() throws Exception { zkCoordinator.start(); final DataSegment segment = makeSegment("test", "1", new Interval("P1d/2011-04-01")); zkCoordinator.removeSegment(segment, new DataSegmentChangeCallback() { @Override public void execute() { } }); Assert.assertFalse(segmentsAnnouncedByMe.contains(segment)); zkCoordinator.addSegment(segment, new DataSegmentChangeCallback() { @Override public void execute() { } }); <START> Thread.sleep(1000); <END> Assert.assertTrue(segmentsAnnouncedByMe.contains(segment)); Assert.assertFalse("segment files shouldn't be deleted", segmentLoader.getSegmentsInTrash().contains(segment)); zkCoordinator.stop(); }</code><technical_language>if ran in 1001 ms</technical_language>

Target:
public void testSegmentLoading1() throws Exception { zkCoordinator.start(); final DataSegment segment = makeSegment("test", "1", new Interval("P1d/2011-04-01")); zkCoordinator.removeSegment(segment, new DataSegmentChangeCallback() { @Override public void execute() { } }); Assert.assertFalse(segmentsAnnouncedByMe.contains(segment)); zkCoordinator.addSegment(segment, new DataSegmentChangeCallback() { @Override public void execute() { } }); for (Runnable runnable : scheduledRunnable) { runnable.run(); } Assert.assertTrue(segmentsAnnouncedByMe.contains(segment)); Assert.assertFalse("segment files shouldn't be deleted", segmentLoader.getSegmentsInTrash().contains(segment)); zkCoordinator.stop(); }
Source:
<code>private void synchronizeSelection() { if (isSingleSelectionOnly()) { setSelectedItem(selectionModel.asSingleSelectionModel().getSelectedObject()); } else { List<T> selectedItems = <START> selectionModel.asMultiSelectionModel().getSelectedList(); <END> setSelectedItems(selectedItems); if (selectedItems.size() == 1) { setSelectedItem(selectedItems.get(0)); } } }</code><technical_language>OvirtSelectionModel#getSelectedObjects</technical_language>

Target:
private void synchronizeSelection() { if (isSingleSelectionOnly()) { setSelectedItem(selectionModel.asSingleSelectionModel().getSelectedObject()); } else { List<T> selectedItems = selectionModel.getSelectedObjects(); setSelectedItems(selectedItems); if (selectedItems.size() == 1) { setSelectedItem(selectedItems.get(0)); } } }
Source:
<code>private void init() { if ( !config.isEnabled() ) { logger.info( "Cassandra client not enabled" ); return; } host = config.getCassandraHost(); port = config.getCassandraPort(); SocketOptions socketOptions = new SocketOptions(); socketOptions.setConnectTimeoutMillis( 120000 ); <START> socketOptions.setReadTimeoutMillis( 120000 ); <END> Cluster.Builder builder = Cluster.builder() .withoutJMXReporting() .addContactPoint( host ) .withPort( port ) .withSocketOptions( socketOptions ); username = config.getCassandraUser(); String password = config.getCassandraPass(); if ( isNotBlank( username ) && isNotBlank( password ) ) { logger.info( "Build with credentials, user: {}, pass: ****", username ); builder.withCredentials( username, password ); } cluster = builder.build(); }</code><technical_language>For timeout issue, need introduce retry policy, <LINK_0> try if needed</technical_language>

Target:
private void init() { if ( !config.isEnabled() ) { logger.info( "Cassandra client not enabled" ); return; } host = config.getCassandraHost(); port = config.getCassandraPort(); SocketOptions socketOptions = new SocketOptions(); socketOptions.setConnectTimeoutMillis( 30000 ); socketOptions.setReadTimeoutMillis( 30000 ); Cluster.Builder builder = Cluster.builder() .withoutJMXReporting() .addContactPoint( host ) .withPort( port ) .withSocketOptions( socketOptions ); username = config.getCassandraUser(); String password = config.getCassandraPass(); if ( isNotBlank( username ) && isNotBlank( password ) ) { logger.info( "Build with credentials, user: {}, pass: ****", username ); builder.withCredentials( username, password ); } cluster = builder.build(); }
Source:
<code>private PoolingListener<C> getDelegatePoolingListener() { if (unwrappedDelegate instanceof PoolingListener) { return new PoolingListener<C>() { @Override public void onBorrow(C connection) { ((PoolingListener) unwrappedDelegate).onBorrow(connection); } @Override public void onReturn(C connection) { ((PoolingListener) unwrappedDelegate).onReturn(connection); } }; } else { return new PoolingListener<C>() { @Override public void onBorrow(C connection) { <START> throw new UnsupportedOperationException("The delegate connection provider does not support Pooling"); <END> } @Override public void onReturn(C connection) { throw new UnsupportedOperationException("The delegate connection provider does not support Pooling"); } }; } }</code><technical_language>This breaks liskov principle. NullObject pattern instead</technical_language>

Target:
private PoolingListener<C> getDelegatePoolingListener() { if (unwrappedDelegate instanceof PoolingListener) { return new PoolingListener<C>() { @Override public void onBorrow(C connection) { ((PoolingListener) unwrappedDelegate).onBorrow(connection); } @Override public void onReturn(C connection) { ((PoolingListener) unwrappedDelegate).onReturn(connection); } }; } else { return new PoolingListener<C>() {}; } }
Source:
<code>public AbstractMap.SimpleEntry<String, JwtClaims> createNewSessionToken(String username, char[] password) { String sessionToken = new IAMRestClient().getSSOTicket(iamURL + IAMConfiguration.IAM_TICKET_REQUEST, username, password, ticketMarker, isJWTSession); JwtClaims claims = isJWTSession ? JWTUtils.parseJWT(sessionToken, tokenSignatureEnabled, tokenSignatureKey, tokenEncryptionEnabled, tokenEncryptionKey, iamURL, iamURL) <START> : null; <END> return new AbstractMap.SimpleEntry(sessionToken, claims); }</code><technical_language>Is other store null? then, of a map record, searching key is a key is null if is key in map</technical_language>

Target:
public AbstractMap.SimpleEntry<String, JwtClaims> createNewSessionToken(String username, char[] password) { String sessionToken = iamRestClient.getSSOTicket(iamURL + IAMConfiguration.IAM_TICKET_REQUEST, username, password, ticketMarker, isJWTSession); JwtClaims claims = isJWTSession ? JWTUtils.parseJWT(sessionToken, tokenSignatureEnabled, tokenSignatureKey, tokenEncryptionEnabled, tokenEncryptionKey, iamURL, iamURL) : null; return new AbstractMap.SimpleEntry(sessionToken, claims); }
Source:
<code><START> protected void onNfcPostExecute() { <END> handleResult(mInputParcel); vAnimator.setDisplayedChild(2); nfcGuideView.setCurrentStatus(NfcGuideView.NfcGuideViewStatus.DONE); new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { while (true) { if (isNfcConnected()) { try { Thread.sleep(200); } catch (InterruptedException ignored) { } } else { return null; } } } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); finish(); } }.execute(); }</code><technical_language>this final maybe? a reason override this</technical_language>

Target:
protected final void onNfcPostExecute() { handleResult(mInputParcel); vAnimator.setDisplayedChild(2); nfcGuideView.setCurrentStatus(NfcGuideView.NfcGuideViewStatus.DONE); new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { while (true) { if (isNfcConnected()) { try { Thread.sleep(200); } catch (InterruptedException ignored) { } } else { return null; } } } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); finish(); } }.execute(); }
Source:
<code>public final Type getType() { <START> return null; END> }</code><technical_language>give this a shot, if type parser is fixed</technical_language>

Target:
public final Type getType() { TypeBuilder builder = new TypeBuilder(); return builder.build(this.getSignature()); }
Source:
<code>public Optional<Argument> build(Type expectedType, Object value, ConfigRegistry config) { return FACTORIES.stream() <START> .map(factory -> factory.build(expectedType, value, config)) <END> .filter(Optional::isPresent) .findFirst() .map(Optional::get); }</code><technical_language>I prefer flatMap for this. sucks left out Optional.stream() in Java 8 java return FACTORIES.stream() .flatMap(factory -> JdbiStreams.toStream( factory.build(expectedType, value, config))) .findFirst();</technical_language>

Target:
public Optional<Argument> build(Type expectedType, Object value, ConfigRegistry config) { return FACTORIES.stream() .flatMap(factory -> JdbiStreams.toStream(factory.build(expectedType, value, config))) .findFirst(); }
Source:
<code>public void testMbeanGetCoordinator() throws Exception { startGrid(0); startClientGrid(1); IgniteEx srv2 = startGrid(2); ZookeeperDiscoverySpiMBean mbean = getMxBean(srv2.context().igniteInstanceName(), "SPIs", ZookeeperDiscoverySpi.class, ZookeeperDiscoverySpiMBean.class); <START> grid(0).close(); <END> assertEquals(mbean.getCoordinatorNodeFormatted(), String.valueOf(srv2.localNode())); }</code><technical_language>stopGrid(0)</technical_language>

Target:
public void testMbeanGetCoordinator() throws Exception { startGrid(0); startClientGrid(1); IgniteEx srv2 = startGrid(2); ZookeeperDiscoverySpiMBean mbean = getMxBean(srv2.context().igniteInstanceName(), "SPIs", ZookeeperDiscoverySpi.class, ZookeeperDiscoverySpiMBean.class); stopGrid(0); assertEquals(mbean.getCoordinator(), srv2.localNode().id()); assertEquals(mbean.getCoordinatorNodeFormatted(), String.valueOf(srv2.localNode())); }