auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static String rescaleImage(BufferedImage fullSizeImage, int width, int height, int size, String fileLocation) { String outputLocation = fileLocation + "." + THUMBNAIL_SUFFIX + size; File outputFile = new File(outputLocation); OutputStream outputFileStream = null; try { outputFileStream = new FileOutputStream(outputFile); } catch (IOException ioex) { logger.warning("caught IO exception trying to open output stream for " + outputLocation); return null; } try { rescaleImage(fullSizeImage, width, height, size, outputFileStream); } catch (Exception ioex) { logger.warning("caught Exceptiopn trying to create rescaled image " + outputLocation); return null; <START> } finally <END> { try{outputFileStream.close();}catch(IOException ic){} } return outputLocation; }</code><technical_language>line 228 reported in Eclipse a leak FileOutputStream create Channel is closed</technical_language>

Target:
public static String rescaleImage(BufferedImage fullSizeImage, int width, int height, int size, String fileLocation) { String outputLocation = fileLocation + "." + THUMBNAIL_SUFFIX + size; File outputFile = new File(outputLocation); OutputStream outputFileStream = null; try { outputFileStream = new FileOutputStream(outputFile); } catch (IOException ioex) { logger.warning("caught IO exception trying to open output stream for " + outputLocation); return null; } try { rescaleImage(fullSizeImage, width, height, size, outputFileStream); } catch (Exception ioex) { logger.warning("caught Exceptiopn trying to create rescaled image " + outputLocation); return null; } finally { IOUtils.closeQuietly(outputFileStream); } return outputLocation; }
Source:
<code>void setOptions(Map<String, String> options) { <START> this.options = new HashMap<>(options); <END> }</code><technical_language>options Immutable</technical_language>

Target:
void setOptions(Map<String, String> options) { this.options = ImmutableMap.copyOf(options); }
Source:
<code>public DefaultClasspathScanner(final List<String> rootPackages) { Assert.requireNonNull(rootPackages, "rootPackages"); LOG.trace("Scanning class path for root packages {}", Arrays.toString(rootPackages.toArray())); ConfigurationBuilder configuration = ConfigurationBuilder.build(DefaultClasspathScanner.class.getClassLoader()); configuration = configuration.setExpandSuperTypes(false); if(rootPackages.size() > 0) { configuration = configuration.forPackages(rootPackages.toArray(new String[rootPackages.size()])); configuration = configuration.setUrls(rootPackages.stream().map(rootPackage -> ClasspathHelper.forPackage(rootPackage)).flatMap(list -> list.stream()).collect(Collectors.toList())); configuration = configuration.filterInputsBy(new FilterBuilder().includePackage(rootPackages.toArray(new String[rootPackages.size()]))); } try { final Enumeration<URL> res = DefaultClasspathScanner.class.getClassLoader().getResources(""); configuration.getUrls().addAll(Collections.list(res)); } catch (final IOException e) { throw new RuntimeException("Error in Dolphin Platform controller class scan", e); } final Set<URL> urls = configuration.getUrls(); final List<URL> toRemove = new ArrayList<>(); <START> for (URL url : urls) { <END> if (url.toString().endsWith(".jnilib")) { toRemove.add(url); } } LOG.trace("Configuration Urls {}", Arrays.toString(configuration.getUrls().toArray())); for (URL url : toRemove) { LOG.trace("Url removed {}", url.toString()); configuration.getUrls().remove(url); } reflections = new Reflections(configuration); }</code><technical_language>Add final keyword</technical_language>

Target:
public DefaultClasspathScanner(final List<String> rootPackages) { Assert.requireNonNull(rootPackages, "rootPackages"); LOG.trace("Scanning class path for root packages {}", Arrays.toString(rootPackages.toArray())); ConfigurationBuilder configuration = ConfigurationBuilder.build(DefaultClasspathScanner.class.getClassLoader()); configuration = configuration.setExpandSuperTypes(false); if(rootPackages.size() > 0) { configuration = configuration.forPackages(rootPackages.toArray(new String[rootPackages.size()])); configuration = configuration.setUrls(rootPackages.stream().map(rootPackage -> ClasspathHelper.forPackage(rootPackage)).flatMap(list -> list.stream()).collect(Collectors.toList())); configuration = configuration.filterInputsBy(new FilterBuilder().includePackage(rootPackages.toArray(new String[rootPackages.size()]))); } try { final Enumeration<URL> res = DefaultClasspathScanner.class.getClassLoader().getResources(""); configuration.getUrls().addAll(Collections.list(res)); } catch (final IOException e) { throw new RuntimeException("Error in Dolphin Platform controller class scan", e); } final Set<URL> urls = configuration.getUrls(); final List<URL> toRemove = new ArrayList<>(); for (final URL url : urls) { if (url.toString().endsWith(".jnilib")) { toRemove.add(url); } } LOG.trace("Configuration Urls {}", Arrays.toString(configuration.getUrls().toArray())); for (final URL url : toRemove) { LOG.trace("Url removed {}", url.toString()); configuration.getUrls().remove(url); } reflections = new Reflections(configuration); }
Source:
<code>public void should_implement_toString_showing_descriptions_of_inner_Conditions() { <START> String expected = "all of:<[\n Condition 1,\n Condition 2\n]>"; <END> assertThat(allOf).hasToString(expected); }</code><technical_language>\n replaced %n String.format for OS independent (thank windows \n\r line separator)</technical_language>

