auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static String process(String origin) { Document doc = Jsoup.parse(origin); Elements components = doc.select("[bennu-component]"); for (Element component : components) { String key = component.attr("bennu-component"); Element result = COMPONENTS.get(key).process(component); component.replaceWith(result); } return doc.toString(); }

Target:
public static String process(String origin) { Document doc = Jsoup.parse(origin); Elements components = doc.select("[bennu-component]"); for (Element component : components) { String key = component.attr("bennu-component"); Optional.ofNullable(COMPONENTS.get(key)).ifPresent(x -> component.replaceWith(x.process(component))); } return doc.toString(); }
Source:
public boolean apply(ServerConfiguration conf, Flags cmdFlags) { ServerConfiguration bfconf = new ServerConfiguration(conf); boolean result = Bookie.format(bfconf, cmdFlags.nonInteractive, cmdFlags.force); if (cmdFlags.deleteCookie) { try { runFunctionWithRegistrationManager(conf, rm -> { try { Versioned<Cookie> cookie = Cookie.readFromRegistrationManager(rm, bfconf); cookie.getValue().deleteFromRegistrationManager(rm, bfconf, cookie.getVersion()); } catch (BookieException.CookieNotFoundException nne) { LOG.warn("No cookie to remove : ", nne); } catch (BookieException e) { e.printStackTrace(); } return null; }); } catch (MetadataException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } return result; }

Target:
public boolean apply(ServerConfiguration conf, Flags cmdFlags) { ServerConfiguration bfconf = new ServerConfiguration(conf); boolean result = Bookie.format(bfconf, cmdFlags.nonInteractive, cmdFlags.force); if (cmdFlags.deleteCookie) { try { runFunctionWithRegistrationManager(conf, rm -> { try { Versioned<Cookie> cookie = Cookie.readFromRegistrationManager(rm, bfconf); cookie.getValue().deleteFromRegistrationManager(rm, bfconf, cookie.getVersion()); } catch (Exception e) { throw new UncheckedExecutionException(e.getMessage(), e); } return null; }); } catch (MetadataException | ExecutionException e) { throw new UncheckedExecutionException(e.getMessage(), e); } } return result; }
Source:
static public Collection<AutoScalingTag> getTagsForDelete(AutoScalingTag[] all, Tag[] tags) { Collection<AutoScalingTag> result = null; if (all != null) { result = new ArrayList<AutoScalingTag>(); for (AutoScalingTag tag : all) { if (!TagUtils.isKeyInTags(tag.getKey(), tags)) { result.add(tag); } } } return result; }

Target:
static public AutoScalingTag[] getTagsForDelete( AutoScalingTag[] all, Tag[] tags ) { Collection<AutoScalingTag> result = new ArrayList<AutoScalingTag>(); if( all != null ) { for( AutoScalingTag tag : all ) { if( !TagUtils.isKeyInTags(tag.getKey(), tags) ) { result.add(tag); } } } return result.toArray(new AutoScalingTag[result.size()]); }
Source:
public void doPolling(Guid cmdId, List<Guid> childCmdIds) { DestroyImageCommand<DestroyImageParameters> command = commandCoordinatorUtil.retrieveCommand(cmdId); ArrayList<Guid> taskIds = command.getReturnValue().getVdsmTaskIdList(); ArrayList<AsyncTaskStatus> taskStatuses = commandCoordinatorUtil.pollTasks(taskIds); for (AsyncTaskStatus status : taskStatuses) { if (status.getTaskIsRunning()) { log.info("Waiting on destroy image command to complete."); return; } } command.setSucceeded(true); command.setCommandStatus(CommandStatus.SUCCEEDED); command.persistCommand(command.getParameters().getParentCommand()); log.info("Destroy image command has completed."); }

Target:
public void doPolling(Guid cmdId, List<Guid> childCmdIds) { DestroyImageCommand<DestroyImageParameters> command = commandCoordinatorUtil.retrieveCommand(cmdId); Set<Guid> taskIds = new HashSet<>(command.getReturnValue().getVdsmTaskIdList()); Map<Guid, AsyncTaskStatus> idToStatusMap = commandCoordinatorUtil.pollTasks(taskIds); for (Map.Entry<Guid, AsyncTaskStatus> idToStatus : idToStatusMap.entrySet()) { final Guid id = idToStatus.getKey(); final AsyncTaskStatus status = idToStatus.getValue(); if (status.getTaskIsRunning()) { log.info("Waiting on destroy image command to complete the task (taskId = {})", id); return; } } List<Guid> failed = new ArrayList<>(); for (Map.Entry<Guid, AsyncTaskStatus> idToStatus : idToStatusMap.entrySet()) { final Guid id = idToStatus.getKey(); final AsyncTaskStatus status = idToStatus.getValue(); if (!status.getTaskEndedSuccessfully()) { failed.add(id); } } if (failed.isEmpty()) { command.setSucceeded(true); command.setCommandStatus(CommandStatus.SUCCEEDED); command.persistCommand(command.getParameters().getParentCommand()); log.info("Destroy image command has completed successfully for images '{}' with async tasks '{}'.", command.getParameters().getImageList(), taskIds); } else { command.setSucceeded(false); command.setCommandStatus(CommandStatus.FAILED); log.info("Destroy image command has failed for images '{}' with async tasks '{}'.", command.getParameters().getImageList(), failed); } command.persistCommand(command.getParameters().getParentCommand()); }
Source:
public void postCollectionAdminGroupCreateAdminGroupForbidden() throws Exception { ObjectMapper mapper = new ObjectMapper(); GroupRest groupRest = new GroupRest(); MetadataRest metadataRest = new MetadataRest(); metadataRest.put("dc.description", new MetadataValueRest("testingDescription")); metadataRest.put("dc.subject", new MetadataValueRest("testSubject")); groupRest.setMetadata(metadataRest); String token = getAuthToken(eperson.getEmail(), password); getClient(token).perform(post("/api/core/collections/" + collection.getID() + "/adminGroup") .content(mapper.writeValueAsBytes(groupRest)) .contentType(contentType)) .andExpect(status().isForbidden()); }

Target:
public void postCollectionAdminGroupCreateAdminGroupForbidden() throws Exception { ObjectMapper mapper = new ObjectMapper(); GroupRest groupRest = new GroupRest(); MetadataRest metadataRest = new MetadataRest(); metadataRest.put("dc.description", new MetadataValueRest("testingDescription")); metadataRest.put("dc.subject", new MetadataValueRest("testSubject")); groupRest.setMetadata(metadataRest); String token = getAuthToken(eperson.getEmail(), password); getClient(token).perform(post("/api/core/collections/" + collection.getID() + "/adminGroup") .content(mapper.writeValueAsBytes(groupRest)) .contentType(contentType)) .andExpect(status().isForbidden()); token = getAuthToken(admin.getEmail(), password); getClient(token).perform(get("/api/core/collections/" + collection.getID() + "/adminGroup")) .andExpect(status().isNoContent()); }
Source:
private void initialize() { viewModel = new ParseTexDialogViewModel(databaseContext, dialogService, taskExecutor, preferencesService); fileTreeView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); fileTreeView.showRootProperty().bindBidirectional(viewModel.successfulSearchProperty()); fileTreeView.rootProperty().bind(EasyBind.map(viewModel.rootProperty(), fileNode -> new RecursiveTreeItem<>(fileNode, FileNodeViewModel::getChildren))); EasyBind.subscribe(fileTreeView.rootProperty(), root -> { if (root != null) { ((CheckBoxTreeItem<FileNodeViewModel>) root).setSelected(true); root.setExpanded(true); EasyBind.listBind(viewModel.getCheckedFileList(), fileTreeView.getCheckModel().getCheckedItems()); } }); new ViewModelTreeCellFactory<FileNodeViewModel>() .withText(FileNodeViewModel::getDisplayText) .install(fileTreeView); texDirectoryField.textProperty().bindBidirectional(viewModel.texDirectoryProperty()); browseButton.disableProperty().bindBidirectional(viewModel.searchInProgressProperty()); searchButton.disableProperty().bindBidirectional(viewModel.searchInProgressProperty()); selectAllButton.disableProperty().bindBidirectional(viewModel.noFilesFoundProperty()); unselectAllButton.disableProperty().bindBidirectional(viewModel.noFilesFoundProperty()); }

