auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public I_R_Request createRequest(@NonNull final RequestCandidate candidate) { final I_R_Request request = newInstance(I_R_Request.class); ; request.setSummary(candidate.getSummary()); request.setConfidentialType(candidate.getConfidentialType()); request.setAD_Org_ID(candidate.getOrgId().getRepoId()); request.setM_Product_ID(ProductId.toRepoId(candidate.getProductId())); request.setAD_Table_ID(candidate.getRecordRef() != null ? candidate.getRecordRef().getAD_Table_ID() : -1); request.setRecord_ID(candidate.getRecordRef() != null ? candidate.getRecordRef().getRecord_ID() : -1); request.setC_BPartner_ID(BPartnerId.toRepoId(candidate.getPartnerId())); request.setC_Order_ID(candidate.getRecordRef() != null ? candidate.getRecordRef().getTableName().equals(I_C_Order.Table_Name) ? candidate.getRecordRef().getRecord_ID() : -1 : -1); request.setM_InOut_ID(candidate.getRecordRef() != null ? candidate.getRecordRef().getTableName().equals(I_M_InOut.Table_Name) ? candidate.getRecordRef().getRecord_ID() : -1 : -1); <START> request.setDateTrx(TimeUtil.asTimestamp(Date.from(Instant.now()))); <END> request.setAD_User_ID(UserId.toRepoId(candidate.getUserId())); request.setR_RequestType_ID(candidate.getRequestTypeId().getRepoId()); request.setM_QualityNote_ID(QualityNoteId.toRepoId(candidate.getQualityNoteId())); request.setPerformanceType(candidate.getPerformanceType()); request.setDateDelivered(TimeUtil.asTimestamp(candidate.getDateDelivered())); saveRecord(request); return request; }</code><technical_language>Please SystemTime instead</technical_language>

Target:
public I_R_Request createRequest(@NonNull final RequestCandidate candidate) { final I_R_Request request = newInstance(I_R_Request.class); ; request.setSummary(candidate.getSummary()); request.setConfidentialType(candidate.getConfidentialType()); request.setAD_Org_ID(candidate.getOrgId().getRepoId()); request.setM_Product_ID(ProductId.toRepoId(candidate.getProductId())); request.setAD_Table_ID(candidate.getRecordRef() != null ? candidate.getRecordRef().getAD_Table_ID() : -1); request.setRecord_ID(candidate.getRecordRef() != null ? candidate.getRecordRef().getRecord_ID() : -1); request.setC_BPartner_ID(BPartnerId.toRepoId(candidate.getPartnerId())); request.setC_Order_ID(candidate.getRecordRef() != null ? candidate.getRecordRef().getTableName().equals(I_C_Order.Table_Name) ? candidate.getRecordRef().getRecord_ID() : -1 : -1); request.setM_InOut_ID(candidate.getRecordRef() != null ? candidate.getRecordRef().getTableName().equals(I_M_InOut.Table_Name) ? candidate.getRecordRef().getRecord_ID() : -1 : -1); request.setDateTrx(SystemTime.asTimestamp()); request.setAD_User_ID(UserId.toRepoId(candidate.getUserId())); request.setR_RequestType_ID(candidate.getRequestTypeId().getRepoId()); request.setM_QualityNote_ID(QualityNoteId.toRepoId(candidate.getQualityNoteId())); request.setPerformanceType(candidate.getPerformanceType()); request.setDateDelivered(TimeUtil.asTimestamp(candidate.getDateDelivered())); saveRecord(request); return request; }
Source:
<code>public void testEntriesWithFilter() throws Exception { <START> final PathMatcher m = Mockito.mock(PathMatcher.class); <END> final Path p = Mockito.mock(Path.class); final Stream s = Mockito.mock(Stream.class); Mockito.when(context.entries(Mockito.any(), Mockito.anyBoolean(), Mockito.any())).thenReturn(s); Assert.assertThat(context.entries(p, m), Matchers.sameInstance(s)); Mockito.verify(context).entries(p, true, m); }</code><technical_language>variable names (filter, path, entries). assertions verifications clearer</technical_language>

Target:
public void testEntriesWithFilter() throws Exception { final PathMatcher filter = Mockito.mock(PathMatcher.class); final Path path = Mockito.mock(Path.class); final Stream stream = Mockito.mock(Stream.class); Mockito.when(context.entries(Mockito.any(), Mockito.anyBoolean(), Mockito.any())) .thenReturn(stream); Assert.assertThat(context.entries(path, filter), Matchers.sameInstance(stream)); Mockito.verify(context).entries(path, true, filter); }
Source:
<code>private void visitorConditionalAnd(BinaryExpressionTree tree) { ConditionalState leftConditionalState = visitCondition(tree.leftOperand()); ConditionalState rightConditionalState = visitCondition(tree.rightOperand(), leftConditionalState.trueState); if (currentConditionalState != null) { leftConditionalState.falseState.merge(leftConditionalState.trueState, null); leftConditionalState.falseState.merge(rightConditionalState.falseState, null); leftConditionalState.trueState.merge(rightConditionalState.trueState, null); <START> currentConditionalState.falseState.apply(leftConditionalState.falseState); <END> currentConditionalState.trueState.apply(leftConditionalState.trueState); } }</code><technical_language>This part of ConditionalState</technical_language>

Target:
private void visitorConditionalAnd(BinaryExpressionTree tree) { ConditionalState leftConditionalState = visitCondition(tree.leftOperand()); ConditionalState rightConditionalState = visitCondition(tree.rightOperand(), leftConditionalState.trueState); if (currentConditionalState != null) { currentConditionalState.mergeConditionalAnd(leftConditionalState, rightConditionalState); } }
Source:
<code>private boolean shouldRetryImmediately(SingularityRequest request, SingularityDeployStatistics deployStatistics, Optional<SingularityTask> task) { if (!request.getNumRetriesOnFailure().isPresent()) { return false; } if (task.isPresent()) { Optional<SingularityTaskHistoryUpdate> taskHistoryUpdate = taskManager.getTaskHistoryUpdate(task.get().getTaskId(), ExtendedTaskState.TASK_CLEANING); if (taskHistoryUpdate.isPresent() && task.get().getTaskRequest().getPendingTask().getPendingTaskId().getPendingType() == PendingType.ONEOFF && taskHistoryUpdate.get().getStatusMessage().orElse("").contains("USER_REQUESTED")) { return false; } <START> if (task.get().getTaskRequest().getPendingTask().getPendingTaskId().getPendingType() == PendingType.IMMEDIATE <END> && request.getRequestType() == RequestType.SCHEDULED) { return false; } } final int numRetriesInARow = deployStatistics.getNumSequentialRetries(); if (numRetriesInARow >= request.getNumRetriesOnFailure().get()) { LOG.debug("Request had retries in a row, not retrying again (num retries on failure: {})", request.getId(), numRetriesInARow, request.getNumRetriesOnFailure()); return false; } LOG.debug("Request had retries in a row - retrying again (num retries on failure: {})", request.getId(), numRetriesInARow, request.getNumRetriesOnFailure()); return true; }</code><technical_language>small nit, do this check for efficiency require task history lookup</technical_language>

