auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void showAppCrashDialog(String error) { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder( this); alertDialogBuilder.setTitle(R.string.crash_dialog_title); alertDialogBuilder .setMessage(R.string.crash_dialog_message) .setCancelable(false) .setPositiveButton(R.string.crash_dialog_positive_button, (dialog, id) -> dialog.cancel()) .setNegativeButton(R.string.crash_dialog_negative_button, (dialog, id) -> finishAffinity()) .setNeutralButton(R.string.crash_dialog_neutral_button, (dialog, id) -> { String filename = OpenMRS.getInstance().getOpenMRSDir() + File.separator + mOpenMRSLogger.getLogFilename(); Intent email = new Intent(Intent.ACTION_SEND); email.putExtra(Intent.EXTRA_SUBJECT, R.string.error_email_subject_app_crashed); email.putExtra(Intent.EXTRA_TEXT, error); email.putExtra(Intent.EXTRA_STREAM, Uri.parse(getString(R.string.file_uri_prefix) + filename)); <START> email.setType(getString(R.string.MIME_type_encapsulated_message)); <END> startActivity(Intent.createChooser(email, getString(R.string.choose_a_email_client))); }); alertDialog = alertDialogBuilder.create(); alertDialog.show(); }</code><technical_language>Place in ApplicationConstants instead</technical_language>

Target:
public void showAppCrashDialog(String error) { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder( this); alertDialogBuilder.setTitle(R.string.crash_dialog_title); alertDialogBuilder .setMessage(R.string.crash_dialog_message) .setCancelable(false) .setPositiveButton(R.string.crash_dialog_positive_button, (dialog, id) -> dialog.cancel()) .setNegativeButton(R.string.crash_dialog_negative_button, (dialog, id) -> finishAffinity()) .setNeutralButton(R.string.crash_dialog_neutral_button, (dialog, id) -> { String filename = OpenMRS.getInstance().getOpenMRSDir() + File.separator + mOpenMRSLogger.getLogFilename(); Intent email = new Intent(Intent.ACTION_SEND); email.putExtra(Intent.EXTRA_SUBJECT, R.string.error_email_subject_app_crashed); email.putExtra(Intent.EXTRA_TEXT, error); email.putExtra(Intent.EXTRA_STREAM, Uri.parse(ApplicationConstants.URI_FILE + filename)); email.setType(ApplicationConstants.MESSAGE_RFC_822); startActivity(Intent.createChooser(email, getString(R.string.choose_a_email_client))); }); alertDialog = alertDialogBuilder.create(); alertDialog.show(); }
Source:
<code>public void register(TypeCodec<?> newCodec) { for (TypeCodec<?> primitiveCodec : primitiveCodecs) { <START> if (primitiveCodec.accepts(newCodec.getCqlType()) <END> && primitiveCodec.accepts(newCodec.getJavaType())) { LOG.warn( "[{}] Ignoring codec because it collides with built-in primitive codec {}", logPrefix, newCodec, primitiveCodec); return; } } for (TypeCodec<?> userCodec : userCodecs) { if (userCodec.accepts(newCodec.getCqlType()) && userCodec.accepts(newCodec.getJavaType())) { LOG.warn( "[{}] Ignoring codec because it collides with previously registered codec {}", logPrefix, newCodec, userCodec); return; } } try { TypeCodec<?> cachedCodec = getCachedCodec(newCodec.getCqlType(), newCodec.getJavaType(), false); LOG.warn( "[{}] Ignoring codec because it collides with previously generated codec {}", logPrefix, newCodec, cachedCodec); return; } catch (CodecNotFoundException ignored) { } userCodecs.add(newCodec); }</code><technical_language>I this check refactored a method reused this line <LINK_0></technical_language>

Target:
public void register(TypeCodec<?> newCodec) { registerLock.lock(); try { for (TypeCodec<?> primitiveCodec : primitiveCodecs) { if (collides(newCodec, primitiveCodec)) { LOG.warn( "[{}] Ignoring codec because it collides with built-in primitive codec {}", logPrefix, newCodec, primitiveCodec); return; } } for (TypeCodec<?> userCodec : userCodecs) { if (collides(newCodec, userCodec)) { LOG.warn( "[{}] Ignoring codec because it collides with previously registered codec {}", logPrefix, newCodec, userCodec); return; } } try { TypeCodec<?> cachedCodec = getCachedCodec(newCodec.getCqlType(), newCodec.getJavaType(), false); LOG.warn( "[{}] Ignoring codec because it collides with previously generated codec {}", logPrefix, newCodec, cachedCodec); return; } catch (CodecNotFoundException ignored) { } userCodecs.add(newCodec); } finally { registerLock.unlock(); } }
Source:
<code>public Object visit(ASTClassOrInterfaceDeclaration node, Object data) { boolean classHasLombok = hasLombokAnnotation(node); Map<VariableNameDeclaration, List<NameOccurrence>> vars = node.getScope() .getDeclarations(VariableNameDeclaration.class); for (Map.Entry<VariableNameDeclaration, List<NameOccurrence>> entry : vars.entrySet()) { VariableNameDeclaration decl = entry.getKey(); AccessNode accessNodeParent = decl.getAccessNodeParent(); if (!accessNodeParent.isPrivate() || isOK(decl.getImage()) || classHasLombok <START> || ((Annotateable) accessNodeParent).isAnyAnnotationPresent(getProperty(ignoredAnnotationsDescriptor))) { <END> continue; } if (!actuallyUsed(entry.getValue())) { if (!usedInOuterClass(node, decl) && !usedInOuterEnum(node, decl)) { addViolation(data, decl.getNode(), decl.getImage()); } } } return super.visit(node, data); }</code><technical_language>abstract rule class a shorthand method for this, write hasIgnoredAnnotation((Annotatable) accessNodeParent) for example</technical_language>

