auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public ImageTemplate buildImageTemplateFromNode(String name, String id) { Droplet droplet = null; try { droplet = api.getDropletApi().get(Integer.valueOf(id)); <START> } catch (Exception ex) { <END> throw new NoSuchElementException("Cannot find droplet with id: " + id); } if (droplet == null) { throw new NoSuchElementException("Cannot find droplet with id: " + id); } return new ImageTemplateBuilder.CloneImageTemplateBuilder().nodeId(id).name(name).build(); }</code><technical_language>Catch a broad exception here</technical_language>

Target:
public ImageTemplate buildImageTemplateFromNode(String name, String id) { Droplet droplet = api.getDropletApi().get(Integer.valueOf(id)); if (droplet == null) { throw new NoSuchElementException("Cannot find droplet with id: " + id); } return new ImageTemplateBuilder.CloneImageTemplateBuilder().nodeId(id).name(name).build(); }
Source:
<code>private StaticAnalysisConfiguration() { List<Preferences.Preference> defaults = new ArrayList<>(Arrays.asList( <START> new Preference("global-enable", "on", Type.BOOLEAN, "This globally enables static analysis. If this is off," <END> + " the static analysis module will not be run, though existing compile errors will still" + " be enabled regardless.", 0) )); prefs = new Preferences(Implementation.GetServerType().getBranding(), Logger.getLogger(StaticAnalysisConfiguration.class.getName()), defaults, "This file controls the static analysis options. As this is a major change, we have" + " provided this configuration file to allow disabling the static analysis entirely," + " or just individual parts, so that in the event you find a bug with your code," + " you do not have to downgrade. Please note that this is a temporary measure in place," + " eventually all static analysis will be a mandatory part of code execution, so if you" + " find bugs, it is essential that you report them before disabling this. Future versions" + " of " + Implementation.GetServerType().getBranding() + " will forcibly reset the" + " configuration you have set here, once known bugs are fixed."); }</code><technical_language>I this is code, change this default "off" for now, change do upgrade routine reset config next version update</technical_language>

Target:
private StaticAnalysisConfiguration() { List<Preferences.Preference> defaults = new ArrayList<>(Arrays.asList( new Preference("global-enable", "off", Type.BOOLEAN, "This globally enables static analysis." + " If this is off, the static analysis module will not be run, though existing compile errors will" + " still be enabled regardless.", 0) )); prefs = new Preferences(Implementation.GetServerType().getBranding(), Logger.getLogger(StaticAnalysisConfiguration.class.getName()), defaults, "This file controls the static analysis options. As this is a major change, we have" + " provided this configuration file to allow disabling the static analysis entirely," + " or just individual parts, so that in the event you find a bug with your code," + " you do not have to downgrade. Please note that this is a temporary measure in place," + " eventually all static analysis will be a mandatory part of code execution, so if you" + " find bugs, it is essential that you report them before disabling this. Future versions" + " of " + Implementation.GetServerType().getBranding() + " will forcibly reset the" + " configuration you have set here, once known bugs are fixed."); }
Source:
<code>@Override protected PluginProvider<?> getPluginProvider(String name){ return new TestAttributeSecurityPluginProvider(name, null, ALLOW_ALL, <START> globalAuth, true, new Consumer<AuthenticationContext>() { <END> @Override public void accept(AuthenticationContext actx) { userAttrs = actx.nodeAttributes(); } }, clientData()); }</code><technical_language>simplify handler lambda</technical_language>

Target:
@Override protected PluginProvider<?> getPluginProvider(String name) { return new TestAuthenticationContextSecurityPluginProvider(name, null, ALLOW_ALL, globalAuth, true, (ctx) -> userAttrs = ctx.nodeAttributes(), clientData()); }
Source:
<code>public void processEvent(final CloudTrailEvent event) { List<String> instanceIds = CloudtrailEventSupport.getInstanceIds(event); for (String instanceId : instanceIds) { String applicationName = getApplicationName(event, instanceId); if (applicationName == null) { return; } RestTemplate restTemplate = new RestTemplate(); ResponseEntity<JsonNode> response = restTemplate.exchange(get( fromHttpUrl(kioApplicationUrl).buildAndExpand( applicationName).toUri()).accept(APPLICATION_JSON).build(), JsonNode.class); if (!response.getStatusCode().is2xxSuccessful()) { <START> LOG.info("Application: is not registered in kio.", applicationName); <END> } } }</code><technical_language>violationstore.save("msg");</technical_language>

Target:
public void processEvent(final CloudTrailEvent event) { List<String> instanceIds = CloudtrailEventSupport.getInstanceIds(event); for (String instanceId : instanceIds) { String applicationName = getApplicationName(event, instanceId); if (applicationName == null) { return; } RestTemplate restTemplate = new RestTemplate(); ResponseEntity<JsonNode> response = restTemplate.exchange(get( fromHttpUrl(kioApplicationUrl).buildAndExpand( applicationName).toUri()).accept(APPLICATION_JSON).build(), JsonNode.class); if (!response.getStatusCode().is2xxSuccessful()) { violationStore.save(format("Application: %s is not registered in kio.",applicationName)); } } }
Source:
<code>public FluentIterable<TYPE> last(int count) {return new LazyFluentIterable<TYPE>() { @Override public Iterator<TYPE> iterator() { return new DecoratingIterator<TYPE>(iterable.iterator()) { int currentIndex = 0; @Override public TYPE computeNext() { List<TYPE> list = new ArrayList<>(); <START> Iterator<TYPE> newIterator = iterable.iterator(); <END> while(newIterator.hasNext()) { list.add(newIterator.next()); } int totalElementsCount = list.size(); int stopIndex = totalElementsCount - count; TYPE candidate = null; while(currentIndex < stopIndex && fromIterator.hasNext()) { currentIndex++; fromIterator.next(); } if(currentIndex >= stopIndex && fromIterator.hasNext()) { candidate = fromIterator.next(); } return candidate; } }; } }; }</code><technical_language>need populate list computeNext(). cache call utilize it. If issues implementing I give a sample</technical_language>

