auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void addFailureCausesFromData(StringBuilder message, FailureCauseDisplayData displayData) { for (FoundFailureCause failureCause : displayData.getFoundFailureCauses()) { if (message.length() > 0) { message.append("\n\n"); } message.append(failureCause.getDescription()); message.append(" ( ") .append(Jenkins.getInstance().getRootUrl()) .append(displayData.getLinks().getBuildUrl()) .append(" )"); } if (displayData.getDownstreamFailureCauses().isEmpty() && displayData.getFoundFailureCauses().isEmpty()) { <START> message.append("Unknown (") <END> .append(Jenkins.getInstance().getRootUrl()) .append(displayData.getLinks().getBuildUrl()) .append(")"); } }</code><technical_language>configured default message</technical_language>

Target:
private void addFailureCausesFromData(StringBuilder message, FailureCauseDisplayData displayData) { for (FoundFailureCause failureCause : displayData.getFoundFailureCauses()) { if (message.length() > 0) { message.append("\n\n"); } message.append(failureCause.getDescription()); message.append(" ( ") .append(Jenkins.getInstance().getRootUrl()) .append(displayData.getLinks().getBuildUrl()) .append(" )"); } if (displayData.getDownstreamFailureCauses().isEmpty() && displayData.getFoundFailureCauses().isEmpty()) { if (message.length() > 0) { message.append("\n\n"); } message.append(PluginImpl.getInstance().getNoCausesMessage()) .append(" ( ") .append(Jenkins.getInstance().getRootUrl()) .append(displayData.getLinks().getBuildUrl()) .append(" )"); } }
Source:
<code>public void shouldReadReuseFromEnvironmentOnly() { assertFalse("no reuse by default", newConfig().environmentSupportsReuse()); classpathProperties.setProperty("testcontainers.reuse.enable", "true"); assertFalse("reuse is not affected by classpath properties", newConfig().environmentSupportsReuse()); environmentProperties.setProperty("testcontainers.reuse.enable", "true"); assertTrue("reuse enabled", newConfig().environmentSupportsReuse()); environmentProperties.setProperty("ryuk.container.image", " testcontainersofficial/ryuk:0.3.0 "); <START> assertEquals("Whitespaces still exists in image property", "testcontainersofficial/ryuk:0.3.0",newConfig().getRyukImage()); <END> }</code><technical_language>I this like: suggestion assertEquals("trailing whitespace is removed image name property", "testcontainersofficial/ryuk:0.3.0",newConfig().getRyukImage());</technical_language>

Target:
public void shouldReadReuseFromEnvironmentOnly() { assertFalse("no reuse by default", newConfig().environmentSupportsReuse()); classpathProperties.setProperty("testcontainers.reuse.enable", "true"); assertFalse("reuse is not affected by classpath properties", newConfig().environmentSupportsReuse()); environmentProperties.setProperty("testcontainers.reuse.enable", "true"); assertTrue("reuse enabled", newConfig().environmentSupportsReuse()); }
Source:
<code>public void incrementCounter(final String name, final long value) { if (!assertIsOpen()) { return; } final ConcurrentLinkedDeque<Quantity> counters = getOrCreateDeque(_counterSamples, name); <START> final TsdCounter counter = _counters.compute(name, (key, existingValue) -> { <END> if (existingValue == null) { final TsdCounter newCounter = TsdCounter.newInstance(key, _isOpen); counters.add(newCounter); return newCounter; } return existingValue; }); counter.increment(value); }</code><technical_language>want pull this out of a lambda more efficient</technical_language>

Target:
public void incrementCounter(final String name, final long value) { if (!assertIsOpen()) { return; } final TsdCounter counter = _counters.compute(name, _createCounterBiFunction); counter.increment(value); }
Source:
<code><START> public void savePageStructures() throws ParserConfigurationException <END> { Package gtPackage = packageService.selectByCode(packageCode); Map<UUID, Iterator<Page>> translationPageDirectoryIteratorMap = Maps.newHashMap(); for(Translation translation : translationService.selectByPackageId(gtPackage.getId())) { Language languageRepresentedByTranslation = languageService.selectLanguageById(translation.getLanguageId()); translationPageDirectoryIteratorMap.put(translation.getId(), new PageDirectory(packageCode, languageRepresentedByTranslation.getPath()).buildPages().iterator()); } List<Page> baseEnglishPages = new PageDirectory(packageCode, "en").buildPages(); for(UUID translationId : translationPageDirectoryIteratorMap.keySet()) { Iterator<Page> i = translationPageDirectoryIteratorMap.get(translationId); Iterator<Page> baseIterator = baseEnglishPages.iterator(); for( ; i.hasNext();) { Page translatedPage = i.next(); PageStructure pageStructure = new PageStructure(); pageStructure.setId(UUID.randomUUID()); pageStructure.setXmlContent(translatedPage.getXmlContent()); pageStructure.setFilename(translatedPage.getFilename()); pageStructure.setTranslationId(translationId); pageStructureService.insert(pageStructure); TranslatableElements translatableElements = new TranslatableElements(baseIterator.next().getXmlContent(), translatedPage.getXmlContent(), translatedPage.getFilename(), translationId, pageStructure.getId()); translatableElements.save(translationElementService); pageStructureService.update(pageStructure); } } }</code><technical_language>method throw a ParserConfigurationException</technical_language>

Target:
public void savePageStructures() { Package gtPackage = packageService.selectByCode(packageCode); Map<UUID, Iterator<Page>> translationPageDirectoryIteratorMap = Maps.newHashMap(); for(Translation translation : translationService.selectByPackageId(gtPackage.getId())) { Language languageRepresentedByTranslation = languageService.selectLanguageById(translation.getLanguageId()); translationPageDirectoryIteratorMap.put(translation.getId(), new PageDirectory(packageCode, languageRepresentedByTranslation.getPath()).buildPages().iterator()); } List<Page> baseEnglishPages = new PageDirectory(packageCode, "en").buildPages(); for(UUID translationId : translationPageDirectoryIteratorMap.keySet()) { Iterator<Page> i = translationPageDirectoryIteratorMap.get(translationId); Iterator<Page> baseIterator = baseEnglishPages.iterator(); for( ; i.hasNext();) { Page translatedPage = i.next(); PageStructure pageStructure = new PageStructure(); pageStructure.setId(UUID.randomUUID()); pageStructure.setXmlContent(translatedPage.getXmlContent()); pageStructure.setFilename(translatedPage.getFilename()); pageStructure.setTranslationId(translationId); pageStructureService.insert(pageStructure); TranslatableElements translatableElements = new TranslatableElements(baseIterator.next().getXmlContent(), translatedPage.getXmlContent(), translatedPage.getFilename(), translationId, pageStructure.getId()); translatableElements.save(translationElementService); pageStructureService.update(pageStructure); } } }
Source:
<code>public Ingredient(String tag, List<IngredientName> names, List<IngredientsRelation> parents, List<IngredientsRelation> children, String wikiDataId) { this.tag = tag; this.names = names; this.parents = parents; this.children = children; this.wikiDataId = wikiDataId; <START> this.isWikiDataIdPresent = true; <END> }</code><technical_language>**isWikiDataIdPresent** redundant check null/empty **wikiDataId** itself</technical_language>