Target:
public void should_implement_toString_showing_descriptions_of_inner_Conditions() { String expected = String.format("all of:<[%n Condition 1,%n Condition 2%n]>"); assertThat(allOf).hasToString(expected); }
Source:
<code><START> protected MongoQuery<? extends MongoBizEntity> getQuery(Tenant<?> tenant) { <END> return mango.select(getEntityClass()).eq(TenantAware.TENANT, tenant); }</code><technical_language>suggestion protected MongoQuery<? extends MongoTenantAware> getQuery(Tenant<?> tenant) {</technical_language>

Target:
protected MongoQuery<? extends MongoTenantAware> getQuery(Tenant<?> tenant) { return mango.select(getEntityClass()).eq(TenantAware.TENANT, tenant); }
Source:
<code>private static <T> SpanSubscriptionProvider<T> scopePassingSpanSubscription( BeanFactory beanFactory, Scannable scannable, CoreSubscriber<? super T> sub) { return new SpanSubscriptionProvider<T>( beanFactory, sub, sub.currentContext(), <START> null) { <END> @Override SpanSubscription newCoreSubscriber(Tracing tracing) { return new ScopePassingSpanSubscriber<T>( sub, sub != null ? sub.currentContext() : Context.empty(), tracing); } }; }</code><technical_language>is name spans. I suggest pass scannable call scannable.name() necessary</technical_language>

Target:
private static <T> SpanSubscriptionProvider<T> scopePassingSpanSubscription( BeanFactory beanFactory, Scannable scannable, CoreSubscriber<? super T> sub) { return new SpanSubscriptionProvider<T>( beanFactory, sub, sub.currentContext(), scannable) { @Override SpanSubscription newCoreSubscriber(Tracing tracing) { return new ScopePassingSpanSubscriber<T>( sub, sub != null ? sub.currentContext() : Context.empty(), tracing); } }; }
Source:
<code>void recalculateRegularity(LocalDate firstAppearance, LocalDate lastAppearance) { <START> final int kAppeared = 1; <END> final int kNotAppeared = 0; Set<LocalDate> remainingAdditions = new HashSet<>(); Set<LocalDate> remainingExclusions = new HashSet<>(); @SuppressWarnings("unchecked") HashSet<LocalDate>[][] subsets = new HashSet[DateTimeConstants.SUNDAY][kAppeared + 1]; for (int dayOfWeek = DateTimeConstants.MONDAY; dayOfWeek <= DateTimeConstants.SUNDAY; dayOfWeek++) { subsets[dayOfWeek - 1][kNotAppeared] = new HashSet<>(); subsets[dayOfWeek - 1][kAppeared] = new HashSet<>(); } for (LocalDate day = firstAppearance; !day.isAfter(lastAppearance); day = day.plusDays(1)) { subsets[day.getDayOfWeek() - 1][isMatch(day) ? kAppeared : kNotAppeared].add(day); } for (int dayOfWeek = DateTimeConstants.MONDAY; dayOfWeek <= DateTimeConstants.SUNDAY; dayOfWeek++) { if (subsets[dayOfWeek - 1][kAppeared].size() > subsets[dayOfWeek - 1][kNotAppeared].size()) { daysOfWeek.add(dayOfWeek); remainingExclusions.addAll(subsets[dayOfWeek - 1][kNotAppeared]); } else { daysOfWeek.remove(dayOfWeek); remainingAdditions.addAll(subsets[dayOfWeek - 1][kAppeared]); } } additions = remainingAdditions; exclusions = remainingExclusions; }</code><technical_language>mentioned above: do introduce unreadable variable names</technical_language>

Target:
void recalculateRegularity(LocalDate firstAppearance, LocalDate lastAppearance) { final int appeared = 1; final int notAppeared = 0; Set<LocalDate> remainingAdditions = new HashSet<>(); Set<LocalDate> remainingExclusions = new HashSet<>(); @SuppressWarnings("unchecked") HashSet<LocalDate>[][] subsets = new HashSet[DateTimeConstants.SUNDAY][appeared + 1]; for (int dayOfWeek = DateTimeConstants.MONDAY; dayOfWeek <= DateTimeConstants.SUNDAY; dayOfWeek++) { subsets[dayOfWeek - 1][notAppeared] = new HashSet<>(); subsets[dayOfWeek - 1][appeared] = new HashSet<>(); } for (LocalDate day = firstAppearance; !day.isAfter(lastAppearance); day = day.plusDays(1)) { subsets[day.getDayOfWeek() - 1][isMatch(day) ? appeared : notAppeared].add(day); } for (int dayOfWeek = DateTimeConstants.MONDAY; dayOfWeek <= DateTimeConstants.SUNDAY; dayOfWeek++) { if (subsets[dayOfWeek - 1][appeared].size() > subsets[dayOfWeek - 1][notAppeared].size()) { daysOfWeek.add(dayOfWeek); remainingExclusions.addAll(subsets[dayOfWeek - 1][notAppeared]); } else { daysOfWeek.remove(dayOfWeek); remainingAdditions.addAll(subsets[dayOfWeek - 1][appeared]); } } additions = remainingAdditions; exclusions = remainingExclusions; }
Source:
<code>public CompletionStage<RestResponse> exec(String taskName, Map<String, ?> parameters) { <START> Objects.nonNull(taskName); <END> Objects.nonNull(parameters); Request.Builder builder = new Request.Builder(); StringBuilder sb = new StringBuilder(baseURL).append('/').append(taskName); sb.append("?action=exec"); for (Map.Entry<String, ?> parameter : parameters.entrySet()) { sb.append("&param."); sb.append(parameter.getKey()); sb.append('='); sb.append(sanitize(parameter.getValue().toString())); } builder.url(sb.toString()); return client.execute(builder); }</code><technical_language>Objects.requireNonNull(taskName);</technical_language>

Target:
public CompletionStage<RestResponse> exec(String taskName, Map<String, ?> parameters) { Objects.requireNonNull(taskName); Objects.requireNonNull(parameters); Request.Builder builder = new Request.Builder(); StringBuilder sb = new StringBuilder(baseURL).append('/').append(taskName); sb.append("?action=exec"); for (Map.Entry<String, ?> parameter : parameters.entrySet()) { sb.append("&param."); sb.append(parameter.getKey()); sb.append('='); sb.append(sanitize(parameter.getValue().toString())); } builder.url(sb.toString()); return client.execute(builder); }
Source:
<code>public void getActiveConditions_shouldGetActiveConditions() { executeDataSet(CONDITION_XML); int patientId = 2; <START> expectedException = ExpectedException.none(); <END> List<Condition> activeConditions = conditionService.getActiveConditions(patientService.getPatient(patientId)); Condition firstActiveCondition = activeConditions.get(0); Condition secondActiveCondition = activeConditions.get(1); String firstUUID = "2cc6880e-2c46-11e4-9138-a6c5e4d20fb7"; String secondUUID = "2cc6880e-2c46-15e4-9038-a6c5e4d22fb7"; Assert.assertFalse(activeConditions.isEmpty()); Assert.assertTrue(activeConditions.size() == 2); Assert.assertEquals(firstUUID,firstActiveCondition.getUuid()); Assert.assertEquals(secondUUID, secondActiveCondition.getUuid()); }</code><technical_language>is of expectedException</technical_language>

Target:
public void getActiveConditions_shouldGetActiveConditions() { List<Condition> activeConditions = conditionService.getActiveConditions(patientService.getPatient(2)); Assert.assertTrue(activeConditions.size() == 2); Assert.assertEquals("2cc6880e-2c46-11e4-9138-a6c5e4d20fb7",activeConditions.get(0).getUuid()); Assert.assertEquals("2cc6880e-2c46-15e4-9038-a6c5e4d22fb7", activeConditions.get(1).getUuid()); }
Source:
<code>public Neo4jTemplate neo4jTemplate() throws Exception { <START> return new Neo4jTemplate(mappingInfrastructure().getObject(), getTypeSafetyPolicy()); <END> }</code><technical_language>part of mapping infrastructure? defaulting is handled there</technical_language>

Target:
public Neo4jTemplate neo4jTemplate() throws Exception { return new Neo4jTemplate(mappingInfrastructure().getObject()); }
Source:
<code>public void query_explain_multipleIndexes_invalidIndexName() { StubMappingScope scope = indexManager.createScope( otherIndexManager ); ElasticsearchSearchQuery<DocumentReference> query = scope.query().extension( ElasticsearchExtension.get() ) .where( f -> f.id().matching( FIRST_ID ) ) .toQuery(); Assertions.assertThatThrownBy( () -> query.explain( "NotAMappedName", FIRST_ID ) ) .isInstanceOf( SearchException.class ) .hasMessageContaining( "type name 'NotAMappedName' is not among the mapped type targeted by this query: [", <START> INDEX_NAME, OTHER_INDEX_NAME <END> ); }</code><technical_language>this TYPE_NAME, OTHER_TYPE_NAME? Also, remove comma square bracket? wrong here</technical_language>

Target:
public void query_explain_multipleIndexes_invalidIndexName() { StubMappingScope scope = indexManager.createScope( otherIndexManager ); ElasticsearchSearchQuery<DocumentReference> query = scope.query().extension( ElasticsearchExtension.get() ) .where( f -> f.id().matching( FIRST_ID ) ) .toQuery(); Assertions.assertThatThrownBy( () -> query.explain( "NotAMappedName", FIRST_ID ) ) .isInstanceOf( SearchException.class ) .hasMessageContaining( "type name 'NotAMappedName' is not among the mapped type targeted by this query: [" + TYPE_NAME + ", " + OTHER_TYPE_NAME + "]" ); }
Source:
<code>public static ExecutorConfiguration defaultConfiguration() { <START> return new ExecutorConfiguration(null, null, null); <END> }</code><technical_language>ExecutorConfiguration(Optional.absent(), Optional.absent(), Optional.absent());</technical_language>

Target:
public static ExecutorConfiguration defaultConfiguration() { return new ExecutorConfiguration(Optional.absent(), Optional.absent(), Optional.absent()); }
Source:
<code>public void testTransferImage() { droplet = api.getDropletApi().create("imagetransferdroplet", defaultImage.getId(), defaultSize.getId(), defaultRegion.getId()); assertTrue(droplet.getId() > 0, "Created droplet id should be > 0"); assertTrue(droplet.getEventId() > 0, "Droplet creation event id should be > 0"); waitForEvent(droplet.getEventId()); int powerOffEvent = api.getDropletApi().powerOff(droplet.getId()); waitForEvent(powerOffEvent); int snapshotEvent = api.getDropletApi().snapshot(droplet.getId(), "imagetransfersnapshot"); waitForEvent(snapshotEvent); snapshot = find(api.getImageApi().list(), byName("imagetransfersnapshot")); Region newRegion = regions.get(1); int transferEvent = api.getImageApi().transfer(snapshot.getId(), newRegion.getId()); <START> assertTrue(transferEvent > 0, "Event id should be > 0"); <END> waitForEvent(transferEvent); }</code><technical_language>"Transfer event id.."</technical_language>

Target:
public void testTransferImage() { droplet = api.getDropletApi().create("imagetransferdroplet", defaultImage.getId(), defaultSize.getId(), defaultRegion.getId()); assertTrue(droplet.getId() > 0, "Created droplet id should be > 0"); assertTrue(droplet.getEventId() > 0, "Droplet creation event id should be > 0"); waitForEvent(droplet.getEventId()); int powerOffEvent = api.getDropletApi().powerOff(droplet.getId()); waitForEvent(powerOffEvent); int snapshotEvent = api.getDropletApi().snapshot(droplet.getId(), "imagetransfersnapshot"); waitForEvent(snapshotEvent); snapshot = find(api.getImageApi().list(), byName("imagetransfersnapshot")); Region newRegion = regions.get(1); int transferEvent = api.getImageApi().transfer(snapshot.getId(), newRegion.getId()); assertTrue(transferEvent > 0, "Transfer event id should be > 0"); waitForEvent(transferEvent); }
Source:
<code>private BooleanSupplier shouldRateLimit(String client) { <START> return Suppliers.compose(f -> f.shouldRateLimit(client), lockControlConfigSupplier::get)::get; <END> }</code><technical_language>nit: config for param? if easier write () -> lockControlConfigSupplier.get().shouldRateLimit(client) this point</technical_language>

Target:
private BooleanSupplier shouldRateLimit(String client) { return () -> lockControlConfigSupplier.get().shouldRateLimit(client); }
Source:
<code>public Date getStartTime() { <START> return this.startTime; <END> }</code><technical_language>This startTime property is mutable. diff, correct before.</technical_language>

Target:
public Date getStartTime() { return new Date(this.startTime.getTime()); }
Source:
<code>public void printAgreementMatrix() { int[][] matrix = new int[this.numLabels][this.numLabels]; for (int i = 0; i < this.numItems; i++) { matrix[this.annotation[i][0]][this.annotation[i][1]]++; } <START> <END> for (int i = 0; i < numLabels; i++) { for (int j = 0; j < numLabels; j++) { logger.info(matrix[i][j] + "\t"); } logger.info(""); } }</code><technical_language>this is a method word "print" in name, assume output STDOUT</technical_language>

Target:
public void printAgreementMatrix() { int[][] matrix = new int[this.numLabels][this.numLabels]; for (int i = 0; i < this.numItems; i++) { matrix[this.annotation[i][0]][this.annotation[i][1]]++; } for (int i = 0; i < numLabels; i++) { for (int j = 0; j < numLabels; j++) { System.out.print(matrix[i][j] + "\t"); } System.out.println(); } }
Source:
<code>public static boolean isReachable(String host, int port) { Socket socket = null; boolean reachable; try { if (ProxyConfiguration.hasSocks()) { Proxy socksProxy = new Proxy(Proxy.Type.SOCKS,new InetSocketAddress(ProxyConfiguration.socks().getAddress(), ProxyConfiguration.socks().getPort())); socket = new Socket(socksProxy); <START> } else if (ProxyConfiguration.hasProxyConfig()) { <END> Proxy httpProxy = new Proxy(Proxy.Type.HTTP,new InetSocketAddress(ProxyConfiguration.proxyAddress().getAddress(),ProxyConfiguration.proxyAddress().getPort())); socket = new Socket(httpProxy); } else { socket = new Socket(); } socket.connect(new InetSocketAddress(host, port), 2000); reachable = true; } catch (IOException e) { reachable = false; } finally { if (socket != null) { try { socket.close(); } catch (IOException e) { } } } return reachable; }</code><technical_language>here,</technical_language>

Target:
public static boolean isReachable(String host, int port) { Socket socket = null; boolean reachable; try { if (ProxyConfiguration.hasSocksProxyConfig()) { Proxy socksProxy = new Proxy(Proxy.Type.SOCKS,new InetSocketAddress(ProxyConfiguration.socks().getAddress(), ProxyConfiguration.socks().getPort())); socket = new Socket(socksProxy); } else if (ProxyConfiguration.hasHttpProxyConfig()) { Proxy httpProxy = new Proxy(Proxy.Type.HTTP,new InetSocketAddress(ProxyConfiguration.proxyAddress().getAddress(),ProxyConfiguration.proxyAddress().getPort())); socket = new Socket(httpProxy); } else { socket = new Socket(); } socket.connect(new InetSocketAddress(host, port), 2000); reachable = true; } catch (IOException e) { reachable = false; } finally { if (socket != null) { try { socket.close(); } catch (IOException e) { } } } return reachable; }
Source:
<code>public List<TextHit> query(Node property, String qs, String graphURI, String lang, int limit, String highlight) { try (IndexReader indexReader = DirectoryReader.open(directory)) { return query$(indexReader, property, qs, graphURI, lang, limit, highlight) ; } catch (ParseException ex) { throw new TextIndexParseException(qs, ex.getMessage()) ; } catch (Exception ex) { <START> ex.printStackTrace(); END> throw new TextIndexException("query", ex) ; } }</code><technical_language>Remove this turn log debug</technical_language>

Target:
public List<TextHit> query(Node property, String qs, String graphURI, String lang, int limit, String highlight) { try (IndexReader indexReader = DirectoryReader.open(directory)) { return query$(indexReader, property, qs, graphURI, lang, limit, highlight) ; } catch (ParseException ex) { throw new TextIndexParseException(qs, ex.getMessage()) ; } catch (Exception ex) { throw new TextIndexException("query", ex) ; } }
Source:
<code>public @NonNull List<@NonNull String> getMarkerCategories() { ITmfTrace activeTrace = TmfTraceManager.getInstance().getActiveTrace(); if (activeTrace == null) { return Collections.emptyList(); } UUID uuid = activeTrace.getUUID(); Collection<String> collection = fCategories.computeIfAbsent(uuid, t -> { ContextDataSource dataProvider = DataProviderManager.getInstance().getDataProvider(activeTrace, ContextDataSource.ID, ContextDataSource.class); if (dataProvider == null) { return Collections.emptyList(); } TmfModelResponse<@NonNull List<@NonNull TimeGraphEntryModel>> <START> tree = <END> dataProvider.fetchTree(new TimeQueryFilter(Collections.emptyList()), new NullProgressMonitor()); List<@NonNull TimeGraphEntryModel> model = tree.getModel(); if (model == null) { return Collections.emptyList(); } Set<String> data = new HashSet<>(); for (TmfTreeDataModel elem : model) { data.add(elem.getName()); } List<String> dataList = Lists.newArrayList(data); dataList.sort(null); return dataList; }); List<String> retVal = new ArrayList<>(collection); retVal.sort(null); return retVal; }</code><technical_language>beware of caching incomplete results</technical_language>

Target:
public @NonNull List<@NonNull String> getMarkerCategories() { ITmfTrace activeTrace = TmfTraceManager.getInstance().getActiveTrace(); if (activeTrace == null) { return Collections.emptyList(); } ContextDataProvider dataProvider = DataProviderManager.getInstance().getDataProvider(activeTrace, ContextDataProvider.ID, ContextDataProvider.class); if (dataProvider == null) { return Collections.emptyList(); } TmfModelResponse<@NonNull List<@NonNull TimeGraphEntryModel>> tree = dataProvider.fetchTree(new TimeQueryFilter(Collections.emptyList()), new NullProgressMonitor()); List<@NonNull TimeGraphEntryModel> model = tree.getModel(); if (model == null) { return Collections.emptyList(); } Set<String> data = new HashSet<>(); for (TmfTreeDataModel elem : model) { data.add(elem.getName()); } List<String> dataList = Lists.newArrayList(data); dataList.sort(null); return dataList; }
Source:
<code>private void rebuildTokenCache(boolean initial) throws IOException { localTokenCache.clear(); List<String> zkTokens; try { zkTokens = zookeeper.getChildren(TOKEN_PATH, false); } catch (KeeperException | InterruptedException e) { throw new IOException("Tokens cannot be fetched from path " + TOKEN_PATH, e); } byte[] data; for (String tokenPath : zkTokens) { try { data = zkClient.getData().forPath( ZK_DTSM_TOKENS_ROOT + "/" + tokenPath); } catch (KeeperException.NoNodeException e) { LOG.debug("No node in path [" + tokenPath + "]"); continue; } catch (Exception ex) { throw new IOException(ex); } <START> processTokenAddOrUpdate(data); <END> AbstractDelegationTokenIdentifier ident = createIdentifier(); DataInputStream din = new DataInputStream(new ByteArrayInputStream(data)); ident.readFields(din); localTokenCache.add(ident); } if (!initial) { for (AbstractDelegationTokenIdentifier ident : currentTokens.keySet()) { if (!localTokenCache.contains(ident)) { currentTokens.remove(ident); } } } }</code><technical_language>double deserialize operations, if merge IMO</technical_language>

Target:
private void rebuildTokenCache(boolean initial) throws IOException { localTokenCache.clear(); List<String> zkTokens; try { zkTokens = zookeeper.getChildren(TOKEN_PATH, false); } catch (KeeperException | InterruptedException e) { throw new IOException("Tokens cannot be fetched from path " + TOKEN_PATH, e); } byte[] data; for (String tokenPath : zkTokens) { try { data = zkClient.getData().forPath( ZK_DTSM_TOKENS_ROOT + "/" + tokenPath); } catch (KeeperException.NoNodeException e) { LOG.debug("No node in path [" + tokenPath + "]"); continue; } catch (Exception ex) { throw new IOException(ex); } AbstractDelegationTokenIdentifier ident = processTokenAddOrUpdate(data); localTokenCache.add(ident); } if (!initial) { for (AbstractDelegationTokenIdentifier ident : currentTokens.keySet()) { if (!localTokenCache.contains(ident)) { currentTokens.remove(ident); } } } }
Source:
<code>public ProgramEnrollment updateProgramEnrollment(String configName, ProgramEnrollment programEnrollment) { ProgramEnrollment updatedProgramEnrollment = null; validateProgramEnrollmentToUpdate(programEnrollment); try { Config config = configService.getConfigByName(configName); <START> if (programEnrollment.getAttributes() != null && !programEnrollment.getAttributes().isEmpty()) { <END> updatedProgramEnrollment = programEnrollmentResource.updateBahmniProgramEnrollment(config, programEnrollment); } else { updatedProgramEnrollment = programEnrollmentResource.updateProgramEnrollment(config, programEnrollment); } return updatedProgramEnrollment; } catch (HttpClientErrorException e) { throw new OpenMRSException("Could not update program enrollment with uuid: " + programEnrollment.getUuid(), e); } }</code><technical_language>CollectionUtils.isNotEmpty</technical_language>

Target:
public ProgramEnrollment updateProgramEnrollment(String configName, ProgramEnrollment programEnrollment) { ProgramEnrollment updatedProgramEnrollment = null; validateProgramEnrollmentToUpdate(programEnrollment); try { Config config = configService.getConfigByName(configName); if (CollectionUtils.isNotEmpty(programEnrollment.getAttributes())) { updatedProgramEnrollment = programEnrollmentResource.updateBahmniProgramEnrollment(config, programEnrollment); } else { updatedProgramEnrollment = programEnrollmentResource.updateProgramEnrollment(config, programEnrollment); } return updatedProgramEnrollment; } catch (HttpClientErrorException e) { throw new OpenMRSException("Could not update program enrollment with uuid: " + programEnrollment.getUuid(), e); } }
Source:
<code>public void sendMessagesToPushNetwork(final MessageHolderWithTokens msg) { final Variant variant = msg.getVariant(); final UnifiedPushMessage unifiedPushMessage = msg.getUnifiedPushMessage(); final Collection<String> deviceTokens = msg.getDeviceTokens(); <START> logger.info(String.format("Received UnifiedPushMessage from JMS queue, will now trigger the Push Notification delivery for the %s variant (%s)", variant.getType().getTypeName(), variant.getVariantID())); <END> senders.select(new SenderTypeLiteral(variant.getType())).get() .sendPushMessage(variant, deviceTokens, unifiedPushMessage, msg.getPushMessageInformation().getId(), new SenderServiceCallback( variant, deviceTokens.size(), msg.getPushMessageInformation() ) ); }</code><technical_language>log statement changed</technical_language>

Target:
public void sendMessagesToPushNetwork(final MessageHolderWithTokens msg) { final Variant variant = msg.getVariant(); final UnifiedPushMessage unifiedPushMessage = msg.getUnifiedPushMessage(); final Collection<String> deviceTokens = msg.getDeviceTokens(); logger.info("UnifiedPushMessage was successfully received. Push Notification delivery for the variant ({}) will now be triggered.", variant.getType().getTypeName(), variant.getVariantID()); senders.select(new SenderTypeLiteral(variant.getType())).get() .sendPushMessage(variant, deviceTokens, unifiedPushMessage, msg.getPushMessageInformation().getId(), new SenderServiceCallback( variant, deviceTokens.size(), msg.getPushMessageInformation() ) ); }
Source:
<code>public static void Init() { mUpdateVmsStatic = new ObjectIdentityChecker(VmHandler.class, Arrays.asList(new String[] { "VM", "VmStatic", "VmDynamic" }), VMStatus.class); mUpdateVmsStatic.AddPermittedFields(new String[] { "vm_name", "description", "domain", "os", "osType", "creation_date", "num_of_monitors", "allowConsoleReconnect", "usb_policy", "is_auto_suspend", "auto_startup", "dedicated_vm_for_vds", "default_display_type", "priority", "default_boot_sequence", "initrd_url", "kernel_url", "kernel_params", "migrationSupport", "minAllocatedMem", "quotaId", "quotaName", "quotaEnforcementType", "cpuPinning", "vmPayload", "balloonEnabled"}); mUpdateVmsStatic.AddFields( Arrays.asList(new Enum<?>[] { VMStatus.Down }), Arrays.asList(new String[] { "vds_group_id", "time_zone", "is_stateless", "nice_level", "mem_size_mb", "num_of_sockets", "cpu_per_socket", "iso_path", "userDefinedProperties", "predefinedProperties", "customProperties" })); <START> mUpdateVmsStatic.AddIgnoredFields(Arrays.asList(new String[] { "images", "interfaces"})); <END> }</code><technical_language>default is ignored? I if add fields updated no</technical_language>

Target:
public static void Init() { mUpdateVmsStatic = new ObjectIdentityChecker(VmHandler.class, Arrays.asList(new String[] { "VM", "VmStatic", "VmDynamic" }), VMStatus.class); mUpdateVmsStatic.AddPermittedFields(new String[] { "vm_name", "description", "domain", "os", "osType", "creation_date", "num_of_monitors", "allowConsoleReconnect", "usb_policy", "is_auto_suspend", "auto_startup", "dedicated_vm_for_vds", "default_display_type", "priority", "default_boot_sequence", "initrd_url", "kernel_url", "kernel_params", "migrationSupport", "minAllocatedMem", "quotaId", "quotaName", "quotaEnforcementType", "cpuPinning", "vmPayload", "balloonEnabled", "images", "interfaces" }); mUpdateVmsStatic.AddFields( Arrays.asList(new Enum<?>[] { VMStatus.Down }), Arrays.asList(new String[] { "vds_group_id", "time_zone", "is_stateless", "nice_level", "mem_size_mb", "num_of_sockets", "cpu_per_socket", "iso_path", "userDefinedProperties", "predefinedProperties", "customProperties" })); }
Source:
<code>public boolean test_sentence (String sent, String sf) { re.do_penn_tagging = false; re.setMaxParses(1); Sentence sntc = re.processSentence(sent); ParsedSentence parse = sntc.getParses().get(0); String rs = SimpleView.printBinaryRelations(parse); String urs = SimpleView.printUnaryRelations(parse); ArrayList<String> exp = split(sf); ArrayList<String> brgot = split(rs); ArrayList<String> urgot = split(urs); int sizeOfGotRelations= brgot.size(); for (int i=0; i< exp.size(); i++) { if(!brgot.contains((String)exp.get(i))) { if(!urgot.contains(exp.get(i))) { System.err.println("Error: content miscompare:\n" + "\tExpected = " + exp + "\n" + "\tGot Binary Relations = " + brgot + "\n" + <START> "\tGot Uinary Relations = " + urgot + "\n" + <END> "\tSentence = " + sent); subfail ++; fail ++; sentfail.add(sent); return false; } sizeOfGotRelations++; } } if (exp.size() < sizeOfGotRelations) { System.err.println("Error: size miscompare:\n" + "\tExpected = " + exp + "\n" + "\tGot Binary Relations = " + brgot + "\n" + "\tGot Uinary Relations = " + urgot + "\n" + "\tSentence = " + sent); subfail ++; fail ++; sentfail.add(sent); return false; } subpass ++; pass ++; return true; }</code><technical_language>Unary is mis-spelled</technical_language>

Target:
public boolean test_sentence (String sent, String sf) { re.do_penn_tagging = false; re.setMaxParses(1); Sentence sntc = re.processSentence(sent); ParsedSentence parse = sntc.getParses().get(0); String rs = SimpleView.printBinaryRelations(parse); String urs = SimpleView.printUnaryRelations(parse); ArrayList<String> exp = split(sf); ArrayList<String> brgot = split(rs); ArrayList<String> urgot = split(urs); int sizeOfGotRelations= brgot.size(); for (int i=0; i< exp.size(); i++) { if(!brgot.contains((String)exp.get(i))) { if(!urgot.contains(exp.get(i))) { System.err.println("Error: content miscompare:\n" + "\tExpected = " + exp + "\n" + "\tGot Binary Relations = " + brgot + "\n" + "\tGot Unary Relations = " + urgot + "\n" + "\tSentence = " + sent); subfail ++; fail ++; sentfail.add(sent); return false; } sizeOfGotRelations++; } } if (exp.size() < sizeOfGotRelations) { System.err.println("Error: size miscompare:\n" + "\tExpected = " + exp + "\n" + "\tGot Binary Relations = " + brgot + "\n" + "\tGot Unary Relations = " + urgot + "\n" + "\tSentence = " + sent); subfail ++; fail ++; sentfail.add(sent); return false; } subpass ++; pass ++; return true; }
Source:
<code>private int runDeleteQuestionDialog(List<String> resNames) { StringBuilder message = new StringBuilder(MessageFormat.format("Delete the following resources from device \"{0}\":", device.getName())); for (String name : resNames) { message.append("\n\t"); message.append(name); <START> END> } MessageDialog dialog = new MessageDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Fully clean device", null, message.toString(), MessageDialog.QUESTION, new String[] { "Delete", "Cancle" }, 0); return dialog.open(); }</code><technical_language>shoulnd't this line above</technical_language>

Target:
private int runDeleteQuestionDialog(List<String> resNames) { StringBuilder message = new StringBuilder(MessageFormat.format("Delete the following resources from device \"{0}\":", device.getName())); for (String name : resNames) { message.append("\n\t"); message.append(name); } MessageDialog dialog = new MessageDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Fully clean device", null, message.toString(), MessageDialog.QUESTION, new String[] { "Delete", SWT.getMessage("SWT_Cancel") }, 0); return dialog.open(); }
Source:
<code>private void flagBadConfig(String message) { <START> logger.warn(message); <END> properlyConfigured = false; updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, message); }</code><technical_language>sufficient in updateStatus duplicated in log files</technical_language>

Target:
private void flagBadConfig(String message) { properlyConfigured = false; updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, message); }
Source:
<code>private Runnable makeFlyWeightTaskBuildable(final BuildableItem p){ if (p.task instanceof FlyweightTask) { Jenkins h = Jenkins.getInstance(); Map<Node, Integer> hashSource = new HashMap<Node, Integer>(h.getNodes().size()); hashSource.put(h, Math.max(h.getNumExecutors() * 100, 1)); for (Node n : h.getNodes()) { hashSource.put(n, n.getNumExecutors() * 100); } ConsistentHash<Node> hash = new ConsistentHash<Node>(NODE_HASH); hash.addAll(hashSource); for (Node n : hash.list(p.task.getFullDisplayName())) { final Computer c = n.toComputer(); if (n.canTake(p) != null) continue; <START> if (c == null || c.isOffline()) continue; <END> return new Runnable() { @Override public void run() { c.startFlyWeightTask(new WorkUnitContext(p).createWorkUnit(p.task)); makePending(p); } }; } } return null; }</code><technical_language>please add brackets ifs (as of change this line)</technical_language>

Target:
private Runnable makeFlyWeightTaskBuildable(final BuildableItem p){ if (p.task instanceof FlyweightTask) { Jenkins h = Jenkins.getInstance(); Map<Node, Integer> hashSource = new HashMap<Node, Integer>(h.getNodes().size()); hashSource.put(h, Math.max(h.getNumExecutors() * 100, 1)); for (Node n : h.getNodes()) { hashSource.put(n, n.getNumExecutors() * 100); } ConsistentHash<Node> hash = new ConsistentHash<Node>(NODE_HASH); hash.addAll(hashSource); Label lbl = p.getAssignedLabel(); for (Node n : hash.list(p.task.getFullDisplayName())) { final Computer c = n.toComputer(); if (c == null || c.isOffline()) { continue; } if (lbl!=null && !lbl.contains(n)) { continue; } if (n.canTake(p) != null) { continue; } return new Runnable() { @Override public void run() { c.startFlyWeightTask(new WorkUnitContext(p).createWorkUnit(p.task)); makePending(p); } }; } } return null; }
Source:
<code>@Test public void checkAbilityToStartServiceUsingCapabilities() throws Exception { <START> File appDir = new File("src/test/java/io/appium/java_client"); <END> File app = new File(appDir, "ApiDemos-debug.apk"); File pageFactoryDir = new File("src/test/java/io/appium/java_client/pagefactory_tests"); File chrome = new File(pageFactoryDir, "chromedriver.exe"); DesiredCapabilities caps = new DesiredCapabilities(); caps.setCapability(PLATFORM_NAME, "Android"); caps.setCapability(FULL_RESET, true); caps.setCapability(NEW_COMMAND_TIMEOUT, 60); caps.setCapability(APP_PACKAGE, "io.appium.android.apis"); caps.setCapability(APP_ACTIVITY, ".view.WebView1"); caps.setCapability(APP, app.getAbsolutePath()); caps.setCapability(CHROMEDRIVER_EXECUTABLE, chrome.getAbsolutePath()); service = new AppiumServiceBuilder().withCapabilities(caps).build(); service.start(); assertTrue(service.isRunning()); }</code><technical_language>common root paths. common part represented a constant, new File(parent, basename) constructor, parent is a constant</technical_language>

Target:
@Test public void checkAbilityToStartServiceUsingCapabilities() throws Exception { File app = ROOT_TEST_PATH.resolve("ApiDemos-debug.apk").toFile(); File chrome = ROOT_TEST_PATH.resolve("pagefactory_tests").resolve("chromedriver.exe").toFile(); DesiredCapabilities caps = new DesiredCapabilities(); caps.setCapability(PLATFORM_NAME, "Android"); caps.setCapability(FULL_RESET, true); caps.setCapability(NEW_COMMAND_TIMEOUT, 60); caps.setCapability(APP_PACKAGE, "io.appium.android.apis"); caps.setCapability(APP_ACTIVITY, ".view.WebView1"); caps.setCapability(APP, app.getAbsolutePath()); caps.setCapability(CHROMEDRIVER_EXECUTABLE, chrome.getAbsolutePath()); service = new AppiumServiceBuilder().withCapabilities(caps).build(); service.start(); assertTrue(service.isRunning()); }
Source:
<code>protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.debug("Entered OAuthTokenInfo QueryString: {}, Parameters : {}", request.getQueryString(), SSOUtils.getRequestParameters(request)); boolean isValidateRequest = false; try { String[] clientIdAndSecret = SSOUtils.getClientIdClientSecret(request); String token = SSOUtils.getRequestParameter(request, SSOConstants.HTTP_PARAM_TOKEN); String scope = SSOUtils.getRequestParameter(request, SSOConstants.HTTP_PARAM_SCOPE, ""); isValidateRequest = SSOUtils.scopeAsList(scope).contains("ovirt-ext=token-info:validate"); SSOUtils.validateClientAcceptHeader(request); SSOUtils.validateClientRequest(request, clientIdAndSecret[0], clientIdAndSecret[1], null, null); SSOUtils.validateRequestScope(request, token, scope); log.debug("Sending json response"); SSOSession ssoSession = SSOUtils.getSsoSession(request, clientIdAndSecret[0], token, true); ssoSession.getAssociatedClientIds().add(clientIdAndSecret[0]); String password = null; if (SSOUtils.scopeAsList(scope).contains("ovirt-ext=token:password-access")) { password = ssoSession.getPassword(); } SSOUtils.sendJsonData(response, isValidateRequest ? Collections.<String, Object>emptyMap() : <START> buildResponse(SSOUtils.getSsoContext(request), ssoSession, password)); <END> } catch(OAuthException ex) { SSOUtils.sendJsonDataWithMessage(response, ex, isValidateRequest); } catch(Exception ex) { SSOUtils.sendJsonDataWithMessage(response, SSOConstants.ERR_CODE_SERVER_ERROR, ex); } }</code><technical_language>acquire context servlet init hold a reference</technical_language>