Target:
private void initialize() { viewModel = new ParseTexDialogViewModel(databaseContext, dialogService, taskExecutor, preferencesService); fileTreeView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); fileTreeView.showRootProperty().bindBidirectional(viewModel.successfulSearchProperty()); fileTreeView.rootProperty().bind(EasyBind.map(viewModel.rootProperty(), fileNode -> new RecursiveTreeItem<>(fileNode, FileNodeViewModel::getChildren))); EasyBind.subscribe(fileTreeView.rootProperty(), root -> { ((CheckBoxTreeItem<FileNodeViewModel>) root).setSelected(true); root.setExpanded(true); EasyBind.listBind(viewModel.getCheckedFileList(), fileTreeView.getCheckModel().getCheckedItems()); }); new ViewModelTreeCellFactory<FileNodeViewModel>() .withText(FileNodeViewModel::getDisplayText) .install(fileTreeView); texDirectoryField.textProperty().bindBidirectional(viewModel.texDirectoryProperty()); validationVisualizer.setDecoration(new IconValidationDecorator()); validationVisualizer.initVisualization(viewModel.texDirectoryValidation(), texDirectoryField); browseButton.disableProperty().bindBidirectional(viewModel.searchInProgressProperty()); searchButton.disableProperty().bind(viewModel.texDirectoryValidation().validProperty().not()); selectAllButton.disableProperty().bindBidirectional(viewModel.noFilesFoundProperty()); unselectAllButton.disableProperty().bindBidirectional(viewModel.noFilesFoundProperty()); progressIndicator.visibleProperty().bindBidirectional(viewModel.searchInProgressProperty()); }
Source:
private static Decimal toHiveDecimal(Object objectValue, int scale) { double value; if (objectValue instanceof Double) { value = (double) objectValue; } else if (objectValue instanceof Integer) { value = (int) objectValue; } else { throw new IllegalStateException("Unsupported decimal representation type: " + objectValue.getClass()); } BigInteger bigInteger = BigInteger.valueOf(Math.round(value * scale)); return new Decimal(ByteBuffer.wrap(bigInteger.toByteArray()), checkedCast(scale)); }

Target:
private static Decimal toHiveDecimal(Object objectValue, int scale) { double value = ((Number) objectValue).doubleValue(); BigInteger bigInteger = BigInteger.valueOf(Math.round(value * scale)); return new Decimal(ByteBuffer.wrap(bigInteger.toByteArray()), checkedCast(scale)); }
Source:
public void testApplyEmptyOrNull() { Assert.assertEquals(null, loadingLookup.apply(null)); if (!NullHandling.replaceWithDefault()) { Assert.assertEquals(null, loadingLookup.apply("")); } }

Target:
public void testApplyEmptyOrNull() { Assert.assertEquals(null, loadingLookup.apply(null)); if (NullHandling.sqlCompatible()) { Assert.assertEquals(null, loadingLookup.apply("")); } }
Source:
public static IContainerDMContext[] getContainerContexts() throws InterruptedException, ExecutionException, TimeoutException { assert!fProcessesService.getExecutor().isInExecutorThread(); Query<IContainerDMContext[]> query = new Query<IContainerDMContext[]>() { @Override protected void execute(final DataRequestMonitor<IContainerDMContext[]> rm) { fProcessesService.getProcessesBeingDebugged(fGdbControl.getContext(), new ImmediateDataRequestMonitor<IDMContext[]>() { @Override protected void handleSuccess() { if (isSuccess()) { IDMContext[] contexts = getData(); rm.done((IContainerDMContext[]) contexts); } } }); } }; fGdbControl.getExecutor().execute(query); return query.get(TestsPlugin.massageTimeout(2000), TimeUnit.MILLISECONDS); }