Target:
private boolean shouldRetryImmediately(SingularityRequest request, SingularityDeployStatistics deployStatistics, Optional<SingularityTask> task) { if (!request.getNumRetriesOnFailure().isPresent()) { return false; } if (task.isPresent()) { if (task.get().getTaskRequest().getPendingTask().getPendingTaskId().getPendingType() == PendingType.IMMEDIATE && request.getRequestType() == RequestType.SCHEDULED) { return false; } Optional<SingularityTaskHistoryUpdate> taskHistoryUpdate = taskManager.getTaskHistoryUpdate(task.get().getTaskId(), ExtendedTaskState.TASK_CLEANING); if (taskHistoryUpdate.isPresent() && request.getRequestType() == RequestType.ON_DEMAND && taskHistoryUpdate.get().getStatusMessage().orElse("").contains("USER_REQUESTED")) { return false; } } final int numRetriesInARow = deployStatistics.getNumSequentialRetries(); if (numRetriesInARow >= request.getNumRetriesOnFailure().get()) { LOG.debug("Request had retries in a row, not retrying again (num retries on failure: {})", request.getId(), numRetriesInARow, request.getNumRetriesOnFailure()); return false; } LOG.debug("Request had retries in a row - retrying again (num retries on failure: {})", request.getId(), numRetriesInARow, request.getNumRetriesOnFailure()); return true; }
Source:
<code>public void visitTryStatement(TryStatementTree tree) { insideTryStatement = true; <START> resourceResolversInTryWithResources = tree.resources().stream() <END> .map(resource -> resource.simpleName().name()) .collect(Collectors.toList()); super.visitTryStatement(tree); resourceResolversInTryWithResources.clear(); insideTryStatement = false; }</code><technical_language>creating new list time, forEach(resourceResolversInTryWithResources ::add) instead of collect(Collectors.toList());</technical_language>

Target:
public void visitTryStatement(TryStatementTree tree) { insideTryStatement = true; tree.resources().stream() .map(resource -> resource.simpleName().name()) .forEach(resourceResolversInTryWithResources::add); super.visitTryStatement(tree); resourceResolversInTryWithResources.clear(); insideTryStatement = false; }
Source:
<code>private String generateOutstandingLocksYaml(Map<LockClient, Set<LockRequest>> outstandingLockRequestsMap) { List<Map<String, SimpleLockRequest>> outstandingLockList = Collections.synchronizedList(Lists.newArrayList()); outstandingLockRequestsMap.forEach((client, requestSet) -> { if (requestSet != null) { <START> LockRequest[] lockRequests = requestSet.toArray(new LockRequest[requestSet.size()]); <END> for (LockRequest lockRequest : lockRequests) { outstandingLockList.add(getDescriptorSimpleRequestMap(client, lockRequest)); } } }); Yaml yaml = new Yaml(getDumperOptions()); return yaml.dump(nameObjectForYamlConvertion(outstandingLockList, OUTSTANDING_LOCK_REQUESTS_TITLE)); }</code><technical_language>copying array this opposed ImmutableSet.copyOf</technical_language>

Target:
private Map<String, Object> generateOutstandingLocksYaml(Map<LockClient, Set<LockRequest>> outstandingLockRequestsMap) { Map<String, SimpleLockRequestsWithSameDescriptor> outstandingRequestMap = Maps.newHashMap(); outstandingLockRequestsMap.forEach((client, requestSet) -> { if (requestSet != null) { ImmutableSet<LockRequest> lockRequests = ImmutableSet.copyOf(requestSet); lockRequests.forEach(lockRequest -> { List<SimpleLockRequest> requestList = getDescriptorSimpleRequestMap(client, lockRequest); requestList.forEach(request -> { outstandingRequestMap.putIfAbsent(request.getLockDescriptor(), new SimpleLockRequestsWithSameDescriptor(request.getLockDescriptor())); outstandingRequestMap.get(request.getLockDescriptor()).addLockRequest(request); }); }); } }); List<SimpleLockRequestsWithSameDescriptor> sortedOutstandingRequests = sortOutstandingRequests(outstandingRequestMap.values()); return nameObjectForYamlConvertion(OUTSTANDING_LOCK_REQUESTS_TITLE, sortedOutstandingRequests); }
Source:
<code>public List<String> updateAppLanguageCodes(@NonNull List<String> codes) { <START> appLanguageCodes.clear(); for (String code : codes) { if (!TextUtils.isEmpty(code)) { appLanguageCodes.add(code); } } <END> Prefs.setAppLanguageCodeCsv(StringUtil.listToCsv(appLanguageCodes)); return appLanguageCodes; }</code><technical_language>This leaves open possibility of making appLanguageCodes empty, is good. guarantee appLanguageCodes contains item</technical_language>

Target:
public List<String> updateAppLanguageCodes(@NonNull List<String> codes) { appLanguageCodes.clear(); for (String code : codes) { if (!TextUtils.isEmpty(code)) { appLanguageCodes.add(code); } } addSystemLanguageCodesIfEmpty(); Prefs.setAppLanguageCodeCsv(StringUtil.listToCsv(appLanguageCodes)); return appLanguageCodes; }
Source:
<code>public void addQuotaPermissionSubject(List<PermissionSubject> quotaPermissionList) { if (!isInternalExecution() && <START> !getStoragePool().getQuotaEnforcementType().equals(QuotaEnforcementTypeEnum.DISABLED)) { <END> for (QuotaConsumptionParameter parameter : getQuotaConsumptionParameters()) { quotaPermissionList.add(new PermissionSubject(parameter.getQuotaGuid(), VdcObjectType.Quota, ActionGroup.CONSUME_QUOTA)); } } }</code><technical_language>switch places in 'equals', getStoragePool().getQuotaEnforcementType() null (or ==)</technical_language>

