auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public String convertStatementRankToJson(StatementRank rank) { <START> return rank.toString().toLowerCase(); <END> }</code><technical_language>Note: this is a robust code it, JSON string create depends name for a constant in Java. I do this too, in places string matter (so I need a readable representation for enum constant). In case, string is defined JSON format, rely Java name</technical_language>

Target:
String convertStatementRankToJson(StatementRank rank) { switch (rank) { case PREFERRED: return NAME_RANK_PREFERRED; case NORMAL: return NAME_RANK_NORMAL; case DEPRECATED: return NAME_RANK_DEPRECATED; default: throw new IllegalArgumentException("Unknown rank " + rank.toString()); } }
Source:
<code>public void replaceWithNameableCollection() { <START> VM vm = new VM(); <END> vm.setVmName(PROPERTY_VALUE); List<Nameable> items = Collections.<Nameable> singletonList(vm); String[] messageItems = ReplacementUtils.replaceWithNameableCollection(PROPERTY_NAME, items); validateMessageItems(messageItems, items); }</code><technical_language>I anonymous implementation of nameable</technical_language>

Target:
public void replaceWithNameableCollection() { Nameable item = new Nameable() { @Override public String getName() { return PROPERTY_VALUE; } }; List<Nameable> items = Collections.<Nameable> singletonList(item); String[] messageItems = ReplacementUtils.replaceWithNameable(PROPERTY_NAME, items); validateMessageItems(messageItems, items); }
Source:
<code>public void testGetCell() throws Exception { final String factType = "org.kiegroup.Car"; final String factField = "color"; <START> final String dataType = DataType.DataTypes.NUMERIC.name(); <END> doReturn(factType).when(column).getFactType(); doReturn(factField).when(column).getFactField(); doReturn(dataType).when(column).getDataType(); testedFactory.getCell(column); verify(testedFactory, never()).makeSingleSelectionEnumCell(factType, factField, dataType); }</code><technical_language>Technically color a STRING</technical_language>

Target:
public void testGetCell() throws Exception { final String factType = "org.kiegroup.Car"; final String factField = "color"; final String dataType = DataType.DataTypes.STRING.name(); doReturn(factType).when(column).getFactType(); doReturn(factField).when(column).getFactField(); doReturn(dataType).when(column).getDataType(); testedFactory.getCell(column); verify(testedFactory, never()).makeSingleSelectionEnumCell(factType, factField, dataType); }
Source:
<code>private void processSingleChargeEvent(long currentId, ChargeStatus fromChargeState, ChargeEventEntity chargeEventEntity) { PaymentGatewayStateTransitions.getInstance() .getEventForTransition(fromChargeState, chargeEventEntity.getStatus()) .ifPresent(eventType -> { Event event = getPaymentEvent(chargeEventEntity, eventType); final boolean emittedBefore = emittedEventDao.hasBeenEmittedBefore(event); if (emittedBefore) { logger.info("[{}/{}] - found - emitted before", currentId, maxId); } else { logger.info("[{}/{}] - found - emitting ", currentId, maxId, event); <START> persistAndEmit(event); <END> } }); }</code><technical_language>end Connector database I emitter process instead of manually emitting -- takes care of handling multiple events created for a transition (refund availability etc.) changes PaSTEE code</technical_language>

Target:
private void processSingleChargeEvent(long currentId, ChargeStatus fromChargeState, ChargeEventEntity chargeEventEntity) { PaymentGatewayStateTransitions.getInstance() .getEventForTransition(fromChargeState, chargeEventEntity.getStatus()) .ifPresent(eventType -> { PaymentStateTransition transition = new PaymentStateTransition(chargeEventEntity.getId(), eventType); offerPaymentStateTransitionEvents(currentId, chargeEventEntity, transition); }); }
Source:
<code>Set<String> byPath(String wsPath) { Set<String> ids = new HashSet<>(); for (Entry<String, Set<Pattern>> entry : patterns.getAll().entrySet()) { String id = entry.getKey(); Set<Pattern> patterns = entry.getValue(); for (Pattern pattern : patterns) { if (pattern.matcher(wsPath).lookingAt()) { ids.add(id); } } } <START> return ImmutableSet.copyOf(ids); <END> }</code><technical_language>returning a new set anyway, do care immutable</technical_language>

Target:
Set<String> byPath(String wsPath) { Set<String> ids = new HashSet<>(); for (Entry<String, Set<Pattern>> entry : patterns.getAll().entrySet()) { String id = entry.getKey(); Set<Pattern> patterns = entry.getValue(); for (Pattern pattern : patterns) { if (pattern.matcher(wsPath).matches()) { ids.add(id); } } } return ImmutableSet.copyOf(ids); }
Source:
<code>public void onFinish(List<SpanExtents> result) { if (isCancelled()) { return; } long time = System.currentTimeMillis(); Object[] prevSpans = textBox.getText().getSpans(0, text.length(), SpanExtents.class); for (Object sp : prevSpans) { textBox.getText().removeSpan(sp); } <START> for (int i = 0; i < result.size(); i++) { <END> textBox.getText().setSpan(result.get(i), result.get(i).getStart(), result.get(i).getEnd(), Spanned.SPAN_INCLUSIVE_INCLUSIVE); } time = System.currentTimeMillis() - time; Log.d(TAG, "That took " + time + "ms"); }</code><technical_language>replace for</technical_language>

Target:
public void onFinish(List<SpanExtents> result) { if (isCancelled()) { return; } long time = System.currentTimeMillis(); Object[] prevSpans = textBox.getText().getSpans(0, text.length(), SpanExtents.class); for (Object sp : prevSpans) { textBox.getText().removeSpan(sp); } for (SpanExtents spanEx : result) { textBox.getText().setSpan(spanEx, spanEx.getStart(), spanEx.getEnd(), Spanned.SPAN_INCLUSIVE_INCLUSIVE); } time = System.currentTimeMillis() - time; Log.d(TAG, "That took " + time + "ms"); }
Source:
<code>public Track(String abPath) { try { song = new Mp3File(abPath); } catch (UnsupportedTagException e) { <START> System.out.println("There was a Unsupported tag exception with file:" + abPath); <END> e.printStackTrace(); } catch (InvalidDataException e) { System.out.println("There was a Invalid data exception with file:" + abPath); e.printStackTrace(); } catch (IOException e) { System.out.println("There was a IO exception with file:" + abPath); e.printStackTrace(); } absolutepath = abPath; getInformation(); }</code><technical_language>I implement a logger instead of printing sysout. For though. :)</technical_language>