Target:
public Ingredient(String tag, List<IngredientName> names, List<IngredientsRelation> parents, List<IngredientsRelation> children, String wikiDataId) { this.tag = tag; this.names = names; this.parents = parents; this.children = children; this.wikiDataId = wikiDataId; }
Source:
<code>private static Token getMissedHtmlTag(RecognitionException exception) { Token htmlTagNameStart = null; final Interval sourceInterval = exception.getCtx().getSourceInterval(); final List<Token> tokenList = ((BufferedTokenStream) exception.getInputStream()) .getTokens(sourceInterval.a, sourceInterval.b); final Deque<Token> stack = new ArrayDeque<>(); for (int i = 0; i < tokenList.size(); i++) { final Token token = tokenList.get(i); if (token.getType() == JavadocParser.HTML_TAG_NAME && tokenList.get(i - 1).getType() == JavadocTokenTypes.START) { stack.push(token); <START> } <END> else if (token.getType() == JavadocParser.HTML_TAG_NAME && !stack.isEmpty()) { if (stack.peek().getText().equals(token.getText())) { stack.pop(); } else { htmlTagNameStart = stack.pop(); } } } if (htmlTagNameStart == null) { htmlTagNameStart = stack.pop(); } return htmlTagNameStart; }</code><technical_language>here. is this parser token types? Is this method called getTokenType why? this get confusing need swap tokens in 2 places instead of 1? Is swap in place assume token types correct else</technical_language>

Target:
private static Token getMissedHtmlTag(RecognitionException exception) { Token htmlTagNameStart = null; final Interval sourceInterval = exception.getCtx().getSourceInterval(); final List<Token> tokenList = ((BufferedTokenStream) exception.getInputStream()) .getTokens(sourceInterval.a, sourceInterval.b); final Deque<Token> stack = new ArrayDeque<>(); int prevTokenType = JavadocTokenTypes.EOF; for (final Token token : tokenList) { final int javadocTokenType = mapAntlrTokenTypeToJavadocTokenType(token.getType()); if (javadocTokenType == JavadocTokenTypes.HTML_TAG_NAME && prevTokenType == JavadocTokenTypes.START) { stack.push(token); } else if (javadocTokenType == JavadocTokenTypes.HTML_TAG_NAME && !stack.isEmpty()) { if (stack.peek().getText().equals(token.getText())) { stack.pop(); } else { htmlTagNameStart = stack.pop(); } } prevTokenType = javadocTokenType; } if (htmlTagNameStart == null) { htmlTagNameStart = stack.pop(); } return htmlTagNameStart; }
Source:
<code>protected Expression getExpressionFromContainer(Container container, long expressionDefinitionId) { if (container != null) { final Expression expression = container.accept(this, expressionDefinitionId); if (expression != null) { return expression; } } return null; <START> } <END></code><technical_language>java return container != null ? container.accept(this, expressionDefinitionId) : null;</technical_language>

Target:
protected Expression getExpressionFromContainer(Container container, long expressionDefinitionId) { return container != null ? container.accept(this, expressionDefinitionId) : null; }
Source:
<code>public void cancel(DefaultGoPublisher publisher, EnvironmentVariableContext environmentVariableContext, TaskExtension taskExtension) { <START> publisher.consumeLineWithPrefix("Cancel task: " + cancelBuilder.getDescription()); <END> try { cancelBuilder.build(new BuildLogElement(), publisher, environmentVariableContext, taskExtension); publisher.consumeLineWithPrefix("Task status: cancelled"); } catch (Exception e) { LOGGER.error("", e); } }</code><technical_language>I Cancel task <task1> incorrectly imply task1 cancelled. Users setup on-cancel-task for a job executed job execution cancelled. description logged for on-cancel task original task executed</technical_language>

Target:
public void cancel(DefaultGoPublisher publisher, EnvironmentVariableContext environmentVariableContext, TaskExtension taskExtension) { publisher.taggedConsumeLineWithPrefix(DefaultGoPublisher.CANCEL_TASK_START, "On Cancel Task: " + cancelBuilder.getDescription()); try { cancelBuilder.build(new BuildLogElement(), publisher, environmentVariableContext, taskExtension); publisher.taggedConsumeLineWithPrefix(DefaultGoPublisher.CANCEL_TASK_PASS, "On Cancel Task completed"); } catch (Exception e) { publisher.taggedConsumeLineWithPrefix(DefaultGoPublisher.CANCEL_TASK_FAIL, "On Cancel Task failed"); LOGGER.error("", e); } }
Source:
<code>protected IStatus run(IProgressMonitor monitor) { IStatus status = Status.OK_STATUS; try { SubmoduleWalk walk = SubmoduleWalk.forIndex(repo); boolean refresh = false; <START> while (walk.next()) { <END> for (StagingEntry entry : nodes) { boolean isSubmodule = entry.getPath().equals( walk.getPath()); entry.setSubmodule(isSubmodule); if (isSubmodule) refresh = true; } } if (refresh) stagingView.refreshViewersPreservingExpandedElements(); } catch (IOException e) { status = Activator.createErrorStatus( UIText.StagingViewContentProvider_SubmoduleError, e); } return status; }</code><technical_language>sense check for monitor.isCancelled() in wile loop</technical_language>