Target:
public void addQuotaPermissionSubject(List<PermissionSubject> quotaPermissionList) { if (!isInternalExecution() && getStoragePool().getQuotaEnforcementType() != QuotaEnforcementTypeEnum.DISABLED) { List<QuotaConsumptionParameter> consumptionParameters = getQuotaConsumptionParameters(); if (consumptionParameters != null) { for (QuotaConsumptionParameter parameter : getQuotaConsumptionParameters()) { quotaPermissionList.add(new PermissionSubject(parameter.getQuotaGuid(), VdcObjectType.Quota, ActionGroup.CONSUME_QUOTA)); } } } }
Source:
<code>public Pattern parseFromInput(String input, ParserContext context) throws InputParseException { if (!input.startsWith("##")) { return null; } String tag = input.substring(2).toLowerCase(); boolean anyState = false; if (tag.startsWith("*")) { tag = tag.substring(1); anyState = true; } BlockCategory category = BlockCategories.get(tag); if (category == null) { throw new InputParseException("Unknown block tag: " + tag); } RandomPattern randomPattern = new RandomPattern(); Set<BlockType> blocks = category.getAll(); if (blocks.isEmpty()) { throw new InputParseException("Block tag " + category.getId() + " had no blocks!"); } if (anyState) { for (BlockState blockState : blocks.stream() <START> .flatMap(blockType -> blockType.getAllStates().stream()).collect(Collectors.toList())) { <END> randomPattern.add(new BlockPattern(blockState), 1.0); } } else { for (BlockType blockType : blocks) { randomPattern.add(new BlockPattern(blockType.getDefaultState()), 1.0); } } return randomPattern; }</code><technical_language>forEach collect iterate</technical_language>

Target:
public Pattern parseFromInput(String input, ParserContext context) throws InputParseException { if (!input.startsWith("##")) { return null; } String tag = input.substring(2).toLowerCase(); boolean anyState = false; if (tag.startsWith("*")) { tag = tag.substring(1); anyState = true; } BlockCategory category = BlockCategories.get(tag); if (category == null) { throw new InputParseException("Unknown block tag: " + tag); } RandomPattern randomPattern = new RandomPattern(); Set<BlockType> blocks = category.getAll(); if (blocks.isEmpty()) { throw new InputParseException("Block tag " + category.getId() + " had no blocks!"); } if (anyState) { blocks.stream().flatMap(blockType -> blockType.getAllStates().stream()).forEach(state -> randomPattern.add(new BlockPattern(state), 1.0)); } else { for (BlockType blockType : blocks) { randomPattern.add(new BlockPattern(blockType.getDefaultState()), 1.0); } } return randomPattern; }
Source:
<code><START> public double getCurrentZoomCenter() { <END> return graphView.getZoomCenter(); }</code><technical_language>int float. long is outdated & double used</technical_language>

Target:
public float getCurrentZoomCenter() { return graphView.getZoomCenter(); }
Source:
<code>public static JSONObject createJsonObjectOfScopeMapping(ScopeListDTO body) throws APIManagementException { JSONObject responseJson = new JSONObject(); JSONArray scopeJson = new JSONArray(); for (ScopeDTO scope : body.getList()) { JSONObject scopeRoleJson = new JSONObject(); <START> String roles = scope.getRoles().toString().replaceAll("\\[", ""). <END> replaceAll("\\]", "").replaceAll("\\s", ""); scopeRoleJson.put("Name", scope.getName()); scopeRoleJson.put("Roles", roles); scopeJson.put(scopeRoleJson); } responseJson.put("Scope", scopeJson); return responseJson; }</code><technical_language>a null check required here</technical_language>

Target:
public static JSONObject createJsonObjectOfScopeMapping(ScopeListDTO body) throws APIManagementException { JSONObject responseJson = new JSONObject(); JSONArray scopeJson = new JSONArray(); for (ScopeDTO scope : body.getList()) { JSONObject scopeRoleJson = new JSONObject(); String roles = scope.getRoles().toString().replaceAll("\\[", ""). replaceAll("\\]", "").replaceAll("\\s", ""); if ( !roles.isEmpty()) { scopeRoleJson.put("Name", scope.getName()); scopeRoleJson.put("Roles", roles); scopeJson.put(scopeRoleJson); } } responseJson.put("Scope", scopeJson); return responseJson; }
Source:
<code>private void connectGithubAccount() { projectSourcePage.clickOnConnectGithubAccountButton(); seleniumWebDriver.switchToNoneCurrentWindow(ideWin); gitHub.waitAuthorizationPageOpened(); gitHub.typeLogin(gitHubUsername); gitHub.typePass(gitHubPassword); gitHub.clickOnSignInButton(); <START> WaitUtils.sleepQuietly(5); <END> if (seleniumWebDriver.getWindowHandles().size() > 1) { gitHub.waitAuthorizeBtn(); gitHub.clickOnAuthorizeBtn(); } seleniumWebDriver.switchTo().window(ideWin); }</code><technical_language>is find another solution</technical_language>

Target:
private void connectGithubAccount() { projectSourcePage.clickOnConnectGithubAccountButton(); seleniumWebDriver.switchToNoneCurrentWindow(ideWin); gitHub.waitAuthorizationPageOpened(); gitHub.typeLogin(gitHubUsername); gitHub.typePass(gitHubPassword); gitHub.clickOnSignInButton(); if (gitHub.isAuthorizeButtonPresent()) { gitHub.clickOnAuthorizeBtn(); } seleniumWebDriver.switchTo().window(ideWin); }
Source:
<code>static File searchPath(final String path, final String... lookFor) { for (final String p : path.split(File.pathSeparator)) { for (String command : lookFor) { final File e = new File(p, command); <START> if (e.isFile()) { <END> return e.getAbsoluteFile(); } } } return null; }</code><technical_language>Style-nit: prefer dropping curly braces, submit this as-is</technical_language>

Target:
static File searchPath(final String path, final String... lookFor) { for (final String p : path.split(File.pathSeparator)) { for (String command : lookFor) { final File e = new File(p, command); if (e.isFile()) return e.getAbsoluteFile(); } } return null; }
Source:
<code><START> public void deleteTaskContainerMappings(Iterable<String> taskNames) { <END> for (String taskName : taskNames) { taskContainerMappingMetadataStore.delete(taskName); taskNameToContainerId.remove(taskName); } }</code><technical_language>Do need delete task mode mapping this is called? In general, sense get/put/delete a complex value</technical_language>