Target:
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.debug("Entered OAuthTokenInfo QueryString: {}, Parameters : {}", request.getQueryString(), SSOUtils.getRequestParameters(request)); boolean isValidateRequest = false; try { String[] clientIdAndSecret = SSOUtils.getClientIdClientSecret(request); String token = SSOUtils.getRequestParameter(request, SSOConstants.HTTP_PARAM_TOKEN); String scope = SSOUtils.getRequestParameter(request, SSOConstants.HTTP_PARAM_SCOPE, ""); isValidateRequest = SSOUtils.scopeAsList(scope).contains("ovirt-ext=token-info:validate"); SSOUtils.validateClientAcceptHeader(request); SSOUtils.validateClientRequest(request, clientIdAndSecret[0], clientIdAndSecret[1], null, null); SSOUtils.validateRequestScope(request, token, scope); log.debug("Sending json response"); SSOSession ssoSession = SSOUtils.getSsoSession(request, clientIdAndSecret[0], token, true); ssoSession.getAssociatedClientIds().add(clientIdAndSecret[0]); String password = null; if (SSOUtils.scopeAsList(scope).contains("ovirt-ext=token:password-access")) { password = ssoSession.getPassword(); } SSOUtils.sendJsonData(response, isValidateRequest ? Collections.<String, Object>emptyMap() : buildResponse(ssoSession, password)); } catch(OAuthException ex) { SSOUtils.sendJsonDataWithMessage(response, ex, isValidateRequest); } catch(Exception ex) { SSOUtils.sendJsonDataWithMessage(response, SSOConstants.ERR_CODE_SERVER_ERROR, ex); } }
Source:
<code>public GeoJSONBuilder value(Object value) { if (value instanceof java.util.Date || value instanceof Calendar) { value = Converters.convert(value, String.class); } <START> if (value instanceof Double) { <END> value = roundToNumberOfDecimalPlaces((Double)value); } super.value(value); return this; }</code><technical_language>"else if" maybe</technical_language>