Target:
public Track(String abPath) { try { song = new Mp3File(abPath); } catch (UnsupportedTagException e) { System.out.println("There was a Unsupported tag exception with file:" + abPath); e.printStackTrace(); } catch (InvalidDataException e) { System.out.println("There was a Invalid data exception with file:" + abPath); e.printStackTrace(); } catch (IOException e) { System.out.println("There was a IO exception with file:" + abPath); e.printStackTrace(); } absolutePath = abPath; getMetadata(); }
Source:
<code>private boolean proceedCommandExecutionFailed() { if (getParameters().getCommandStep() == RemoveSnapshotSingleDiskLiveStep.MERGE) { <START> log.debug("Merge <END> failed, retrying to recover from MERGE_STATUS step"); getParameters().setCommandStep(RemoveSnapshotSingleDiskLiveStep.MERGE_STATUS); return true; } if (getParameters().getCommandStep() == RemoveSnapshotSingleDiskLiveStep.MERGE_STATUS) { log.debug("Merge failed at MERGE_STATUS step"); if (getParameters().getMergeStatusReturnValue() != null && getParameters().getMergeStatusReturnValue().isMergeRunning()) { log.debug("Merge block job is still running, recovering from MERGE step"); getParameters().setCommandStep(RemoveSnapshotSingleDiskLiveStep.MERGE); return true; } setCommandStatus(CommandStatus.FAILED); return false; } if (getParameters().getCommandStep() == RemoveSnapshotSingleDiskLiveStep.DESTROY_IMAGE) { log.warn("Child command '{}' failed, proceeding to verify", getParameters().getCommandStep()); getParameters().setCommandStep(getParameters().getNextCommandStep()); return true; } log.error("Failed child command status for step '{}'", getParameters().getCommandStep()); setCommandStatus(CommandStatus.FAILED); return false; }</code><technical_language>warning</technical_language>

Target:
private boolean proceedCommandExecutionFailed() { if (getParameters().getCommandStep() == RemoveSnapshotSingleDiskLiveStep.MERGE) { log.warn("Merge failed, retrying to recover from MERGE_STATUS step"); getParameters().setCommandStep(RemoveSnapshotSingleDiskLiveStep.MERGE_STATUS); return true; } if (getParameters().getCommandStep() == RemoveSnapshotSingleDiskLiveStep.MERGE_STATUS) { log.warn("Merge failed at MERGE_STATUS step"); if (getParameters().getMergeStatusReturnValue() != null && getParameters().getMergeStatusReturnValue().isMergeRunning()) { log.info("Merge block job is still running, recovering from MERGE step"); getParameters().setCommandStep(RemoveSnapshotSingleDiskLiveStep.MERGE); return true; } setCommandStatus(CommandStatus.FAILED); return false; } if (getParameters().getCommandStep() == RemoveSnapshotSingleDiskLiveStep.DESTROY_IMAGE) { log.warn("Child command '{}' failed, proceeding to verify", getParameters().getCommandStep()); getParameters().setCommandStep(getParameters().getNextCommandStep()); return true; } log.error("Failed child command status for step '{}'", getParameters().getCommandStep()); setCommandStatus(CommandStatus.FAILED); return false; }
Source:
<code>public synchronized void chooseSinks() { List<ServerName> slaveAddresses = endpoint.getRegionServers(); <START> if(slaveAddresses==null){ <END> LOG.warn("No sinks available at peer. Will not be able to replicate"); sinks = new ArrayList<ServerName>(); } else { Collections.shuffle(slaveAddresses, ThreadLocalRandom.current()); int numSinks = (int) Math.ceil(slaveAddresses.size() * ratio); sinks = slaveAddresses.subList(0, numSinks); } lastUpdateToPeers = System.currentTimeMillis(); badReportCounts.clear(); }</code><technical_language>HBaseReplicationEndpoint returns null. Guarding custom endpoint implementations? expose getRegionServers a base-class interface explicitly expect a non-null answer. Follow-on.. If easy, this good write a quick unit test cover this method</technical_language>

Target:
public synchronized void chooseSinks() { List<ServerName> slaveAddresses = endpoint.getRegionServers(); if(slaveAddresses.isEmpty()){ LOG.warn("No sinks available at peer. Will not be able to replicate"); } Collections.shuffle(slaveAddresses, ThreadLocalRandom.current()); int numSinks = (int) Math.ceil(slaveAddresses.size() * ratio); sinks = slaveAddresses.subList(0, numSinks); lastUpdateToPeers = System.currentTimeMillis(); badReportCounts.clear(); }
Source:
<code>private void optOut() { <START> String token = mUser.getAccountToken(); <END> String metricType = mSettings.getSurveyType(); String endUserId = Long.toString(mEndUser.getId()); String endUserEmail = mEndUser.getEmail(); String uniqueLink = mUniqueLink; String optOutToken = mAccessToken; String optOutUrl = "<LINK_0>" + token + "&metric_type=" + metricType + "&end_user_id=" + endUserId + "&end_user_email=" + endUserEmail + "&unique_link=" + uniqueLink + "&opt_out_token=" + optOutToken; Intent optOut = new Intent(Intent.ACTION_VIEW, Uri.parse(optOutUrl)); startActivity(optOut); }</code><technical_language>vars once. method call directly? i.e. "<LINK_0>" + mUser.getAccountToken() + ...</technical_language>

Target:
private void optOut() { String optOutUrl = "<LINK_0>" + mUser.getAccountToken() + "&metric_type=" + mSettings.getSurveyType() + "&end_user_id=" + Long.toString(mEndUser.getId()) + "&end_user_email=" + mEndUser.getEmail() + "&unique_link=" + mUniqueLink + "&opt_out_token=" + mAccessToken; Intent optOut = new Intent(Intent.ACTION_VIEW, Uri.parse(optOutUrl)); startActivity(optOut); dismiss(); }
Source:
<code>public void testSimple() { CachingConnectionFactory cf = new CachingConnectionFactory("localhost"); ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setThreadNamePrefix("client-"); executor.afterPropertiesSet(); cf.setExecutor(executor); DirectMessageListenerContainer container = new DirectMessageListenerContainer(cf); container.setQueueNames(Q1, Q2); container.setConsumersPerQueue(2); <START> container.setMessageListener(new MessageListenerAdapter((ReplyingMessageListener<String, String>) in -> { <END> LogFactory.getLog(this.getClass()).info(in); if ("foo".equals(in) || "bar".equals(in)) { return in.toUpperCase(); } else { return null; } })); container.afterPropertiesSet(); container.start(); RabbitTemplate template = new RabbitTemplate(cf); assertEquals("FOO", template.convertSendAndReceive(Q1, "foo")); assertEquals("BAR", template.convertSendAndReceive(Q2, "bar")); }</code><technical_language>relax a bit pass a new ReplyingMessageListener internally wrap MessageListenerAdapter? OTOH I see: public <I, O> void setMessageListener(ReplyingMessageListener<I, O> messageListener) { setMessageListener(new MessageListenerAdapter(messageListener)); } WDYT</technical_language>