Target:
public void deleteTaskContainerMappings(Iterable<String> taskNames) { for (String taskName : taskNames) { taskContainerMappingMetadataStore.delete(taskName); taskModeMappingMetadataStore.delete(taskName); taskNameToContainerId.remove(taskName); } }
Source:
<code><START> public AudioController() { <END> setInstance(this); }</code><technical_language>please this private protected,</technical_language>

Target:
protected AudioController() { setInstance(this); }
Source:
<code>public void setConnectionPoolingProperties( Properties properties ) { ArrayList<String> itemsToRemove = new ArrayList<>(); for ( Iterator<Object> iter = attributes.keySet().iterator(); iter.hasNext(); ) { String key = (String) iter.next(); if ( key.startsWith( ATTRIBUTE_POOLING_PARAMETER_PREFIX ) ) { itemsToRemove.add( key ); } } <START> for ( String item : itemsToRemove ) { <END> attributes.remove( item ); } for ( Iterator<Object> iter = properties.keySet().iterator(); iter.hasNext(); ) { String element = (String) iter.next(); String value = properties.getProperty( element ); if ( !Utils.isEmpty( element ) && !Utils.isEmpty( value ) ) { attributes.put( ATTRIBUTE_POOLING_PARAMETER_PREFIX + element, value ); } } }</code><technical_language>Unclear this done in a separate loop. This more time-consuming. Suggest this a performance regression. Suggest instead iterating EntrySet of attributes calling remove method of iterator. is *no* reason do this other misunderstanding deal iterators collections. this: Map.Entry<Object, Object> anEntry; for ( Iterator<Map.Entry<Object, Object>> iter = attributes.entrySet().iterator(); iter.hasNext(); ) { anEntry = iter.next(); if ( ( (String)anEntry.getKey() ).startsWith( ATTRIBUTE_POOLING_PARAMETER_PREFIX )) { iter.remove(); // Removes collection immediately correctly } )</technical_language>

Target:
public void setConnectionPoolingProperties( Properties properties ) { for ( Iterator<Object> iter = attributes.keySet().iterator(); iter.hasNext(); ) { String key = (String) iter.next(); if ( key.startsWith( ATTRIBUTE_POOLING_PARAMETER_PREFIX ) ) { iter.remove(); } } for ( Iterator<Object> iter = properties.keySet().iterator(); iter.hasNext(); ) { String element = (String) iter.next(); String value = properties.getProperty( element ); if ( !Utils.isEmpty( element ) && !Utils.isEmpty( value ) ) { attributes.put( ATTRIBUTE_POOLING_PARAMETER_PREFIX + element, value ); } } }
Source:
<code>private ResponseEntity<Object> indexObject(String id) { Map<String, Object> result = new HashMap<>(); result.put("action", "reindex"); result.put("pid", id); PID objectPid = PIDs.get(id); log.info("Updating object " + id); try { indexingService.reindexObject(AgentPrincipals.createFromThread(), objectPid); } catch (Exception e) { result.put("error", e.getMessage()); if (e instanceof AuthorizationException || e instanceof AccessRestrictionException) { return new ResponseEntity<>(result, HttpStatus.FORBIDDEN); } else { <START> log.error("Failed to reindex repository due to {}", e); <END> return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR); } } result.put("timestamp", System.currentTimeMillis()); return new ResponseEntity<>(result, HttpStatus.OK); }</code><technical_language>this switched log.error("Failed reindex object {}", id, e);? Also, exception need formatted message</technical_language>

Target:
private ResponseEntity<Object> indexObject(String id) { Map<String, Object> result = new HashMap<>(); result.put("action", "reindex"); result.put("pid", id); PID objectPid = PIDs.get(id); log.info("Indexing object " + id); try { indexingService.reindexObject(AgentPrincipals.createFromThread(), objectPid); } catch (Exception e) { result.put("error", e.getMessage()); if (e instanceof AuthorizationException || e instanceof AccessRestrictionException) { return new ResponseEntity<>(result, HttpStatus.FORBIDDEN); } else { log.error("Failed to reindex object {}", id, e); return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR); } } result.put("timestamp", System.currentTimeMillis()); return new ResponseEntity<>(result, HttpStatus.OK); }
Source:
<code>public void directSelectionAllowed() { FridgeDTO in = createFridgeDTO(); FridgeDTO out = DirectMapper.INSTANCE.map( in ); assertThat( out ).isNotNull(); assertThat( out.getShelve() ).isNotNull(); <START> assertThat( out.getShelve() ).isEqualTo( in.getShelve() ); <END> }</code><technical_language>suggestion assertThat( out.getShelve() ).isSameAs( in.getShelve() );</technical_language>

Target:
public void directSelectionAllowed() { FridgeDTO in = createFridgeDTO(); FridgeDTO out = DirectMapper.INSTANCE.map( in ); assertThat( out ).isNotNull(); assertThat( out.getShelve() ).isNotNull(); assertThat( out.getShelve() ).isSameAs( in.getShelve() ); }
Source:
<code>public void run() { final List<CucumberFeature> features = featureSupplier.get(); bus.send(new TestRunStarted(bus.getInstant())); for (CucumberFeature feature : features) { bus.send(new TestSourceRead(bus.getInstant(), feature.getUri().toString(), feature.getSource())); } final List<Future<?>> executingPickles = features.stream() .flatMap(feature -> feature.getPickles().stream()) .filter(filter) .collect(Collectors.collectingAndThen(Collectors.toList(), list -> pickleOrder.orderPickleEvents(list).stream())) .limit(limit > 0 ? limit : Integer.MAX_VALUE) .map(pickleEvent -> executor.submit(() -> runnerSupplier.get().runPickle(pickleEvent))) <START> .collect(Collectors.toList()); <END> executor.shutdown(); List<Throwable> thrown = new ArrayList<>(); for (Future executingPickle : executingPickles) { try { executingPickle.get(); } catch (ExecutionException e) { log.error("Exception while executing pickle", e); thrown.add(e.getCause()); } catch (InterruptedException e) { executor.shutdownNow(); throw new CucumberException(e); } } if (thrown.size() == 1) { throw new CucumberException(thrown.get(0)); } else if (thrown.size() > 1) { throw new CompositeCucumberException(thrown); } bus.send(new TestRunFinished(bus.getInstant())); }</code><technical_language>collectingAndThen neat</technical_language>