Target:
public GeoJSONBuilder value(Object value) { if (value instanceof java.util.Date || value instanceof Calendar) { value = Converters.convert(value, String.class); } super.value(value); return this; }
Source:
<code>public void setEnvironmentFlags(Map<String, String> flags) { try { metadata.update(metadata.new Updater() { @Override public void updateCopy(HostMetadata currentCopy) { currentCopy.set_environment_flags(flags); } }); <START> } catch (InterruptedException e) { <END> throw new RuntimeException(e); } catch (KeeperException e) { throw new RuntimeException(e); } }</code><technical_language>consolidate this catch (InterruptedException | KeeperException e)</technical_language>

Target:
public void setEnvironmentFlags(Map<String, String> flags) { try { metadata.update(metadata.new Updater() { @Override public void updateCopy(HostMetadata currentCopy) { currentCopy.set_environment_flags(flags); } }); } catch (InterruptedException | KeeperException e) { throw new RuntimeException(e); } }
Source:
<code>public void run() { int input = 0; Scanner sc = new Scanner(System.in); System.out.println("Welcome to our application!"); while (input != 4) { System.out.println("Option 1: Construct playlist! Enter foldername"); System.out.println("Option 2: About"); <START> System.out.println("Option 3: Play music!"); <END> System.out.println("Option 4: Close"); input = sc.nextInt(); switch (input) { case 1 : try { this.setFileName(sc.nextLine()); FolderLoader folderLoader = new FolderLoader(this.getFileName()); this.result = new Playlist(folderLoader.load()); } catch (Exception e) { System.out.println(e.getMessage()); } break; case 2 : System.out.println(this.aboutDevs()); break; case 3 : System.out.println("Let's play some music!"); break; default : break; } } sc.close(); }</code><technical_language>I thought include this in current sprint, remove for now. (else user confused this option nothing)</technical_language>