Target:
public void testSimple() { CachingConnectionFactory cf = new CachingConnectionFactory("localhost"); ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setThreadNamePrefix("client-"); executor.afterPropertiesSet(); cf.setExecutor(executor); DirectMessageListenerContainer container = new DirectMessageListenerContainer(cf); container.setQueueNames(Q1, Q2); container.setConsumersPerQueue(2); container.setMessageListener(new MessageListenerAdapter((ReplyingMessageListener<String, String>) in -> { if ("foo".equals(in) || "bar".equals(in)) { return in.toUpperCase(); } else { return null; } })); container.afterPropertiesSet(); container.start(); RabbitTemplate template = new RabbitTemplate(cf); assertEquals("FOO", template.convertSendAndReceive(Q1, "foo")); assertEquals("BAR", template.convertSendAndReceive(Q2, "bar")); }
Source:
<code>public void testFreeStyleAntOnSlave() throws Exception { Assume.assumeTrue((jenkins.getDescriptorByType(Ant.DescriptorImpl.class).getInstallations().length > 0); <START> <END> FreeStyleProject project = createFreeStyleProject(); project.setJDK(jenkins.getJDK("varJDK")); project.setScm(new ExtractResourceSCM(getClass().getResource( "/simple-projects.zip"))); String buildFile = "build.xml${" + DUMMY_LOCATION_VARNAME + "}"; project.getBuildersList().add( new Ant("-Dtest.property=cor${" + DUMMY_LOCATION_VARNAME + "}rect", "varAnt", "", buildFile, "")); project.setAssignedLabel(slaveRegular.getSelfLabel()); FreeStyleBuild build = project.scheduleBuild2(0).get(); System.out.println(build.getDisplayName() + " completed"); assertBuildStatus(Result.FAILURE, build); String buildLogRegular = getBuildLog(build); assertTrue(buildLogRegular.contains(Ant_ExecutableNotFound("varAnt"))); project.setAssignedLabel(slaveEnv.getSelfLabel()); build = project.scheduleBuild2(0).get(); System.out.println(build.getDisplayName() + " completed"); assertBuildStatusSuccess(build); String buildLogEnv = getBuildLog(build); System.out.println(buildLogEnv); assertTrue(buildLogEnv.contains("Ant home: ")); assertTrue(buildLogEnv.contains("Test property: correct")); assertFalse(buildLogEnv.matches("(?s)^.*Ant home: [^\\n\\r]*" + DUMMY_LOCATION_VARNAME + ".*$")); assertFalse(buildLogEnv.matches("(?s)^.*Test property: [^\\n\\r]*" + DUMMY_LOCATION_VARNAME + ".*$")); }</code><technical_language>intend consistent</technical_language>

Target:
public void testFreeStyleAntOnSlave() throws Exception { Assume.assumeFalse( "Cannot do testFreeStyleAntOnSlave without ANT_HOME", jenkins.getDescriptorByType(Ant.DescriptorImpl.class).getInstallations().length == 0 ); FreeStyleProject project = createFreeStyleProject(); project.setJDK(jenkins.getJDK("varJDK")); project.setScm(new ExtractResourceSCM(getClass().getResource( "/simple-projects.zip"))); String buildFile = "build.xml${" + DUMMY_LOCATION_VARNAME + "}"; project.getBuildersList().add( new Ant("-Dtest.property=cor${" + DUMMY_LOCATION_VARNAME + "}rect", "varAnt", "", buildFile, "")); project.setAssignedLabel(slaveRegular.getSelfLabel()); FreeStyleBuild build = project.scheduleBuild2(0).get(); System.out.println(build.getDisplayName() + " completed"); assertBuildStatus(Result.FAILURE, build); String buildLogRegular = getBuildLog(build); assertTrue(buildLogRegular.contains(Ant_ExecutableNotFound("varAnt"))); project.setAssignedLabel(slaveEnv.getSelfLabel()); build = project.scheduleBuild2(0).get(); System.out.println(build.getDisplayName() + " completed"); assertBuildStatusSuccess(build); String buildLogEnv = getBuildLog(build); System.out.println(buildLogEnv); assertTrue(buildLogEnv.contains("Ant home: ")); assertTrue(buildLogEnv.contains("Test property: correct")); assertFalse(buildLogEnv.matches("(?s)^.*Ant home: [^\\n\\r]*" + DUMMY_LOCATION_VARNAME + ".*$")); assertFalse(buildLogEnv.matches("(?s)^.*Test property: [^\\n\\r]*" + DUMMY_LOCATION_VARNAME + ".*$")); }
Source:
<code>public int read() throws IOException { try { return RetryUtils.retry( <START> delegate::read, <END> retryCondition, maxTry ); } catch (Exception e) { throw new IOException(e); } }</code><technical_language>This is a capturing lambda, i. e. object created method invocation. in this class. I suggest RetryUtils in this class inline logic this class specifically. This allows avoid obscure side-effect assignment of delegate in retryCondition</technical_language>

Target:
public int read() throws IOException { for (int nTry = 0; nTry < maxRetry; nTry++) { try { return delegate.read(); } catch (Throwable t) { waitOrThrow(t, nTry); } } return delegate.read(); }
Source:
<code>public static void main(String[] args) throws InterruptedException { String connectionString = "Endpoint={fully-qualified-namespace};SharedAccessKeyName={policy-name};" + "SharedAccessKey={key}"; ServiceBusSessionReceiverAsyncClient sessionReceiver = new ServiceBusClientBuilder() .connectionString(connectionString) .sessionReceiver() .receiveMode(ServiceBusReceiveMode.PEEK_LOCK) .topicName("<<topic-name>>") .subscriptionName("<<subscription-name>>") .buildAsyncClient(); Mono<ServiceBusReceiverAsyncClient> receiverMono = sessionReceiver.acceptNextSession(); <START> <END> Disposable subscription = receiverMono.flatMapMany(receiver -> receiver.receiveMessages()) .subscribe(message -> { System.out.printf("Session: %s. Sequence #: %s. Contents: %s%n", message.getSessionId(), message.getSequenceNumber(), message.getBody()); }, error -> System.err.println("Error occurred: " + error)); TimeUnit.SECONDS.sleep(60); subscription.dispose(); sessionReceiver.close(); }</code><technical_language>of need for acceptSession() API show user fail. if session get accepted need do something? next session some code log message it</technical_language>

Target:
public static void main(String[] args) throws InterruptedException { String connectionString = "Endpoint={fully-qualified-namespace};SharedAccessKeyName={policy-name};" + "SharedAccessKey={key}"; ServiceBusSessionReceiverAsyncClient sessionReceiver = new ServiceBusClientBuilder() .connectionString(connectionString) .sessionReceiver() .receiveMode(ServiceBusReceiveMode.PEEK_LOCK) .topicName("<<topic-name>>") .subscriptionName("<<subscription-name>>") .buildAsyncClient(); Mono<ServiceBusReceiverAsyncClient> receiverMono = sessionReceiver.acceptNextSession(); Disposable subscription = Flux.usingWhen(receiverMono, receiver -> receiver.receiveMessages(), receiver -> Mono.fromRunnable(() -> receiver.close())) .subscribe(message -> { System.out.printf("Session: %s. Sequence #: %s. Contents: %s%n", message.getSessionId(), message.getSequenceNumber(), message.getBody()); }, error -> System.err.println("Error occurred: " + error)); TimeUnit.SECONDS.sleep(60); subscription.dispose(); sessionReceiver.close(); }
Source:
<code>public RepositoryGroups() { List<String> groups = split( preferences.get(PREFS_GROUPS, EMPTY_STRING)); for (String groupUUIDString : groups) { UUID <START> groupUUIDuuid = <END> UUID.fromString(groupUUIDString); String name = preferences .get(PREFS_GROUP_NAME_PREFIX + groupUUIDString, EMPTY_STRING); List<String> repos = split( preferences.get(PREFS_GROUP_PREFIX + groupUUIDString, EMPTY_STRING)); RepositoryGroup group = new RepositoryGroup(groupUUIDuuid, name, repos); groupMap.put(groupUUIDuuid, group); } }</code><technical_language>Strange name. simply groupId? generally hungarian notation (putting type info variable names). below</technical_language>

Target:
public RepositoryGroups() { List<String> groups = split( preferences.get(PREFS_GROUPS, EMPTY_STRING)); for (String groupIdString : groups) { UUID groupId = UUID.fromString(groupIdString); String name = preferences .get(PREFS_GROUP_NAME_PREFIX + groupIdString, EMPTY_STRING); List<String> repos = split(preferences .get(PREFS_GROUP_PREFIX + groupIdString, EMPTY_STRING)); RepositoryGroup group = new RepositoryGroup(groupId, name, repos); groupMap.put(groupId, group); } }
Source:
<code>protected Function<Object, IterableWithMarker<Image>> markerToNextForArgs(final List<Object> args) { if (args == null || args.isEmpty()) throw new IllegalStateException("Can't advance the PagedIterable"); final String regionId = args.get(0).toString(); <START> final Optional<Object> optionalPaginationOptions = Optional.fromNullable(!args.isEmpty() && args.size() == 2 ? args.get(1) : null); <END> final ListImagesOptions original = (ListImagesOptions) optionalPaginationOptions.orNull(); return new Function<Object, IterableWithMarker<Image>>() { @Override public IterableWithMarker<Image> apply(Object input) { ListImagesOptions options = original == null ? ListImagesOptions.Builder.paginationOptions(PaginationOptions.class.cast(input)) : original.paginationOptions(PaginationOptions.class.cast(input)); return api.imageApi().list(regionId, options); } }; }</code><technical_language>instanceOf method Predicates class for a more safe approach</technical_language>

Target:
protected Function<Object, IterableWithMarker<Image>> markerToNextForArgs(final List<Object> args) { if (args == null || args.isEmpty()) throw new IllegalStateException("Can't advance the PagedIterable"); final String regionId = args.get(0).toString(); final ListImagesOptions original = (ListImagesOptions) Iterables.tryFind(args, Predicates.instanceOf(ListImagesOptions.class)).orNull(); return new Function<Object, IterableWithMarker<Image>>() { @Override public IterableWithMarker<Image> apply(Object input) { ListImagesOptions options = original == null ? ListImagesOptions.Builder.paginationOptions(PaginationOptions.class.cast(input)) : original.paginationOptions(PaginationOptions.class.cast(input)); return api.imageApi().list(regionId, options); } }; }
Source:
<code>public void validate(final PreparedUpdate update, final UpdateContext updateContext) { final RpslObject originalObject = update.getReferenceObject(); <START> if (! OrgType.LIR.getName().equals(originalObject.getValueForAttribute(AttributeType.ORG_TYPE))) { <END> return; } final RpslObject updatedObject = update.getUpdatedObject(); final Collection<CIString> userMntner = filterUserMntner(updatedObject); if (userMntner.size() > 1) { updateContext.addMessage(update, UpdateMessages.multipleUserMntBy(userMntner)); } }</code><technical_language>LIR == OrgType.getFor(originalObject.getValueForAttribute(AttributeType.ORG_TYPE)) is a bit cleaner..</technical_language>

Target:
public void validate(final PreparedUpdate update, final UpdateContext updateContext) { final RpslObject originalObject = update.getReferenceObject(); if (!isLir(originalObject)) { return; } final RpslObject updatedObject = update.getUpdatedObject(); final Collection<CIString> userMntner = filterUserMntner(updatedObject); if (userMntner.size() > 1) { updateContext.addMessage(update, UpdateMessages.multipleUserMntBy(userMntner)); } }
Source:
<code>private void nativeOpenFile(String filePath) { if (Desktop.isDesktopSupported()) { new Thread(() -> { try { File file = new File(filePath); Desktop.getDesktop().open(file); LOGGER.info("Opened file with Desktop integration"); } catch (Exception e) { <START> LOGGER.error("Open operation not successful: " + e.getMessage()); <END> } }).start(); } else { LOGGER.error("No operation possible"); } }</code><technical_language>suggestion LOGGER.error("Open operation successful", e); Logger error overload accepts throwable/eception</technical_language>

Target:
private void nativeOpenFile(String filePath) { JabRefExecutorService.INSTANCE.execute(() -> { try { File file = new File(filePath); Desktop.getDesktop().open(file); System.out.println("Open file in default application with Desktop integration"); } catch (IllegalArgumentException e) { System.out.println("Fail back to xdg-open"); try { String[] cmd = {"xdg-open", filePath}; Runtime.getRuntime().exec(cmd); } catch (Exception e2) { System.out.println("Open operation not successful: " + e2); } } catch (IOException e) { System.out.println("Native open operation not successful: " + e); } }); }
Source:
<code>public String value() { <START> this.lastAccessTime = System.currentTimeMillis(); <END> return this.value; }</code><technical_language>if matter for tests, calling value() is updates access time. is Cache/Store operation returned value</technical_language>

Target:
public String value() { return this.value; }
Source:
<code>private String uriToPath(final String URI) { if (URI.startsWith(baseUri)) { return URI.substring(baseUri.length()); <START> } else { <END> return URI; } }</code><technical_language>point else here..</technical_language>

Target:
private String uriToPath(final String URI) { if (URI.startsWith(baseUri)) { return URI.substring(baseUri.length()); } return URI; }
Source:
<code>public IBuildConfiguration[] getAllBuildConfigReferences(String configName, boolean makeCopy) { if (!hasBuildConfig(configName)) return EMPTY_BUILD_CONFIG_REFERENCE_ARRAY; IBuildConfiguration[] refs = cachedConfigRefs.get(configName); if (refs == null) { Set<IBuildConfiguration> references = new LinkedHashSet<>(); IBuildConfiguration[] dynamicBuildConfigs = dynamicConfigRefs.containsKey(configName) ? dynamicConfigRefs.get(configName) : EMPTY_BUILD_CONFIG_REFERENCE_ARRAY; Collection<BuildConfiguration> dynamic = <START> getBuildConfigReferencesFromProjects(ProjectDescription.computeDynamicReferencesForProject(getName(), <END> configName, getBuildSpec())); Collection<BuildConfiguration> legacyDynamic = getBuildConfigReferencesFromProjects(dynamicRefs); Collection<BuildConfiguration> statik = getBuildConfigReferencesFromProjects(staticRefs); references.addAll(Arrays.asList(dynamicBuildConfigs)); references.addAll(statik); references.addAll(legacyDynamic); references.addAll(dynamic); refs = references.toArray(new IBuildConfiguration[references.size()]); cachedConfigRefs.put(configName, refs); } return makeCopy ? (IBuildConfiguration[]) refs.clone() : refs; }</code><technical_language>Redundant qualifier</technical_language>

Target:
public IBuildConfiguration[] getAllBuildConfigReferences(String configName, boolean makeCopy) { if (!hasBuildConfig(configName)) return EMPTY_BUILD_CONFIG_REFERENCE_ARRAY; IBuildConfiguration[] refs = cachedConfigRefs.get(configName); if (refs == null) { Set<IBuildConfiguration> references = new LinkedHashSet<>(); IBuildConfiguration[] dynamicBuildConfigs = dynamicConfigRefs.containsKey(configName) ? dynamicConfigRefs.get(configName) : EMPTY_BUILD_CONFIG_REFERENCE_ARRAY; IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(getName()); Collection<BuildConfiguration> dynamic; try { IBuildConfiguration buildConfig = project.getBuildConfig(configName); dynamic = getBuildConfigReferencesFromProjects(computeDynamicReferencesForProject(buildConfig, getBuildSpec())); } catch (CoreException e) { dynamic = Collections.emptyList(); } Collection<BuildConfiguration> legacyDynamic = getBuildConfigReferencesFromProjects(dynamicRefs); Collection<BuildConfiguration> statik = getBuildConfigReferencesFromProjects(staticRefs); references.addAll(Arrays.asList(dynamicBuildConfigs)); references.addAll(statik); references.addAll(legacyDynamic); references.addAll(dynamic); refs = references.toArray(new IBuildConfiguration[references.size()]); cachedConfigRefs.put(configName, refs); } return makeCopy ? (IBuildConfiguration[]) refs.clone() : refs; }
Source:
<code><START> public static Object valuesFor(DCValue[] values) { <END> if (values.length == 0) { return null; } if (values.length ==1 ) { return values[0].value; } String vals[] = new String[values.length]; for (int i = 0; i < values.length; i++) { vals[i] = values[i].value; } return vals; }</code><technical_language>return object ? return a String[] ? Saves trouble of casting</technical_language>

Target:
public static String[] valuesFor(DCValue[] values) { String vals[] = new String[values.length]; for (int i = 0; i < values.length; i++) { vals[i] = values[i].value; } return vals; }
Source:
<code>public static void copyStreamAndClose(@Nonnull Reader in, @Nonnull Writer out) throws IOException { try { copyStream(in,out); } finally { <START> in.close(); <END> out.close(); } }</code><technical_language>for change. If code fails close in, try close out</technical_language>

Target:
public static void copyStreamAndClose(@Nonnull Reader in, @Nonnull Writer out) throws IOException { try (Reader _in = in; Writer _out = out) { copyStream(in,out); } }
Source:
<code>private void clickPopup(final int buttonNo) { <START> if (AbstractScene.getPopup() != null) { <END> ObservableList<Node> buttons; sleep(1); buttons = ((VBox) AbstractScene.getPopup().getContent().get(1)) .getChildren(); buttons = ((HBox) buttons.get(buttons.size() - 1)).getChildren(); try { clickOn(buttons.get(buttonNo), MouseButton.PRIMARY); } catch (ArrayIndexOutOfBoundsException e) { fail("ButtonNo " + buttonNo + " does not exist"); } sleep(SHORT); } }</code><technical_language>Ye, a PMD warning.. :P I fix it, easier. ;) <review, layout</technical_language>