Target:
public FluentIterable<TYPE> last(int count) { return new LazyFluentIterable<TYPE>() { @Override public Iterator<TYPE> iterator() { return new DecoratingIterator<TYPE>(iterable.iterator()) { private int stopIndex; private int totalElementsCount; private List<TYPE> list; private int currentIndex = 0; @Override public TYPE computeNext() { initialize(); TYPE candidate = null; while (currentIndex < stopIndex && fromIterator.hasNext()) { currentIndex++; fromIterator.next(); } if (currentIndex >= stopIndex && fromIterator.hasNext()) { candidate = fromIterator.next(); } return candidate; } private void initialize() { if (list == null) { list = new ArrayList<>(); Iterator<TYPE> newIterator = iterable.iterator(); while (newIterator.hasNext()) { list.add(newIterator.next()); } totalElementsCount = list.size(); stopIndex = totalElementsCount - count; } } }; } }; }
Source:
<code>public static Integer getConceptIdForUnits(String units) { String appDataDir = OpenmrsUtil.getApplicationDataDirectory(); Properties props = new Properties(); String conceptId = null; try { FileInputStream fis = new FileInputStream(appDataDir + System.getProperty("file.separator") + DatabaseUtil.ORDER_ENTRY_UPGRADE_SETTINGS_FILENAME); props.load(fis); for (Map.Entry prop : props.entrySet()) { if (prop.getKey().equals(units)) { conceptId = prop.getValue().toString(); if (conceptId != null) { <START> fis.close(); <END> return Integer.valueOf(conceptId); } else { fis.close(); return null; } } } } catch (NumberFormatException e) { throw new APIException("upgrade.settings.file.invalid.mapping", new Object[] { units, conceptId }, e); } catch (IOException e) { if (e instanceof FileNotFoundException) { throw new APIException("upgrade.settings.unable.find.file", new Object[] { appDataDir }, e); } else { throw new APIException(e); } } throw new APIException("upgrade.settings.file.not.have.mapping", new Object[] { units }); }</code><technical_language>Need close streams in a finally blocks</technical_language>

Target:
public static Integer getConceptIdForUnits(String units) { String appDataDir = OpenmrsUtil.getApplicationDataDirectory(); Properties props = new Properties(); String conceptId = null; try { FileInputStream fis = new FileInputStream(appDataDir + System.getProperty("file.separator") + DatabaseUtil.ORDER_ENTRY_UPGRADE_SETTINGS_FILENAME); props.load(fis); for (Map.Entry prop : props.entrySet()) { if (prop.getKey().equals(units)) { conceptId = prop.getValue().toString(); if (conceptId != null) { return Integer.valueOf(conceptId); } else { return null; } } } fis.close(); } catch (NumberFormatException e) { throw new APIException("upgrade.settings.file.invalid.mapping", new Object[] { units, conceptId }, e); } catch (IOException e) { if (e instanceof FileNotFoundException) { throw new APIException("upgrade.settings.unable.find.file", new Object[] { appDataDir }, e); } else { throw new APIException(e); } } throw new APIException("upgrade.settings.file.not.have.mapping", new Object[] { units }); }
Source:
<code>private void assertWritable() { <START> Assert.isLegal(!hasStyle(widget, SWT.READ_ONLY), "TextBox is read-only"); END> }</code><technical_language>this include check for isEnabled isVisible? SWTBot is supposed grain user, enabled visible state requirements change text</technical_language>