Target:
protected IStatus run(IProgressMonitor monitor) { IStatus status = Status.OK_STATUS; try { SubmoduleWalk walk = SubmoduleWalk.forIndex(repo); boolean refresh = false; while (walk.next() && !monitor.isCanceled()) { for (StagingEntry entry : nodes) { boolean isSubmodule = entry.getPath().equals( walk.getPath()); entry.setSubmodule(isSubmodule); if (isSubmodule) refresh = true; } } if (refresh) stagingView.refreshViewersPreservingExpandedElements(); } catch (IOException e) { status = Activator.createErrorStatus( UIText.StagingViewContentProvider_SubmoduleError, e); } return status; }
Source:
<code>public void contextDisposed() { <START> super.contextDisposed(); <END> eventBroker.unsubscribe(itemUpdater); eventBroker.unsubscribe(labelUpdater); eventBroker.unsubscribe(selectionUpdater); eventBroker.unsubscribe(enabledUpdater); eventBroker.unsubscribe(toBeRenderedUpdater); ContextInjectionFactory.uninject(MenuManagerEventHelper.getInstance() .getShowHelper(), context); MenuManagerEventHelper.getInstance().setShowHelper(null); ContextInjectionFactory.uninject( MenuManagerEventHelper.getInstance() .getHideHelper(), context); MenuManagerEventHelper.getInstance().setHideHelper(null); context.remove(MenuManagerRendererFilter.class); Display display = context.get(Display.class); if (display != null && !display.isDisposed() && rendererFilter != null) { display.removeFilter(SWT.Show, rendererFilter); display.removeFilter(SWT.Hide, rendererFilter); display.removeFilter(SWT.Dispose, rendererFilter); } if (rendererFilter != null) { ContextInjectionFactory.uninject(rendererFilter, context); rendererFilter = null; } context.remove(MenuManagerRenderer.class); }</code><technical_language>call super dispose end</technical_language>

Target:
public void contextDisposed() { eventBroker.unsubscribe(itemUpdater); eventBroker.unsubscribe(labelUpdater); eventBroker.unsubscribe(selectionUpdater); eventBroker.unsubscribe(enabledUpdater); eventBroker.unsubscribe(toBeRenderedUpdater); ContextInjectionFactory.uninject(MenuManagerEventHelper.getInstance() .getShowHelper(), context); MenuManagerEventHelper.getInstance().setShowHelper(null); ContextInjectionFactory.uninject( MenuManagerEventHelper.getInstance() .getHideHelper(), context); MenuManagerEventHelper.getInstance().setHideHelper(null); context.remove(MenuManagerRendererFilter.class); Display display = context.get(Display.class); if (display != null && !display.isDisposed() && rendererFilter != null) { display.removeFilter(SWT.Show, rendererFilter); display.removeFilter(SWT.Hide, rendererFilter); display.removeFilter(SWT.Dispose, rendererFilter); } if (rendererFilter != null) { ContextInjectionFactory.uninject(rendererFilter, context); rendererFilter = null; } context.remove(MenuManagerRenderer.class); super.contextDisposed(); }
Source:
<code>public void validateUpdateDatastreams(List<Datastream> datastreams, List<Datastream> allDatastreams) throws DatastreamValidationException { for (Datastream newDatastream : datastreams) { List<Datastream> existingDatastreams = allDatastreams.stream().filter(ds -> ds.getName() .equals(newDatastream.getName())).collect(Collectors.toList()); Validate.isTrue(existingDatastreams.size() == 1, "Bad state: Multiple datastreams exist with the " + "same name " + existingDatastreams); Datastream existingDatastream = existingDatastreams.get(0); if (newDatastream.equals(existingDatastream)) { <START> continue; <END> } if (!doesSourceMatch(newDatastream, existingDatastream) || !doesDestinationMatch(newDatastream, existingDatastream)) { throw new DatastreamValidationException(String.format("Only metadata update is allowed. " + "Source and destination cannot be updated. Old stream: {%s}; New stream: {%s}", existingDatastream, newDatastream)); } if (newDatastream.hasMetadata() && existingDatastream.hasMetadata() && newDatastream.getMetadata().equals(existingDatastream.getMetadata())) { throw new DatastreamValidationException(String.format("Only metadata update is allowed. " + "Old stream: {%s}; New stream: {%s}", existingDatastream, newDatastream)); } } }</code><technical_language>log datastream is skipped of changes</technical_language>

Target:
public void validateUpdateDatastreams(List<Datastream> datastreams, List<Datastream> allDatastreams) throws DatastreamValidationException { for (Datastream newDatastream : datastreams) { List<Datastream> existingDatastreams = allDatastreams.stream().filter(ds -> ds.getName() .equals(newDatastream.getName())).collect(Collectors.toList()); Validate.isTrue(existingDatastreams.size() == 1, "Bad state: Multiple datastreams exist with the " + "same name " + existingDatastreams); Datastream existingDatastream = existingDatastreams.get(0); if (newDatastream.equals(existingDatastream)) { LOG.info(String.format("Skipping update for datastream {%s} due to no change", existingDatastream)); continue; } if (!doesSourceMatch(newDatastream, existingDatastream) || !doesDestinationMatch(newDatastream, existingDatastream)) { throw new DatastreamValidationException(String.format("Only metadata update is allowed. " + "Source and destination cannot be updated. Old stream: {%s}; New stream: {%s}", existingDatastream, newDatastream)); } if (newDatastream.hasMetadata() && existingDatastream.hasMetadata() && newDatastream.getMetadata().equals(existingDatastream.getMetadata())) { throw new DatastreamValidationException(String.format("Only metadata update is allowed. " + "Old stream: {%s}; New stream: {%s}", existingDatastream, newDatastream)); } } }
Source:
<code>public String buildInsertSelective(ProviderContext context) { final String tableName = context.getMapperType().getAnnotation(BaseMapper.Meta.class).tableName(); Map<String, String> columnMap = getColumnMap(context); <START> StringBuffer sqlBuffer = new StringBuffer(); <END> sqlBuffer.append("<script>"); sqlBuffer.append("insert into "); sqlBuffer.append(tableName); sqlBuffer.append("<trim prefix=\"(\" suffix=\")\" suffixOverrides=\",\">"); for (Map.Entry<String, String> entry : columnMap.entrySet()) { sqlBuffer.append("<if test=\"").append(entry.getValue()).append(" != null\">"); sqlBuffer.append(entry.getKey()).append(","); sqlBuffer.append("</if>"); } sqlBuffer.append("</trim>"); sqlBuffer.append("<trim prefix=\"VALUES (\" suffix=\")\" suffixOverrides=\",\">"); for (String field : columnMap.values()) { sqlBuffer.append("<if test=\"").append(field).append(" != null\">"); sqlBuffer.append("#{").append(field).append("} ,"); sqlBuffer.append("</if>"); } sqlBuffer.append("</trim>"); sqlBuffer.append("</script>"); return sqlBuffer.toString(); }</code><technical_language>Please StringBuilder</technical_language>