Target:
private void clickPopup(final int buttonNo) { if (AbstractScene.getPopup() == null) { fail("There is no popup available in AbstractScene!"); } else { ObservableList<Node> buttons; sleep(1); buttons = ((VBox) AbstractScene.getPopup().getContent().get(1)) .getChildren(); buttons = ((HBox) buttons.get(buttons.size() - 1)).getChildren(); try { clickOn(buttons.get(buttonNo), MouseButton.PRIMARY); } catch (ArrayIndexOutOfBoundsException e) { fail("ButtonNo " + buttonNo + " does not exist"); } sleep(SHORT); } }
Source:
<code>private void fireContainerInitializedEvent() { beanManager().fireEvent(new ContainerInitialized(id), Initialized.Literal.APPLICATION); <START> WeldSELogger.LOG.weldContainerInitialized(id); <END> }</code><technical_language>Hm, move message - logged event, if a ContainerInitialized observer blocks..</technical_language>

Target:
private void fireContainerInitializedEvent() { WeldSELogger.LOG.weldContainerInitialized(id); beanManager().fireEvent(new ContainerInitialized(id), Initialized.Literal.APPLICATION); }
Source:
<code>private static List<SiteModel> getSelfHostedSitesFromDeprecatedDB(Context context) { List<SiteModel> siteList = new ArrayList<>(); try { SQLiteDatabase db = context.getApplicationContext().openOrCreateDatabase(DEPRECATED_DATABASE_NAME, 0, null); String[] fields = new String[]{"username", "password", "url"}; String byString = "dotcomFlag=0"; Cursor c = db.query(DEPRECATED_BLOGS_TABLE, fields, byString, null, null, null, null); <START> int numRows = c.getCount(); <END> c.moveToFirst(); for (int i = 0; i < numRows; i++) { SiteModel siteModel = new SiteModel(); siteModel.setUsername(c.getString(0)); siteModel.setPassword(c.getString(1)); siteModel.setUrl(c.getString(2)); siteList.add(siteModel); c.moveToNext(); } c.close(); } catch (SQLException e) { } return siteList; }</code><technical_language>a jetpack site (we want migrate jetpack sites added signing in wpcom user)</technical_language>