Target:
public void run() { Scanner sc = new Scanner(System.in); System.out.println("Welcome to our application!"); while (true) { System.out.println("Construct playlist! Enter foldername"); try { String fileName = sc.next(); FolderLoader folderLoader = new FolderLoader(fileName); Playlist result = new Playlist(folderLoader.load()); System.out.println("\\TODO!"); } catch (Exception e) { System.out.println(e.getMessage()); } sc.close(); } }
Source:
<code><START> public boolean <END> validatePMAgentPort() { String portStr = null; Integer port = getParameters().getAgent().getPort(); if (port == null) { if (getParameters().getAgent().getOptionsMap().containsKey(PORT)) { portStr = getParameters().getAgent().getOptionsMap().get(PORT); if (StringUtils.isNumeric(portStr)) { port = Integer.parseInt(portStr); } else { return false; } } else { return true; } } portStr = portStr == null ? getParameters().getAgent().getPort().toString() : portStr; return portStr.equals("") || ValidationUtils.validatePort(port); }</code><technical_language>this reduce protected, called of class hierarchy</technical_language>

Target:
protected boolean validatePMAgentPort() { Integer port = getParameters().getAgent().getPort(); if (port == null) { String portStr; if (getParameters().getAgent().getOptionsMap().containsKey(PORT)) { portStr = getParameters().getAgent().getOptionsMap().get(PORT); if (StringUtils.isNumeric(portStr)) { port = Integer.valueOf(portStr); } else { return false; } } else { return true; } } return port == null || ValidationUtils.validatePort(port); }
Source:
<code>public RepositoryVersion(@NonNull String version) { orgVersion = version; Matcher versionMatcher = VERSION_PATTERN.matcher(version); if (versionMatcher.matches()) { major = parseInt(versionMatcher.group(2)); if (versionMatcher.group(5) != null) { minor = parseInt(versionMatcher.group(5)); } else { <START> minor = null; <END> } if (versionMatcher.group(7) != null) { micro = parseInt(versionMatcher.group(7)); } else { micro = null; } if (versionMatcher.group(8) != null) { qualifier = (versionMatcher.group(8)); } else { qualifier = null; } } else { qualifier = version; } }</code><technical_language>fields final, I point of setting null explicitly</technical_language>