Target:
public void run() { final List<CucumberFeature> features = featureSupplier.get(); bus.send(new TestRunStarted(bus.getInstant())); for (CucumberFeature feature : features) { bus.send(new TestSourceRead(bus.getInstant(), feature.getUri().toString(), feature.getSource())); } final List<Future<?>> executingPickles = features.stream() .flatMap(feature -> feature.getPickles().stream()) .filter(filter) .collect(collectingAndThen(toList(), list -> pickleOrder.orderPickleEvents(list).stream())) .limit(limit > 0 ? limit : Integer.MAX_VALUE) .map(pickleEvent -> executor.submit(() -> runnerSupplier.get().runPickle(pickleEvent))) .collect(toList()); executor.shutdown(); List<Throwable> thrown = new ArrayList<>(); for (Future executingPickle : executingPickles) { try { executingPickle.get(); } catch (ExecutionException e) { log.error("Exception while executing pickle", e); thrown.add(e.getCause()); } catch (InterruptedException e) { executor.shutdownNow(); throw new CucumberException(e); } } if (thrown.size() == 1) { throw new CucumberException(thrown.get(0)); } else if (thrown.size() > 1) { throw new CompositeCucumberException(thrown); } bus.send(new TestRunFinished(bus.getInstant())); }
Source:
<code>public static Pair<Integer,Integer> parse(String portRange) { int idx = portRange.indexOf('-'); if (idx != -1) { int low = Integer.parseInt(portRange.substring(0, idx)); int high = Integer.parseInt(portRange.substring(idx + 1)); <START> if (!VALID_RANGE.contains(low) || !VALID_RANGE.contains(high) || !(low <= high)) { <END> throw new IllegalArgumentException( "Invalid port range specified, only 1024 to 65535 supported."); } return new Pair<>(low, high); } throw new IllegalArgumentException( "Invalid port range specification, must use M-N notation."); }</code><technical_language>nice change !(low <= high) > high. suggestion if (!VALID_RANGE.contains(low) || !VALID_RANGE.contains(high) || > high) {</technical_language>

Target:
public static Pair<Integer,Integer> parse(String portRange) { int idx = portRange.indexOf('-'); if (idx != -1) { int low = Integer.parseInt(portRange.substring(0, idx)); int high = Integer.parseInt(portRange.substring(idx + 1)); if (!VALID_RANGE.contains(low) || !VALID_RANGE.contains(high) || low > high) { throw new IllegalArgumentException( "Invalid port range specified, only 1024 to 65535 supported."); } return new Pair<>(low, high); } throw new IllegalArgumentException( "Invalid port range specification, must use M-N notation."); }
Source:
<code>public void testIsDataStall_EvaluationTcp() { setDataStallEvaluationType(DATA_STALL_EVALUATION_TYPE_TCP); WrappedNetworkMonitor wrappedMonitor = makeMonitorWithTst(METERED_CAPABILITIES, <START> mTcpSocketTracker); <END> wrappedMonitor.setLastProbeTime(SystemClock.elapsedRealtime() - 1000); makeDnsTimeoutEvent(wrappedMonitor, DEFAULT_DNS_TIMEOUT_THRESHOLD); assertFalse(wrappedMonitor.isDataStall()); when(mTcpSocketTracker.isDataStallSuspected()).thenReturn(true); setTcpPollingInterval(0); wrappedMonitor.sendTcpPollingEvent(); HandlerUtilsKt.waitForIdle(wrappedMonitor.getHandler(), HANDLER_TIMEOUT_MS); assertTrue(wrappedMonitor.isDataStall()); }</code><technical_language>sense instead - WrappedNetworkMonitor create a mock TcpSocketTracker. set operate something. - a getter for TcpSocketTracker in WrappedNetworkMonitor. Methods want a behavior call mock methods caller</technical_language>

Target:
public void testIsDataStall_EvaluationTcp() { setDataStallEvaluationType(DATA_STALL_EVALUATION_TYPE_TCP); WrappedNetworkMonitor wrappedMonitor = makeMonitor(METERED_CAPABILITIES); wrappedMonitor.setLastProbeTime(SystemClock.elapsedRealtime() - 1000); makeDnsTimeoutEvent(wrappedMonitor, DEFAULT_DNS_TIMEOUT_THRESHOLD); assertFalse(wrappedMonitor.isDataStall()); when(wrappedMonitor.getTcpSocketTracker().isDataStallSuspected()).thenReturn(true); setTcpPollingInterval(0); wrappedMonitor.sendTcpPollingEvent(); HandlerUtilsKt.waitForIdle(wrappedMonitor.getHandler(), HANDLER_TIMEOUT_MS); assertTrue(wrappedMonitor.isDataStall()); }
Source:
<code><START> public Flux<KeyBase> listKeys() { <END> return service.getKeys(endpoint, DEFAULT_MAX_PAGE_RESULTS, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE).flatMapMany(this::extractAndFetchKeys); }</code><technical_language>Flux<KeyBase> [](start = 11, length = 13) this Flux<Response<KeyBase>></technical_language>

Target:
public Flux<KeyBase> listKeys() { return service.getKeys(endpoint, DEFAULT_MAX_PAGE_RESULTS, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE).flatMapMany(r -> extractAndFetchKeys(r, Context.NONE)); }
Source:
<code>public void updateReportsAvailability() { <START> updateReportsAvailability(SystemTreeItemType.System); <END> }</code><technical_language>time init reports- if tree selected item is system initialized? current treeSelectedItem passed, it</technical_language>

Target:
public void updateReportsAvailability() { updateReportsAvailability(getSystemTree().getSelectedItem() == null ? SystemTreeItemType.System : getSystemTree().getSelectedItem().getType()); }
Source:
<code>public static void enhanceRuleMetadata(RuleProvider provider, Rule rule) { if (rule instanceof Context) { Context context = (Context) rule; if (!context.containsKey(RuleMetadata.ORIGIN)) context.put(RuleMetadata.ORIGIN, provider.getMetadata().getOrigin()); if (!context.containsKey(RuleMetadata.RULE_PROVIDER)) context.put(RuleMetadata.RULE_PROVIDER, provider); if (!context.containsKey(RuleMetadata.TAGS)) context.put(RuleMetadata.TAGS, provider.getMetadata().getTags()); <START> } <END> }</code><technical_language>ultimate storage for metadata in end? Is Context? metadata API load there? If so, I it, I before, if insist... :)</technical_language>