Target:
private static List<SiteModel> getSelfHostedSitesFromDeprecatedDB(Context context) { List<SiteModel> siteList = new ArrayList<>(); try { SQLiteDatabase db = context.getApplicationContext().openOrCreateDatabase(DEPRECATED_DATABASE_NAME, 0, null); String[] fields = new String[]{"username", "password", "url"}; String byString = String.format("dotcomFlag=0 AND NOT(dotcomFlag=0 AND password='%s')", encryptPassword("")); Cursor c = db.query(DEPRECATED_BLOGS_TABLE, fields, byString, null, null, null, null); int numRows = c.getCount(); c.moveToFirst(); for (int i = 0; i < numRows; i++) { SiteModel siteModel = new SiteModel(); siteModel.setUsername(c.getString(0)); String encryptedPwd = c.getString(1); siteModel.setPassword(decryptPassword(encryptedPwd)); String url = c.getString(2); siteModel.setUrl(url); siteModel.setXmlRpcUrl(url); siteList.add(siteModel); c.moveToNext(); } c.close(); } catch (SQLException e) { } return siteList; }
Source:
<code>public synchronized void handleDataDeleted(String s) throws Exception { if (_zkClient.isClosed()) { return; } <START> _zkClient.unsubscribeAll(); <END> _zkClient.subscribeChildChanges(MetadataStoreRoutingConstants.ROUTING_DATA_PATH, this); for (String child : _zkClient.getChildren(MetadataStoreRoutingConstants.ROUTING_DATA_PATH)) { _zkClient.subscribeDataChanges(MetadataStoreRoutingConstants.ROUTING_DATA_PATH + "/" + child, this); } _routingDataListener.updateRoutingData(_namespace); }</code><technical_language>share need unsubscribe here</technical_language>