Target:
public String buildInsertSelective(ProviderContext context) { final String tableName = context.getMapperType().getAnnotation(BaseMapper.Meta.class).tableName(); Map<String, String> columnMap = getColumnMap(context); StringBuilder sqlBuffer = new StringBuilder(); sqlBuffer.append("<script>"); sqlBuffer.append("insert into "); sqlBuffer.append(tableName); sqlBuffer.append("<trim prefix=\"(\" suffix=\")\" suffixOverrides=\",\">"); for (Map.Entry<String, String> entry : columnMap.entrySet()) { sqlBuffer.append("<if test=\"").append(entry.getValue()).append(" != null\">"); sqlBuffer.append(entry.getKey()).append(","); sqlBuffer.append("</if>"); } sqlBuffer.append("</trim>"); sqlBuffer.append("<trim prefix=\"VALUES (\" suffix=\")\" suffixOverrides=\",\">"); for (String field : columnMap.values()) { sqlBuffer.append("<if test=\"").append(field).append(" != null\">"); sqlBuffer.append("#{").append(field).append("} ,"); sqlBuffer.append("</if>"); } sqlBuffer.append("</trim>"); sqlBuffer.append("</script>"); return sqlBuffer.toString(); }
Source:
<code>public List<Comment> getComment(String uuid) throws CommentManagementException{ if (log.isDebugEnabled()) { log.debug("Getting comment with the application release(" +uuid + ") from the database"); } Connection conn; PreparedStatement stmt = null; ResultSet rs ; String sql = ""; List<Comment> comments=new ArrayList<>(); try { conn = this.getDBConnection(); <START> sql += "SELECT COMMENT_TEXT FROM AP_APP_COMMENT WHERE (SELECT ID FROM AP_APP_RELEASE where UUID=?)AND " + <END> "(SELECT AP_APP_ID FROM AP_APP_RELEASE where UUID=?);"; stmt = conn.prepareStatement(sql); stmt.setString(1, uuid); stmt.setString(2,uuid); rs=stmt.executeQuery(); while (rs.next()) { Comment comment=new Comment(); comment.setId(rs.getInt("ID")); comment.setTenantId(rs.getInt("TENANT_ID")); comment.setComment(rs.getString("COMMENT_TEXT")); comment.setCreatedAt(rs.getTimestamp("CREATED_AT")); comment.setCreatedBy(rs.getString("CREATED_BY")); comment.setModifiedAt(rs.getTimestamp("MODEFIED_AT")); comment.setModifiedBy(rs.getString("MODEFIED_AT")); comment.setParent(rs.getInt("PARENT_ID")); comments.add(comment); } } catch (DBConnectionException e) { log.error("DB Connection Exception occurs.", e); } catch (SQLException e) { throw new CommentManagementException("Error occurred while retrieving comments", e); } finally { Util.cleanupResources(stmt, null); } return comments; }</code><technical_language>IMO is need a string concatenation here. initiate string SQL query itself</technical_language>

Target:
public List<Comment> getComment(String uuid) throws CommentManagementException { if (log.isDebugEnabled()) { log.debug("Getting comment with the application release(" + uuid + ") from the database"); } Connection conn; PreparedStatement statement = null; ResultSet rs; List<Comment> comments = new ArrayList<>(); try { conn = this.getDBConnection(); sql = "SELECT COMMENT_TEXT FROM AP_APP_COMMENT WHERE (SELECT ID FROM AP_APP_RELEASE where UUID=?)AND " + "(SELECT AP_APP_ID FROM AP_APP_RELEASE where UUID=?);"; statement = conn.prepareStatement(sql); statement.setString(1, uuid); statement.setString(2, uuid); rs = statement.executeQuery(); while (rs.next()) { Comment comment = new Comment(); comment.setId(rs.getInt("ID")); comment.setTenantId(rs.getInt("TENANT_ID")); comment.setComment(rs.getString("COMMENT_TEXT")); comment.setCreatedAt(rs.getTimestamp("CREATED_AT")); comment.setCreatedBy(rs.getString("CREATED_BY")); comment.setModifiedAt(rs.getTimestamp("MODEFIED_AT")); comment.setModifiedBy(rs.getString("MODEFIED_AT")); comment.setParent(rs.getInt("PARENT_ID")); comments.add(comment); } } catch (DBConnectionException e) { log.error("DB Connection Exception occurred while retrieving comments", e); } catch (SQLException e) { throw new CommentManagementException("SQL Error occurred while retrieving comments", e); } finally { Util.cleanupResources(statement, null); } return comments; }
Source:
<code>protected void cleanTransactionsTable() { LOG.info("cleanTransactionsTable, cleaning CorporateBilledCorporatePaidTransaction table"); <START> businessObjectService.deleteMatching(CorporateBilledCorporatePaidTransaction.class, new HashMap()); <END> }</code><technical_language>Missing generics HashMap</technical_language>

Target:
protected void cleanTransactionsTable() { LOG.info("cleanTransactionsTable, cleaning CorporateBilledCorporatePaidTransaction table"); businessObjectService.deleteMatching(CorporateBilledCorporatePaidTransaction.class, new HashMap<String, String>()); }
Source:
<code>@Override public void run(@Nonnull JSession session) throws Exception { Set<JDefinedClass> classesToEmit = Sets.newHashSet(); for (JDefinedClassOrInterface type : session.getTypesToEmit()) { if (type instanceof JDefinedClass) { classesToEmit.add((JDefinedClass) type); } } State state = new State(); for (JDefinedClass thisClass : classesToEmit) { JClass superClass = thisClass.getSuperClass(); if (!(superClass instanceof JDefinedClass) || !classesToEmit.contains(superClass)) { trackOverridingChains(thisClass, state); } } for (JMethod method : state.effectivelyFinalMethods) { if (!method.isAbstract()) { assert !method.isStatic() && !method.isPrivate() && !(method instanceof JConstructor); EffectivelyFinalMarker.markAsEffectivelyFinal(method); if (!preserveReflections()) { method.setFinal(); <START> tracer.getStatistic(METHODS_FINALIZED).incValue(); <END> } } } }</code><technical_language>Idem for final method</technical_language>