Target:
public RepositoryVersion(@NonNull String version) { orgVersion = version; Matcher versionMatcher = VERSION_PATTERN.matcher(version); if (versionMatcher.matches()) { major = parseInt(versionMatcher.group(2)); if (versionMatcher.group(4) != null) { minor = parseInt(versionMatcher.group(4)); } else { minor = null; } if (versionMatcher.group(6) != null) { micro = parseInt(versionMatcher.group(6)); } else { micro = null; } if (versionMatcher.group(7) != null) { qualifier = (versionMatcher.group(7)); } else { qualifier = null; } } else { major = null; minor = null; micro = null; qualifier = version; } normalizedVersion = buildNormalizedVersion(); }
Source:
<code>public void testGetAlertsPersistentStoreError() throws Exception { when(persistentStore.get(eq("alerts"), any())).thenThrow(new PersistenceException("error")); List<Map<String, Object>> alertList = adminAlert.getAlerts(); <START> assertThat(alertList.size(), equalTo(1)); <END> }</code><technical_language>assert is solr alert here</technical_language>

Target:
public void testGetAlertsPersistentStoreError() throws Exception { when(persistentStore.get(eq("alerts"), any())).thenThrow(new PersistenceException("error")); List<Map<String, Object>> alertList = adminAlert.getAlerts(); assertThat(alertList.size(), equalTo(1)); assertThat( alertList.get(0).get(Alert.SYSTEM_NOTICE_SOURCE_KEY), equalTo("unable_to_retrieve_alerts")); }
Source:
<code>private void discontinueExistingOrdersIfRequired(Order order) { if (!Order.Action.DISCONTINUE.equals(order.getAction())) return; Order previousOrder = order.getPreviousOrder(); if (previousOrder != null) { if (!previousOrder.getConcept().equals(order.getConcept())) { throw new APIException("Concept of previous order and this order should be the same"); } if (previousOrder.getDateStopped() == null) { discontinueOrder(previousOrder, order.getStartDate()); } return; } <START> List<? extends Order> orders = getActiveOrders(order.getPatient(), order.getClass(), order.getCareSetting(), false); <END> for (Order activeOrder : orders) { if (activeOrder.getConcept().equals(order.getConcept())) { order.setPreviousOrder(activeOrder); discontinueOrder(activeOrder, order.getStartDate()); return; } } throw new APIException("We could not find an active order with the concept " + order.getConcept() + " to discontinue. "); }</code><technical_language>I dont care setting order class matter, i filter</technical_language>

Target:
private void discontinueExistingOrdersIfRequired(Order order) { if (!Order.Action.DISCONTINUE.equals(order.getAction())) return; Order previousOrder = order.getPreviousOrder(); if (previousOrder != null) { if (!previousOrder.getConcept().equals(order.getConcept())) { throw new APIException("Concept of previous order and this order should be the same"); } if (previousOrder.getDateStopped() == null) { discontinue(previousOrder, order.getStartDate()); } return; } List<? extends Order> orders = getActiveOrders(order.getPatient(), order.getClass(), order.getCareSetting(), false); for (Order activeOrder : orders) { if (activeOrder.getConcept().equals(order.getConcept())) { order.setPreviousOrder(activeOrder); discontinue(activeOrder, order.getStartDate()); return; } } throw new APIException("Could not find an active order with the concept " + order.getConcept() + " to discontinue. "); }