Target:
public synchronized void handleDataDeleted(String s) throws Exception { if (_zkClient.isClosed()) { return; } _zkClient.subscribeChildChanges(MetadataStoreRoutingConstants.ROUTING_DATA_PATH, this); for (String child : _zkClient.getChildren(MetadataStoreRoutingConstants.ROUTING_DATA_PATH)) { _zkClient.subscribeDataChanges(MetadataStoreRoutingConstants.ROUTING_DATA_PATH + "/" + child, this); } _routingDataListener.refreshRoutingData(_namespace); }
Source:
<code>public void deserializationHandlesNullRoles() throws Exception { CrewMember crewMember = new CrewMember("uri", "", Publisher.METABROADCAST); <START> crewMember.withRole(null); <END> assertThat( serialization.deserialize( serialization.serialize( crewMember ) ) .role(), is(nullValue()) ); }</code><technical_language>put .withRole(null) line returns a builder, totally optional</technical_language>

Target:
public void deserializationHandlesNullRoles() throws Exception { @SuppressWarnings("ConstantConditions") CrewMember crewMember = new CrewMember("uri", "", Publisher.METABROADCAST) .withRole(null); assertThat( serialization.deserialize( serialization.serialize( crewMember ) ) .role(), is(nullValue()) ); }
Source:
<code>public void linkRequested() { assertLockHeld(); Binding<?> binding; while ((binding = toLink.poll()) != null) { if (binding instanceof DeferredBinding) { DeferredBinding deferredBinding = (DeferredBinding) binding; String key = deferredBinding.deferredKey; boolean mustBeInjectable = deferredBinding.mustBeInjectable; if (bindings.containsKey(key)) { continue; } try { Binding<?> jitBinding = createJitBinding(key, binding.requiredBy, mustBeInjectable); <START> jitBinding.setNecessary(binding.necessary()); <END> jitBinding.setDependedOn(binding.dependedOn()); if (!key.equals(jitBinding.provideKey) && !key.equals(jitBinding.membersKey)) { throw new IllegalStateException("Unable to create binding for " + key); } Binding<?> scopedJitBinding = scope(jitBinding); toLink.add(scopedJitBinding); putBinding(scopedJitBinding); } catch (Exception e) { if (e.getMessage() != null) { addError(e.getMessage() + " required by " + binding.requiredBy); bindings.put(key, Binding.UNRESOLVED); } else if (e instanceof RuntimeException) { throw (RuntimeException) e; } else { throw new RuntimeException(e); } } } else { attachSuccess = true; binding.attach(this); if (attachSuccess) { binding.setLinked(); } else { toLink.add(binding); } } } try { errorHandler.handleErrors(errors); } finally { errors.clear(); } }</code><technical_language>nuke of these? redundant</technical_language>