Target:
@Override public void run(@Nonnull JSession session) throws Exception { Set<JDefinedClass> classesToEmit = Sets.newHashSet(); for (JDefinedClassOrInterface type : session.getTypesToEmit()) { if (type instanceof JDefinedClass) { classesToEmit.add((JDefinedClass) type); } } State state = new State(); for (JDefinedClass thisClass : classesToEmit) { JClass superClass = thisClass.getSuperClass(); if (!(superClass instanceof JDefinedClass) || !classesToEmit.contains(superClass)) { trackOverridingChains(thisClass, state); } } for (JMethod method : state.effectivelyFinalMethods) { if (!method.isAbstract() && !method.isFinal()) { assert !method.isStatic() && !method.isPrivate() && !(method instanceof JConstructor); EffectivelyFinalMethodMarker.markAsEffectivelyFinal(method); if (!preserveReflections()) { method.setFinal(); tracer.getStatistic(METHODS_FINALIZED).incValue(); } } } }
Source:
<code>private static void raw(BitstampAccountServiceRaw accountService) throws IOException { BitstampBalance bitstampBalance = accountService.getBitstampBalance(); System.out.println("BitstampBalance: " + bitstampBalance); BitstampDepositAddress depositAddress = accountService.getBitstampBitcoinDepositAddress(); System.out.println("BitstampDepositAddress address: " + depositAddress); accountService.withdrawSepa( new BigDecimal("150"), <START> "Kovin Kostner", <END> "BY13NBRB3600900000002Z00AB00", "DABAIE2D", "Minsk, Belarus, Main street 2", "197372", "Minsk", Country.Belarus.alpha2); accountService.withdrawInternational( new BigDecimal("150"), "Kovin Kostner", "BY13NBRB3600900000002Z00AB00", "DABAIE2D", "Minsk, Belarus, Main street 2", "197372", "Minsk", Country.Belarus.alpha2, "Great Bank", "Great Bank Address", "Great Bank Postal Code", "Great Bank City", "Bank Country Alpha 2 code", BankCurrency.AUD ); }</code><technical_language>some fake data instead here</technical_language>

Target:
private static void raw(BitstampAccountServiceRaw accountService) throws IOException { BitstampBalance bitstampBalance = accountService.getBitstampBalance(); System.out.println("BitstampBalance: " + bitstampBalance); BitstampDepositAddress depositAddress = accountService.getBitstampBitcoinDepositAddress(); System.out.println("BitstampDepositAddress address: " + depositAddress); accountService.withdrawSepa( new BigDecimal("150"), "Test User", "BY13NBRB3600900000002Z00AB00", "DABAIE2D", "Minsk, Belarus, Main street 2", "197372", "Minsk", Country.Belarus.alpha2); accountService.withdrawInternational( new BigDecimal("150"), "Test User", "BY13NBRB3600900000002Z00AB00", "DABAIE2D", "Minsk, Belarus, Main street 2", "197372", "Minsk", Country.Belarus.alpha2, "Great Bank", "Great Bank Address", "Great Bank Postal Code", "Great Bank City", "Bank Country Alpha 2 code", BankCurrency.AUD ); }
Source:
<code>private List<String> getProviderStringList(List<Result> providerList) { List<String> list = new ArrayList<String>(); switch (edit_new) { <START> case 0: <END> list.add("Set Provider"); for (int i = 0; i < providerList.size(); i++) { list.add(providerList.get(i).getDisplay()); } break; case 1: list.add(info.get(1)); for (int i = 0; i < providerList.size(); i++) { list.add(providerList.get(i).getDisplay()); } break; default: list.add("Set Provider"); for (int i = 0; i < providerList.size(); i++) { list.add(providerList.get(i).getDisplay()); } break; } return list; }</code><technical_language>Again, constants nice for readability</technical_language>

Target:
private List<String> getProviderStringList(List<Result> providerList) { List<String> list = new ArrayList<String>(); switch (edit_new) { case "new_form": list.add("Set Provider"); for (int i = 0; i < providerList.size(); i++) { list.add(providerList.get(i).getDisplay()); } break; case "edit_form": list.add(info.get(1)); for (int i = 0; i < providerList.size(); i++) { list.add(providerList.get(i).getDisplay()); } break; default: list.add("Set Provider"); for (int i = 0; i < providerList.size(); i++) { list.add(providerList.get(i).getDisplay()); } break; } return list; }
Source:
<code>private void getUnSyncedEntries(Map<String, Object> map) { Object[] healInfos = (Object[]) map.get(BRICKS); for (Object healInfoObj : healInfos) { Map<String, String> healInfo = (Map<String, String>) healInfoObj; String hostUuid = (String) healInfo.get(HOST_UUID); GlusterServer glusterServer = dbUtils.getServerByUuid(Guid.createGuidFromString(hostUuid)); String brickName = (String) healInfo.get(NAME); String[] brickParts = brickName.split(":", -1); if (brickParts.length != 2) { throw new RuntimeException("Invalid brick representation [" + brickName + "]"); } if (glusterServer == null) { log.warn("Could not fetch heal info for brick '{}' - server uuid '{}' not found", brickName, hostUuid); return; } GlusterBrickEntity brick = dbUtils.getGlusterBrickByServerUuidAndBrickDir(glusterServer.getId(), brickParts[1]); String status = (String) healInfo.get(STATUS); Integer entries = null; <START> if ("Connected".equals(status)) { <END> entries = Integer.valueOf((String) healInfo.get(NO_OF_ENTRIES)); } unSyncedEntries.put(brick.getId(), entries); } }</code><technical_language>values for status? Is unsyncedEntries null indication brick is connected</technical_language>

Target:
private void getUnSyncedEntries(Map<String, Object> map) { Object[] healInfos = (Object[]) map.get(BRICKS); for (Object healInfoObj : healInfos) { Map<String, String> healInfo = (Map<String, String>) healInfoObj; String status = (String) healInfo.get(STATUS); Integer entries = null; if ("Connected".equals(status)) { String hostUuid = (String) healInfo.get(HOST_UUID); GlusterServer glusterServer = dbUtils.getServerByUuid(Guid.createGuidFromString(hostUuid)); String brickName = (String) healInfo.get(NAME); String[] brickParts = brickName.split(":", -1); if (brickParts.length != 2) { throw new RuntimeException("Invalid brick representation [" + brickName + "]"); } if (glusterServer == null) { log.warn("Could not fetch heal info for brick '{}' - server uuid '{}' not found", brickName, hostUuid); return; } GlusterBrickEntity brick = dbUtils.getGlusterBrickByServerUuidAndBrickDir(glusterServer.getId(), brickParts[1]); entries = Integer.valueOf((String) healInfo.get(NO_OF_ENTRIES)); unSyncedEntries.put(brick.getId(), entries); } } }
Source:
<code>private static void addAllLogicalStructures( List<JavaLogicalStructure> pluginContributedJavaLogicalStructures) { for (JavaLogicalStructure <START> javaLogicalStructure : <END> pluginContributedJavaLogicalStructures) { addLogicalStructure(javaLogicalStructure); } }</code><technical_language>consistency: logicalStructure</technical_language>