Target:
private void assertWritable() { assertEnabled(); SWTBotAssert.assertVisible(this); Assert.isLegal(!hasStyle(widget, SWT.READ_ONLY), "TextBox is read-only"); }
Source:
<code>public FeatureIterator(final Path inputPath, final FeatureCodec<FEATURE_TYPE, SOURCE> codec) { if (inputPath == null) { throw new IllegalArgumentException("FeatureIterator input file cannot be null"); } this.codec = codec; <START> this.inputPath = Paths.get(codec.getPathToDataFile(inputPath.toUri().toString())); <END> try { if (IOUtil.hasBlockCompressedExtension(inputPath)) { final BlockCompressedInputStream bcs = initIndexableBlockCompressedStream(inputPath); source = (SOURCE) codec.makeIndexableSourceFromStream(bcs); } else { final PositionalBufferedStream ps = initIndexablePositionalStream(inputPath); source = (SOURCE) codec.makeIndexableSourceFromStream(ps); } this.codec.readHeader(source); readNextFeature(); } catch (final IOException e) { throw new TribbleException.InvalidHeader("Error reading header " + e.getMessage()); } }</code><technical_language>ugh... path -> uri -> string -> string -> path do :(</technical_language>

Target:
public FeatureIterator(final Path inputPath, final FeatureCodec<FEATURE_TYPE, SOURCE> codec) { ValidationUtils.nonNull(inputPath, "FeatureIterator input path cannot be null"); this.codec = codec; final String filePath = codec.getPathToDataFile(inputPath.toUri().toString()); try { this.inputPath = IOUtil.getPath(filePath); } catch (final IOException e) { throw new TribbleException("Failed while constructing a FeatureIterator due to a problem converting String to Path", e); } try { if (IOUtil.hasBlockCompressedExtension(this.inputPath)) { final BlockCompressedInputStream bcs = initIndexableBlockCompressedStream(this.inputPath); source = (SOURCE) codec.makeIndexableSourceFromStream(bcs); } else { final PositionalBufferedStream ps = initIndexablePositionalStream(this.inputPath); source = (SOURCE) codec.makeIndexableSourceFromStream(ps); } this.codec.readHeader(source); readNextFeature(); } catch (final IOException e) { throw new TribbleException.InvalidHeader("Error reading header " + e.getMessage()); } }
Source:
<code>public void closeEnvironment() throws IOException { final EC2Environment env = this.mockEnvironment(); <START> env.close(); <END> MatcherAssert.assertThat( env.toString(), Matchers .containsString( "EC2 `instance` instance accessed with Mock for EC2Client" ) ); }</code><technical_language>testing completely separate features of class: 1) closing of environment, 2) converting environment string. separate test methods. This anti-pattern is called "Test all" (<LINK_0></technical_language>

Target:
public void closeEnvironment() throws IOException { final EC2Environment env = this.mockEnvironment(); env.close(); }
Source:
<code>private ICPPEvaluation createOperatorOverloadEvaluation(ICPPFunction overload, IASTNode point, ICPPEvaluation arg1, ICPPEvaluation arg2) { EvalFunctionCall operatorCall; if(overload instanceof ICPPMethod) { EvalMemberAccess opAccess = new EvalMemberAccess(arg1.getType(point), ValueCategory.LVALUE, overload, arg1, false, point); ICPPEvaluation[] args = new ICPPEvaluation[]{opAccess, arg2}; operatorCall = new EvalFunctionCall(args, arg1, point); } else { ICPPASTName name = new CPPASTName(overload.getNameCharArray()); name.setBinding(overload); IASTIdExpression idExpr = new CPPASTIdExpression(name); <START> ICPPEvaluation op = EvalID.create(idExpr); <END> ICPPEvaluation[] args = new ICPPEvaluation[]{op, arg1, arg2}; operatorCall = new EvalFunctionCall(args, null, point); } return operatorCall; }</code><technical_language>mentioned elsewhere, please do invent AST nodes call EvalID.create(). EvalBinding instead</technical_language>

Target:
private ICPPEvaluation createOperatorOverloadEvaluation(ICPPFunction overload, IASTNode point, ICPPEvaluation arg1, ICPPEvaluation arg2) { EvalFunctionCall operatorCall; if(overload instanceof ICPPMethod) { EvalMemberAccess opAccess = new EvalMemberAccess(arg1.getType(point), ValueCategory.LVALUE, overload, arg1, false, point); ICPPEvaluation[] args = new ICPPEvaluation[]{opAccess, arg2}; operatorCall = new EvalFunctionCall(args, arg1, point); } else { EvalBinding op = new EvalBinding(overload, overload.getType(), point); ICPPEvaluation[] args = new ICPPEvaluation[]{op, arg1, arg2}; operatorCall = new EvalFunctionCall(args, null, point); } return operatorCall; }
Source:
<code>public static String authoriseChargeUrlForApplePay(String chargeId) { <START> return "/v1/frontend/charges/{chargeId}/wallets/apple-pay".replace("{chargeId}", chargeId); <END> }</code><technical_language>needs -pay part? repeat other wallets added</technical_language>

Target:
public static String authoriseChargeUrlForApplePay(String chargeId) { return "/v1/frontend/charges/{chargeId}/wallets/apple".replace("{chargeId}", chargeId); }
Source:
<code>public void removeAndRestoreManyLogs() { gaeSimulation.loginAsAdmin("admin"); gaeSimulation.clearLogs(); <START> Instant today = TimeHelper.getInstantDaysOffsetFromNow(0); <END> insertLogMessageAtTimeWithInterval(logMessages.get(LOG_MESSAGE_INDEX_MANY_LOGS), today.toEpochMilli(), LOG_MESSAGE_INTERVAL_MANY_LOGS); }</code><technical_language>delete this variable altogether Instant.now().toEpochMilli() below</technical_language>

Target:
public void removeAndRestoreManyLogs() { gaeSimulation.loginAsAdmin("admin"); gaeSimulation.clearLogs(); insertLogMessageAtTimeWithInterval(logMessages.get(LOG_MESSAGE_INDEX_MANY_LOGS), Instant.now().toEpochMilli(), LOG_MESSAGE_INTERVAL_MANY_LOGS); }
Source:
<code>protected ListenableFuture<Map<Long, Long>> getCommitTimestamps( @Nullable TableReference tableRef, Iterable<Long> startTimestamps, boolean shouldWaitForCommitterToComplete, AsyncTransactionService asyncTransactionService) { if (Iterables.isEmpty(startTimestamps)) { return Futures.immediateFuture(ImmutableMap.of()); } Map<Long, Long> startToCommitTimestamps = Maps.newHashMap(); Set<Long> gets = Sets.newHashSet(); for (Long startTs : startTimestamps) { Long cached = timestampValidationReadCache.getCommitTimestampIfPresent(startTs); if (cached != null) { startToCommitTimestamps.put(startTs, cached); } else { gets.add(startTs); } } if (gets.isEmpty()) { return Futures.immediateFuture(startToCommitTimestamps); } if (shouldWaitForCommitterToComplete) { waitForCommitterToComplete(tableRef, startTimestamps); } traceGetCommitTimestamps(tableRef, gets); if (gets.size() > transactionConfig.get().getThresholdForLoggingLargeNumberOfTransactionLookups()) { logLargeNumberOfTransactions(tableRef, gets); } getCounter(AtlasDbMetricNames.NUMBER_OF_TRANSACTIONS_READ_FROM_DB, tableRef).inc(gets.size()); <START> <END> return Futures.transform(loadCommitTimestamps(asyncTransactionService, gets), rawResults -> { for (Map.Entry<Long, Long> e : rawResults.entrySet()) { if (e.getValue() != null) { Long startTs = e.getKey(); Long commitTs = e.getValue(); startToCommitTimestamps.put(startTs, commitTs); timestampValidationReadCache.putAlreadyCommittedTransaction(startTs, commitTs); } } return startToCommitTimestamps; }, MoreExecutors.directExecutor()); }</code><technical_language>switch counter</technical_language>

Target:
protected ListenableFuture<Map<Long, Long>> getCommitTimestamps( @Nullable TableReference tableRef, Iterable<Long> startTimestamps, boolean shouldWaitForCommitterToComplete, AsyncTransactionService asyncTransactionService) { if (Iterables.isEmpty(startTimestamps)) { return Futures.immediateFuture(ImmutableMap.of()); } Map<Long, Long> startToCommitTimestamps = Maps.newHashMap(); Set<Long> gets = Sets.newHashSet(); for (Long startTs : startTimestamps) { Long cached = timestampValidationReadCache.getCommitTimestampIfPresent(startTs); if (cached != null) { startToCommitTimestamps.put(startTs, cached); } else { gets.add(startTs); } } if (gets.isEmpty()) { return Futures.immediateFuture(startToCommitTimestamps); } if (shouldWaitForCommitterToComplete) { waitForCommitterToComplete(tableRef, startTimestamps); } traceGetCommitTimestamps(tableRef, gets); if (gets.size() > transactionConfig.get().getThresholdForLoggingLargeNumberOfTransactionLookups()) { logLargeNumberOfTransactions(tableRef, gets); } getHistogram(AtlasDbMetricNames.NUMBER_OF_TRANSACTIONS_READ_FROM_DB, tableRef).update(gets.size()); return Futures.transform(loadCommitTimestamps(asyncTransactionService, gets), rawResults -> { for (Map.Entry<Long, Long> e : rawResults.entrySet()) { if (e.getValue() != null) { Long startTs = e.getKey(); Long commitTs = e.getValue(); startToCommitTimestamps.put(startTs, commitTs); timestampValidationReadCache.putAlreadyCommittedTransaction(startTs, commitTs); } } return startToCommitTimestamps; }, MoreExecutors.directExecutor()); }
Source:
<code>private void compute() { log.trace("Start compute continuous {}", summary.variable.getName()); double variance = summary.descriptiveStats.getVariance(); if(Double.isNaN(variance) || Double.isInfinite(variance) || variance <= 0) return; IntervalFrequency intervalFrequency = new IntervalFrequency(summary.descriptiveStats.getMin(), summary.descriptiveStats.getMax(), summary.intervals, summary.getVariable().getValueType() == IntegerType.get()); for(double d : summary.descriptiveStats.getSortedValues()) { intervalFrequency.add(d); } for(IntervalFrequency.Interval interval : intervalFrequency.intervals()) { summary.intervalFrequencies.add(interval); } RealDistribution realDistribution = summary.distribution.getDistribution(summary.descriptiveStats); for(Double p : summary.defaultPercentiles) { summary.percentiles.add(summary.descriptiveStats.getPercentile(p)); if(realDistribution != null) { summary.distributionPercentiles.add(realDistribution.inverseCumulativeProbability(p / 100d)); } } Iterator<String> concat = freqNames(summary.frequencyDist); while(concat.hasNext()) { String value = concat.next(); summary.frequencies.add(new Frequency(value, summary.frequencyDist.getCount(value), Double.isNaN(summary.frequencyDist.getPct(value)) ? 0.0 : summary.frequencyDist.getPct(value), <START> !value.equals(NOT_NULL_NAME))); <END> } }</code><technical_language>Flip equals in case of null value: NOT_NULL_NAME.equals(value)</technical_language>

Target:
private void compute() { log.trace("Start compute continuous {}", summary.variable.getName()); double variance = summary.descriptiveStats.getVariance(); if(Double.isNaN(variance) || Double.isInfinite(variance) || variance <= 0) return; IntervalFrequency intervalFrequency = new IntervalFrequency(summary.descriptiveStats.getMin(), summary.descriptiveStats.getMax(), summary.intervals, summary.getVariable().getValueType() == IntegerType.get()); for(double d : summary.descriptiveStats.getSortedValues()) { intervalFrequency.add(d); } for(IntervalFrequency.Interval interval : intervalFrequency.intervals()) { summary.intervalFrequencies.add(interval); } RealDistribution realDistribution = summary.distribution.getDistribution(summary.descriptiveStats); for(Double p : summary.defaultPercentiles) { summary.percentiles.add(summary.descriptiveStats.getPercentile(p)); if(realDistribution != null) { summary.distributionPercentiles.add(realDistribution.inverseCumulativeProbability(p / 100d)); } } Iterator<String> concat = freqNames(summary.frequencyDist); while(concat.hasNext()) { String value = concat.next(); summary.frequencies.add(new Frequency(value, summary.frequencyDist.getCount(value), Double.isNaN(summary.frequencyDist.getPct(value)) ? 0.0 : summary.frequencyDist.getPct(value), !NOT_NULL_NAME.equals(value))); } }
Source:
<code>private static int getInCoreLimit(Config config) { return config.getInt( ConfigConstants.CONFIG_MERGE_SECTION, ConfigConstants.CONFIG_KEY_IN_CORE_LIMIT, <START> 10); <END> }</code><technical_language>This 10 << 20 default is 10 MiB. allows users configuration standard suffix units e.g.: [merge] inCoreLimit = 10m for a 10 MiB limit</technical_language>

Target:
private static int getInCoreLimit(Config config) { return config.getInt( ConfigConstants.CONFIG_MERGE_SECTION, ConfigConstants.CONFIG_KEY_IN_CORE_LIMIT, 10 << 20); }
Source:
<code>public String getQuestionResultStatisticsCsv( List<FeedbackResponseAttributes> responses, FeedbackQuestionAttributes question, FeedbackSessionResultsBundle bundle) { if (responses.isEmpty()) { return ""; } StringBuilder csv = new StringBuilder(); csv.append(getResponseSummaryStatsCsv(responses, bundle)); if (hasAssignedWeights) { <START> csv.append(System.lineSeparator()); <END> csv.append("Per Recipient Statistics").append(System.lineSeparator()); csv.append(getPerRecipientResponseStatsCsv(responses, bundle)); } return csv.toString(); }</code><technical_language>chain? csv.append(xxxx) .append(xxxx) .append(xxxx)</technical_language>

Target:
public String getQuestionResultStatisticsCsv( List<FeedbackResponseAttributes> responses, FeedbackQuestionAttributes question, FeedbackSessionResultsBundle bundle) { if (responses.isEmpty()) { return ""; } StringBuilder csv = new StringBuilder(); McqStatistics mcqStats = new McqStatistics(this); csv.append(mcqStats.getResponseSummaryStatsCsv(responses, bundle)); if (hasAssignedWeights) { csv.append(System.lineSeparator()) .append("Per Recipient Statistics").append(System.lineSeparator()) .append(mcqStats.getPerRecipientResponseStatsCsv(responses, bundle)); } return csv.toString(); }
Source:
<code>public final Object[] getChildren(Object element) { final Object[] children; if (element instanceof CompareInputAdapter) { <START> children = getCompareInputAdapterChildren((CompareInputAdapter)element); <END> } else if (element instanceof ICompareInput) { children = new Object[] {}; } else { children = super.getChildren(element); } Iterable<?> compareInputs = adapt(children, getAdapterFactory(), ICompareInput.class); return toArray(compareInputs, Object.class); }</code><technical_language>change this. getTarget this is do in getCompareInputAdapterChildren method</technical_language>

Target:
public final synchronized Object[] getChildren(Object element) { final Object[] children; if (element instanceof CompareInputAdapter) { children = getCompareInputAdapterChildren((CompareInputAdapter)element); } else if (element instanceof ICompareInput) { children = new Object[] {}; } else { children = super.getChildren(element); } final Object[] compareInputChildren; if (!Iterables.all(Arrays.asList(children), Predicates.instanceOf(PendingUpdateAdapter.class))) { Iterable<?> compareInputs = adapt(children, getAdapterFactory(), ICompareInput.class); compareInputChildren = toArray(compareInputs, Object.class); } else { compareInputChildren = children; } return compareInputChildren; }
Source:
<code><START> public void testRequestsWithContent() throws Exception { <END> HttpClient mockClient = mock(HttpClient.class); HttpResponse mockResponse = mock(HttpResponse.class); when(mockClient.execute(any(HttpUriRequest.class))).thenReturn(mockResponse); ApacheHttpTransport transport = new ApacheHttpTransport(mockClient); subtestUnsupportedRequestsWithContent( transport.buildRequest("GET", "<LINK_0>"), "GET"); subtestUnsupportedRequestsWithContent( transport.buildRequest("DELETE", "<LINK_0>"), "DELETE"); subtestUnsupportedRequestsWithContent( transport.buildRequest("HEAD", "<LINK_0>"), "HEAD"); execute(transport.buildRequest("PATCH", "<LINK_0>")); execute(transport.buildRequest("PUT", "<LINK_0>")); execute(transport.buildRequest("POST", "<LINK_0>")); execute(transport.buildRequest("PATCH", "<LINK_0>")); }</code><technical_language>Personally I prefer explicit exceptions a test throw</technical_language>

Target:
public void testRequestsWithContent() throws IOException { HttpClient mockClient = mock(HttpClient.class); HttpResponse mockResponse = mock(HttpResponse.class); when(mockClient.execute(any(HttpUriRequest.class))).thenReturn(mockResponse); ApacheHttpTransport transport = new ApacheHttpTransport(mockClient); subtestUnsupportedRequestsWithContent( transport.buildRequest("GET", "<LINK_0>"), "GET"); subtestUnsupportedRequestsWithContent( transport.buildRequest("DELETE", "<LINK_0>"), "DELETE"); subtestUnsupportedRequestsWithContent( transport.buildRequest("HEAD", "<LINK_0>"), "HEAD"); execute(transport.buildRequest("PATCH", "<LINK_0>")); execute(transport.buildRequest("PUT", "<LINK_0>")); execute(transport.buildRequest("POST", "<LINK_0>")); execute(transport.buildRequest("PATCH", "<LINK_0>")); }
Source:
<code>public void handleRequests(Request request) throws InterruptedException { try { logger.trace("{}", request); DataInputStream stream = new DataInputStream(request.getInputStream()); RequestResponseType type = RequestResponseType.values()[stream.readShort()]; switch (type) { case PutRequest: handlePutRequest(request); break; case GetRequest: handleGetRequest(request); break; case DeleteRequest: handleDeleteRequest(request); break; case TTLRequest: handleTTLRequest(request); break; case ReplicaMetadataRequest: handleReplicaMetadataRequest(request); break; default: throw new UnsupportedOperationException("Request type not supported"); } } catch (Exception e) { <START> e.printStackTrace(); <END> logger.error("Error while handling request" + request + "Closing connection", e); requestResponseChannel.closeConnection(request); } }</code><technical_language>Remove debugging output</technical_language>

Target:
public void handleRequests(Request request) throws InterruptedException { try { logger.trace("{}", request); DataInputStream stream = new DataInputStream(request.getInputStream()); RequestResponseType type = RequestResponseType.values()[stream.readShort()]; switch (type) { case PutRequest: handlePutRequest(request); break; case GetRequest: handleGetRequest(request); break; case DeleteRequest: handleDeleteRequest(request); break; case TTLRequest: handleTTLRequest(request); break; case ReplicaMetadataRequest: handleReplicaMetadataRequest(request); break; default: throw new UnsupportedOperationException("Request type not supported"); } } catch (Exception e) { logger.error("Error while handling request" + request + "Closing connection", e); requestResponseChannel.closeConnection(request); } }
Source:
<code>public void load() { if (CoreModule.user.isSystemAdministrator() || CoreModule.user.hasGroupAccess(GateLabConstants.GROUP_GATELAB)) { for(String GateLabClass:ApplicationModule.reservedGateClasses){ CoreModule.addApplicationsTileGrid(new GateLabTileGrid(GateLabClass)); } } if (CoreModule.user.isSystemAdministrator() || CoreModule.user.hasGroupAccess(GateLabConstants.GROUP_GATELABTEST)) { <START> for(String GateLabClass:ApplicationModule.reservedTestClasses){ <END> CoreModule.addApplicationsTileGrid(new GateLabTileGrid(GateLabClass)); } } TimelineParser.getInstance().addParser(new GateLabTimelineParser()); MonitorParser.getInstance().addParser(new GateLabMonitorParser()); }</code><technical_language>This solution works for 2 GATE classes, is ad-hoc. I do following: for(String GateLabClass:ApplicationModule.reservedGateClasses){ // Check groups access GateLabClass. // Check if user access of groups. If yes, addApplicationsTileGrid. } In this way, GateLabConstants.GROUP_GATELAB\* necessary more. way, GateLabClass capitalized a class name</technical_language>

Target:
public void load() { if (CoreModule.user.isSystemAdministrator() || CoreModule.user.hasGroupAccess(GateLabConstants.GROUP_GATELAB)) { for(String GateLabClass:ApplicationModule.reservedClasses.keySet()){ if(ApplicationModule.reservedClasses.get(GateLabClass)==0){ CoreModule.addApplicationsTileGrid(new GateLabTileGrid(GateLabClass)); } } } if (CoreModule.user.isSystemAdministrator() || CoreModule.user.hasGroupAccess(GateLabConstants.GROUP_GATELABTEST)) { for(String GateLabClass:ApplicationModule.reservedClasses.keySet()){ if(ApplicationModule.reservedClasses.get(GateLabClass)==1){ CoreModule.addApplicationsTileGrid(new GateLabTileGrid(GateLabClass)); } } } TimelineParser.getInstance().addParser(new GateLabTimelineParser()); MonitorParser.getInstance().addParser(new GateLabMonitorParser()); }
Source:
<code>public void testSizeLimitReachWaits() throws InterruptedException { ExecutorService pool = Executors.newCachedThreadPool(); try { ResourceLimiter resourceLimiter = new ResourceLimiter(1l, 1); final RpcThrottler underTest = new RpcThrottler(resourceLimiter); long id = underTest.registerOperationWithHeapSize(5l); assertTrue(underTest.hasInflightRequests()); assertTrue(resourceLimiter.isFull()); final CountDownLatch secondRequestRegisteredLatch = new CountDownLatch(1); pool.submit(new Runnable() { @Override public void run() { try { underTest.registerOperationWithHeapSize(5l); secondRequestRegisteredLatch.countDown(); } catch (InterruptedException e) { throw new RuntimeException(e); } } }); Thread.sleep(10); assertEquals(1, secondRequestRegisteredLatch.getCount()); resourceLimiter.markCanBeCompleted(id); <START> secondRequestRegisteredLatch.await(1, TimeUnit.MINUTES); <END> } finally { pool.shutdownNow(); } }</code><technical_language>do assertTrue(secondRequestRegisteredLatch.await(1, TimeUnit.MINUTES))</technical_language>

Target:
public void testSizeLimitReachWaits() throws InterruptedException { ExecutorService pool = Executors.newCachedThreadPool(); try { ResourceLimiter resourceLimiter = new ResourceLimiter(1l, 1); final RpcThrottler underTest = new RpcThrottler(resourceLimiter); long id = underTest.registerOperationWithHeapSize(5l); assertTrue(underTest.hasInflightRequests()); assertTrue(resourceLimiter.isFull()); final CountDownLatch secondRequestRegisteredLatch = new CountDownLatch(1); pool.submit(new Runnable() { @Override public void run() { try { underTest.registerOperationWithHeapSize(5l); secondRequestRegisteredLatch.countDown(); } catch (InterruptedException e) { throw new RuntimeException(e); } } }); Thread.sleep(10); assertEquals(1, secondRequestRegisteredLatch.getCount()); resourceLimiter.markCanBeCompleted(id); assertTrue(secondRequestRegisteredLatch.await(1, TimeUnit.MINUTES)); } finally { pool.shutdownNow(); } }
Source:
<code>public void testBroadcastWithMaintenance() { final ForeverBroadcastDistributionRule rule = new ForeverBroadcastDistributionRule(ImmutableList.of("large_source")); CoordinatorStats stats = rule.run( null, DruidCoordinatorRuntimeParams.newBuilder() .withDruidCluster(secondCluster) .withSegmentReplicantLookup(SegmentReplicantLookup.make(secondCluster)) .withBalancerReferenceTimestamp(DateTimes.of("2013-01-01")) <START> .withAvailableSegments(Lists.newArrayList( <END> smallSegment, largeSegments.get(0), largeSegments.get(1) )).build(), smallSegment ); assertEquals(1L, stats.getGlobalStat(LoadRule.ASSIGNED_COUNT)); assertEquals(false, stats.hasPerTierStats()); assertEquals(1, generalServer.getPeon().getSegmentsToLoad().size()); assertEquals(1, maintenanceServer1.getPeon().getSegmentsToDrop().size()); assertEquals(0, maintenanceServer2.getPeon().getSegmentsToLoad().size()); }</code><technical_language>add withAvailableSegments(DataSegment... segments) method for convenience</technical_language>

Target:
public void testBroadcastWithMaintenance() { final ForeverBroadcastDistributionRule rule = new ForeverBroadcastDistributionRule(ImmutableList.of("large_source")); CoordinatorStats stats = rule.run( null, DruidCoordinatorRuntimeParams.newBuilder() .withDruidCluster(secondCluster) .withSegmentReplicantLookup(SegmentReplicantLookup.make(secondCluster)) .withBalancerReferenceTimestamp(DateTimes.of("2013-01-01")) .withAvailableSegments( smallSegment, largeSegments.get(0), largeSegments.get(1) ).build(), smallSegment ); assertEquals(1L, stats.getGlobalStat(LoadRule.ASSIGNED_COUNT)); assertEquals(false, stats.hasPerTierStats()); assertEquals(1, generalServer.getPeon().getSegmentsToLoad().size()); assertEquals(1, maintenanceServer1.getPeon().getSegmentsToDrop().size()); assertEquals(0, maintenanceServer2.getPeon().getSegmentsToLoad().size()); }
Source:
<code>private static void printStream(InputStream in) throws Exception { byte[] buffer = new byte[1024]; try { for (int i = in.read(buffer); i != -1; i = in.read(buffer)) System.err.write(buffer, 0, i); } finally { <START> in.close(); <END> } }</code><technical_language>closing in this method instead of caller do it</technical_language>

Target:
private static void printStream(InputStream in) throws Exception { byte[] buffer = new byte[1024]; for (int i = in.read(buffer); i != -1; i = in.read(buffer)) System.err.write(buffer, 0, i); }
Source:
<code>private void sendResource(JarFile jar, JarEntry entry, ResourceKey key, HttpServletResponse res) throws IOException { byte[] data = null; if (entry.getSize() <= SMALL_RESOURCE) { data = readWholeEntry(jar, entry); } String contentType = null; String charEnc = null; Attributes atts = entry.getAttributes(); if (atts != null) { contentType = Strings.emptyToNull(atts.getValue("Content-Type")); charEnc = Strings.emptyToNull(atts.getValue("Character-Encoding")); } if (contentType == null) { contentType = mimeUtil.getMimeType(entry.getName(), data).toString(); if ("application/octet-stream".equals(contentType) && entry.getName().endsWith(".js")) { contentType = "application/javascript"; } } long time = entry.getTime(); if (0 < time) { res.setDateHeader("Last-Modified", time); } res.setHeader("Content-Length", Long.toString(entry.getSize())); res.setContentType(contentType); if (charEnc != null) { res.setCharacterEncoding(charEnc); } if (data != null) { resourceCache.put(key, new SmallResource(data) .setContentType(contentType) .setCharacterEncoding(charEnc) .setLastModified(time)); res.getOutputStream().write(data); } else { <START> InputStream in = jar.getInputStream(entry); <END> writeToResponse(res, in); } }</code><technical_language>inline variable here</technical_language>

Target:
private void sendResource(JarFile jar, JarEntry entry, ResourceKey key, HttpServletResponse res) throws IOException { byte[] data = null; if (entry.getSize() <= SMALL_RESOURCE) { data = readWholeEntry(jar, entry); } String contentType = null; String charEnc = null; Attributes atts = entry.getAttributes(); if (atts != null) { contentType = Strings.emptyToNull(atts.getValue("Content-Type")); charEnc = Strings.emptyToNull(atts.getValue("Character-Encoding")); } if (contentType == null) { contentType = mimeUtil.getMimeType(entry.getName(), data).toString(); if ("application/octet-stream".equals(contentType) && entry.getName().endsWith(".js")) { contentType = "application/javascript"; } } long time = entry.getTime(); if (0 < time) { res.setDateHeader("Last-Modified", time); } res.setHeader("Content-Length", Long.toString(entry.getSize())); res.setContentType(contentType); if (charEnc != null) { res.setCharacterEncoding(charEnc); } if (data != null) { resourceCache.put(key, new SmallResource(data) .setContentType(contentType) .setCharacterEncoding(charEnc) .setLastModified(time)); res.getOutputStream().write(data); } else { writeToResponse(res, jar.getInputStream(entry)); } }
Source:
<code>public void expressionListVerifyResultTest() { String expressionCollectionJsonString = new TextNode("JsonText").toString(); <START> expressionEvaluator.verifyResult(expressionCollectionJsonString, new ArrayList<>(), null); <END> }</code><technical_language>please Collections.empyList()</technical_language>

Target:
public void expressionListVerifyResultTest() { String expressionCollectionJsonString = new TextNode("10").toString(); List<BigDecimal> contextValue = Collections.singletonList(BigDecimal.valueOf(10)); assertTrue(expressionEvaluator.verifyResult(expressionCollectionJsonString, contextValue, List.class)); }
Source:
<code>public String rewriteQuery(Query query) { Integer maxRows = query.getMaxRows(); Integer firstRow = query.getFirstRow(); if(firstRow != null && firstRow > 1) { if(query.getOrderByClause().getItemCount() == 0) { throw new MetaModelException("OFFSET requires an ORDER BY clause"); } } if (maxRows == null && (firstRow == null || firstRow.intValue() == 1)) { return super.rewriteQuery(query); } if ((firstRow == null || firstRow.intValue() == 1) && maxRows != null && maxRows > 0) { return super.rewriteQuery(query) + " LIMIT " + maxRows; } final Query innerQuery = query.clone(); innerQuery.setFirstRow(null); innerQuery.setMaxRows(null); final Query outerQuery = new Query(); final FromItem subQuerySelectItem = new FromItem(innerQuery).setAlias("metamodel_subquery"); outerQuery.from(subQuerySelectItem); final List<SelectItem> innerSelectItems = innerQuery.getSelectClause().getItems(); for (SelectItem selectItem : innerSelectItems) { outerQuery.select(new SelectItem(selectItem, subQuerySelectItem)); } final String rewrittenOrderByClause = rewriteOrderByClause(innerQuery, innerQuery.getOrderByClause()); <START> final String rowOver = "ROW_NUMBER() " + "OVER(" + rewrittenOrderByClause + ")"; <END> innerQuery.select(new SelectItem(rowOver, "metamodel_row_number")); innerQuery.getOrderByClause().removeItems(); final String baseQueryString = rewriteQuery(outerQuery); if (maxRows == null) { return baseQueryString + " WHERE metamodel_row_number > " + (firstRow - 1); } return baseQueryString + " WHERE metamodel_row_number BETWEEN " + firstRow + " AND " + (firstRow - 1 + maxRows); }</code><technical_language>need for " + " part here</technical_language>

Target:
public String rewriteQuery(Query query) { Integer maxRows = query.getMaxRows(); Integer firstRow = query.getFirstRow(); if (maxRows == null && (firstRow == null || firstRow.intValue() == 1)) { return super.rewriteQuery(query); } if ((firstRow == null || firstRow.intValue() == 1) && maxRows != null && maxRows > 0) { return super.rewriteQuery(query) + " LIMIT " + maxRows; } else { return getRowNumberSql(query, maxRows, firstRow); } }
Source:
<code>private void updateExpiryTimeForAllPuts(List<IndexEntry> indexEntries) throws StoreException { for (IndexEntry entry : indexEntries) { IndexValue entryValue = entry.getValue(); if (!entryValue.isFlagSet(IndexValue.Flags.Ttl_Update_Index) && !entryValue.isFlagSet( IndexValue.Flags.Delete_Index)) { IndexValue indexValue = index.findKey(entry.getKey()); if (indexValue != null) { entryValue.setExpiresAtMs(indexValue.getExpiresAtMs()); } else { <START> logger.info("No index value found for {}", entry.getKey().getID()); <END> } } } }</code><technical_language>I in case PUT is updating Ttl for key. worth a warn here</technical_language>

Target:
private void updateExpiryTimeForAllPuts(List<IndexEntry> indexEntries) throws StoreException { for (IndexEntry entry : indexEntries) { IndexValue entryValue = entry.getValue(); if (!entryValue.isFlagSet(IndexValue.Flags.Ttl_Update_Index) && !entryValue.isFlagSet( IndexValue.Flags.Delete_Index)) { IndexValue indexValue = index.findKey(entry.getKey()); if (indexValue != null) { entryValue.setExpiresAtMs(indexValue.getExpiresAtMs()); } else { logger.warn("No index value found for {}", entry.getKey().getID()); } } } }
Source:
<code>public void gatewayDiagnosticsOnException() throws CosmosClientException { CosmosItemProperties cosmosItemProperties = getCosmosItemProperties(); CosmosItemResponse createResponse = null; try { createResponse = this.container.createItem(cosmosItemProperties); CosmosItemRequestOptions cosmosItemRequestOptions = new CosmosItemRequestOptions(); cosmosItemRequestOptions.setPartitionKey(new PartitionKey("wrongPartitionKey")); CosmosItemResponse readResponse = this.container.getItem(createResponse.getItem().getId(), null).read(cosmosItemRequestOptions); fail("request should fail as partition key is wrong"); } catch (CosmosClientException exception) { String diagnostics = exception.getCosmosResponseDiagnostics().toString(); assertThat(exception.getStatusCode()).isEqualTo(HttpConstants.StatusCodes.NOTFOUND); assertThat(diagnostics).contains("Connection Mode : " + ConnectionMode.GATEWAY); assertThat(diagnostics).contains("Gateway statistics"); assertThat(diagnostics).contains("Status Code : 404"); assertThat(diagnostics).contains("Operation Type : " + OperationType.Read); assertThat(exception.getCosmosResponseDiagnostics().getRequestLatency()).isNotNull(); <START> System.out.println(diagnostics); <END> } }</code><technical_language>please logger in test system.out</technical_language>

Target:
public void gatewayDiagnosticsOnException() throws CosmosClientException { CosmosItemProperties cosmosItemProperties = getCosmosItemProperties(); CosmosItemResponse createResponse = null; try { createResponse = this.container.createItem(cosmosItemProperties); CosmosItemRequestOptions cosmosItemRequestOptions = new CosmosItemRequestOptions(); cosmosItemRequestOptions.setPartitionKey(new PartitionKey("wrongPartitionKey")); CosmosItemResponse readResponse = this.container.getItem(createResponse.getItem().getId(), null).read(cosmosItemRequestOptions); fail("request should fail as partition key is wrong"); } catch (CosmosClientException exception) { String diagnostics = exception.getCosmosResponseDiagnostics().toString(); assertThat(exception.getStatusCode()).isEqualTo(HttpConstants.StatusCodes.NOTFOUND); assertThat(diagnostics).contains("Connection Mode : " + ConnectionMode.GATEWAY); assertThat(diagnostics).contains("Gateway statistics"); assertThat(diagnostics).contains("Status Code : 404"); assertThat(diagnostics).contains("Operation Type : " + OperationType.Read); assertThat(exception.getCosmosResponseDiagnostics().getRequestLatency()).isNotNull(); } }
Source:
<code>public void propertyChange(PropertyChangeEvent evt) { <START> if(evt.getPropertyName().equals(switchToOrFromIOCLogProperty)) { <END> start(); } }</code><technical_language>suggestion if(Objects.equals(evt.getPropertyName(), switchToOrFromIOCLogProperty)) { in case evt.getPropertyName() returns null want crash</technical_language>

Target:
public void propertyChange(PropertyChangeEvent evt) { if(Objects.equals(evt.getPropertyName(), switchToOrFromIOCLogProperty)) { start(); } }
Source:
<code>protected void doStart() throws Exception { super.doStart(); if (configuration.isWebhookAutoRegister()) { <START> log.info("Registering webhook for endpoint " + delegateEndpoint); <END> delegateEndpoint.registerWebhook(); } }</code><technical_language>{} syntax for logging</technical_language>

Target:
protected void doStart() throws Exception { super.doStart(); if (configuration.isWebhookAutoRegister()) { log.info("Registering webhook for endpoint {}", delegateEndpoint); delegateEndpoint.registerWebhook(); } }
Source:
<code>public Run getLastRun() { Run lastRun = null; for (Run thisRun : getRuns()) { <START> if (thisRun == null) continue; <END> if (lastRun == null) { lastRun = thisRun; } else if (thisRun.getStatus() != null && thisRun.getStatus().getStartDate().after(lastRun.getStatus().getStartDate())) { lastRun = thisRun; } } return lastRun; }</code><technical_language>nulls a lot of collections in MISO... :worried:</technical_language>

Target:
public Run getLastRun() { Run lastRun = null; for (Run thisRun : getRuns()) { if (lastRun == null) { lastRun = thisRun; } else if (lastRun.getStatus().getStartDate() == null && thisRun.getStatus().getStartDate() == null) { if (thisRun.getLastUpdated().after(lastRun.getLastUpdated())) lastRun = thisRun; } else if (lastRun.getStatus().getStartDate() == null && thisRun.getStatus().getStartDate() != null) { lastRun = thisRun; } else if (lastRun.getStatus().getStartDate() != null && thisRun.getStatus().getStartDate() == null) { continue; } else if (thisRun.getStatus().getStartDate().after(lastRun.getStatus().getStartDate())) { lastRun = thisRun; } } return lastRun; }
Source:
<code>public LogReplicationConfig(Set<String> streamsToReplicate) { this.streamsToReplicate = streamsToReplicate; <START> this.maxNumMsgPerBatch = DEFAULT_MAX_NUM_MSG_PER_BATCH; <END> this.maxMsgSize = MAX_LOG_REPLICATION_DATA_MSG_SIZE_SUPPORTED; this.maxDataSizePerMsg = maxMsgSize * DATA_FRACTION_PER_MSG / 100; }</code><technical_language>simplify with: this(streamsToReplicate, DEFAULT_MAX_NUM_MSG_PER_BATCH, MAX_LOG_REPLICATION_DATA_MSG_SIZE_SUPPORTED);</technical_language>

Target:
public LogReplicationConfig(Set<String> streamsToReplicate) { this(streamsToReplicate, DEFAULT_MAX_NUM_MSG_PER_BATCH, MAX_DATA_MSG_SIZE_SUPPORTED); }
Source:
<code>public void authenticateUser(UserDao mockedUserDao) throws AuthenticationException, RecordNotFoundException { String email = "user@example.com"; String password = "secret"; Credentials credentials = createCredentials(email, password); <START> User fakeUser = new User(); <END> fakeUser.setEmail(email); fakeUser.setPassword(password); when(mockedUserDao.findByEmail(email)).thenReturn(fakeUser); User user = authenticationInteractor.authenticate(credentials); assertEquals(fakeUser.getEmail(), user.getEmail()); }</code><technical_language>Quelques lignes bas: User mockedUser = mock(User.class); when(mockedUser.getEmail()).thenReturn(email); when(mockedUser.getPassword()).thenReturn(password);</technical_language>

Target:
public void authenticateUser(UserDao mockedUserDao) throws AuthenticationException, RecordNotFoundException { Credentials credentials = createMockedCredentials(AN_EMAIL, A_PASSWORD); User mockedUser = mock(User.class); when(mockedUser.getEmail()).thenReturn(AN_EMAIL); when(mockedUser.getPassword()).thenReturn(A_PASSWORD); when(mockedUserDao.findByEmail(AN_EMAIL)).thenReturn(mockedUser); User user = authenticationInteractor.authenticate(credentials); assertEquals(mockedUser.getEmail(), user.getEmail()); }
Source:
<code>static void flushUIEvents() { final Display display = Display.getCurrent(); <START> for (;;) { <END> if (!display.readAndDispatch()) { break; } } }</code><technical_language>a simple while loop? removing for if</technical_language>

Target:
static void flushUIEvents() { final Display display = Display.getCurrent(); while (display.readAndDispatch()) { } }
Source:
<code>public void testMainMethodExclusionForJunit() { XmlSuite xmlSuite = createXmlSuite("suite"); xmlSuite.setJunit(true); createXmlTest(xmlSuite, "test", JUnitTestClassSample.class); <START> TestNG tng = create(); <END> tng.setXmlSuites(Collections.singletonList(xmlSuite)); tng.run(); Assert.assertEquals(tng.getStatus(), 0); }</code><technical_language>create(xmlSuite)</technical_language>

Target:
public void testMainMethodExclusionForJunit() { XmlSuite xmlSuite = createXmlSuite("suite"); xmlSuite.setJunit(true); createXmlTest(xmlSuite, "test", JUnitTestClassSample.class); TestNG tng = create(xmlSuite); tng.run(); Assert.assertEquals(tng.getStatus(), 0); }