Target:
public void linkRequested() { assertLockHeld(); Binding<?> binding; while ((binding = toLink.poll()) != null) { if (binding instanceof DeferredBinding) { DeferredBinding deferredBinding = (DeferredBinding) binding; String key = deferredBinding.deferredKey; boolean mustBeInjectable = deferredBinding.mustBeInjectable; if (bindings.containsKey(key)) { continue; } try { Binding<?> jitBinding = createJitBinding(key, binding.requiredBy, mustBeInjectable); jitBinding.setLibrary(binding.library()); jitBinding.setDependedOn(binding.dependedOn()); if (!key.equals(jitBinding.provideKey) && !key.equals(jitBinding.membersKey)) { throw new IllegalStateException("Unable to create binding for " + key); } Binding<?> scopedJitBinding = scope(jitBinding); toLink.add(scopedJitBinding); putBinding(scopedJitBinding); } catch (Exception e) { if (e.getMessage() != null) { addError(e.getMessage() + " required by " + binding.requiredBy); bindings.put(key, Binding.UNRESOLVED); } else if (e instanceof RuntimeException) { throw (RuntimeException) e; } else { throw new RuntimeException(e); } } } else { attachSuccess = true; binding.attach(this); if (attachSuccess) { binding.setLinked(); } else { toLink.add(binding); } } } try { errorHandler.handleErrors(errors); } finally { errors.clear(); } }
Source:
<code>public static boolean isSystemProtocol(Collaboration element) { <START> return (UMLUtil.getStereotypeApplication(element, SystemProtocol.class) != null) ? true : false; <END> }</code><technical_language>need ternary operator: parenthesized boolean expression is result. Also, checked collaboration is a <<Protocol>> start with</technical_language>

Target:
public static boolean isSystemProtocol(Collaboration element) { return (UMLUtil.getStereotypeApplication(element, SystemProtocol.class) != null); }
Source:
<code>public void commit() throws TransactionException { final MessagingTransaction transaction = getCurrentTransaction(); logger.trace("Committing transaction: " + transaction.transactionId()); transaction.applyActions(messagePublisher); currentTransaction.remove(); <START> logger.trace("Transaction successfully commit: " + transaction.transactionId()); <END> }</code><technical_language>Replace 'commit' 'committed'</technical_language>

Target:
public void commit() throws TransactionException { final MessagingTransaction transaction = getCurrentTransaction(); logger.trace("Committing transaction: " + transaction.transactionId()); transaction.applyActions(messagePublisher); currentTransaction.remove(); logger.trace("Transaction successfully committed: " + transaction.transactionId()); }
Source:
<code>static Platform parsePlatform(@Nullable PlatformInfo executionPlatform, @Nullable String defaultPlatformProperties) { Platform.Builder platformBuilder = Platform.newBuilder(); if (executionPlatform != null && !Strings.isNullOrEmpty(executionPlatform.remoteExecutionProperties())) { try { TextFormat.getParser().merge(executionPlatform.remoteExecutionProperties(), platformBuilder); } catch (ParseException e) { <START> throw new IllegalArgumentException( <END> String.format( "Failed to parse remote_execution_properties from platform %s", executionPlatform.label()), e); } } else if (!Strings.isNullOrEmpty(defaultPlatformProperties)) { try { TextFormat.getParser().merge(defaultPlatformProperties, platformBuilder); } catch (ParseException e) { throw new IllegalArgumentException( String.format("Failed to parse --remote_default_platform_properties %s", defaultPlatformProperties), e); } } List<Platform.Property> properties = platformBuilder.getPropertiesList(); platformBuilder.clearProperties(); platformBuilder.addAllProperties( Ordering.from(Comparator.comparing(Platform.Property::getName)).sortedCopy(properties)); return platformBuilder.build(); }</code><technical_language>I a runtime exception, this kill Bazel server. Prefer AbruptExitException similar provide a user friendly error</technical_language>

Target:
static Platform parsePlatform( @Nullable PlatformInfo executionPlatform, @Nullable String defaultPlatformProperties) throws UserExecException { if (executionPlatform == null && Strings.isNullOrEmpty(defaultPlatformProperties)) { return null; } Platform.Builder platformBuilder = Platform.newBuilder(); if (executionPlatform != null && !Strings.isNullOrEmpty(executionPlatform.remoteExecutionProperties())) { try { TextFormat.getParser().merge(executionPlatform.remoteExecutionProperties(), platformBuilder); } catch (ParseException e) { throw new UserExecException( String.format( "Failed to parse remote_execution_properties from platform %s", executionPlatform.label()), e); } } else if (!Strings.isNullOrEmpty(defaultPlatformProperties)) { try { TextFormat.getParser().merge(defaultPlatformProperties, platformBuilder); } catch (ParseException e) { throw new UserExecException( String.format( "Failed to parse --remote_default_platform_properties %s", defaultPlatformProperties), e); } } List<Platform.Property> properties = platformBuilder.getPropertiesList(); platformBuilder.clearProperties(); platformBuilder.addAllProperties( Ordering.from(Comparator.comparing(Platform.Property::getName)).sortedCopy(properties)); return platformBuilder.build(); }
Source:
<code>public boolean isValid() { Token userToken = getSyncUser().getUserToken(); <START> return syncUser.isLoggedIn() && SyncManager.getUserStore().isActive(syncUser.getIdentity()) && userToken != null && userToken.expiresMs() > System.currentTimeMillis(); <END> }</code><technical_language>native isActive account loggedin/expireDate? If so, this statement greatly reduced</technical_language>

Target:
public boolean isValid() { Token userToken = getSyncUser().getUserToken(); return syncUser.isLoggedIn() && userToken != null && userToken.expiresMs() > System.currentTimeMillis() && SyncManager.getUserStore().isActive(syncUser.getIdentity()); }
Source:
<code><START> default String headerFormat() { <END> StringBuilder builder = new StringBuilder(serviceName()); instanceId().ifPresent(id -> builder.append("/").append(id)); builder.append(" (").append(version()).append(")"); return builder.toString(); }</code><technical_language>implement toString instead</technical_language>

Target:
default String headerFormat() { return Joiner.on(", ").join(Lists.transform(agents(), Agent::headerFormat)); }
Source:
<code>private String cacheSensorPrefix(final String threadId, final String taskId, final String cacheName) { return taskSensorPrefix(threadId, taskId) <START> + SENSOR_PREFIX_DELIMITER + "cache" + SENSOR_PREFIX_DELIMITER + cacheName; <END> }</code><technical_language>for cache</technical_language>