Target:
private static void addAllLogicalStructures( List<JavaLogicalStructure> pluginContributedJavaLogicalStructures) { for (JavaLogicalStructure logicalStructure : pluginContributedJavaLogicalStructures) { addLogicalStructure(logicalStructure); } }
Source:
<code>private static Stream<Symbol.MethodSymbol> getAllMembers(Symbol.TypeSymbol symbol) { if ("java.lang.Object".equals(symbol.type().fullyQualifiedName())) { return Stream.empty(); } Stream<Symbol.MethodSymbol> members = symbol.memberSymbols().stream().filter(Symbol::isMethodSymbol).map(Symbol.MethodSymbol.class::cast); Type superClass = symbol.superClass(); if (superClass != null) { members = Stream.concat(members, getAllMembers(superClass.symbol())); } Stream<Symbol.MethodSymbol> defaultMethodsFromInterfaces = symbol.interfaces().stream() .flatMap(i -> getAllMembers(i.symbol())) .filter(m -> ((JavaSymbol.MethodJavaSymbol) m).isDefault()); for (Symbol s : symbol.memberSymbols()) { <START> if (s instanceof Symbol.TypeSymbol) { <END> if (s.metadata().isAnnotatedWith("org.junit.jupiter.api.Nested")) { members = Stream.concat(members, getAllMembers((Symbol.TypeSymbol) s)); } } } members = Stream.concat(members, defaultMethodsFromInterfaces); return members; }</code><technical_language>I prefer if s.isTypeSymbol() instead. allow remove instanceof stay simpler usage of semantic API for semantic checking. combine if statements in a single conditions combined &&</technical_language>

Target:
private static Stream<Symbol.MethodSymbol> getAllMembers(Symbol.TypeSymbol symbol) { if ("java.lang.Object".equals(symbol.type().fullyQualifiedName())) { return Stream.empty(); } Stream<Symbol.MethodSymbol> members = symbol.memberSymbols().stream().filter(Symbol::isMethodSymbol).map(Symbol.MethodSymbol.class::cast); Type superClass = symbol.superClass(); if (superClass != null) { members = Stream.concat(members, getAllMembers(superClass.symbol())); } Stream<Symbol.MethodSymbol> defaultMethodsFromInterfaces = symbol.interfaces().stream() .flatMap(i -> getAllMembers(i.symbol())) .filter(m -> ((JavaSymbol.MethodJavaSymbol) m).isDefault()); for (Symbol s : symbol.memberSymbols()) { if (s.isTypeSymbol() && s.metadata().isAnnotatedWith("org.junit.jupiter.api.Nested")) { members = Stream.concat(members, getAllMembers((Symbol.TypeSymbol) s)); } } members = Stream.concat(members, defaultMethodsFromInterfaces); return members; }
Source:
<code>protected AddDiskParameters buildAddDiskParameters(DiskImage image) { image.setVolumeFormat(VolumeFormat.COW); <START> image.setVolumeType(VolumeType.Sparse); <END> AddDiskParameters diskParameters = new AddDiskParameters(image.getDiskVmElementForVm(getVmTemplateId()), image); diskParameters.setStorageDomainId(getParameters().getImageToDestinationDomainMap().get(image.getId())); diskParameters.setParentCommand(getActionType()); diskParameters.setParentParameters(getParameters()); diskParameters.setShouldRemainIllegalOnFailedExecution(true); diskParameters.setEndProcedure(EndProcedure.COMMAND_MANAGED); diskParameters.setUsePassedDiskId(true); diskParameters.setUsePassedImageId(true); return diskParameters; }</code><technical_language>is good for a method change DiskImage. move this createDisk()</technical_language>

Target:
protected AddDiskParameters buildAddDiskParameters(DiskImage image) { AddDiskParameters diskParameters = new AddDiskParameters(image.getDiskVmElementForVm(getVmTemplateId()), image); diskParameters.setStorageDomainId(getParameters().getImageToDestinationDomainMap().get(image.getId())); diskParameters.setParentCommand(getActionType()); diskParameters.setParentParameters(getParameters()); diskParameters.setShouldRemainIllegalOnFailedExecution(true); diskParameters.setEndProcedure(EndProcedure.COMMAND_MANAGED); diskParameters.setUsePassedDiskId(true); diskParameters.setUsePassedImageId(true); return diskParameters; }
Source:
<code>private void perform( Action action ) throws Exception { ExecutorService service = Executors.newFixedThreadPool( lifecycles.size() ); List<Future<?>> futures = new ArrayList<>(); for ( Lifecycle lifecycle : lifecycles ) { futures.add( service.submit( () -> { try { action.act( lifecycle ); } catch ( Throwable e ) { throw new RuntimeException( e ); } } ) ); } service.shutdown(); if ( !service.awaitTermination( timeout, unit ) ) { for ( Future<?> future : futures ) { future.cancel( true ); } } Exception exception = null; for ( Future<?> future : futures ) { try { future.get(); } catch ( InterruptedException | ExecutionException e ) { <START> exception = combine( exception, e ); <END> } } if ( exception != null ) { throw exception; } }</code><technical_language>a bit of NPE's happen of combine exception</technical_language>

Target:
private void perform( Action action ) throws Exception { ExecutorService service = Executors.newFixedThreadPool( lifecycles.size() ); List<Future<?>> futures = new ArrayList<>(); for ( Lifecycle lifecycle : lifecycles ) { futures.add( service.submit( () -> { try { action.act( lifecycle ); } catch ( Throwable e ) { throw new RuntimeException( e ); } } ) ); } service.shutdown(); if ( !service.awaitTermination( timeout, unit ) ) { for ( Future<?> future : futures ) { future.cancel( true ); } } Exception exception = null; for ( Future<?> future : futures ) { try { future.get(); } catch ( InterruptedException | ExecutionException e ) { if ( exception == null ) { exception = new RuntimeException(); } exception.addSuppressed( e ); } } if ( exception != null ) { throw exception; } }
Source:
<code>private void addColumnName(String columnName, boolean updateUI) { <START> JTextField columnNameField = WidgetFactory.createTextField(); <END> if (columnName != null) { columnNameField.setText(columnName); } _innerPanel.add(columnNameField); if (updateUI) { _innerPanel.updateUI(); } }</code><technical_language>final</technical_language>