Target:
public static void enhanceRuleMetadata(RuleProvider provider, Rule rule) { if (rule instanceof Context) { Context context = (Context) rule; if (!context.containsKey(RuleMetadataType.ORIGIN)) context.put(RuleMetadataType.ORIGIN, provider.getMetadata().getOrigin()); if (!context.containsKey(RuleMetadataType.RULE_PROVIDER)) context.put(RuleMetadataType.RULE_PROVIDER, provider); if (!context.containsKey(RuleMetadataType.TAGS)) context.put(RuleMetadataType.TAGS, provider.getMetadata().getTags()); } }
Source:
<code>public boolean run(CommandSender sender, Player sender_p, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { if (args.length < 2) { return false; } Player player = getPlayer(args[0]); if (player == null) { playerMsg(TotalFreedomMod.PLAYER_NOT_FOUND); return true; } if (sender instanceof Player) { if (player == (Player) sender) { playerMsg(ChatColor.RED + "Please, don't try to report yourself."); return true; } } if (TFM_AdminList.isSuperAdmin(player)) { <START> playerMsg(ChatColor.RED + "You may not report " + player.getName() + ", they are an admin."); <END> return true; } String reported = player.getName(); String reporter = sender.getName(); String report = StringUtils.join(ArrayUtils.subarray(args, 1, args.length), " "); sender.sendMessage(ChatColor.GREEN + "Thank you, your report has been successfully logged."); for (Player p : Bukkit.getOnlinePlayers()) { if (TFM_AdminList.isSuperAdmin(p)) { p.sendMessage(ChatColor.RED + "[REPORTS] " + ChatColor.GOLD + reporter + " has reported " + reported + " for " + report); } } return true; }</code><technical_language>change this "You report admin"</technical_language>

Target:
public boolean run(CommandSender sender, Player sender_p, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { if (args.length < 2) { return false; } Player player = getPlayer(args[0]); if (player == null) { playerMsg(PLAYER_NOT_FOUND); return true; } if (sender instanceof Player) { if (player.equals(sender_p)) { playerMsg(ChatColor.RED + "Please, don't try to report yourself."); return true; } } if (TFM_AdminList.isSuperAdmin(player)) { playerMsg(ChatColor.RED + "You can not report an admin."); return true; } String report = StringUtils.join(ArrayUtils.subarray(args, 1, args.length), " "); TFM_Util.reportAction(sender_p, player, report); playerMsg(ChatColor.GREEN + "Thank you, your report has been successfully logged."); return true; }
Source:
<code>public static long getMillisFromString(String strDate) { <START> long millis = ISO8601.parse(strDate).getTimeInMillis(); <END> return millis; }</code><technical_language>I "return ISO8601.parse(strDate).getTimeInMillis();" enough</technical_language>

Target:
public static long getMillisFromString(String strDate) { return ISO8601.parse(strDate).getTimeInMillis(); }
Source:
<code>private boolean isHelp(List<String> rawArgs) { <START> if(F.isEmpty(rawArgs)) <END> return true; if (rawArgs.size() > 2) return false; boolean help = false; boolean experimental = false; for (String arg : rawArgs) { if (CMD_HELP.equalsIgnoreCase(arg)) help = true; else if (CMD_ENABLE_EXPERIMENTAL.equalsIgnoreCase(arg)) experimental = true; } return (help && experimental) || ((help || experimental) && rawArgs.size() == 1); }</code><technical_language>Missed space, if (F.isEmpty(rawArgs))</technical_language>

Target:
private boolean isHelp(List<String> rawArgs) { if (F.isEmpty(rawArgs)) return true; if (rawArgs.size() > 2) return false; boolean help = false; boolean experimental = false; for (String arg : rawArgs) { if (CMD_HELP.equalsIgnoreCase(arg)) help = true; else if (CMD_ENABLE_EXPERIMENTAL.equalsIgnoreCase(arg)) experimental = true; else return false; } return help || experimental; }
Source:
<code>@Test public void testTimezone() throws Exception { CronTabList tabs = CronTabList.create("TZ=Australia/Sydney\nH * * * *\nH * * * *", Hash.from("seed")); List<Integer> times = new ArrayList<Integer>(); for (int i = 0; i < 60; i++) { <START> GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("Australia/Sydney")); <END> calendar.set(2013, Calendar.APRIL, 3, 11, i, 0); if (tabs.check(calendar)) { times.add(i); } } assertEquals("[35, 56]", times.toString()); }</code><technical_language>suggestion GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));</technical_language>