Target:
private String cacheSensorPrefix(final String threadId, final String taskId, final String cacheName) { return taskSensorPrefix(threadId, taskId) + SENSOR_PREFIX_DELIMITER + SENSOR_CACHE_LABEL + SENSOR_PREFIX_DELIMITER + cacheName; }
Source:
<code>public void work() { openSystemSession(); RetentionManager retentionManager = Framework.getService(RetentionManager.class); for (String string : docIds) { <START> DocumentModel doc; <END> try { doc = session.getDocument(new IdRef(string)); } catch (DocumentNotFoundException e) { log.warn("Document impacted by retention no longer exists {}", string); continue; } Record record = doc.getAdapter(Record.class); if (record == null) { log.warn("Document should be impacted by retention but is no longer a Record: {}", string); continue; } retentionManager.evalExpressionEventBasedRules(record, docsToCheckAndEvents.get(string), session); } }</code><technical_language>rename string -> docId for more clarity</technical_language>

Target:
public void work() { openSystemSession(); RetentionManager retentionManager = Framework.getService(RetentionManager.class); for (String docId : docIds) { DocumentModel doc; try { doc = session.getDocument(new IdRef(docId)); } catch (DocumentNotFoundException e) { log.warn("Document impacted by retention no longer exists {}", docId); continue; } Record record = doc.getAdapter(Record.class); if (record == null) { log.warn("Document should be impacted by retention but is no longer a Record: {}", docId); continue; } retentionManager.evalExpressionEventBasedRules(record, docsToCheckAndEvents.get(docId), session); } }
Source:
<code>public void handle(Request request, Response response) throws Exception { String projectKey = request.mandatoryParam(PARAM_PROJECT); List<String> tags = request.mandatoryParamAsStrings(PARAM_TAGS).stream() .filter(StringUtils::isNotBlank) .map(t -> t.toLowerCase(Locale.ENGLISH)) .map(SetAction::checkTag) .distinct() .collect(Collectors.toList()); try (DbSession dbSession = dbClient.openSession(false)) { ComponentDto project = componentFinder.getByKey(dbSession, projectKey); <START> checkRequest(Qualifiers.PROJECT.equals(project.qualifier()), "Component '%s' is not a project", project.key()); <END> userSession.checkComponentUuidPermission(UserRole.ADMIN, project.uuid()); project.setTags(tags); dbClient.componentDao().updateTags(dbSession, project); dbSession.commit(); indexers.forEach(i -> i.indexProject(project.uuid(), PROJECT_TAGS_UPDATE)); } response.noContent(); }</code><technical_language>Please static import</technical_language>

Target:
public void handle(Request request, Response response) throws Exception { String projectKey = request.mandatoryParam(PARAM_PROJECT); List<String> tags = request.mandatoryParamAsStrings(PARAM_TAGS).stream() .filter(StringUtils::isNotBlank) .map(t -> t.toLowerCase(Locale.ENGLISH)) .map(SetAction::checkTag) .distinct() .collect(Collectors.toList()); try (DbSession dbSession = dbClient.openSession(false)) { ComponentDto project = componentFinder.getByKey(dbSession, projectKey); checkRequest(PROJECT.equals(project.qualifier()), "Component '%s' is not a project", project.key()); userSession.checkComponentUuidPermission(UserRole.ADMIN, project.uuid()); project.setTags(tags); dbClient.componentDao().updateTags(dbSession, project); dbSession.commit(); indexers.forEach(i -> i.indexProject(project.uuid(), PROJECT_TAGS_UPDATE)); } response.noContent(); }
Source:
<code>void handleTermination(final SchedulingService service) throws IOException, ClassNotFoundException { for (TaskTerminationData taskToTerminate : tasksToTerminate.values()) { RunningTaskData taskData = taskToTerminate.taskData; <START> if (!taskToTerminate.killedWhileNotRunning()) { <END> Map<String, String> genericInformation = new HashMap<>(); VariablesMap variables = null; if (taskToTerminate.internalJob != null) { genericInformation = taskData.getTask().getRuntimeGenericInformation(); } try { variables = getStringSerializableMap(service, taskToTerminate); } catch (Exception e) { logger.error("Exception occurred, fail to get variables into the cleaning script: ", e); } try { if (!taskToTerminate.normalTermination) { taskData.getLauncher().kill(); } } catch (Throwable t) { logger.info("Cannot terminate task launcher for task '" + taskData.getTask().getId() + "'", t); try { logger.info("Task launcher that cannot be terminated is identified by " + taskData.getLauncher().toString()); } catch (Throwable ignore) { logger.info("Getting information about Task launcher failed (remote object not accessible?)"); } } try { logger.debug("Releasing nodes for task '" + taskData.getTask().getId() + "'"); RMProxiesManager proxiesManager = service.getInfrastructure().getRMProxiesManager(); proxiesManager.getUserRMProxy(taskData.getUser(), taskData.getCredentials()) .releaseNodes(taskData.getNodes(), taskData.getTask().getCleaningScript(), variables, genericInformation, taskToTerminate.taskData.getTask().getId()); } catch (Throwable t) { logger.info("Failed to release nodes for task '" + taskData.getTask().getId() + "'", t); } } } for (final TaskRestartData restartData : tasksToRestart.values()) { service.getInfrastructure().schedule(new Runnable() { public void run() { service.getJobs().restartWaitingTask(restartData.taskId); } }, restartData.waitTime); } for (JobId jobId : jobsToTerminate) { service.terminateJobHandling(jobId); } }</code><technical_language>condition name is confused, s more clear reverse logic.. if (taskToTerminate.killedWhileRunning())</technical_language>

Target:
void handleTermination(final SchedulingService service) throws IOException, ClassNotFoundException { for (TaskTerminationData taskToTerminate : tasksToTerminate.values()) { RunningTaskData taskData = taskToTerminate.taskData; if (taskToTerminate.terminatedWhileRunning()) { terminateRunningTask(service, taskToTerminate, taskData); } } for (final TaskRestartData restartData : tasksToRestart.values()) { service.getInfrastructure().schedule(new Runnable() { public void run() { service.getJobs().restartWaitingTask(restartData.taskId); } }, restartData.waitTime); } for (JobId jobId : jobsToTerminate) { service.terminateJobHandling(jobId); } }