Target:
private void addColumnName(String columnName, boolean updateUI) { final JTextField columnNameField = WidgetFactory.createTextField(); if (columnName != null) { columnNameField.setText(columnName); } _innerPanel.add(columnNameField); if (updateUI) { _innerPanel.updateUI(); } }
Source:
<code>public void testSampleExtremeMeanCoverage(final List<SampleCoverageStats> sampleStats, final double minMean, final double maxMean) throws IOException { final File samplesFile = createSampleStatsFile(sampleStats); final List<SampleCoverageStats> leftInSamples = sampleStats.stream() .filter(stats -> stats.mean >= minMean && stats.mean <= maxMean) .collect(Collectors.toList()); final List<SampleCoverageStats> leftOutSamples = sampleStats.stream() .filter(stats -> stats.mean < minMean || stats.mean > maxMean) .collect(Collectors.toList()); final File outputFile = createTempFile("output", ".tab"); final File rejectionFile = createTempFile("reject", ".tab"); runCommandLine(new String[] { "-" + StandardArgumentDefinitions.INPUT_SHORT_NAME, samplesFile.getPath(), "-" + StandardArgumentDefinitions.OUTPUT_SHORT_NAME, outputFile.getPath(), "-" + FilterSamples.MINIMUM_MEAN_COVERAGE_SHORT_NAME, String.valueOf(minMean), "-" + FilterSamples.MAXIMUM_MEAN_COVERAGE_SHORT_NAME, String.valueOf(maxMean), "-" + FilterTargets.REJECT_OUTPUT_FILE_SHORT_NAME, rejectionFile.getPath(), }); <START> checkLeftInTargets(leftInSamples, outputFile); <END> checkRejectedTargets(leftOutSamples, rejectionFile, FilterSamples.SampleFilter.ExtremeCoverageMean); }</code><technical_language>I detect some copy-and-paste PR -- wrong that, need Targets --> Samples in a places</technical_language>

Target:
public void testSampleExtremeMeanCoverage(final List<SampleCoverageStats> sampleStats, final double minMean, final double maxMean) throws IOException { final File samplesFile = createSampleStatsFile(sampleStats); final List<SampleCoverageStats> leftInSamples = sampleStats.stream() .filter(stats -> stats.mean >= minMean && stats.mean <= maxMean) .collect(Collectors.toList()); final List<SampleCoverageStats> leftOutSamples = sampleStats.stream() .filter(stats -> stats.mean < minMean || stats.mean > maxMean) .collect(Collectors.toList()); final File outputFile = createTempFile("output", ".tab"); final File rejectionFile = createTempFile("reject", ".tab"); runCommandLine(new String[] { "-" + StandardArgumentDefinitions.INPUT_SHORT_NAME, samplesFile.getPath(), "-" + StandardArgumentDefinitions.OUTPUT_SHORT_NAME, outputFile.getPath(), "-" + FilterSamples.MINIMUM_MEAN_COVERAGE_SHORT_NAME, String.valueOf(minMean), "-" + FilterSamples.MAXIMUM_MEAN_COVERAGE_SHORT_NAME, String.valueOf(maxMean), "-" + FilterSamples.REJECTION_FILE_SHORT_NAME, rejectionFile.getPath(), }); checkLeftInSamples(leftInSamples, outputFile); checkRejectedSamples(leftOutSamples, rejectionFile, FilterSamples.SampleFilter.ExtremeCoverageMean); }
Source:
<code>private void swapHyperLogLogPlus() { if (System.currentTimeMillis() - hyperLogSwapTS.get() > hyperLogLogPlusSwapPeriod && hyperLogSwapLock.compareAndExchange(false, true)) { <START> hyperLog = new HyperLogLogPlus(14, 25); <END> hyperLogSwapTS = new AtomicLong(System.currentTimeMillis()); hyperLogSwapLock.set(false); } }</code><technical_language>i wrong I need a synchronized bit threads new reference. i need this part</technical_language>

Target:
private void swapHyperLogLogPlus() { if (System.currentTimeMillis() - hyperLogSwapTS.get() > hyperLogLogPlusSwapPeriodMS && hyperLogSwapLock.compareAndExchange(false, true)) { hyperLog.set(new HyperLogLogPlus( HYPER_LOG_LOG_PLUS_PRECISION_NORMAL, HYPER_LOG_LOG_PLUS_PRECISION_SPARSE)); hyperLogSwapTS.set(System.currentTimeMillis()); hyperLogSwapLock.set(false); } }
Source:
<code>public StramLocalCluster(LogicalPlan dag) throws IOException, ClassNotFoundException { dag.validate(); cloneLogicalPlan(dag); String pathUri = CLUSTER_WORK_DIR.toURI().toString(); try { FileContext.getLocalFSFileContext().delete(new Path(pathUri ), true); } catch (IllegalArgumentException e) { throw e; } catch (IOException e) { throw new RuntimeException("could not cleanup test dir", e); } dag.getAttributes().put(LogicalPlan.APPLICATION_ID, "app_local_" + System.currentTimeMillis()); if (dag.getAttributes().get(LogicalPlan.APPLICATION_PATH) == null) { dag.getAttributes().put(LogicalPlan.APPLICATION_PATH, pathUri); } StorageAgent agent = dag.getAttributes().get(OperatorContext.STORAGE_AGENT); if (agent != null && agent instanceof AppIdAwareStorageAgent) { AppIdAwareStorageAgent ap = (AppIdAwareStorageAgent)dag.getAttributes().get(OperatorContext.STORAGE_AGENT); ap.saveAppId(dag.getAttributes().get(LogicalPlan.APPLICATION_ID)); <START> dag.setAttribute(OperatorContext.STORAGE_AGENT, ap); <END> } if (dag.getAttributes().get(OperatorContext.STORAGE_AGENT) == null) { dag.setAttribute(OperatorContext.STORAGE_AGENT, new AsyncFSStorageAgent(new Path(pathUri, LogicalPlan.SUBDIR_CHECKPOINTS).toString(), null)); } this.dnmgr = new StreamingContainerManager(dag); this.umbilical = new UmbilicalProtocolLocalImpl(); if (!perContainerBufferServer) { StreamingContainer.eventloop.start(); bufferServer = new Server(0, 1024 * 1024,8); bufferServer.setSpoolStorage(new DiskStorage()); SocketAddress bindAddr = bufferServer.run(StreamingContainer.eventloop); this.bufferServerAddress = ((InetSocketAddress)bindAddr); LOG.info("Buffer server started: {}", bufferServerAddress); } }</code><technical_language>This is needed</technical_language>