Target:
@Test public void testTimezone() throws Exception { CronTabList tabs = CronTabList.create("TZ=Australia/Sydney\nH * * * *\nH * * * *", Hash.from("seed")); List<Integer> times = new ArrayList<Integer>(); for (int i = 0; i < 60; i++) { GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC")); calendar.set(2013, Calendar.APRIL, 3, 11, i, 0); if (tabs.check(calendar)) { times.add(i); } } assertEquals("[35, 56]", times.toString()); }
Source:
<code>private void storeStatement(final Statement statement) throws IOException, IllegalArgumentException { final boolean isValidPredicate = validPredicates == null || validPredicates.isEmpty() || validPredicates.contains(statement.getPredicate()); if (!isValidPredicate || !(statement.getObject() instanceof Literal)) { return; } final DateTime[] indexDateTimes = new DateTime[2]; extractDateTime(statement, indexDateTimes); if (indexDateTimes[0]==null) { return; } <START> if (!this.isInit) <END> throw new RuntimeException("Method .init() was not called (or failed) before attempting to store statements."); try { if (indexDateTimes[1] != null) { final TemporalInterval interval = new TemporalInterval(new TemporalInstantRfc3339(indexDateTimes[0]), new TemporalInstantRfc3339(indexDateTimes[1])); addInterval(temporalIndexBatchWriter, interval, statement); } else { final TemporalInstant instant = new TemporalInstantRfc3339(indexDateTimes[0]); addInstant(temporalIndexBatchWriter, instant, statement); } } catch (final MutationsRejectedException e) { throw new IOException("While adding interval/instant for statement =" + statement, e); } }</code><technical_language>call init beginning of this method ensure initialized</technical_language>

Target:
private void storeStatement(final Statement statement) throws IOException, IllegalArgumentException { Objects.requireNonNull(temporalIndexBatchWriter,"This is not initialized for writing. Must call setMultiTableBatchWriter() and init()."); final boolean isValidPredicate = validPredicates == null || validPredicates.isEmpty() || validPredicates.contains(statement.getPredicate()); if (!isValidPredicate || !(statement.getObject() instanceof Literal)) { return; } final DateTime[] indexDateTimes = new DateTime[2]; extractDateTime(statement, indexDateTimes); if (indexDateTimes[0]==null) { return; } if (!this.isInit) throw new RuntimeException("Method .init() was not called (or failed) before attempting to store statements."); try { if (indexDateTimes[1] != null) { final TemporalInterval interval = new TemporalInterval(new TemporalInstantRfc3339(indexDateTimes[0]), new TemporalInstantRfc3339(indexDateTimes[1])); addInterval(temporalIndexBatchWriter, interval, statement); } else { final TemporalInstant instant = new TemporalInstantRfc3339(indexDateTimes[0]); addInstant(temporalIndexBatchWriter, instant, statement); } } catch (final MutationsRejectedException e) { throw new IOException("While adding interval/instant for statement =" + statement, e); } }
Source:
<code>public void shouldUpdatePerson() throws Exception { Person person = preparePerson(); <START> URI url = config.toInstancePathWithParams("/person/{uuid}", person.getUuid()); <END> when(restOperations.exchange(eq(url), eq(HttpMethod.POST), any(HttpEntity.class), eq(String.class))) .thenReturn(getResponse(PERSON_RESPONSE_JSON)); Person updated = personResource.updatePerson(config, person); verify(restOperations).exchange(eq(url), eq(HttpMethod.POST), requestCaptor.capture(), eq(String.class)); assertThat(updated, equalTo(preparePerson())); assertThat(requestCaptor.getValue().getHeaders(), equalTo(getHeadersForPost(config))); assertThat(JsonUtils.readJson(requestCaptor.getValue().getBody(), JsonObject.class), equalTo(readFromFile(CREATE_PERSON_JSON, JsonObject.class))); }</code><technical_language>remove this</technical_language>

Target:
public void shouldUpdatePerson() throws Exception { Person person = preparePerson(); URI url = config.toInstancePathWithParams("/person/{uuid}?v=full", person.getUuid()); when(restOperations.exchange(eq(url), eq(HttpMethod.POST), any(HttpEntity.class), eq(String.class))) .thenReturn(getResponse(PERSON_RESPONSE_JSON)); Person updated = personResource.updatePerson(config, person); verify(restOperations).exchange(eq(url), eq(HttpMethod.POST), requestCaptor.capture(), eq(String.class)); assertThat(updated, equalTo(preparePerson())); assertThat(requestCaptor.getValue().getHeaders(), equalTo(getHeadersForPost(config))); assertThat(JsonUtils.readJson(requestCaptor.getValue().getBody(), JsonObject.class), equalTo(readFromFile(CREATE_PERSON_JSON, JsonObject.class))); }
Source:
<code>public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { boolean doFilter = false; try { HttpSession httpSession = ((HttpServletRequest) request).getSession(false); if (httpSession != null) { String engineSession = (String) httpSession.getAttribute(SessionConstants.HTTP_SESSION_ENGINE_SESSION_ID_KEY); InitialContext ctx = null; if (engineSession != null) { ctx = new InitialContext(); try { VdcQueryReturnValue returnValue = FiltersHelper.getBackend(ctx) .runPublicQuery(VdcQueryType.ValidateSession, new VdcQueryParametersBase(engineSession)); if (!returnValue.getSucceeded()) { httpSession.invalidate(); } } finally { ctx.close(); } } } doFilter = true; } catch (Exception ex) { <START> log.error(String.format("An error has occurred while session validation. Message is %1$s", ex.getMessage())); <END> if (log.isDebugEnabled()) { log.debug("", ex); } ((HttpServletResponse) response).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } if (doFilter) { chain.doFilter(request, response); } }</code><technical_language>exception stack trace log, debug is enabled</technical_language>

Target:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { boolean doFilter = false; try { HttpSession httpSession = ((HttpServletRequest) request).getSession(false); if (httpSession != null) { String engineSession = (String) httpSession.getAttribute(SessionConstants.HTTP_SESSION_ENGINE_SESSION_ID_KEY); InitialContext ctx = null; if (engineSession != null) { ctx = new InitialContext(); try { VdcQueryReturnValue returnValue = FiltersHelper.getBackend(ctx) .runPublicQuery(VdcQueryType.ValidateSession, new VdcQueryParametersBase(engineSession)); if (!returnValue.getSucceeded()) { httpSession.invalidate(); } } finally { ctx.close(); } } } doFilter = true; } catch (Exception ex) { log.error("An error has occurred while session validation.", ex); ((HttpServletResponse) response).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } if (doFilter) { chain.doFilter(request, response); } }
Source:
<code>public ResponseEntity<List<String>> syncRepository(String repositoryUrl) { boolean validRequest = !StringUtils.isEmpty(repositoryUrl); if (validRequest) { String oldUrl = configurationService.getModelRepositoryUrl(); LOGGER.info(String.format(LOG_TRYING_TO_SYNC_REPOSITORY, repositoryUrl)); if (!repositoryUrl.equals(oldUrl)) { configurationService.setModelRepositoryUrl(repositoryUrl); } try { sourceCodeManager.updateRepository(); List<String> versions = sourceCodeManager.getAvailableVersions(); if (!repositoryUrl.equals(oldUrl)) { LOGGER.info(LOG_CLEARING_MODEL_VERSION); configurationService.setModelRepositoryVersion(""); } LOGGER.info(LOG_SYNC_REPO_SUCCESSFUL); return new ResponseEntity<List<String>>(versions, HttpStatus.OK); } catch (Exception e) { LOGGER.warn(LOG_SYNC_REPO_FAILED); <START> LOGGER.error(e); <END> if (!repositoryUrl.equals(oldUrl)) { LOGGER.info(LOG_REVERTING_MODEL_REPOSITORY_URL); configurationService.setModelRepositoryUrl(oldUrl); } } } return new ResponseEntity<List<String>>(HttpStatus.BAD_REQUEST); }</code><technical_language>above: LOGGER.error(LOG_SYNC_REPO_FAILED, e)</technical_language>

Target:
public ResponseEntity<List<String>> syncRepository(String repositoryUrl) { boolean validRequest = !StringUtils.isEmpty(repositoryUrl); if (validRequest) { String oldUrl = configurationService.getModelRepositoryUrl(); LOGGER.info(String.format(LOG_TRYING_TO_SYNC_REPOSITORY, repositoryUrl)); if (!repositoryUrl.equals(oldUrl)) { configurationService.setModelRepositoryUrl(repositoryUrl); } try { sourceCodeManager.updateRepository(); List<String> versions = sourceCodeManager.getAvailableVersions(); if (!repositoryUrl.equals(oldUrl)) { LOGGER.info(LOG_CLEARING_MODEL_VERSION); configurationService.setModelRepositoryVersion(""); } LOGGER.info(LOG_SYNC_REPO_SUCCESSFUL); return new ResponseEntity<List<String>>(versions, HttpStatus.OK); } catch (Exception e) { LOGGER.error(LOG_SYNC_REPO_FAILED, e); if (!repositoryUrl.equals(oldUrl)) { LOGGER.info(LOG_REVERTING_MODEL_REPOSITORY_URL); configurationService.setModelRepositoryUrl(oldUrl); } } } return new ResponseEntity<List<String>>(HttpStatus.BAD_REQUEST); }
Source:
<code>public void testAsyncTasks() throws Exception { LimitedExecutor limitedExecutor = new LimitedExecutor(NAME, executor, 1); CompletableFuture<Void> blockingFuture = new CompletableFuture<>(); CompletableFuture<String> cf1 = new CompletableFuture<>(); limitedExecutor.executeAsync(() -> blockingFuture.thenRunAsync(() -> cf1.complete("bla"))); CompletableFuture<String> cf2 = new CompletableFuture<>(); limitedExecutor.execute(() -> cf2.complete("bla")); <START> Thread.sleep(100); <END> assertFalse(cf2.isDone()); blockingFuture.complete(null); assertEquals("bla", cf1.get(10, SECONDS)); assertEquals("bla", cf2.get(10, SECONDS)); }</code><technical_language>get rid of sleeps somehow</technical_language>

Target:
public void testAsyncTasks() throws Exception { LimitedExecutor limitedExecutor = new LimitedExecutor(NAME, executor, 1); CompletableFuture<Void> blockingFuture = new CompletableFuture<>(); CompletableFuture<String> cf1 = new CompletableFuture<>(); limitedExecutor.executeAsync(() -> blockingFuture.thenRunAsync(() -> cf1.complete("bla"))); CompletableFuture<String> cf2 = new CompletableFuture<>(); limitedExecutor.execute(() -> cf2.complete("bla")); Thread.sleep(10); assertFalse(cf2.isDone()); blockingFuture.complete(null); assertEquals("bla", cf1.get(10, SECONDS)); assertEquals("bla", cf2.get(10, SECONDS)); }
Source:
<code>private void adjustKVMDataForBlockSD() { if (getVm().getOrigin() == OriginType.KVM && getActionState() == CommandActionState.EXECUTE && getStorageDomain() != null && getStorageDomain().getStorageType().isBlockDomain()) { getVm().getImages().forEach(image -> { image.setActualSizeInBytes(image.getSize()); <START> image.setVolumeType(VolumeType.Preallocated); <END> }); } }</code><technical_language>OK, write log in backend. If changing allocation type in engine libvirt logging easy I guess helpful for users future debugging</technical_language>

Target:
private void adjustKVMDataForBlockSD() { if (getVm().getOrigin() == OriginType.KVM && getActionState() == CommandActionState.EXECUTE && getStorageDomain() != null && getStorageDomain().getStorageType().isBlockDomain()) { getVm().getImages().forEach(image -> { image.setActualSizeInBytes(image.getSize()); image.setVolumeType(VolumeType.Preallocated); }); log.info("Block Storage Domains do not support Sparseness. The Import is defaulting to Preallocated."); } }
Source:
<code>public final boolean waitForLockRelease(long lockAcquisitionTimeout) throws InterruptedException { <START> notifier.await(lockAcquisitionTimeout, TimeUnit.MILLISECONDS); <END> return txComplete; }</code><technical_language>I missed PR, Notifier a lot CompletedFuture</technical_language>

Target:
public final boolean waitForLockRelease(long lockAcquisitionTimeout) throws InterruptedException { try { notifier.get(lockAcquisitionTimeout, TimeUnit.MILLISECONDS); } catch (ExecutionException e) { throw new IllegalStateException("Should never happen", e); } catch (TimeoutException e) { } return txComplete; }
Source:
<code><START> public UnionCondition(final ConditionType conditionType, final List<AbstractCondition> conditions) { <END> super(conditionType); this.conditions = conditions; }</code><technical_language>mentioned above, hide this construction</technical_language>

Target:
private UnionCondition(final ConditionType conditionType, final List<AbstractCondition> conditions) { super(conditionType); this.conditions = conditions; }
Source:
<code>public void testTransformMetacardFromUpstreamResponse() throws CatalogTransformerException, IOException, XpathException, SAXException { MetacardImpl metacard = createMockMetacard(); metacard.setLocation(POINT_WKT); <START> Result result = mock(Result.class); <END> doReturn(metacard).when(result).getMetacard(); SourceResponseImpl sourceResponse = new SourceResponseImpl(null, singletonList(result)); BinaryContent content = kmlTransformer.transform(sourceResponse, emptyMap()); assertThat(content.getMimeTypeValue(), is(KMLTransformerImpl.KML_MIMETYPE.toString())); final String kmlString = IOUtils.toString(content.getInputStream(), StandardCharsets.UTF_8); assertXpathEvaluatesTo("Results (1)", "/m:kml/m:Document/m:name", kmlString); assertXpathExists(" assertXpathEvaluatesTo("myTitle", " }</code><technical_language>I need mock result; instantiated metacard</technical_language>

Target:
public void testTransformMetacardFromUpstreamResponse() throws CatalogTransformerException, IOException, XpathException, SAXException { MetacardImpl metacard = createMockMetacard(); metacard.setLocation(POINT_WKT); Result result = new ResultImpl(metacard); SourceResponseImpl sourceResponse = new SourceResponseImpl(null, singletonList(result)); BinaryContent content = kmlTransformer.transform(sourceResponse, emptyMap()); assertThat(content.getMimeTypeValue(), is(KMLTransformerImpl.KML_MIMETYPE.toString())); final String kmlString = IOUtils.toString(content.getInputStream(), StandardCharsets.UTF_8); assertXpathEvaluatesTo("Results (1)", "/m:kml/m:Document/m:name", kmlString); assertXpathExists(" assertXpathEvaluatesTo("myTitle", " }