Target:
public Object visit(ASTClassOrInterfaceDeclaration node, Object data) { boolean classHasLombok = hasLombokAnnotation(node); Map<VariableNameDeclaration, List<NameOccurrence>> vars = node.getScope() .getDeclarations(VariableNameDeclaration.class); for (Map.Entry<VariableNameDeclaration, List<NameOccurrence>> entry : vars.entrySet()) { VariableNameDeclaration decl = entry.getKey(); AccessNode accessNodeParent = decl.getAccessNodeParent(); if (!accessNodeParent.isPrivate() || isOK(decl.getImage()) || classHasLombok || hasIgnoredAnnotation((Annotatable) accessNodeParent)) { continue; } if (!actuallyUsed(entry.getValue())) { if (!usedInOuterClass(node, decl) && !usedInOuterEnum(node, decl)) { addViolation(data, decl.getNode(), decl.getImage()); } } } return super.visit(node, data); }
Source:
<code>public Navigate toPage(String pageName) { String host = UrlBuilder.getHostForWiki(); String cacheBuster = pageName.equals("") || pageName.equals("/") ? "" : "?cb=" + DateTime.now().getMillis(); <START> driver.get("http://" + host + pageName + cacheBuster + "&" + defaultTestingGroup); <END> return this; }</code><technical_language>[appendQueryStringToURL](tests/blob/master/src/test/java/com/wikia/webdriver/common/core/url/UrlBuilder.java#L71) method for appending URL params URL</technical_language>

Target:
public Navigate toPage(String pageName) { String host = UrlBuilder.getHostForWiki(); String cacheBuster = pageName.equals("") || pageName.equals("/") ? "" : "?cb=" + DateTime.now().getMillis(); driver.get("http://" + host + pageName + cacheBuster + "?" + defaultTestingGroup); return this; }
Source:
<code>public DefaultCustomerInSession(final Configuration configuration, final ObjectStoringSessionStrategy session, final UserInfoViewModelFactory userInfoViewModelFactory) { this.customerIdSessionKey = configuration.getString("session.customer.customerId", DEFAULT_CUSTOMER_ID_SESSION_KEY); this.customerEmailSessionKey = configuration.getString("session.customer.customerEmail", DEFAULT_CUSTOMER_EMAIL_SESSION_KEY); <START> this.customerGroupIdSessionKey = configuration.getString("session.customer.customerGroup", DEFAULT_CUSTOMER_GROUP_SESSION_KEY); <END> this.userInfoSessionKey = configuration.getString("session.customer.userInfo", DEFAULT_USER_INFO_SESSION_KEY); this.session = session; this.userInfoViewModelFactory = userInfoViewModelFactory; }</code><technical_language>I session.customer.customerGroupId configuration key</technical_language>

Target:
public DefaultCustomerInSession(final Configuration configuration, final ObjectStoringSessionStrategy session, final UserInfoViewModelFactory userInfoViewModelFactory) { this.customerIdSessionKey = configuration.getString("session.customer.customerId", DEFAULT_CUSTOMER_ID_SESSION_KEY); this.customerEmailSessionKey = configuration.getString("session.customer.customerEmail", DEFAULT_CUSTOMER_EMAIL_SESSION_KEY); this.customerGroupIdSessionKey = configuration.getString("session.customer.customerGroupId", DEFAULT_CUSTOMER_GROUP_SESSION_KEY); this.userInfoSessionKey = configuration.getString("session.customer.userInfo", DEFAULT_USER_INFO_SESSION_KEY); this.session = session; this.userInfoViewModelFactory = userInfoViewModelFactory; }
Source:
<code>List<Supplier<PageFilter>> makeReorderableFilters(Optional<RowExpression> filter, Optional<String> classNameSuffix) { if (!filter.isPresent()) { return ImmutableList.of(); } ImmutableList.Builder<RowExpression> conjunctBuilder = ImmutableList.builder(); collectConjuncts(filter.get(), conjunctBuilder); List<RowExpression> allConjuncts = conjunctBuilder.build(); if (allConjuncts.size() == 1) { return ImmutableList.of(pageFunctionCompiler.compileFilter(filter.get(), classNameSuffix)); } ImmutableList.Builder<Supplier<PageFilter>> result = ImmutableList.builder(); CallExpression topAnd = (CallExpression) filter.get(); Map<Set<InputReferenceExpression>, List<RowExpression>> inputsToConjuncts = new HashMap(); for (RowExpression conjunct : allConjuncts) { ImmutableSet.Builder<InputReferenceExpression> inputs = ImmutableSet.builder(); collectInputs(conjunct, inputs); inputsToConjuncts.compute(inputs.build(), (k, v) -> { if (v == null) { <START> v = new ArrayList(); <END> v.add(conjunct); return v; } else { v.add(conjunct); } return v; }); } for (List<RowExpression> conjuncts : inputsToConjuncts.values()) { RowExpression firstConjunct = conjuncts.get(0); for (int i = 1; i < conjuncts.size(); i++) { firstConjunct = new CallExpression(topAnd.getSignature(), topAnd.getType(), ImmutableList.of(firstConjunct, conjuncts.get(i))); } result.add(pageFunctionCompiler.compileFilter(firstConjunct, classNameSuffix)); } return result.build(); }</code><technical_language>a check conjuncts is empty</technical_language>

Target:
List<Supplier<PageFilter>> makeReorderableFilters(Optional<RowExpression> filter, Optional<String> classNameSuffix) { if (!filter.isPresent()) { return ImmutableList.of(); } ImmutableList.Builder<RowExpression> conjunctBuilder = ImmutableList.builder(); collectConjuncts(filter.get(), conjunctBuilder); List<RowExpression> allConjuncts = conjunctBuilder.build(); if (allConjuncts.size() == 1) { return ImmutableList.of(pageFunctionCompiler.compileFilter(filter.get(), classNameSuffix)); } ImmutableList.Builder<Supplier<PageFilter>> result = ImmutableList.builder(); CallExpression topAnd = (CallExpression) filter.get(); Map<Set<InputReferenceExpression>, List<RowExpression>> inputsToConjuncts = new HashMap(); for (RowExpression conjunct : allConjuncts) { ImmutableSet.Builder<InputReferenceExpression> inputs = ImmutableSet.builder(); collectInputs(conjunct, inputs); inputsToConjuncts.computeIfAbsent(inputs.build(), k -> new ArrayList<>()).add(conjunct); } for (List<RowExpression> conjuncts : inputsToConjuncts.values()) { RowExpression firstConjunct = conjuncts.get(0); for (int i = 1; i < conjuncts.size(); i++) { firstConjunct = new CallExpression(topAnd.getSignature(), topAnd.getType(), ImmutableList.of(firstConjunct, conjuncts.get(i))); } result.add(pageFunctionCompiler.compileFilter(firstConjunct, classNameSuffix)); } return result.build(); }
Source:
<code>public <T> void registerInstance(final T instance) { requireNonNull(instance); streamCategories() .filter(category -> category.isAssignableFrom(instance.getClass())) <START> .map(category -> (InstanceRegistry<? super T>) instanceRegistry(category)) <END> .forEach(registry -> registry.register(instance)); }</code><technical_language>consider passing in Class<T> type a parameter avoid this cast</technical_language>

Target:
public <T> void registerInstance(final T instance) { ensureArgumentNonNull("instance", instance); streamCategories().filter(category -> category.isAssignableFrom(instance.getClass())) .map(category -> (InstanceRegistry<? super T>) instanceRegistry(category)) .forEach(registry -> registry.register(instance)); }
Source:
<code>public boolean deleteUsers(List<String> userNames) { return (Boolean) transactionTemplate.execute(new TransactionCallback() { @Override public Object doInTransaction(TransactionStatus status) { <START> ArrayList<String> nullUsers = new ArrayList<>(); <END> ArrayList<String> enabledUsers = new ArrayList<>(); checkAndCollectInvalidUsers(nullUsers, enabledUsers, userNames); if(nullUsers.isEmpty() && enabledUsers.isEmpty()){ String queryString = String.format("delete from User where name in (:userNames)"); Query query = sessionFactory.getCurrentSession().createQuery(queryString); query.setParameterList("userNames", userNames); query.executeUpdate(); return Boolean.TRUE; } throw new BulkDeleteException(nullUsers, enabledUsers); } }); }</code><technical_language>a nullUsers nonExistantUsers</technical_language>

Target:
public boolean deleteUsers(List<String> userNames) { return (Boolean) transactionTemplate.execute(new TransactionCallback() { @Override public Object doInTransaction(TransactionStatus status) { String queryString = "delete from User where name in (:userNames)"; Query query = sessionFactory.getCurrentSession().createQuery(queryString); query.setParameterList("userNames", userNames); query.executeUpdate(); return Boolean.TRUE; } }); }
Source:
<code>private void assertSuccessCompletion(CompletableFuture<Void> future) { try { <START> CompletionStages.join(future); <END> } catch (Exception e) { Assert.fail("Future should've completed successfully"); } }</code><technical_language>FunctionalTestUtils class for awaits timeout</technical_language>

Target:
private void assertSuccessCompletion(CompletableFuture<Void> future) { try { FunctionalTestUtils.await(future); } catch (Exception e) { Assert.fail("Future should've completed successfully"); } }
Source:
<code>public Duration getAdbExecTimeout() { <START> return (Duration) getCapability(AndroidMobileCapabilityType.ADB_EXEC_TIMEOUT); <END> }</code><technical_language>this return Duration.ofMillis(getCapability(AndroidMobileCapabilityType.ADB_EXEC_TIMEOUT))</technical_language>

Target:
public Duration getAdbExecTimeout() { Object duration = getCapability(AndroidMobileCapabilityType.ADB_EXEC_TIMEOUT); if (duration.getClass().isAssignableFrom(Long.class)) { return Duration.ofMillis((Long) duration); } Integer integer = (Integer) duration; Long value = Long.valueOf(integer); return Duration.ofMillis(value); }
Source:
<code>void checkMaxEnvironmentRam(Workspace workspace) throws ServerException { if (workspace.getConfig() != null) { checkMaxEnvironmentRam(workspace.getId(), workspace.getConfig()); } else { LOG.warn( <START> "Can not estimate memory needed for devfile based workspace {}. Set environment memory limits may work incorrectly", <END> workspace.getId()); } }</code><technical_language>about: "Cannot estimate memory requirements of a devfile-based workspace {}. memory limits applied correctly."</technical_language>

Target:
void checkMaxEnvironmentRam(Workspace workspace) throws ServerException { if (workspace.getConfig() != null) { checkMaxEnvironmentRam(workspace.getId(), workspace.getConfig()); } else { LOG.warn( "Can not estimate memory needed for devfile based workspace `{}`." + " The environment memory limits may not be applied correctly.", workspace.getId()); } }
Source:
<code>public void drawMapImage(final Graphics g) { final Graphics2D g2d = (Graphics2D) checkNotNull(g); final GameData gameData = this.gameData; gameData.acquireReadLock(); try { final Rectangle2D.Double bounds = new Rectangle2D.Double(0, 0, getImageWidth(), getImageHeight()); final Collection<Tile> tileList = tileManager.getTiles(bounds); for (final Tile tile : tileList) { <START> tile.drawImage(gameData, uiContext.getMapData()); final Image img = tile.getImage(); <END> g2d.drawImage( img, AffineTransform.getTranslateInstance(tile.getBounds().x, tile.getBounds().y), this); } } finally { gameData.releaseReadLock(); } }</code><technical_language>sense drawImage return rendered image? EG: final var image = tile.drawImage(gameData, uiContext.getMapData())</technical_language>

Target:
public void drawMapImage(final Graphics g) { final Graphics2D g2d = (Graphics2D) checkNotNull(g); final GameData gameData = this.gameData; gameData.acquireReadLock(); try { final Rectangle2D.Double bounds = new Rectangle2D.Double(0, 0, getImageWidth(), getImageHeight()); final Collection<Tile> tileList = tileManager.getTiles(bounds); for (final Tile tile : tileList) { tile.drawImage(gameData, uiContext.getMapData()); g2d.drawImage( tile.getImage(), AffineTransform.getTranslateInstance(tile.getBounds().x, tile.getBounds().y), this); } } finally { gameData.releaseReadLock(); } }
Source:
<code>private String putBlob(AmbryCoordinator ac) throws InterruptedException, StoreException, IOException, CoordinatorException { BlobProperties putBlobProperties = new BlobProperties(100, "serviceId", "memberId", "contentType", false, Utils.Infinite_Time); ByteBuffer putUserMetadata = ByteBuffer.allocate(10); for (byte b = 0; b < 10; b++) { putUserMetadata.put(b); } <START> ByteBuffer putContent = ByteBuffer.allocate(100); <END> for (byte b = 0; b < 100; b++) { putContent.put(b); } putContent.flip(); return putBlob(ac, putBlobProperties, putUserMetadata, putContent); }</code><technical_language>Consider making 5 lines of code (allocating a byte buffer, filling up, flipping it) a helper method in this file</technical_language>

Target:
private String putBlob(AmbryCoordinator ac) throws InterruptedException, StoreException, IOException, CoordinatorException { BlobProperties putBlobProperties = new BlobProperties(100, "serviceId", "memberId", "contentType", false, Utils.Infinite_Time); ByteBuffer putUserMetadata = getByteBuffer(10, false); ByteBuffer putContent = getByteBuffer(100, true); return putBlob(ac, putBlobProperties, putUserMetadata, putContent); }
Source:
<code>public Extensions() { <START> factories = new CopyOnWriteArrayList<>(); <END> }</code><technical_language>Again, this initializer repeated in additional constructors added</technical_language>

Target:
public Extensions()
Source:
<code><START> Plumber initPlumber() <END> { log.info("Someone get us a plumber!"); plumber = fireDepartment.findPlumber(); return plumber; }</code><technical_language>this method private, need return Plumber</technical_language>

Target:
private void initPlumber() { log.info("Someone get us a plumber!"); plumber = fireDepartment.findPlumber(); }
Source:
<code><START> public boolean trySyncAcl(ACLDocumentOperation operation) { <END> LOGGER.debug("Syncing the ACL to ElasticSearch"); try { lock.lock(); Collection<SearchGuardACLDocument> docs = loadAcls(); if(docs.size() < 2) { return false; } operation.syncDocuments(docs); return isSuccessfulWrite(writeAcl(operation, docs)); } catch (Exception e) { LOGGER.error("Exception while syncing ACL with cache", e); } finally { lock.unlock(); } return false; }</code><technical_language>this method sychronized instead of locks</technical_language>

Target:
public boolean trySyncAcl(ACLDocumentOperation operation) { LOGGER.debug("Syncing the ACL to ElasticSearch"); try { lock.lock(); Collection<SearchGuardACLDocument> docs = loadAcls(); if(docs.size() < 2) { return false; } operation.syncDocuments(docs); return isSuccessfulWrite(writeAcl(operation, docs)); } catch (Exception e) { LOGGER.error("Exception while syncing ACL to Elasticsearch", e); } finally { lock.unlock(); } return false; }
Source:
<code>public Chain getAndAppend(final long key, final ByteBuffer payLoad) throws TimeoutException { <START> Chain chain = delegate.getAndAppend(key, payLoad); <END> incrementInvalidationsCounter(key); return chain; }</code><technical_language>Nitpicking here: intend do returned chain? I kept? change set just: java incrementInvalidationsCounter(key); return delegate.getAndAppend(key, payLoad); right</technical_language>

Target:
public Chain getAndAppend(final long key, final ByteBuffer payLoad) throws TimeoutException { return delegate.getAndAppend(key, payLoad); }
Source:
<code>protected void finished(Description description) { <START> stopRecording(); <END> }</code><technical_language>for future enhancements ([JUnitAttachmentsPlugin attach files](<LINK_0></technical_language>

Target:
protected void finished(Description description) { stopRecordingWithFinalWaiting(); }
Source:
<code>public void testConfigureAsyncDeletes() throws Exception { Cache cache = cacheManager.getCache(); ExecutorService executor = spy(Executors.newFixedThreadPool(1)); try (Directory directory = DirectoryBuilder.newDirectoryInstance(cache, cache, cache, INDEX_NAME) .chunkSize(BUFFER_SIZE) .deleteOperationsExecutor(executor) .create()) { createFile(directory, "file"); assertEquals(directory.listAll().length, 1); directory.deleteFile("file"); eventuallyEquals(0, () -> { try { return directory.listAll().length; } catch (IOException e) { Assert.fail("Error inspecting directory", e); return null; } }); <START> verify(executor).execute(any(Runnable.class)); <END> } finally { executor.shutdownNow(); } }</code><technical_language>picky, verify(executor).execute(any(DirectoryLucene.DeleteTask.class))</technical_language>

Target:
public void testConfigureAsyncDeletes() throws Exception { Cache cache = cacheManager.getCache(); ExecutorService executor = spy(Executors.newFixedThreadPool(1)); try (Directory directory = DirectoryBuilder.newDirectoryInstance(cache, cache, cache, INDEX_NAME) .chunkSize(BUFFER_SIZE) .deleteOperationsExecutor(executor) .create()) { createFile(directory, "file"); assertEquals(directory.listAll().length, 1); directory.deleteFile("file"); eventuallyEquals(0, () -> { try { return directory.listAll().length; } catch (IOException e) { Assert.fail("Error inspecting directory", e); return null; } }); verify(executor).execute(any(DirectoryLucene.DeleteTask.class)); } finally { executor.shutdownNow(); } }
Source:
<code>public static boolean assertPmCounter(int expectedCounter) { int actualCounter = pmPage.getMessagesCounter(); info("Expected counter: " + expectedCounter + ", actual counter: " + actualCounter); if (expectedCounter == actualCounter) { <START> info("Assertion successful"); <END> return true; } throw new AssertionFailedError("Actual PM counter differs from the expected value"); }</code><technical_language>This text added previous logging, need for a separate line</technical_language>

Target:
public static void assertPmCounter(int expectedCounter) { int actualCounter = pmPage.getMessagesCounter(); info("Checking PM counter. Expected: " + expectedCounter + ", actual: " + actualCounter); if (expectedCounter != actualCounter) { throw new AssertionFailedError("Actual PM counter differs from the expected value"); } info("Success. Expected counter equals actual number."); }
Source:
<code>public void onTestFailure(ITestResult result) { driver = DriverProvider.getWebDriver(); if (Global.LOG_ENABLED) { try { CommonUtils .captureScreenshot(screenPath + imageCounter, driver); CommonUtils.appendTextToFile(screenPath + imageCounter + ".html", driver.getPageSource()); } catch (Exception e) { log("onException", "driver has no ability to catch screenshot or html source - driver may died", false); } <START> StackTraceElement[] stackTrace = result.getThrowable().getStackTrace(); <END> StringBuilder stackTraceBuilder = new StringBuilder(); for (int i=0; i<stackTrace.length; i++){ stackTraceBuilder.append(stackTrace[i]); stackTraceBuilder.append("\n"); } StringBuilder builder = new StringBuilder(); builder.append("<tr class=\"error\"><td>error</td><td>" + result.getThrowable().toString() + "\n" +stackTraceBuilder.toString() + "</td><td> <br/><a href='screenshots/screenshot" + imageCounter + ".png'>Screenshot</a><br/><a href='screenshots/screenshot" + imageCounter + ".html'>HTML Source</a></td></tr>"); CommonUtils.appendTextToFile(logPath, builder.toString()); imageCounter += 1; logJSError(driver); } }</code><technical_language>ExceptionUtils import org.apache.commons.lang.exception.ExceptionUtils convert String</technical_language>

Target:
public void onTestFailure(ITestResult result) { driver = DriverProvider.getWebDriver(); if (Global.LOG_ENABLED) { try { CommonUtils .captureScreenshot(screenPath + imageCounter, driver); CommonUtils.appendTextToFile(screenPath + imageCounter + ".html", driver.getPageSource()); } catch (Exception e) { log("onException", "driver has no ability to catch screenshot or html source - driver may died", false); } String exception = result.getThrowable().toString() + "\n" +ExceptionUtils.getStackTrace(result.getThrowable()); StringBuilder builder = new StringBuilder(); builder.append("<tr class=\"error\"><td>error</td><td>" + exception + "</td><td> <br/><a href='screenshots/screenshot" + imageCounter + ".png'>Screenshot</a><br/><a href='screenshots/screenshot" + imageCounter + ".html'>HTML Source</a></td></tr>"); CommonUtils.appendTextToFile(logPath, builder.toString()); imageCounter += 1; logJSError(driver); onTestSuccess(result); } }
Source:
<code>public void tearDown() { <START> fBot.closeAllEditors(); SWTBotUtils.deleteProject(PROJECT_NAME, fBot); <END> }</code><technical_language>This part move cleanUp(). Right project is deleted test created</technical_language>

Target:
public void tearDown() { fBot.closeAllEditors(); }
Source:
<code>private SslContext getClientSslContext() throws SSLException { return SslContextBuilder .forClient() .sslProvider(BaseSslContextFactory.chooseSslProvider()) .startTls(true) <START> .build(); <END> }</code><technical_language>add .protocols() explicitly here. a getProtocols() method in BaseSslContextFactory. TLSv1.2. I a cleaner solution is subclass class create a ClientSslContextFactory holds this logic. initialize in constructor of this class call this method in init block</technical_language>

Target:
private SslContext getClientSslContext() throws SSLException { return SslContextBuilder .forClient() .sslProvider(BaseSslContextFactory.chooseSslProvider()) .build(); }
Source:
<code>private WrappedServletRequest wrapDeflatedRequest(HttpServletRequest request) throws IOException { final Inflater inflater = buildInflater(); try { final InflaterInputStream input = new InflaterInputStream(request.getInputStream(), inflater, inputBufferSize) { @Override public void close() throws IOException { super.close(); localInflater.set(inflater); } }; <START> InputStream exceptionHandlingInput = new ZipExceptionHandlingInputStream(input, DEFLATE); <END> return new WrappedServletRequest(request, exceptionHandlingInput); } catch (ZipException e) { throw ZipExceptionHandlingInputStream.buildBadDataException(DEFLATE, e); } catch (EOFException e) { throw ZipExceptionHandlingInputStream.buildPrematureEofException(DEFLATE, e); } }</code><technical_language>I inline stream constructor declaring a variable</technical_language>

Target:
private WrappedServletRequest wrapDeflatedRequest(HttpServletRequest request) throws IOException { final Inflater inflater = buildInflater(); try { final InflaterInputStream input = new InflaterInputStream(request.getInputStream(), inflater, inputBufferSize) { @Override public void close() throws IOException { super.close(); localInflater.set(inflater); } }; return new WrappedServletRequest(request, new ZipExceptionHandlingInputStream(input, DEFLATE)); } catch (IOException e) { throw ZipExceptionHandlingInputStream.handleException(DEFLATE, e); } }
Source:
<code>public void shouldReduceAnEmptyListAndANonEmptyListAndReturnConcatenation() { final List<Integer> list = Collections.unmodifiableList( <START> IntStream.range(0, 5) <END> .boxed() .collect(Collectors.toList()) ); final List<Integer> actual = ListOps.reduce(list, new ArrayList<Integer>(), accumulator, combiner); final List<Integer> expected = IntStream.range(0, 5) .boxed() .collect(Collectors.toList()); assertNotNull(actual); assertFalse(actual.isEmpty()); assertEquals(expected, actual); }</code><technical_language>Arrays.asList(...) for short lists</technical_language>

Target:
public void shouldReduceAnEmptyListAndANonEmptyListAndReturnConcatenation() { final List<Integer> list = Collections.unmodifiableList( Arrays.asList(0, 1, 2, 3, 4, 5) ); final List<Integer> actual = ListOps.reduce(list, new ArrayList<Integer>(), accumulator, combiner); final List<Integer> expected = Arrays.asList(0, 1, 2, 3, 4, 5); assertNotNull(actual); assertFalse(actual.isEmpty()); assertEquals(expected, actual); }
Source:
<code>private Map<String, Map<String, String>> parseVolumeConfigDetails(Map<String, Object> configs) { Map<String, Map<String, String>> volumeConfigs = new HashMap<String, Map<String, String>>(); for (Map.Entry<String, Object> entry : configs.entrySet()) { Map<String, Object> fetchedVolumeConfig = (Map<String, Object>) entry.getValue(); Map<String, String> volConfig = new HashMap<String, String>(); for (Map.Entry<String, Object> config : fetchedVolumeConfig.entrySet()) { String value = (String) config.getValue(); <START> volConfig.put(config.getKey(), value == null ? "" : value); <END> } volumeConfigs.put(entry.getKey(), volConfig); } return volumeConfigs; }</code><technical_language>null value</technical_language>

Target:
private Map<String, Map<String, String>> parseVolumeConfigDetails(Map<String, Object> configs) { Map<String, Map<String, String>> volumeConfigs = new HashMap<String, Map<String, String>>(); for (Map.Entry<String, Object> entry : configs.entrySet()) { Map<String, Object> fetchedVolumeConfig = (Map<String, Object>) entry.getValue(); Map<String, String> volConfig = new HashMap<String, String>(); for (Map.Entry<String, Object> config : fetchedVolumeConfig.entrySet()) { String value = (String) config.getValue(); volConfig.put(config.getKey(), value); } volumeConfigs.put(entry.getKey(), volConfig); } return volumeConfigs; }
Source:
<code>public AuthRequest authenticate(final AuthRequest who) throws AccountException { final String authUsername = who.getLocalUser(); final String authPassword = who.getPassword(); if (this.username == null) { this.username = authUsername; <START> this.password = authPassword; <END> } try { final DirContext ctx = open(); try { final LdapQuery.Result m = findAccount(ctx, authUsername); if (authConfig.getAuthType() == AuthType.LDAP) { authenticate(m.getDN(), authPassword); } who.setDisplayName(apply(accountFullName, m)); who.setUserName(apply(accountSshUserName, m)); if (accountEmailAddress != null) { who.setEmailAddress(apply(accountEmailAddress, m)); } else if (emailExpander.canExpand(authUsername)) { who.setEmailAddress(emailExpander.expand(authUsername)); } membershipCache.put(authUsername, queryForGroups(ctx, authUsername, m)); return who; } finally { try { ctx.close(); } catch (NamingException e) { log.warn("Cannot close LDAP query handle", e); } } } catch (NamingException e) { log.error("Cannot query LDAP to autenticate user", e); throw new AccountException("Cannot query LDAP for account", e); } }</code><technical_language>I mentioned above, do this assignment here. this fix bug fix? need find another accomplish modifying this class's members</technical_language>

Target:
public AuthRequest authenticate(final AuthRequest who) throws AccountException { try { DirContext ctx = null; AuthType authType = authConfig.getAuthType(); String username = who.getLocalUser(); String password = who.getPassword(); if (this.username != null) { ctx = open(); if (authType == AuthType.LDAP) { ctx = authenticate(username, password); } } else if (authType == AuthType.LDAP) { ctx = authenticate(username, password); } else { ctx = open(); } try { final LdapQuery.Result m = findAccount(ctx, username); who.setDisplayName(apply(accountFullName, m)); who.setUserName(apply(accountSshUserName, m)); if (accountEmailAddress != null) { who.setEmailAddress(apply(accountEmailAddress, m)); } else if (emailExpander.canExpand(username)) { who.setEmailAddress(emailExpander.expand(username)); } membershipCache.put(username, queryForGroups(ctx, username, m)); return who; } finally { try { ctx.close(); } catch (NamingException e) { log.warn("Cannot close LDAP query handle", e); } } } catch (NamingException e) { log.error("Cannot query LDAP to autenticate user", e); throw new AccountException("Cannot query LDAP for account", e); } }
Source:
<code>public void firstConnectionAutoUpgradeDisabled() throws Exception { startMiniClusterWithToggleNamespaceMapping(Boolean.FALSE.toString()); Map<String, String> props = new HashMap<>(); props.put(QueryServices.AUTO_UPGRADE_ENABLED, Boolean.FALSE.toString()); ReadOnlyProps readOnlyProps = new ReadOnlyProps(props); SystemCatalogCreationOnConnectionIT.PhoenixSysCatCreationTestingDriver driver = new SystemCatalogCreationOnConnectionIT.PhoenixSysCatCreationTestingDriver(readOnlyProps); try { driver.getConnectionQueryServices(getJdbcUrl(), new Properties()); fail("Client should not be able to create SYSTEM.CATALOG since we set the isAutoUpgradeEnabled property to false"); } catch (Exception e) { assertTrue(e instanceof UpgradeRequiredException); } hbaseTables = getHBaseTables(); assertFalse(hbaseTables.contains(PHOENIX_SYSTEM_CATALOG) || hbaseTables.contains(PHOENIX_NAMESPACE_MAPPED_SYSTEM_CATALOG)); assertTrue(hbaseTables.size() == 0); assertEquals(1, countUpgradeAttempts); Connection conn = driver.getConnectionQueryServices(getJdbcUrl(), new Properties()).connect(getJdbcUrl(), new Properties()); try { conn.createStatement().execute(EXECUTE_UPGRADE_COMMAND); <START> } catch (Exception e) { <END> fail("EXECUTE UPGRADE should not fail"); } finally { conn.close(); } hbaseTables = getHBaseTables(); assertTrue(PHOENIX_SYSTEM_TABLES.containsAll(hbaseTables)); assertTrue(hbaseTables.size() == 4); }</code><technical_language>Remove this catch exception thrown easier diagnose (and test fail is want)</technical_language>

Target:
private SystemCatalogCreationOnConnectionIT.PhoenixSysCatCreationTestingDriver firstConnectionAutoUpgradeDisabled() throws Exception { startMiniClusterWithToggleNamespaceMapping(Boolean.FALSE.toString()); Map<String, String> props = new HashMap<>(); props.put(QueryServices.AUTO_UPGRADE_ENABLED, Boolean.FALSE.toString()); ReadOnlyProps readOnlyProps = new ReadOnlyProps(props); SystemCatalogCreationOnConnectionIT.PhoenixSysCatCreationTestingDriver driver = new SystemCatalogCreationOnConnectionIT.PhoenixSysCatCreationTestingDriver(readOnlyProps); try { driver.getConnectionQueryServices(getJdbcUrl(), new Properties()); fail("Client should not be able to create SYSTEM.CATALOG since we set the isAutoUpgradeEnabled property to false"); } catch (Exception e) { assertTrue(e instanceof UpgradeRequiredException); } hbaseTables = getHBaseTables(); assertFalse(hbaseTables.contains(PHOENIX_SYSTEM_CATALOG) || hbaseTables.contains(PHOENIX_NAMESPACE_MAPPED_SYSTEM_CATALOG)); assertTrue(hbaseTables.size() == 0); assertEquals(1, countUpgradeAttempts); Connection conn = driver.getConnectionQueryServices(getJdbcUrl(), new Properties()).connect(getJdbcUrl(), new Properties()); try { conn.createStatement().execute(EXECUTE_UPGRADE_COMMAND); } finally { conn.close(); } hbaseTables = getHBaseTables(); assertEquals(PHOENIX_SYSTEM_TABLES, hbaseTables); return driver; }
Source:
<code>private List<IProject> findProjectContainingTest(Path projectPath, IProgressMonitor monitor) { FixedRequestAttributes requestAttributes = this.runConfigurationAttributes.toFixedRequestAttributes(); <START> GradleBuild gradleBuild = CorePlugin.gradleWorkspaceManager().getGradleBuild(requestAttributes); <END> Collection<EclipseProject> models = gradleBuild.fetchCompositeModel(EclipseProject.class, getToken(), monitor); ImmutableSet.Builder<OmniEclipseProject> projects = ImmutableSet.builder(); for (EclipseProject model : models) { projects.addAll(DefaultOmniEclipseProject.from(model).getAll()); } Set<OmniEclipseProject> eclipseProjects = projects.build(); List<IProject> result = new ArrayList<IProject>(); for (OmniEclipseProject eclipseProject : eclipseProjects) { if (eclipseProject.getPath().equals(projectPath)) { Optional<IProject> workspaceProject = CorePlugin.workspaceOperations().findProjectByName(eclipseProject.getName()); if (workspaceProject.isPresent()) { result.add(workspaceProject.get()); } } } return result; }</code><technical_language>This code in model provider</technical_language>

Target:
private List<IProject> findProjectContainingTest(Path projectPath, IProgressMonitor monitor) { FixedRequestAttributes requestAttributes = this.runConfigurationAttributes.toFixedRequestAttributes(); ModelProvider modelProvider = CorePlugin.gradleWorkspaceManager().getGradleBuild(requestAttributes).getModelProvider(); Set<OmniEclipseProject> eclipseProjects = modelProvider.fetchEclipseGradleProjects(FetchStrategy.LOAD_IF_NOT_CACHED, getToken(), monitor); List<IProject> result = new ArrayList<IProject>(); for (OmniEclipseProject eclipseProject : eclipseProjects) { if (eclipseProject.getPath().equals(projectPath)) { Optional<IProject> workspaceProject = CorePlugin.workspaceOperations().findProjectByName(eclipseProject.getName()); if (workspaceProject.isPresent()) { result.add(workspaceProject.get()); } } } return result; }
Source:
<code>public boolean containsValue(Object value) { LinkedList<Object> linkedList = new LinkedList<Object>(); linkedList.add(value); <START> return validate().litems.containsValue(linkedList); <END> }</code><technical_language>this work</technical_language>

Target:
public boolean containsValue(Object value) { LinkedList<Object> linkedList = new LinkedList<Object>(); linkedList.add(value); return validate().linkedListItems.containsValue(linkedList); }
Source:
<code>private static Method find(String methodName) { try { <START> Method method = ManagementFactory.getOperatingSystemMXBean().getClass().getMethod(methodName); <END> if (!method.isAccessible()) { method.setAccessible(true); } return method; } catch (NoSuchMethodException e) { LOGGER.warn("Unable to find method '{}' on the {}", methodName, OperatingSystemMXBean.class.getSimpleName()); return null; } }</code><technical_language>getMethod(methodName) throw a SecurityException well</technical_language>

Target:
private static Method find(String methodName) { try { Method method = ManagementFactory.getOperatingSystemMXBean().getClass().getMethod(methodName); if (!method.isAccessible()) { method.setAccessible(true); } return method; } catch (NoSuchMethodException | SecurityException e) { LOGGER.trace("Unable to find or access method '{}' on the {}", methodName, OperatingSystemMXBean.class.getSimpleName()); return null; } }
Source:
<code>public static void addPostWithHWAccelerationOff(int localSiteId, int localPostId) { if (localSiteId == 0 || localPostId == 0 || isPostWithHWAccelerationOff(localSiteId, localPostId)) { return; } String key = localSiteId + "-" + localPostId; <START> List<String> currentIds = getPostWithHWAccelerationOff(); <END> currentIds.add(key); String idsAsString = TextUtils.join(",", currentIds); setString(DeletablePrefKey.AZTEC_EDITOR_DISABLE_HW_ACC_KEYS, idsAsString); }</code><technical_language>this line List<String> currentIds = new ArrayList<String>(getPostWithHWAccelerationOff());, getPostWithHWAccelerationOff() returns Arrays.asList() is a "fixed-size list" [the docs](<LINK_0>, line of code currentIds.add(key); crash</technical_language>

Target:
public static void addPostWithHWAccelerationOff(int localSiteId, int localPostId) { if (localSiteId == 0 || localPostId == 0 || isPostWithHWAccelerationOff(localSiteId, localPostId)) { return; } String key = localSiteId + "-" + localPostId; List<String> currentIds = new ArrayList<>(getPostWithHWAccelerationOff()); currentIds.add(key); String idsAsString = TextUtils.join(",", currentIds); setString(DeletablePrefKey.AZTEC_EDITOR_DISABLE_HW_ACC_KEYS, idsAsString); }
Source:
<code>public static Flux<ByteBuffer> toFluxByteBuffer(InputStream inputStream) { Pair pair = new Pair(); return Flux.just(true) .repeat() .map(ignore -> { byte[] buffer = new byte[BYTE_BUFFER_CHUNK_SIZE]; try { int numBytes = inputStream.read(buffer); if (numBytes > 0) { return pair.buffer(ByteBuffer.wrap(buffer, 0, numBytes)).readBytes(numBytes); } else { return pair.buffer(null).readBytes(numBytes); } } catch (IOException ioe) { <START> throw Exceptions.propagate(ioe); <END> } }) .takeUntil(p -> p.readBytes() == -1) .filter(p -> p.readBytes() > 0) .map(Pair::buffer); }</code><technical_language>this logger throw</technical_language>

Target:
public static Flux<ByteBuffer> toFluxByteBuffer(InputStream inputStream) { Pair pair = new Pair(); return Flux.just(true) .repeat() .map(ignore -> { byte[] buffer = new byte[BYTE_BUFFER_CHUNK_SIZE]; try { int numBytes = inputStream.read(buffer); if (numBytes > 0) { return pair.buffer(ByteBuffer.wrap(buffer, 0, numBytes)).readBytes(numBytes); } else { return pair.buffer(null).readBytes(numBytes); } } catch (IOException ioe) { throw LOGGER.logExceptionAsError(new RuntimeException(ioe)); } }) .takeUntil(p -> p.readBytes() == -1) .filter(p -> p.readBytes() > 0) .map(Pair::buffer); }
Source:
<code>protected void verifyAdsFromProvider(String providerName, List<WebElement> slots) { String providerSpecificSelector = AdsContent.getElementForProvider(providerName); for (WebElement slot: slots) { if (!checkIfElementInElement(providerSpecificSelector, slot)) { PageObjectLogging.log( "NoAdsFromProvider", "Ads from " + providerName + " not found in slot: " + slot.getAttribute("id"), false ); throw new NoSuchElementException( "Call to provider: " + providerName + " in slot: " + slot.getAttribute("id") + " not found!" ); } PageObjectLogging.log( "AdsFromProviderFound", "Ads from " + providerName <START> + " found in slot: " + providerSpecificSelector, <END> true ); } }</code><technical_language>bad selector</technical_language>

Target:
protected void verifyAdsFromProvider(String providerName, List<WebElement> slots) { String providerSpecificSelector = AdsContent.getElementForProvider(providerName); for (WebElement slot: slots) { if (!checkIfElementInElement(providerSpecificSelector, slot)) { PageObjectLogging.log( "NoAdsFromProvider", "Ads from " + providerName + " not found in slot: " + slot.getAttribute("id"), false ); throw new NoSuchElementException( "Call to provider: " + providerName + " in slot: " + slot.getAttribute("id") + " not found!" ); } PageObjectLogging.log( "AdsFromProviderFound", "Ads from " + providerName + " found in slot: " + slot.getAttribute("id"), true ); } }
Source:
<code>private void browseSources() { File directory = null; if (rootFileLocation != null) { directory = new File(rootPathLocation); } else { return; } File[] files = directory.listFiles(); if (files == null) { <START> Toast.makeText(getActivity(), getString(R.string.error_reading_local_storage), Toast.LENGTH_LONG); <END> return; } Arrays.sort(files); rootFileLocation.clear(); browseRootAlready = true; for (File file : files) { boolean isDir = file.isDirectory(); rootFileLocation.add( new LocalFileLocation(file.getName(), file.getAbsolutePath(), isDir) ); } ((MediaPictureListAdapter) getAdapter()).setFilelistItems(rootFileLocation); }</code><technical_language>Missing call .show()</technical_language>

Target:
private void browseSources() { File directory = null; if (rootFileLocation != null) { directory = new File(rootPathLocation); } else { return; } File[] files = directory.listFiles(); if (files == null) { Toast.makeText(getActivity(), getString(R.string.error_reading_local_storage), Toast.LENGTH_LONG).show(); return; } Arrays.sort(files); rootFileLocation.clear(); browseRootAlready = true; for (File file : files) { boolean isDir = file.isDirectory(); rootFileLocation.add( new LocalFileLocation(file.getName(), file.getAbsolutePath(), isDir) ); } ((MediaPictureListAdapter) getAdapter()).setFilelistItems(rootFileLocation); }
Source:
<code>MetacardTransformer lookupTransformerReference(String metacardTransformerId) { <START> Bundle bundle = FrameworkUtil.getBundle(this.getClass()); <END> if (bundle != null) { BundleContext bundleContext = bundle.getBundleContext(); try { Collection<ServiceReference<MetacardTransformer>> transformerReference = bundleContext.getServiceReferences( MetacardTransformer.class, "(id=" + metacardTransformerId + ")"); return bundleContext.getService(transformerReference.iterator().next()); } catch (InvalidSyntaxException | NoSuchElementException e) { LOGGER.warn( "Unable to resolve MetacardTransformer {}. Backup will not be performed.", metacardTransformerId, e); } } return null; }</code><technical_language>inject a Function<Class<T>, Bundle> bundleLookup bundleLookup.apply(this.getClass()) instead of making method @VisibleForTesting change visibility? This decrease code coverage</technical_language>

Target:
private MetacardTransformer lookupTransformerReference(String metacardTransformerId) { Bundle bundle = bundleLookup.apply(this.getClass()); if (bundle != null) { BundleContext bundleContext = bundle.getBundleContext(); try { Collection<ServiceReference<MetacardTransformer>> transformerReference = bundleContext.getServiceReferences( MetacardTransformer.class, "(id=" + metacardTransformerId + ")"); return bundleContext.getService(transformerReference.iterator().next()); } catch (InvalidSyntaxException | NoSuchElementException e) { LOGGER.warn( "Unable to resolve MetacardTransformer {}. Backup will not be performed.", metacardTransformerId, e); } } return null; }
Source:
<code>public static void main(String[] args) throws Exception { if (args.length == 0) { throw new IllegalArgumentException("Topology name must be provided."); } final String name = args[0]; NimbusClient.withConfiguredClient(new NimbusClient.WithNimbus() { @Override public void run(Nimbus.Iface client) throws Exception { GetInfoOptions opts = new GetInfoOptions(); opts.set_num_err_choice(NumErrorsChoice.ONE); TopologyInfo topologyInfo = client.getTopologyInfoByNameWithOpts(name, opts); Map<String, Object> outputMap = new HashMap<>(); <START> if (topologyInfo == null) { <END> outputMap.put("Failure", "No topologies running with name " + name); } else { String topologyName = topologyInfo.get_name(); Map<String, List<ErrorInfo>> topologyErrors = topologyInfo.get_errors(); outputMap.put("Topology Name", topologyName); outputMap.put("Comp-Errors", getComponentErrors(topologyErrors)); } System.out.println(JSONValue.toJSONString(outputMap)); } private Map<String, String> getComponentErrors(Map<String, List<ErrorInfo>> topologyErrors) { Map<String, String> componentErrorMap = new HashMap<>(); for (Map.Entry<String, List<ErrorInfo>> compNameToCompErrors : topologyErrors.entrySet()) { String compName = compNameToCompErrors.getKey(); List<ErrorInfo> compErrors = compNameToCompErrors.getValue(); if (compErrors != null && !compErrors.isEmpty()) { ErrorInfo latestError = compErrors.get(0); componentErrorMap.put(compName, latestError.get_error()); } } return componentErrorMap; } }); }</code><technical_language>topologyInfo null</technical_language>

Target:
public static void main(String[] args) throws Exception { if (args.length == 0) { throw new IllegalArgumentException("Topology name must be provided."); } final String name = args[0]; NimbusClient.withConfiguredClient(new NimbusClient.WithNimbus() { @Override public void run(Nimbus.Iface client) throws Exception { GetInfoOptions opts = new GetInfoOptions(); opts.set_num_err_choice(NumErrorsChoice.ONE); Map<String, Object> outputMap = new HashMap<>(); try { TopologyInfo topologyInfo = client.getTopologyInfoByNameWithOpts(name, opts); String topologyName = topologyInfo.get_name(); Map<String, List<ErrorInfo>> topologyErrors = topologyInfo.get_errors(); outputMap.put("Topology Name", topologyName); outputMap.put("Comp-Errors", getComponentErrors(topologyErrors)); } catch (NotAliveException notAliveException) { outputMap.put("Failure", "No topologies running with name " + name); } System.out.println(JSONValue.toJSONString(outputMap)); } private Map<String, String> getComponentErrors(Map<String, List<ErrorInfo>> topologyErrors) { Map<String, String> componentErrorMap = new HashMap<>(); for (Map.Entry<String, List<ErrorInfo>> compNameToCompErrors : topologyErrors.entrySet()) { String compName = compNameToCompErrors.getKey(); List<ErrorInfo> compErrors = compNameToCompErrors.getValue(); if (compErrors != null && !compErrors.isEmpty()) { ErrorInfo latestError = compErrors.get(0); componentErrorMap.put(compName, latestError.get_error()); } } return componentErrorMap; } }); }