Target:
public static IContainerDMContext[] getContainerContexts() throws InterruptedException, ExecutionException, TimeoutException { assert!fProcessesService.getExecutor().isInExecutorThread(); Query<IContainerDMContext[]> query = new Query<IContainerDMContext[]>() { @Override protected void execute(final DataRequestMonitor<IContainerDMContext[]> rm) { fProcessesService.getProcessesBeingDebugged(fGdbControl.getContext(), new ImmediateDataRequestMonitor<IDMContext[]>() { @Override protected void handleSuccess() { IDMContext[] contexts = getData(); rm.done((IContainerDMContext[]) contexts); } }); } }; fGdbControl.getExecutor().execute(query); return query.get(TestsPlugin.massageTimeout(2000), TimeUnit.MILLISECONDS); }
Source:
private void startDiscovery() { log.info("Shard organizer start discovery, organizationDiscoveryIntervalMillis: %s", organizationDiscoveryIntervalMillis); discoveryService.scheduleWithFixedDelay(() -> { try { SECONDS.sleep(ThreadLocalRandom.current().nextLong(1, organizationDiscoveryIntervalMillis / 1000)); log.info("Running shard organizer..."); submitJobs(discoverAndInitializeTablesToOrganize()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (Throwable t) { log.error(t, "Error running shard organizer"); } }, 0, organizationDiscoveryIntervalMillis, TimeUnit.MILLISECONDS); }

Target:
private void startDiscovery() { discoveryService.scheduleWithFixedDelay(() -> { try { SECONDS.sleep(ThreadLocalRandom.current().nextLong(1, organizationDiscoveryIntervalMillis)); log.info("Running shard organizer..."); submitJobs(discoverAndInitializeTablesToOrganize()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (Throwable t) { log.error(t, "Error running shard organizer"); } }, 0, organizationDiscoveryIntervalMillis, TimeUnit.MILLISECONDS); }
Source:
static AwsDates fromXAmzDate(String xAmzDate) { return new AwsDates(xAmzDate, xAmzDate, xAmzDate.substring(0, 8)); }

Target:
static AwsDates fromXAmzDate(String xAmzDate) throws ParseException { new SimpleDateFormat(AwsDates.X_AMZ_DATE_FORMAT).parse(xAmzDate); return new AwsDates(xAmzDate); }
Source:
private Set<InsightCard.Category> getRecentInsightsCategories(final Long accountId) { final DateTime aWeekAgo = DateTime.now(DateTimeZone.UTC).minusDays(14); final Boolean chronological = true; final List<InsightCard> cards = this.insightsDAODynamoDB.getInsightsByDate(accountId, aWeekAgo, chronological, RECENT_DAYS); final Set<InsightCard.Category> seenCategories = new HashSet<>(); for (InsightCard card : cards) { seenCategories.add(card.category); } return seenCategories; }

Target:
private Set<InsightCard.Category> getRecentInsightsCategories(final Long accountId) { final DateTime twoWeeksAgo = DateTime.now(DateTimeZone.UTC).minusDays(13); final Boolean chronological = true; final List<InsightCard> cards = this.insightsDAODynamoDB.getInsightsByDate(accountId, twoWeeksAgo, chronological, RECENT_DAYS); final Set<InsightCard.Category> seenCategories = new HashSet<>(); for (InsightCard card : cards) { seenCategories.add(card.category); } return seenCategories; }
Source:
public void setUp() throws Exception { super.setUp(); if (SystemUtils.IS_OS_LINUX) { try { eventLoopGroup = new EpollEventLoopGroup(); } catch (Exception e) { LOG.warn("Could not use Netty Epoll event loop"); eventLoopGroup = new NioEventLoopGroup(); } } else { eventLoopGroup = new NioEventLoopGroup(); } executor = OrderedSafeExecutor.newBuilder() .name("BKClientOrderedSafeExecutor") .numThreads(2) .build(); }

Target:
public void setUp() throws Exception { super.setUp(); if (SystemUtils.IS_OS_LINUX) { try { eventLoopGroup = new EpollEventLoopGroup(); } catch (Throwable t) { LOG.warn("Could not use Netty Epoll event loop {}", t.getMessage()); eventLoopGroup = new NioEventLoopGroup(); } } else { eventLoopGroup = new NioEventLoopGroup(); } executor = OrderedSafeExecutor.newBuilder() .name("BKClientOrderedSafeExecutor") .numThreads(2) .build(); }
Source:
public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (elementId: "); result.append(elementId); if(tags != null){ result.append(", tags: "); result.append(tags); } if(contributorURI != null){ result.append(", contributorURI: "); result.append(contributorURI); } if(persistedState != null){ result.append(", persistedState: "); result.append(persistedState); } if(transientData != null && !transientData.isEmpty()){ result.append(", transientData: "); result.append(transientData); } result.append(')'); return result.toString(); }

Target:
public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (elementId: "); result.append(elementId); result.append(", tags: "); result.append(tags); result.append(", contributorURI: "); result.append(contributorURI); result.append(')'); return result.toString(); }
Source:
private Collection<EStructuralFeature.Setting> safGetNonNavigableInverseReferences(EObject eObject, ECrossReferenceAdapter crossReferencer) { final Collection<EStructuralFeature.Setting> originInverseReference; if (eObject != null) { originInverseReference = crossReferencer.getNonNavigableInverseReferences(eObject, false); } else { originInverseReference = ImmutableList.of(); } return originInverseReference; }

Target:
private Collection<EStructuralFeature.Setting> safGetNonNavigableInverseReferences(EObject eObject, ECrossReferenceAdapter crossReferencer) { final Collection<EStructuralFeature.Setting> inverseReference; if (eObject != null) { inverseReference = crossReferencer.getNonNavigableInverseReferences(eObject, false); } else { inverseReference = ImmutableList.of(); } return inverseReference; }
Source:
void dropTables(final Set<TableReference> tablesToDrop) { try { clientPool.runWithRetry(client -> { KsDef ks = client.describe_keyspace(config.getKeyspaceOrThrow()); Set<TableReference> existingTables = Sets.newHashSet(); existingTables.addAll(ks.getCf_defs().stream() .map(CassandraKeyValueServices::tableReferenceFromCfDef) .collect(Collectors.toList())); for (TableReference table : tablesToDrop) { CassandraVerifier.sanityCheckTableName(table); if (existingTables.contains(table)) { cassandraTableTruncator.runTruncateOnClient(ImmutableSet.of(table), client); client.system_drop_column_family(CassandraKeyValueServiceImpl.internalTableName(table)); updateMetadataForTable(table); } else { log.warn("Ignored call to drop a table ({}) that did not exist.", LoggingArgs.tableRef(table)); } } CassandraKeyValueServices.waitForSchemaVersions(config, client, "after dropping the column " + "family for tables " + tablesToDrop + " in a call to drop tables"); return null; }); } catch (Exception e) { throw Throwables.unwrapAndThrowAtlasDbDependencyException(e); } }

Target:
void dropTables(final Set<TableReference> tablesToDrop) { try { clientPool.runWithRetry(client -> { KsDef ks = client.describe_keyspace(config.getKeyspaceOrThrow()); Set<TableReference> existingTables = Sets.newHashSet(); existingTables.addAll(ks.getCf_defs().stream() .map(CassandraKeyValueServices::tableReferenceFromCfDef) .collect(Collectors.toList())); for (TableReference table : tablesToDrop) { CassandraVerifier.sanityCheckTableName(table); if (existingTables.contains(table)) { CassandraKeyValueServices.runWithWaitingForSchemas( () -> truncateThenDrop(table, client), config, client, "dropping the column family for table " + table + " in a call to drop tables"); deleteAtlasMetadataForTable(table); } else { log.warn("Ignored call to drop a table ({}) that did not exist.", LoggingArgs.tableRef(table)); } } return null; }); } catch (Exception e) { throw Throwables.unwrapAndThrowAtlasDbDependencyException(e); } }
Source:
private void log(Environment result) { logger.info(String.format("Located environment: name=%s, profiles=%s, label=%s, version=%s, state=%s", result.getName(), result.getProfiles() == null ? "" : Arrays.asList(result.getProfiles()), result.getLabel(), result.getVersion(), result.getState())); if (logger.isDebugEnabled()) { List<PropertySource> propertySourceList = result.getPropertySources(); if (propertySourceList != null) { int propertyCount = 0; for (PropertySource propertySource: propertySourceList) { propertyCount += propertySource.getSource().size(); } logger.debug(String.format("Environment %s has %d property sources with %d properties.", result.getName(), result.getPropertySources().size(), propertyCount)); } } }

Target:
private void log(Environment result) { if (logger.isInfoEnabled()) { logger.info(String.format("Located environment: name=%s, profiles=%s, label=%s, version=%s, state=%s", result.getName(), result.getProfiles() == null ? "" : Arrays.asList(result.getProfiles()), result.getLabel(), result.getVersion(), result.getState())); } if (logger.isDebugEnabled()) { List<PropertySource> propertySourceList = result.getPropertySources(); if (propertySourceList != null) { int propertyCount = 0; for (PropertySource propertySource: propertySourceList) { propertyCount += propertySource.getSource().size(); } logger.debug(String.format("Environment %s has %d property sources with %d properties.", result.getName(), result.getPropertySources().size(), propertyCount)); } } }
Source:
public void mustRecommendHeapMemory() { assertThat( recommendHeapMemory( mebiBytes( 100 ) ), between( mebiBytes( 45 ), mebiBytes( 55 ) ) ); assertThat( recommendHeapMemory( gibiBytes( 1 ) ), between( mebiBytes( 450 ), mebiBytes( 550 ) ) ); assertThat( recommendHeapMemory( gibiBytes( 3 ) ), between( mebiBytes( 1256 ), mebiBytes( 1356 ) ) ); assertThat( recommendHeapMemory( gibiBytes( 6 ) ), between( mebiBytes( 3000 ), mebiBytes( 3200 ) ) ); assertThat( recommendHeapMemory( gibiBytes( 192 ) ), between( gibiBytes( 31 ), gibiBytes( 33 ) ) ); assertThat( recommendHeapMemory( gibiBytes( 1920 ) ), between( gibiBytes( 31 ), gibiBytes( 33 ) ) ); }

Target:
public void mustRecommendHeapMemory() { assertThat( recommendHeapMemory( mebiBytes( 100 ) ), between( mebiBytes( 45 ), mebiBytes( 55 ) ) ); assertThat( recommendHeapMemory( gibiBytes( 1 ) ), between( mebiBytes( 450 ), mebiBytes( 550 ) ) ); assertThat( recommendHeapMemory( gibiBytes( 3 ) ), between( mebiBytes( 1256 ), mebiBytes( 1356 ) ) ); assertThat( recommendHeapMemory( gibiBytes( 6 ) ), between( mebiBytes( 3000 ), mebiBytes( 3200 ) ) ); assertThat( recommendHeapMemory( gibiBytes( 192 ) ), between( gibiBytes( 30 ), gibiBytes( 32 ) ) ); assertThat( recommendHeapMemory( gibiBytes( 1920 ) ), between( gibiBytes( 30 ), gibiBytes( 32 ) ) ); }
Source:
public void createFHIRCondition_shouldReturnCreatedFHIRCondition() { Condition condition = new Condition(); IdType id = new IdType(); id.setValue(CONDITION_UUID); condition.setId(id); Patient patientRef = Context.getPatientService().getPatient(2); Reference patient = FHIRUtils.buildPatientOrPersonResourceReference(patientRef); condition.setSubject(patient); condition.setClinicalStatus(Condition.ConditionClinicalStatus.ACTIVE); condition.setCode(new CodeableConcept().addCoding( new Coding().setCode("999").setDisplay("NO").setSystem(FHIRConstants.OPENMRS_URI)).setText("NO")); Condition justCreatedCondition = getService().createFHIRCondition(condition); assertNotNull(justCreatedCondition); assertEquals(justCreatedCondition.getSubject().getReference(), patient.getReference()); assertEquals(justCreatedCondition.getClinicalStatus(), Condition.ConditionClinicalStatus.ACTIVE); assertEquals(justCreatedCondition.getOnset(), condition.getOnset()); }

Target:
public void createFHIRCondition_shouldReturnCreatedFHIRCondition() { Condition condition = new Condition(); IdType id = new IdType(); id.setValue(CONDITION_UUID); condition.setId(id); Patient patientRef = Context.getPatientService().getPatient(2); Reference patient = FHIRUtils.buildPatientOrPersonResourceReference(patientRef); condition.setSubject(patient); condition.setClinicalStatus(Condition.ConditionClinicalStatus.ACTIVE); condition.setCode(new CodeableConcept().addCoding( new Coding().setCode("999").setDisplay("NO").setSystem(FHIRConstants.OPENMRS_URI)).setText("NO")); Condition justCreatedCondition = getService().createFHIRCondition(condition); Condition getSavedCondition = getService().getConditionByUuid(justCreatedCondition.getId()); assertNotNull(justCreatedCondition); assertEquals(justCreatedCondition.getSubject().getReference(), patient.getReference()); assertEquals(justCreatedCondition.getClinicalStatus(), Condition.ConditionClinicalStatus.ACTIVE); assertEquals(justCreatedCondition.getOnset(), condition.getOnset()); assertNotNull(getSavedCondition); assertEquals(justCreatedCondition.getId(), getSavedCondition.getId()); assertEquals(justCreatedCondition.getClinicalStatus(), getSavedCondition.getClinicalStatus()); assertEquals(justCreatedCondition.getOnset(), getSavedCondition.getOnset()); }
Source:
private Throwable mapError(Throwable throwable, ServiceBusErrorSource errorSource) { if (throwable instanceof ServiceBusAmqpException) { return throwable; } if (throwable instanceof AmqpException) { return new ServiceBusAmqpException((AmqpException) throwable, errorSource); } else { return throwable; } }

Target:
private Throwable mapError(Throwable throwable, ServiceBusErrorSource errorSource) { if ((throwable instanceof ServiceBusAmqpException) || !(throwable instanceof AmqpException)) { return throwable; } else { return new ServiceBusAmqpException((AmqpException) throwable, errorSource); } }
Source:
public byte[] serialize(final String topic, final Set<Statement> data) { if(data == null) { return null; } final ByteArrayOutputStream boas = new ByteArrayOutputStream(); final RDFWriter writer = WRITER_FACTORY.getWriter(boas); writer.startRDF(); for(final Statement stmt : data) { log.debug("Writing Statement: " + stmt); writer.handleStatement(stmt); } writer.endRDF(); return boas.toByteArray(); }

Target:
public byte[] serialize(final String topic, final Set<Statement> data) { if(data == null) { return null; } final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final RDFWriter writer = WRITER_FACTORY.getWriter(baos); writer.startRDF(); for(final Statement stmt : data) { log.debug("Writing Statement: " + stmt); writer.handleStatement(stmt); } writer.endRDF(); return baos.toByteArray(); }
Source:
public List<Ref> getRefsByPrefix(String... prefixes) throws IOException { List<Ref> result = new ArrayList<>(); if (prefixes.length == 0) { result.addAll(getRefsByPrefix(ALL)); } else { for (String prefix : prefixes) { result.addAll(getRefsByPrefix(prefix)); } } return Collections.unmodifiableList(result); }

Target:
public List<Ref> getRefsByPrefix(String... prefixes) throws IOException { List<Ref> result = new ArrayList<>(); for (String prefix : prefixes) { result.addAll(getRefsByPrefix(prefix)); } return Collections.unmodifiableList(result); }
Source:
public final Object write(final SFileDescriptor file, final long nBytes, final long offset, final SBlock fail) { file.write((int) nBytes, offset, fail); return Nil.nilObject; }

Target:
public final Object write(final SFileDescriptor file, final long nBytes, final long offset, final SBlock fail) { file.write((int) nBytes, offset, fail, dispatchHandler); return file; }
Source:
private IncrementalResultsImpl getIncrementalResults(Map<String, Collection<KnowledgeBuilderError>> currentErrors) { IncrementalResultsImpl results = new IncrementalResultsImpl(); for (Map.Entry<String, Collection<KnowledgeBuilderError>> entry : currentErrors.entrySet()) { Collection<KnowledgeBuilderError> previousErrorsInKB = previousErrors.remove(entry.getValue()); for ( KnowledgeBuilderError error : entry.getValue() ) { if ( previousErrorsInKB == null || !previousErrorsInKB.remove( error ) ) { results.addMessage( error, entry.getKey() ); } } if (previousErrorsInKB != null) { for ( KnowledgeBuilderError error : previousErrorsInKB ) { results.removeMessage( error, entry.getKey() ); } } } for (Map.Entry<String, Collection<KnowledgeBuilderError>> entry : previousErrors.entrySet()) { for ( KnowledgeBuilderError error : entry.getValue() ) { results.removeMessage( error, entry.getKey() ); } } return results; }

Target:
private IncrementalResultsImpl getIncrementalResults(Map<String, Collection<KnowledgeBuilderError>> currentErrors) { IncrementalResultsImpl results = new IncrementalResultsImpl(); for (Map.Entry<String, Collection<KnowledgeBuilderError>> entry : currentErrors.entrySet()) { Collection<KnowledgeBuilderError> previousErrorsInKB = previousErrors.remove(entry.getKey()); for ( KnowledgeBuilderError error : entry.getValue() ) { if ( previousErrorsInKB == null || !previousErrorsInKB.remove( error ) ) { results.addMessage( error, entry.getKey() ); } } if (previousErrorsInKB != null) { for ( KnowledgeBuilderError error : previousErrorsInKB ) { results.removeMessage( error, entry.getKey() ); } } } for (Map.Entry<String, Collection<KnowledgeBuilderError>> entry : previousErrors.entrySet()) { for ( KnowledgeBuilderError error : entry.getValue() ) { results.removeMessage( error, entry.getKey() ); } } return results; }
Source:
protected ImmutableValue<Double> getValueGetter() { return new ImmutableSpongeValue<>(this.usedKey, DataConstants.Entity.DEFAULT_ABSORPTION, this.getValue()); }

Target:
protected ImmutableValue<Double> getValueGetter() { return this.value; }
Source:
public void onReceive(Context context, Intent intent) { final String methodName = ":onReceive"; if (intent.getAction().equals(Intent.ACTION_PACKAGE_ADDED)) { Logger.v(TAG + methodName, "Application install message is received"); if (intent != null && intent.getData() != null) { Logger.v(TAG + methodName, "Installing:" + intent.getData().toString()); final String receivedInstalledPackageName = intent.getData().toString(); if (receivedInstalledPackageName.equalsIgnoreCase("package:" + AuthenticationConstants.Broker.AZURE_AUTHENTICATOR_APP_PACKAGE_NAME) || receivedInstalledPackageName.equalsIgnoreCase("package:" + AuthenticationSettings.INSTANCE.getBrokerPackageName())) { Logger.v(TAG + methodName, receivedInstalledPackageName + " is installed, start sending request to broker."); String request = getInstallRequestInthisApp(context); if (!StringExtensions.IsNullOrBlank(request)) { resumeRequestInBroker(context, request); } else { Logger.v(TAG + methodName, "No request saved in sharedpreferences, cannot resume broker request."); } } } } }

Target:
public void onReceive(Context context, Intent intent) { final String methodName = "onReceive"; if (intent.getAction().equals(Intent.ACTION_PACKAGE_ADDED)) { Logger.v(TAG + methodName, "Application install message is received"); if (intent != null && intent.getData() != null) { Logger.v(TAG + methodName, "ApplicationReceiver detectes the installation of " + intent.getData().toString()); final String receivedInstalledPackageName = intent.getData().toString(); if (receivedInstalledPackageName.equalsIgnoreCase("package:" + AuthenticationConstants.Broker.AZURE_AUTHENTICATOR_APP_PACKAGE_NAME) || receivedInstalledPackageName.equalsIgnoreCase("package:" + AuthenticationSettings.INSTANCE.getBrokerPackageName())) { installedPackageName = receivedInstalledPackageName.equalsIgnoreCase("package:" + AuthenticationConstants.Broker.AZURE_AUTHENTICATOR_APP_PACKAGE_NAME)? AuthenticationConstants.Broker.AZURE_AUTHENTICATOR_APP_PACKAGE_NAME : AuthenticationConstants.Broker.COMPANY_PORTAL_APP_PACKAGE_NAME; String request = getInstallRequestInthisApp(context); brokerProxy = new BrokerProxy(context); final Date dateTimeForSavedRequest = new Date(getInstallRequestTimeStamp(context)); if (!StringExtensions.IsNullOrBlank(request) && brokerProxy.canSwitchToBroker() && isRequestTimestampValidForResume(dateTimeForSavedRequest)) { Logger.v(TAG + methodName, receivedInstalledPackageName + " is installed, start sending request to broker."); resumeRequestInBroker(context, request); } else { Logger.v(TAG + methodName, "No request saved in sharedpreferences or request already timeout" + ", cannot resume broker request."); } } } } }
Source:
public boolean isBlacklisted(String name) { if (Main.isUnitTest && name.contains("$$EnhancerByMockitoWithCGLIB$$")) { mockOff(); return false; } for (CustomClassFilter f : ExtensionList.lookup(CustomClassFilter.class)) { Boolean r = f.permits(name); if (r != null) { if (r) { LOGGER.log(Level.FINER, "{0} specifies a policy for {1}: {2}", new Object[] {f, name, r}); } else { notifyRejected(null, name, String.format("%s specifies a policy for %s: %s", f, name, r)); } return !r; } } if (ClassFilter.STANDARD.isBlacklisted(name)) { if (SUPPRESS_ALL) { LOGGER.log(Level.WARNING, "would normally reject {0} according to standard blacklist; see <LINK_0>", name); return false; } notifyRejected(null, name, String.format("rejecting %s according to standard blacklist; see <LINK_0>", name)); return true; } else { return false; } }

Target:
public boolean isBlacklisted(String name) { if (Main.isUnitTest && name.contains("$$EnhancerByMockitoWithCGLIB$$")) { mockOff(); return false; } for (CustomClassFilter f : ExtensionList.lookup(CustomClassFilter.class)) { Boolean r = f.permits(name); if (r != null) { if (r) { LOGGER.log(Level.FINER, "{0} specifies a policy for {1}: {2}", new Object[] {f, name, r}); } else { notifyRejected(null, name, String.format("%s specifies a policy for %s: %s", f, name, r)); } return !r; } } if (ClassFilter.STANDARD.isBlacklisted(name)) { if (SUPPRESS_ALL) { notifyRejected(null, name, String.format("would normally reject %s according to standard blacklist; see <LINK_0>", name)); return false; } notifyRejected(null, name, String.format("rejecting %s according to standard blacklist; see <LINK_0>", name)); return true; } else { return false; } }
Source:
public LineParameters(Color c, Double op, Double w, String d){ color = c == null ? Color.BLACK : c; opacity = op == null ? 1.0 : Math.min(1.0, Math.max(0,op)); width = w == null ? .25 : w; dash = d == null || !ParameterUtil.validateDashArray(d)? "" : d; }

Target:
public LineParameters(Color c, Double op, Double w, String d){ color = c == null ? Color.BLACK : c; opacity = op == null ? SolidFill.DEFAULT_OPACITY : Math.min(1.0, Math.max(0,op)); width = w == null ? PenStroke.DEFAULT_WIDTH : w; dash = d == null || !ParameterUtil.validateDashArray(d)? "" : d; }
Source:
public void testGetBlockDeviceTemplateGroups() { Set<VirtualGuestBlockDeviceTemplateGroup> privateImages = api().getBlockDeviceTemplateGroups(); assertNotNull(privateImages); }

Target:
public void testGetBlockDeviceTemplateGroups() { Set<VirtualGuestBlockDeviceTemplateGroup> privateImages = api().getBlockDeviceTemplateGroups(); assertNotNull(privateImages); for (VirtualGuestBlockDeviceTemplateGroup privateImage : privateImages) { assertTrue(privateImage.getId() > 0, "id must be greater than 0"); assertTrue(privateImage.getStatusId() > 0, "status id must be greater than 0"); assertTrue(privateImage.getAccountId() > 0, "id must be greater than 0"); } }
Source:
public void channelInactiveTest() { HttpRequest request = createRequestWithHeaders(HttpMethod.GET, TestingUri.Close.toString()); ChunkedWriteHandler chunkedWriteHandler = new ChunkedWriteHandler(); EmbeddedChannel channel = new EmbeddedChannel(chunkedWriteHandler); NettyResponseChannel nettyResponseChannel = new NettyResponseChannel(new MockChannelHandlerContext(channel), new NettyMetrics(new MetricRegistry()), new PerformanceConfig(new VerifiableProperties(new Properties())), new NettyConfig(new VerifiableProperties(new Properties()))); channel.disconnect().awaitUninterruptibly(); assertFalse("Channel should be closed", channel.isOpen()); Future<Long> future = nettyResponseChannel.write(Unpooled.buffer(1), null); try { future.get(); fail("Future.get() should throw exception."); } catch (InterruptedException | ExecutionException e) { assertTrue("Should be ClosedChannelException", e.getCause() instanceof ClosedChannelException); } }

Target:
public void channelInactiveTest() { HttpRequest request = createRequestWithHeaders(HttpMethod.GET, TestingUri.Close.toString()); ChunkedWriteHandler chunkedWriteHandler = new ChunkedWriteHandler(); EmbeddedChannel channel = new EmbeddedChannel(chunkedWriteHandler); VerifiableProperties verifiableProperties = new VerifiableProperties(new Properties()); NettyResponseChannel nettyResponseChannel = new NettyResponseChannel(new MockChannelHandlerContext(channel), new NettyMetrics(new MetricRegistry()), new PerformanceConfig(verifiableProperties), new NettyConfig(verifiableProperties)); channel.disconnect().awaitUninterruptibly(); assertFalse("Channel should be closed", channel.isOpen()); Future<Long> future = nettyResponseChannel.write(Unpooled.buffer(1), null); try { future.get(); fail("Future.get() should throw exception."); } catch (InterruptedException | ExecutionException e) { assertTrue("Should be ClosedChannelException", e.getCause() instanceof ClosedChannelException); } }
Source:
public boolean isModified(File packFile) { return super.isModified(packFile) || (checksum != MISSING_CHECKSUM && !checksum.equals(readChecksum(packFile))); }

Target:
public boolean isModified(File packFile) { if (!super.isModified(packFile)) { return false; } if (wasSizeChanged() || wasFileKeyChanged() || !wasLastModifiedRacilyClean()) { return true; } return isChecksumChanged(packFile); }
Source:
public static SAXParser getSAXParser() { try { return SAX_PARSER_FACTORY.newSAXParser(); } catch (Exception e) { throw new XmlBeanDefinitionException("Error occurred using SAXParserFactory to create a SAXParser.", e); } }

Target:
public static SAXParser getSAXParser() { try { return SAX_PARSER_FACTORY.newSAXParser(); } catch (Exception e) { throw new XmlBeanDefinitionException("Error occurred while creating a SAXParserFactory from SAXParser.", e); } }
Source:
private RemoteFieldValue[] convertChanges(HashMap<IssueAttribute, String> changes) { Set<IssueAttribute> changedAttributes = new HashSet<IssueAttribute>(changes.keySet()); ArrayList<RemoteFieldValue> remoteFields = new ArrayList<RemoteFieldValue>(); if (changedAttributes.contains(Issue.Field.STATUS)) { Issue.Status status = Issue.Status.valueOf(changes.get(Issue.Field.STATUS)); RemoteFieldValue rfv = new RemoteFieldValue(); rfv.setId("STATUS"); rfv.setValues(new String[]{StatusConverter.fromIssueStatus(status)}); changedAttributes.remove(Issue.Field.STATUS); remoteFields.add(rfv); } if (changedAttributes.contains(Issue.Field.TYPE)) { Issue.Type type = Issue.Type.valueOf(changes.get(Issue.Field.TYPE)); RemoteFieldValue rfv = new RemoteFieldValue(); rfv.setId("issuetype"); rfv.setValues(new String[]{TypeConverter.fromIssueType(type)}); changedAttributes.remove(Issue.Field.TYPE); remoteFields.add(rfv); } if (changedAttributes.contains(Issue.Field.PRIORITY)) { Issue.Priority priority = Issue.Priority.valueOf(changes.get(Issue.Field.PRIORITY)); RemoteFieldValue rfv = new RemoteFieldValue(); rfv.setId("priority"); rfv.setValues(new String[]{PriorityConverter.fromIssuePriority(priority)}); changedAttributes.remove(Issue.Field.PRIORITY); remoteFields.add(rfv); } for (IssueAttribute attribute : changedAttributes) { String targetField = FieldConverter.fromIssueField((Issue.Field) attribute); if (targetField != null) { RemoteFieldValue rfv = new RemoteFieldValue(); rfv.setId("priority"); rfv.setValues(new String[]{changes.get(attribute)}); remoteFields.add(rfv); } } RemoteFieldValue[] remoteFieldArray = new RemoteFieldValue[remoteFields.size()]; remoteFields.toArray(remoteFieldArray); return remoteFieldArray; }

Target:
private RemoteFieldValue[] convertChanges(HashMap<IssueAttribute, String> changes) { Set<IssueAttribute> changedAttributes = new HashSet<IssueAttribute>(changes.keySet()); ArrayList<RemoteFieldValue> remoteFields = new ArrayList<RemoteFieldValue>(); for (IssueAttribute attribute : changedAttributes) { String targetField = FieldConverter.fromIssueField((Issue.Field) attribute); String targetValue = JiraValueConverter.convert(changes.get(attribute)); if (targetField != null && targetValue != null) { RemoteFieldValue rfv = new RemoteFieldValue(); rfv.setId(targetField); rfv.setValues(new String[]{targetValue}); remoteFields.add(rfv); } } RemoteFieldValue[] remoteFieldArray = new RemoteFieldValue[remoteFields.size()]; remoteFields.toArray(remoteFieldArray); return remoteFieldArray; }
Source:
protected TestResultSummary run() throws Exception { FilePath workspace = getContext().get(FilePath.class); workspace.mkdirs(); Run<?,?> run = getContext().get(Run.class); TaskListener listener = getContext().get(TaskListener.class); Launcher launcher = getContext().get(Launcher.class); FlowNode node = getContext().get(FlowNode.class); String nodeId = node.getId(); List<FlowNode> enclosingBlocks = getEnclosingStagesAndParallels(node); PipelineTestDetails pipelineTestDetails = new PipelineTestDetails(); pipelineTestDetails.setNodeId(nodeId); pipelineTestDetails.setEnclosingBlocks(getEnclosingBlockIds(enclosingBlocks)); pipelineTestDetails.setEnclosingBlockNames(getEnclosingBlockNames(enclosingBlocks)); try { TestResultAction testResultAction = JUnitResultArchiver.parseAndAttach(step, pipelineTestDetails, run, workspace, launcher, listener); if (testResultAction != null) { int testFailures = testResultAction.getResult().getResultByNode(nodeId).getFailCount(); if (testFailures > 0) { node.addOrReplaceAction(new WarningAction(testFailures + " tests failed")); run.setResult(Result.UNSTABLE); } return new TestResultSummary(testResultAction.getResult().getResultByNode(nodeId)); } } catch (Exception e) { listener.getLogger().println(e.getMessage()); throw e; } return new TestResultSummary(); }

Target:
protected TestResultSummary run() throws Exception { FilePath workspace = getContext().get(FilePath.class); workspace.mkdirs(); Run<?,?> run = getContext().get(Run.class); TaskListener listener = getContext().get(TaskListener.class); Launcher launcher = getContext().get(Launcher.class); FlowNode node = getContext().get(FlowNode.class); String nodeId = node.getId(); List<FlowNode> enclosingBlocks = getEnclosingStagesAndParallels(node); PipelineTestDetails pipelineTestDetails = new PipelineTestDetails(); pipelineTestDetails.setNodeId(nodeId); pipelineTestDetails.setEnclosingBlocks(getEnclosingBlockIds(enclosingBlocks)); pipelineTestDetails.setEnclosingBlockNames(getEnclosingBlockNames(enclosingBlocks)); try { TestResultAction testResultAction = JUnitResultArchiver.parseAndAttach(step, pipelineTestDetails, run, workspace, launcher, listener); if (testResultAction != null) { TestResult testResult = testResultAction.getResult().getResultByNode(nodeId); int testFailures = testResult.getFailCount(); if (testFailures > 0) { node.addOrReplaceAction(new WarningAction(Result.UNSTABLE).withMessage(testFailures + " tests failed")); run.setResult(Result.UNSTABLE); } return new TestResultSummary(testResult); } } catch (Exception e) { listener.getLogger().println(e.getMessage()); throw e; } return new TestResultSummary(); }
Source:
void stubGetUserBySessionIdQuery() { VdcQueryReturnValue returnValue = new VdcQueryReturnValue(); returnValue.setSucceeded(true); returnValue.setReturnValue(mockUser); when(mockBackend.runQuery( eq(VdcQueryType.GetUserBySessionId), isA(VdcQueryParametersBase.class) )).thenReturn(returnValue); }

Target:
void stubGetUserBySessionIdQuery() { when(mockBackend.runQuery( eq(VdcQueryType.GetUserBySessionId), isA(VdcQueryParametersBase.class) )).thenReturn(new VdcQueryReturnValue() { { setSucceeded(true); setReturnValue(mockUser); } }); }
Source:
private Map<StoreKey, StoreKey> batchConvertReplicaMetadataResponseKeys(ReplicaMetadataResponse response) throws IOException { try { List<StoreKey> storeKeysToConvert = new ArrayList<>(); for (int i = 0; i < response.getReplicaMetadataResponseInfoList().size(); i++) { ReplicaMetadataResponseInfo replicaMetadataResponseInfo = response.getReplicaMetadataResponseInfoList().get(i); List<MessageInfo> messageInfoList = replicaMetadataResponseInfo.getMessageInfoList(); for (MessageInfo messageInfo : messageInfoList) { storeKeysToConvert.add(messageInfo.getStoreKey()); } } return storeKeyConverter.convert(storeKeysToConvert); } catch (Exception e) { throw new IOException("Problem with store key conversion", e); } }

Target:
private Map<StoreKey, StoreKey> batchConvertReplicaMetadataResponseKeys(ReplicaMetadataResponse response) throws IOException { try { List<StoreKey> storeKeysToConvert = new ArrayList<>(); for (ReplicaMetadataResponseInfo replicaMetadataResponseInfo : response.getReplicaMetadataResponseInfoList()) { for (MessageInfo messageInfo : replicaMetadataResponseInfo.getMessageInfoList()) { storeKeysToConvert.add(messageInfo.getStoreKey()); } } return storeKeyConverter.convert(storeKeysToConvert); } catch (Exception e) { throw new IOException("Problem with store key conversion", e); } }
Source:
private void mocksForUpdateBeforeSave() { ParseCurrentInstallationController controller = mock(ParseCurrentInstallationController.class); when(controller.isCurrent(any(ParseInstallation.class))).thenReturn(true); ParseCorePlugins.getInstance().registerCurrentInstallationController(controller); RobolectricPackageManager packageManager = spy(RuntimeEnvironment.getRobolectricPackageManager()); doReturn("parseTest").when(packageManager).getApplicationLabel(any(ApplicationInfo.class)); RuntimeEnvironment.setRobolectricPackageManager(packageManager); ParsePlugins.Android plugins = mock(ParsePlugins.Android.class); InstallationId installationId = mock(InstallationId.class); when(installationId.get()).thenReturn("installationId"); when(plugins.installationId()).thenReturn(installationId); when(plugins.applicationContext()).thenReturn(RuntimeEnvironment.application); ParsePlugins.set(plugins); }

Target:
private static void mocksForUpdateBeforeSave() { ParseCurrentInstallationController controller = mock(ParseCurrentInstallationController.class); when(controller.isCurrent(any(ParseInstallation.class))).thenReturn(true); ParseCorePlugins.getInstance().registerCurrentInstallationController(controller); RobolectricPackageManager packageManager = spy(RuntimeEnvironment.getRobolectricPackageManager()); doReturn("parseTest").when(packageManager).getApplicationLabel(any(ApplicationInfo.class)); RuntimeEnvironment.setRobolectricPackageManager(packageManager); ParsePlugins.Android plugins = mock(ParsePlugins.Android.class); InstallationId installationId = mock(InstallationId.class); when(installationId.get()).thenReturn("installationId"); when(plugins.installationId()).thenReturn(installationId); when(plugins.applicationContext()).thenReturn(RuntimeEnvironment.application); ParsePlugins.set(plugins); }
Source:
private int getNotificationIdForPost(Post post) { int remotePostId = 0; try { remotePostId = Integer.parseInt(post.getRemotePostId()); } catch (NumberFormatException nfe) { } return post.getLocalTableBlogId() + remotePostId; }

Target:
private int getNotificationIdForPost(Post post) { int remotePostId = StringUtils.stringToInt(post.getRemotePostId()); return post.getLocalTableBlogId() + remotePostId; }
Source:
public List<JobDetails> start() { scheduler.start(); List<JobDetails> backgroundJobs = new ArrayList<>(); Configuration configuration = configurationService.load("org.hawkular.metrics.jobs") .toBlocking().lastOrDefault(null); deleteTenant = new DeleteTenant(session, metricsService); Map<JobDetails, Integer> deleteTenantAttempts = new ConcurrentHashMap<>(); Func2<JobDetails, Throwable, RetryPolicy> deleteTenantRetryPolicy = (details, throwable) -> () -> { logger.warn("Execution of " + details + " failed", throwable); logger.info(details + " will be retried in 5 minutes"); return Minutes.minutes(5).toStandardDuration().getMillis(); }; scheduler.register(DeleteTenant.JOB_NAME, deleteTenant, deleteTenantRetryPolicy); Boolean compressionEnabled = Boolean.valueOf(configuration.get(CompressData.ENABLED_CONFIG, "true")); if(compressionEnabled) { CompressData compressDataJob = new CompressData(metricsService, configurationService); scheduler.register(CompressData.JOB_NAME, compressDataJob); maybeScheduleCompressData(backgroundJobs); } return backgroundJobs; }

Target:
public List<JobDetails> start() { scheduler.start(); List<JobDetails> backgroundJobs = new ArrayList<>(); Configuration configuration = configurationService.load("org.hawkular.metrics.jobs") .toBlocking().lastOrDefault(null); deleteTenant = new DeleteTenant(session, metricsService); Map<JobDetails, Integer> deleteTenantAttempts = new ConcurrentHashMap<>(); Func2<JobDetails, Throwable, RetryPolicy> deleteTenantRetryPolicy = (details, throwable) -> () -> { logger.warn("Execution of " + details + " failed", throwable); logger.info(details + " will be retried in 5 minutes"); return Minutes.minutes(5).toStandardDuration().getMillis(); }; scheduler.register(DeleteTenant.JOB_NAME, deleteTenant, deleteTenantRetryPolicy); CompressData compressDataJob = new CompressData(metricsService, configurationService); scheduler.register(CompressData.JOB_NAME, compressDataJob); maybeScheduleCompressData(backgroundJobs); return backgroundJobs; }