Target:
public StramLocalCluster(LogicalPlan dag) throws IOException, ClassNotFoundException { dag.validate(); cloneLogicalPlan(dag); String pathUri = CLUSTER_WORK_DIR.toURI().toString(); try { FileContext.getLocalFSFileContext().delete(new Path(pathUri ), true); } catch (IllegalArgumentException e) { throw e; } catch (IOException e) { throw new RuntimeException("could not cleanup test dir", e); } dag.getAttributes().put(LogicalPlan.APPLICATION_ID, "app_local_" + System.currentTimeMillis()); if (dag.getAttributes().get(LogicalPlan.APPLICATION_PATH) == null) { dag.getAttributes().put(LogicalPlan.APPLICATION_PATH, pathUri); } if (dag.getAttributes().get(OperatorContext.STORAGE_AGENT) == null) { dag.setAttribute(OperatorContext.STORAGE_AGENT, new AsyncFSStorageAgent(new Path(pathUri, LogicalPlan.SUBDIR_CHECKPOINTS).toString(), null)); } this.dnmgr = new StreamingContainerManager(dag); this.umbilical = new UmbilicalProtocolLocalImpl(); if (!perContainerBufferServer) { StreamingContainer.eventloop.start(); bufferServer = new Server(0, 1024 * 1024,8); bufferServer.setSpoolStorage(new DiskStorage()); SocketAddress bindAddr = bufferServer.run(StreamingContainer.eventloop); this.bufferServerAddress = ((InetSocketAddress)bindAddr); LOG.info("Buffer server started: {}", bufferServerAddress); } }
Source:
<code>public void onEvent(@NonNull Action action, @NonNull KubernetesSlave node, @NonNull Pod pod) { String ns = pod.getMetadata().getNamespace(); String name = pod.getMetadata().getName(); List<ContainerStatus> backOffContainers = PodUtils.getContainers(pod, cs -> { ContainerStateWaiting waiting = cs.getState().getWaiting(); return waiting != null && waiting.getMessage() != null && waiting.getMessage().contains("Back-off pulling image"); }); if (backOffContainers.isEmpty()) { return; } backOffContainers.forEach(cs -> { TaskListener runListener = node.getTemplate().getListener(); runListener.error("Unable to pull Docker image \""+cs.getImage()+"\". Check if image tag name is spelled correctly."); }); Queue q = Jenkins.get().getQueue(); String runUrl = pod.getMetadata().getAnnotations().get("runUrl"); for (Queue.Item item: q.getItems()) { if (item.task.getUrl().equals(runUrl)) { q.cancel(item); break; } } try { node.terminate(); <START> } catch (Exception x) { <END> LOGGER.log(Level.WARNING, "failed to reap " + ns + "/" + name, x); } }</code><technical_language>for caller <LINK_0> catch Exception for listener</technical_language>

Target:
public void onEvent(@NonNull Action action, @NonNull KubernetesSlave node, @NonNull Pod pod) throws IOException, InterruptedException { List<ContainerStatus> backOffContainers = PodUtils.getContainers(pod, cs -> { ContainerStateWaiting waiting = cs.getState().getWaiting(); return waiting != null && waiting.getMessage() != null && waiting.getMessage().contains("Back-off pulling image"); }); if (backOffContainers.isEmpty()) { return; } backOffContainers.forEach(cs -> { TaskListener runListener = node.getTemplate().getListener(); runListener.error("Unable to pull Docker image \""+cs.getImage()+"\". Check if image tag name is spelled correctly."); }); Queue q = Jenkins.get().getQueue(); String runUrl = pod.getMetadata().getAnnotations().get("runUrl"); for (Queue.Item item: q.getItems()) { if (item.task.getUrl().equals(runUrl)) { q.cancel(item); break; } } node.terminate(); }
Source:
<code>public void deleteByUnknownId() throws Exception { <START> Cellular3GPPNetwork cellularNetwork = new Cellular3GPPNetwork("name", 359, 55); <END> repository.create(new NewServiceProvider("name1", "Description1", cellularNetwork)); repository.delete(new ID("someID")); List<ServiceProvider> result = repository.findAll(); assertThat(result.size(), is(1)); }</code><technical_language>I a builder in this test (please review others)</technical_language>

Target:
public void deleteByUnknownId() throws Exception { NewServiceProvider provider = newServiceProvider().build(); repository.create(provider); repository.delete(new ID("someID")); List<ServiceProvider> result = repository.findAll(); assertThat(result.size(), is(1)); }
Source:
<code>public void testJSONBeanValueTypes() throws Exception { JSONBean bean = new JSONBean(); StringWriter stringWriter = new StringWriter(); try ( PrintWriter printWriter = new PrintWriter(stringWriter); JSONBean.Writer jsonWriter = bean.open(printWriter)) { jsonWriter.write(getMockMBeanServer(), null, null, false); } <START> final Gson GSON = GsonUtil.createGson().create(); <END> Type typeOfHashMap = new TypeToken<Map<String, Object>>() {}.getType(); Map<String, Object> expectedJson = GSON.fromJson(getExpectedJSON(), typeOfHashMap); Map<String, Object> actualJson = GSON.fromJson(stringWriter.toString(), typeOfHashMap); assertEquals(expectedJson, actualJson); }</code><technical_language>This is a 'public static final' field 'gson' name</technical_language>

Target:
public void testJSONBeanValueTypes() throws Exception { JSONBean bean = new JSONBean(); StringWriter stringWriter = new StringWriter(); try ( PrintWriter printWriter = new PrintWriter(stringWriter); JSONBean.Writer jsonWriter = bean.open(printWriter)) { jsonWriter.write(getMockMBeanServer(), null, null, false); } final Gson gson = GsonUtil.createGson().create(); Type typeOfHashMap = new TypeToken<Map<String, Object>>() {}.getType(); Map<String, Object> expectedJson = gson.fromJson(getExpectedJSON(), typeOfHashMap); Map<String, Object> actualJson = gson.fromJson(stringWriter.toString(), typeOfHashMap); assertEquals(expectedJson, actualJson); }