auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void test() { fix().addInputLines( "Test.java", "import java.util.Objects;", "public class Test {", " void f(Object a, Object[] b, String[] c) {", " Objects.hash(a);", " Objects.hash(a, a);", " Objects.hash(b);", " Objects.hash(c);", " }", "}") .addOutputLines( "Test.java", "import java.util.Objects;", "public class Test {", " void f(Object a, Object[] b, String[] c) {", " Objects.hashCode(a);", " Objects.hash(a, a);", " Objects.hash(b);", " Objects.hashCode(c);", " }", "}") .doTest(); }

Target:
public void test() { fix().addInputLines( "Test.java", "import java.util.Objects;", "public class Test {", " void f(Object a, Object[] b, String[] c, String d) {", " Objects.hash(a);", " Objects.hash(a, a);", " Objects.hash(b);", " Objects.hash(c);", " Objects.hash(d);", " }", "}") .addOutputLines( "Test.java", "import java.util.Objects;", "public class Test {", " void f(Object a, Object[] b, String[] c, String d) {", " Objects.hashCode(a);", " Objects.hash(a, a);", " Objects.hash(b);", " " Objects.hash(c);", " Objects.hashCode(d);", " }", "}") .doTest(); }
Source:
public boolean inBank() { Area bankArea = new Area(new Tile(3179, 3447), new Tile(3191,3433)); return bankArea.contains(ctx.players.local()); }

Target:
public boolean inBank() { return bankArea.contains(ctx.players.local()); }
Source:
public void directDiagnostics() { CosmosClient directClient = null; try { directClient = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .directMode() .buildClient(); CosmosContainer cosmosContainer = directClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId()); InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = cosmosContainer.createItem(internalObjectNode); String diagnostics = createResponse.getDiagnostics().toString(); assertThat(diagnostics).contains("\"connectionMode\":\"DIRECT\""); assertThat(diagnostics).contains("supplementalResponseStatisticsList"); assertThat(diagnostics).contains("\"gatewayStatistics\":null"); assertThat(diagnostics).contains("addressResolutionStatistics"); assertThat(diagnostics).contains("\"metaDataName\":\"CONTAINER_LOOK_UP\""); assertThat(diagnostics).contains("\"metaDataName\":\"PARTITION_KEY_RANGE_LOOK_UP\""); assertThat(diagnostics).contains("\"metaDataName\":\"SERVER_ADDRESS_LOOKUP\""); assertThat(diagnostics).contains("\"serializationType\":\"PARTITION_KEY_FETCH_SERIALIZATION\""); assertThat(diagnostics).contains("\"userAgent\":\"" + Utils.getUserAgent() + "\""); assertThat(createResponse.getDiagnostics().getDuration()).isNotNull(); validateTransportRequestTimelineDirect(diagnostics); validateJson(diagnostics); } finally { if (directClient != null) { directClient.close(); } } }

Target:
public void directDiagnostics() { CosmosClient testDirectClient = null; try { testDirectClient = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .directMode() .buildClient(); CosmosContainer cosmosContainer = testDirectClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId()); InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = cosmosContainer.createItem(internalObjectNode); String diagnostics = createResponse.getDiagnostics().toString(); assertThat(diagnostics).contains("\"connectionMode\":\"DIRECT\""); assertThat(diagnostics).contains("supplementalResponseStatisticsList"); assertThat(diagnostics).contains("\"gatewayStatistics\":null"); assertThat(diagnostics).contains("addressResolutionStatistics"); assertThat(diagnostics).contains("\"metaDataName\":\"CONTAINER_LOOK_UP\""); assertThat(diagnostics).contains("\"metaDataName\":\"PARTITION_KEY_RANGE_LOOK_UP\""); assertThat(diagnostics).contains("\"metaDataName\":\"SERVER_ADDRESS_LOOKUP\""); assertThat(diagnostics).contains("\"serializationType\":\"PARTITION_KEY_FETCH_SERIALIZATION\""); assertThat(diagnostics).contains("\"userAgent\":\"" + Utils.getUserAgent() + "\""); assertThat(createResponse.getDiagnostics().getDuration()).isNotNull(); validateTransportRequestTimelineDirect(diagnostics); validateJson(diagnostics); } finally { if (testDirectClient != null) { testDirectClient.close(); } } }
Source:
public void testBalancerWithNullLocalityManager() { Set<TaskModel> taskModels = generateTaskModels(3); Set<ContainerModel> containers = new GroupByContainerCount(3).balance(taskModels, null); Map<String, ContainerModel> containersMap = new HashMap<>(); for (ContainerModel container : containers) { containersMap.put(container.getProcessorId(), container); } assertEquals(3, containers.size()); ContainerModel container0 = containersMap.get("0"); ContainerModel container1 = containersMap.get("1"); ContainerModel container2 = containersMap.get("2"); assertNotNull(container0); assertNotNull(container1); assertNotNull(container2); assertEquals("0", container0.getProcessorId()); assertEquals("1", container1.getProcessorId()); assertEquals("2", container2.getProcessorId()); assertEquals(1, container0.getTasks().size()); assertEquals(1, container1.getTasks().size()); assertEquals(1, container2.getTasks().size()); assertTrue(container0.getTasks().containsKey(getTaskName(0))); assertTrue(container1.getTasks().containsKey(getTaskName(1))); assertTrue(container2.getTasks().containsKey(getTaskName(2))); }

Target:
public void testBalancerWithNullLocalityManager() { Set<TaskModel> taskModels = generateTaskModels(3); Set<ContainerModel> groupContainers = new GroupByContainerCount(3).group(taskModels); Set<ContainerModel> balanceContainers = new GroupByContainerCount(3).balance(taskModels, null); assertEquals(groupContainers, balanceContainers); }
Source:
protected ChangeJdbcTransactionAttributes(Builder builder) { useJdbcStore = builder.useJdbcStore; actionStoreDropTable = builder.actionStoreDropTable; actionStoreTablePrefix = builder.actionStoreTablePrefix; communicationStoreDropTable = builder.communicationStoreDropTable; communicationStoreTablePrefix = builder.communicationStoreTablePrefix; stateStoreTablePrefix = builder.stateStoreTablePrefix; storeDatasource = builder.storeDatasource; stateStoreDropTable = builder.stateStoreDropTable; }

Target:
private ChangeJdbcTransactionAttributes(Builder builder) { useJdbcStore = builder.useJdbcStore; actionStoreDropTable = builder.actionStoreDropTable; actionStoreTablePrefix = builder.actionStoreTablePrefix; communicationStoreDropTable = builder.communicationStoreDropTable; communicationStoreTablePrefix = builder.communicationStoreTablePrefix; stateStoreTablePrefix = builder.stateStoreTablePrefix; storeDatasource = builder.storeDatasource; stateStoreDropTable = builder.stateStoreDropTable; }
Source:
public void testInsertFirstAndAdd3() throws Exception { KieSession ksession = session.getStateful(); insertNotEvent(ksession); ksession.fireAllRules(); Assertions.assertThat(firedRules.isRuleFired(RULE1)).as(RULE1).isFalse(); Assertions.assertThat(firedRules.isRuleFired(RULE3)).as(RULE3).isFalse(); insertNotEvent(ksession, "different value"); ksession.fireAllRules(); insertNotEvent(ksession, "different value"); ksession.fireAllRules(); insertNotEvent(ksession, "different value"); ksession.fireAllRules(); insertNotEvent(ksession, "different value"); ksession.fireAllRules(); Assertions.assertThat(firedRules.isRuleFired(RULE3)).as(RULE3).isTrue(); Assertions.assertThat(firedRules.isRuleFired(RULE1)).as(RULE1).isTrue(); }

Target:
public void testInsertFirstAndAdd3() throws Exception { KieSession ksession = session.getStateful(); insertNotEvent(ksession); ksession.fireAllRules(); Assertions.assertThat(firedRules.isRuleFired(RULE1)).as(RULE1).isFalse(); Assertions.assertThat(firedRules.isRuleFired(RULE3)).as(RULE3).isFalse(); for (int i = 0; i < 4; i++) { insertNotEvent(ksession, "different value"); ksession.fireAllRules(); } Assertions.assertThat(firedRules.isRuleFired(RULE3)).as(RULE3).isTrue(); Assertions.assertThat(firedRules.isRuleFired(RULE1)).as(RULE1).isTrue(); }
Source:
private Map<String, LabelInfo> labelsFor(ChangeData cd, boolean standard, boolean detailed) throws OrmException { if (!standard && !detailed) { return null; } ChangeControl ctl = control(cd); if (ctl == null) { return Collections.emptyMap(); } LabelTypes labelTypes = ctl.getLabelTypes(); if (cd.getChange().getStatus().isOpen()) { return labelsForOpenChange(cd, labelTypes, standard, detailed); } else { return labelsForClosedChange(cd, labelTypes, standard, detailed); } }

Target:
private Map<String, LabelInfo> labelsFor(ChangeData cd, boolean standard, boolean detailed) throws OrmException { if (!standard && !detailed) { return null; } ChangeControl ctl = control(cd); if (ctl == null) { return null; } LabelTypes labelTypes = ctl.getLabelTypes(); if (cd.getChange().getStatus().isOpen()) { return labelsForOpenChange(cd, labelTypes, standard, detailed); } else { return labelsForClosedChange(cd, labelTypes, standard, detailed); } }
Source:
public Object visitGetKeysInGroupCommand(final InvocationContext ctx, GetKeysInGroupCommand command) throws Throwable { final String groupName = command.getGroupName(); if (!command.isGroupOwner()) { return invokeNextInterceptor(ctx, command); } dataContainer.executeTask(new GroupFilter<>(groupName, groupManager), new ParallelIterableMap.KeyValueAction<Object, InternalCacheEntry<? super Object, ? super Object>>() { @Override public void apply(Object o, InternalCacheEntry<? super Object, ? super Object> internalCacheEntry) { synchronized (ctx) { ctx.putLookedUpEntry(o, null); } } }); return invokeNextInterceptor(ctx, command); }

Target:
public Object visitGetKeysInGroupCommand(final InvocationContext ctx, GetKeysInGroupCommand command) throws Throwable { final String groupName = command.getGroupName(); if (!command.isGroupOwner()) { return invokeNextInterceptor(ctx, command); } final KeyFilter<Object> keyFilter = new CompositeKeyFilter<>(new GroupFilter<>(groupName, groupManager), new CollectionKeyFilter<>(ctx.getLookedUpEntries().keySet())); dataContainer.executeTask(keyFilter, new ParallelIterableMap.KeyValueAction<Object, InternalCacheEntry<? super Object, ? super Object>>() { @Override public void apply(Object o, InternalCacheEntry<? super Object, ? super Object> internalCacheEntry) { synchronized (ctx) { entryFactory.wrapEntryForReading(ctx, o, internalCacheEntry).setSkipLookup(true); } } }); return invokeNextInterceptor(ctx, command); }
Source:
private E toEntity(I id, EntityStorageRecord record) { return toEntity(id, record, null); }

Target:
private E toEntity(I id, EntityStorageRecord record) { return toEntity(id, record, FieldMask.getDefaultInstance()); }
Source:
public FileVisitResult visitFile(final Path path, final BasicFileAttributes attrs)throws IOException{ if(!includeHiddenFiles && Files.isHidden(path) && !path.endsWith(".keep")){ logger.debug("Skipping since we are ignoring hidden files", path); } else{ try(final InputStream is = new BufferedInputStream(Files.newInputStream(path, StandardOpenOption.READ))){ final byte[] buffer = new byte[CHUNK_SIZE]; int read = is.read(buffer); while(read != -1) { for(final Hasher hasher : bagitNameToHasherMap.values()){ hasher.update(buffer, read); } read = is.read(buffer); } for(final Entry<String, Hasher> entry: bagitNameToHasherMap.entrySet()){ bagitNameToManifestMap.get(entry.getKey()).getFileToChecksumMap().put(path, entry.getValue().getCalculatedValue()); entry.getValue().clear(); } } } return FileVisitResult.CONTINUE; }

Target:
public FileVisitResult visitFile(final Path path, final BasicFileAttributes attrs)throws IOException{ if(!includeHiddenFiles && Files.isHidden(path) && !path.endsWith(".keep")){ logger.debug("Skipping since we are ignoring hidden files", path); } else{ try(final InputStream inputStream = new BufferedInputStream(Files.newInputStream(path, StandardOpenOption.READ))){ final byte[] buffer = new byte[CHUNK_SIZE]; int numberOfBytesRead = inputStream.read(buffer); while(numberOfBytesRead != -1) { for(final Hasher hasher : bagitNameToHasherMap.values()){ hasher.update(buffer, numberOfBytesRead); } numberOfBytesRead = inputStream.read(buffer); } for(final Entry<String, Hasher> entry: bagitNameToHasherMap.entrySet()){ bagitNameToManifestMap.get(entry.getKey()).getFileToChecksumMap().put(path, entry.getValue().getCalculatedValue()); entry.getValue().clear(); } } } return FileVisitResult.CONTINUE; }
Source:
public FeedbackMsqQuestionDetails() { super(FeedbackQuestionType.MSQ); this.msqChoices = new ArrayList<>(); this.otherEnabled = false; this.generateOptionsFor = FeedbackParticipantType.NONE; this.maxSelectableChoices = 0; this.minSelectableChoices = 0; this.hasAssignedWeights = false; this.msqWeights = new ArrayList<>(); this.msqOtherWeight = 0; }

Target:
public FeedbackMsqQuestionDetails() { super(FeedbackQuestionType.MSQ); this.msqChoices = new ArrayList<>(); this.otherEnabled = false; this.generateOptionsFor = FeedbackParticipantType.NONE; this.maxSelectableChoices = -1; this.minSelectableChoices = -1; this.hasAssignedWeights = false; this.msqWeights = new ArrayList<>(); this.msqOtherWeight = 0; }
Source:
public Object start(IApplicationContext context) throws Exception { @SuppressWarnings("rawtypes") final Map args = context.getArguments(); String[] appArg = (String[])args.get("application.args"); if (appArg == null) { appArg = new String[] {}; } AbstractLogicalCommand cmd; Object returnCode; try { returnCode = execute(appArg); } catch (Die error) { return handleDieError(error); } if (System.out.checkError() || System.err.checkError()) { System.out.println("Unknown error"); returnCode = ERROR; } return returnCode; }

Target:
public Object start(IApplicationContext context) throws Exception { @SuppressWarnings("rawtypes") final Map args = context.getArguments(); String[] appArg = (String[])args.get("application.args"); if (appArg == null) { appArg = new String[] {}; } Object returnCode; try { returnCode = execute(appArg); } catch (Die error) { return handleDieError(error); } if (System.out.checkError() || System.err.checkError()) { System.out.println("Unknown error"); returnCode = ERROR; } return returnCode; }
Source:
private Publisher getSource(SearchHit hit) { if (hit == null || hit.field(EsContent.SOURCE) == null) { return null; } String source = hit.field(EsContent.SOURCE).<String>value(); Maybe<Publisher> publisherMaybe = Publisher.fromKey(source); return publisherMaybe.valueOrNull(); }

Target:
private Optional<Publisher> getSource(SearchHit hit) { if (hit == null || hit.field(EsContent.SOURCE) == null) { return Optional.empty(); } String source = hit.field(EsContent.SOURCE).<String>value(); Maybe<Publisher> publisherMaybe = Publisher.fromKey(source); return Optional.ofNullable(publisherMaybe.valueOrNull()); }
Source:
private void executeBlocking(final ActionRequest action) { try { final RestHighLevelClient client = getDataContext().getRestHighLevelClient(); final ActionResponse result; if (action instanceof BulkRequest) { result = client.bulk((BulkRequest) action, RequestOptions.DEFAULT); } else if (action instanceof IndexRequest) { result = client.index((IndexRequest) action, RequestOptions.DEFAULT); } else if (action instanceof DeleteRequest) { result = client.delete((DeleteRequest) action, RequestOptions.DEFAULT); } else if (action instanceof ClearScrollRequest) { result = client.clearScroll((ClearScrollRequest) action, RequestOptions.DEFAULT); } else if (action instanceof SearchScrollRequest) { result = client.scroll((SearchScrollRequest) action, RequestOptions.DEFAULT); } else { result = null; } if (result instanceof BulkResponse && ((BulkResponse) result).hasFailures()) { BulkItemResponse[] failedItems = ((BulkResponse) result).getItems(); for (int i = 0; i < failedItems.length; i++) { if (failedItems[i].isFailed()) { final BulkItemResponse failedItem = failedItems[i]; logger .error("Bulk failed with item no. of {}: id={} op={} status={} error={}", i + 1, failedItems.length, failedItem.getId(), failedItem.getOpType(), failedItem .status(), failedItem.getFailureMessage()); } } } } catch (IOException e) { logger.warn("Could not execute command ", action, e); throw new MetaModelException("Could not execute " + action, e); } }

Target:
private void executeBlocking(final ActionRequest action) { try { final ActionResponse result = executeActionRequest(action); if (result instanceof BulkResponse && ((BulkResponse) result).hasFailures()) { BulkItemResponse[] failedItems = ((BulkResponse) result).getItems(); for (int i = 0; i < failedItems.length; i++) { if (failedItems[i].isFailed()) { final BulkItemResponse failedItem = failedItems[i]; logger .error("Bulk failed with item no. of {}: id={} op={} status={} error={}", i + 1, failedItems.length, failedItem.getId(), failedItem.getOpType(), failedItem .status(), failedItem.getFailureMessage()); } } } } catch (IOException e) { logger.warn("Could not execute command ", action, e); throw new MetaModelException("Could not execute " + action, e); } }
Source:
protected Constraint periodPenalty(ConstraintFactory constraintFactory) { return constraintFactory.from(Exam.class) .ifExists(Period.class, equal(Exam::getPeriod, Function.identity()), filtering((exam, period) -> period.getPenalty() != 0)) .penalize("Period penalty", HardSoftScore.ONE_SOFT, exam -> exam.getPeriod().getPenalty()); }

Target:
protected Constraint periodPenalty(ConstraintFactory constraintFactory) { return constraintFactory.from(Exam.class) .filter(exam -> exam.getPeriod().getPenalty() != 0) .penalizeConfigurable("periodPenalty", exam -> exam.getPeriod().getPenalty()); }
Source:
protected void decodeValue(Klv klv) { byte[] bytes = klv.getValue(); CharsetDetector charsetDetector = new CharsetDetector(); charsetDetector.setText(bytes); CharsetMatch charsetMatch = charsetDetector.detect(); try { if (charsetMatch != null) { value = new String(bytes, charsetMatch.getName()); return; } } catch (UnsupportedEncodingException e) { LOGGER.trace( "Unsupported encoding of %s, falling back to default encoding", charsetMatch.getName()); } value = new String(bytes, Charset.defaultCharset()); }

Target:
protected void decodeValue(Klv klv) { byte[] bytes = klv.getValue(); CharsetDetector charsetDetector = new CharsetDetector(); charsetDetector.setText(bytes); CharsetMatch charsetMatch = charsetDetector.detect(); Charset charset = Charset.defaultCharset(); if (charsetMatch != null) { try { charset = Charset.forName(charsetMatch.getName()); } catch (IllegalArgumentException e) { LOGGER.trace( "Unsupported encoding of %s, falling back to default encoding", charsetMatch.getName()); } } value = new String(bytes, charset); }
Source:
public String getBaseUrl() { return thingIfApi.getBaseUrl(); }

Target:
public String getBaseUrl() { return this.thingIfApi.getBaseUrl(); }
Source:
public Object fill(final Object... args) { return ops().run(Ops.Image.Fill.NAME, args); }

Target:
public Object fill(final Object... args) { return ops().run(Ops.Image.Fill.class, args); }
Source:
private void destroyServerStore(ClientDescriptor clientDescriptor, DestroyServerStore destroyServerStore) throws ClusterException { validateClusteredTierManagerConfigured(clientDescriptor); String name = destroyServerStore.getName(); final Set<ClientDescriptor> clients = storeClientMap.get(name); if (clients != null && !clients.isEmpty()) { throw new ResourceBusyException("Cannot destroy clustered tier '" + name + "': in use by " + clients.size() + " other client(s)"); } boolean isDuplicate = isLifeCycleMessageDuplicate(destroyServerStore); if (!isDuplicate) { ServerStoreImpl store = ehcacheStateService.getStore(name); if (store != null) { StatisticsManager.nodeFor(store.getPageSource()).clean(); } LOGGER.info("Client destroying clustered tier '{}'", clientDescriptor, name); ehcacheStateService.destroyServerStore(name); } storeClientMap.remove(name); }

Target:
private void destroyServerStore(ClientDescriptor clientDescriptor, DestroyServerStore destroyServerStore) throws ClusterException { validateClusteredTierManagerConfigured(clientDescriptor); String name = destroyServerStore.getName(); final Set<ClientDescriptor> clients = storeClientMap.get(name); if (clients != null && !clients.isEmpty()) { throw new ResourceBusyException("Cannot destroy clustered tier '" + name + "': in use by " + clients.size() + " other client(s)"); } boolean isDuplicate = isLifeCycleMessageDuplicate(destroyServerStore); if (!isDuplicate) { LOGGER.info("Client destroying clustered tier '{}'", clientDescriptor, name); management.serverStoreDestroyed(name); ehcacheStateService.destroyServerStore(name); } storeClientMap.remove(name); }
Source:
public static void classSetup() { originalEclipseHomeLocation = System.getProperty("eclipse.home.location", ""); System.setProperty("eclipse.home.location", "file:/C:/Users/Test/"); originalEclipseLauncher = System.getProperty("eclipse.launcher", ""); System.setProperty("eclipse.launcher", "C:\\Users\\Test\\eclipse.exe"); }

Target:
public static void classSetup() { originalEclipseHomeLocation = System.getProperty("eclipse.home.location", ""); originalEclipseLauncher = System.getProperty("eclipse.launcher", ""); }
Source:
static boolean shouldCheck(Class<?> clazz) { String name = clazz.getName(); return !name.startsWith("java") && !name.startsWith("android"); }

Target:
static boolean shouldCheck(Class<?> clazz) { if (clazz == null) { return false; } String name = clazz.getName(); return !name.startsWith("java.") && !name.startsWith("android."); }
Source:
private void cleanupLeftOverJobs(final long msid) { try { Transaction.execute(new TransactionCallbackNoReturn() { @Override public void doInTransactionWithoutResult(TransactionStatus status) { _queueMgr.cleanupActiveQueueItems(msid, true); List<AsyncJobVO> jobs = _jobDao.getResetJobs(msid); for (AsyncJobVO job : jobs) { if (s_logger.isDebugEnabled()) { s_logger.debug("Cancel left-over job-" + job.getId()); } job.setStatus(JobInfo.Status.FAILED); job.setResultCode(ApiErrorCode.INTERNAL_ERROR.getHttpCode()); job.setResult("job cancelled because of management server restart or shutdown"); job.setCompleteMsid(msid); _jobDao.update(job.getId(), job); if (s_logger.isDebugEnabled()) { s_logger.debug("Purge queue item for cancelled job-" + job.getId()); } List<SnapshotVO> snapshotList = _snapshotDao.listAllByStatus(Snapshot.State.BackingUp); for (SnapshotVO snapshotVO : snapshotList) { SnapshotInfo snapshot = snapshotFactory.getSnapshot(snapshotVO.getId(), DataStoreRole.Primary); snapshotSrv.processEventOnSnapshotObject(snapshot, Snapshot.Event.OperationFailed); } _queueMgr.purgeAsyncJobQueueItemId(job.getId()); } } }); } catch (Throwable e) { s_logger.warn("Unexpected exception in cleaning up left over jobs for mamagement server node " + msid, e); } }

Target:
private void cleanupLeftOverJobs(final long msid) { try { Transaction.execute(new TransactionCallbackNoReturn() { @Override public void doInTransactionWithoutResult(TransactionStatus status) { _queueMgr.cleanupActiveQueueItems(msid, true); List<AsyncJobVO> jobs = _jobDao.getResetJobs(msid); for (AsyncJobVO job : jobs) { if (s_logger.isDebugEnabled()) { s_logger.debug("Cancel left-over job-" + job.getId()); } job.setStatus(JobInfo.Status.FAILED); job.setResultCode(ApiErrorCode.INTERNAL_ERROR.getHttpCode()); job.setResult("job cancelled because of management server restart or shutdown"); job.setCompleteMsid(msid); _jobDao.update(job.getId(), job); if (s_logger.isDebugEnabled()) { s_logger.debug("Purge queue item for cancelled job-" + job.getId()); } _queueMgr.purgeAsyncJobQueueItemId(job.getId()); if (job.getInstanceType().equals(ApiCommandJobType.Volume.toString())) { try { _volumeDetailsDao.removeDetail(job.getInstanceId(), "SNAPSHOT_ID"); _volsDao.remove(job.getInstanceId()); } catch (Exception e) { s_logger.error("Unexpected exception while removing concurrent request meta data :" + e.getLocalizedMessage()); } } } List<SnapshotDetailsVO> snapshotList = _snapshotDetailsDao.findDetails(AsyncJob.Constants.MS_ID, Long.toString(msid), false); for (SnapshotDetailsVO snapshotDetailsVO : snapshotList) { SnapshotInfo snapshot = snapshotFactory.getSnapshot(snapshotDetailsVO.getResourceId(), DataStoreRole.Primary); snapshotSrv.processEventOnSnapshotObject(snapshot, Snapshot.Event.OperationFailed); _snapshotDetailsDao.removeDetail(snapshotDetailsVO.getResourceId(), AsyncJob.Constants.MS_ID); } } }); } catch (Throwable e) { s_logger.warn("Unexpected exception in cleaning up left over jobs for mamagement server node " + msid, e); } }
Source:
private List<String> export(ExportConfiguration defaultConfiguration) { form.disableUI(); terminationFuture.reset(); List<String> errors = forms.getSelectedForms().parallelStream() .peek(FormStatus::clearStatusHistory) .map(formStatus -> (BriefcaseFormDefinition) formStatus.getFormDefinition()) .flatMap(formDefinition -> this.export(defaultConfiguration, formDefinition).stream()) .collect(toList()); form.enableUI(); return errors; }

Target:
private List<String> export(ExportConfiguration defaultConfiguration) { form.disableUI(); terminationFuture.reset(); List<String> errors = forms.getSelectedForms().parallelStream() .peek(FormStatus::clearStatusHistory) .map(formStatus -> (BriefcaseFormDefinition) formStatus.getFormDefinition()) .flatMap(formDefinition -> ExportAction.export(formDefinition, forms.getConfiguration(formDefinition).orElse(defaultConfiguration), terminationFuture).stream()) .collect(toList()); form.enableUI(); return errors; }
Source:
public void authenticate(String dn, String password) throws AuthenticationException { if (password == null || password.isEmpty()) { throw new AuthenticationException("Empty password used"); } LdapContext authCtx = null; try { Hashtable<Object, Object> env = LDAPContextManager.getConnectionProperties(config); env.put("com.sun.jndi.ldap.connect.pool", "false"); env.put(Context.SECURITY_AUTHENTICATION, this.config.getAuthType()); env.put(Context.SECURITY_PRINCIPAL, dn); env.put(Context.SECURITY_CREDENTIALS, password); authCtx = new InitialLdapContext(env, null); if (config.isStartTls()) { LDAPContextManager.startTLS(authCtx); } } catch (AuthenticationException ae) { if (logger.isDebugEnabled()) { logger.debugf(ae, "Authentication failed for DN [%s]", dn); } throw ae; } catch (Exception e) { logger.errorf(e, "Unexpected exception when validating password of DN [%s]", dn); throw new AuthenticationException("Unexpected exception when validating password of user"); } finally { if (authCtx != null) { try { authCtx.close(); } catch (NamingException e) { } } } }

Target:
public void authenticate(String dn, String password) throws AuthenticationException { if (password == null || password.isEmpty()) { throw new AuthenticationException("Empty password used"); } LdapContext authCtx = null; StartTlsResponse tlsResponse = null; try { Hashtable<Object, Object> env = LDAPContextManager.getConnectionProperties(config); env.put("com.sun.jndi.ldap.connect.pool", "false"); if(!this.config.isStartTls()) { env.put(Context.SECURITY_AUTHENTICATION, this.config.getAuthType()); env.put(Context.SECURITY_PRINCIPAL, dn); env.put(Context.SECURITY_CREDENTIALS, password); } authCtx = new InitialLdapContext(env, null); if (config.isStartTls()) { tlsResponse = LDAPContextManager.startTLS(authCtx, this.config.getAuthType(), dn, password.toCharArray()); } } catch (AuthenticationException ae) { if (logger.isDebugEnabled()) { logger.debugf(ae, "Authentication failed for DN [%s]", dn); } throw ae; } catch (Exception e) { logger.errorf(e, "Unexpected exception when validating password of DN [%s]", dn); throw new AuthenticationException("Unexpected exception when validating password of user"); } finally { if (tlsResponse != null) { try { tlsResponse.close(); } catch (IOException e) { e.printStackTrace(); } } if (authCtx != null) { try { authCtx.close(); } catch (NamingException e) { e.printStackTrace(); } } } }
Source:
public boolean isEndOfInput() { return lastByteWasWritten; }

Target:
public boolean isEndOfInput() { return endOfInput; }
Source:
public void connectionChanged(@Nonnull EnderLiquidConduit con, @Nonnull EnumFacing conDir) { NetworkTankKey key = new NetworkTankKey(con, conDir); NetworkTank tank = new NetworkTank(con, conDir); boolean sort = false; NetworkTank oldTank = tankMap.get(key); if (oldTank != null && oldTank.priority != tank.priority) { sort = true; } int oldIndex = tanks.indexOf(oldTank); if (oldIndex == -1) { tanks.add(tank); } else { tanks.set(oldIndex, tank); } tankMap.remove(key); tankMap.put(key, tank); if (sort) { tanks.sort(new Comparator<NetworkTank>() { @Override public int compare(NetworkTank arg0, NetworkTank arg1) { return arg1.priority - arg0.priority; } }); } }

Target:
public void connectionChanged(@Nonnull EnderLiquidConduit con, @Nonnull EnumFacing conDir) { NetworkTankKey key = new NetworkTankKey(con, conDir); NetworkTank tank = new NetworkTank(con, conDir); tanks.remove(tank); tanks.add(tank); tankMap.remove(key); tankMap.put(key, tank); tanks.sort((left, right) -> right.priority - left.priority); }
Source:
private FateStatus getFateStatus() throws KeeperException, InterruptedException { Instance instance = getConnector().getInstance(); AdminUtil<String> admin = new AdminUtil<>(false); String secret = "DONTTELL"; IZooReaderWriter zk = new ZooReaderWriter(instance.getZooKeepers(), instance.getZooKeepersSessionTimeOut(), SCHEME, (USER + ":" + secret).getBytes()); ZooStore<String> zs = new ZooStore<String>(ZooUtil.getRoot(instance) + Constants.ZFATE, zk); FateStatus fateStatus = admin.getStatus(zs, zk, ZooUtil.getRoot(instance) + Constants.ZTABLE_LOCKS, null, null); return fateStatus; }

Target:
private FateStatus getFateStatus() throws KeeperException, InterruptedException { Instance instance = getConnector().getInstance(); AdminUtil<String> admin = new AdminUtil<>(false); String secret = getCluster().getSiteConfiguration().get(Property.INSTANCE_SECRET); IZooReaderWriter zk = new ZooReaderWriterFactory().getZooReaderWriter(instance.getZooKeepers(), instance.getZooKeepersSessionTimeOut(), secret); ZooStore<String> zs = new ZooStore<String>(ZooUtil.getRoot(instance) + Constants.ZFATE, zk); FateStatus fateStatus = admin.getStatus(zs, zk, ZooUtil.getRoot(instance) + Constants.ZTABLE_LOCKS, null, null); return fateStatus; }
Source:
private BlobReadOptions getDeletedBlobReadOptions(IndexValue value, StoreKey key, ConcurrentSkipListMap<Offset, IndexSegment> indexSegments) throws StoreException { BlobReadOptions readOptions; IndexValue putValue = findKey(key, new FileSpan(getStartOffset(indexSegments), value.getOffset()), EnumSet.of(IndexEntryType.PUT), indexSegments); if (putValue != null) { readOptions = new BlobReadOptions(log, putValue.getOffset(), new MessageInfo(key, putValue.getSize(), true, value.isFlagSet(IndexValue.Flags.Ttl_Update_Index), value.getExpiresAtMs(), putValue.getAccountId(), putValue.getContainerId(), putValue.getOperationTimeInMs())); } else { throw new StoreException("Did not find PUT index entry for key [" + key + "] and the the original offset in value of the DELETE entry was [" + value.getOriginalMessageOffset() + "]", StoreErrorCodes.ID_Deleted); } return readOptions; }

Target:
private BlobReadOptions getDeletedBlobReadOptions(IndexValue value, StoreKey key, ConcurrentSkipListMap<Offset, IndexSegment> indexSegments) throws StoreException { BlobReadOptions readOptions; IndexValue putValue = findKey(key, new FileSpan(getStartOffset(indexSegments), value.getOffset()), EnumSet.of(IndexEntryType.PUT), indexSegments); if (putValue != null) { readOptions = new BlobReadOptions(log, putValue.getOffset(), new MessageInfo(key, putValue.getSize(), true, value.isTTLUpdate(), value.getExpiresAtMs(), putValue.getAccountId(), putValue.getContainerId(), putValue.getOperationTimeInMs())); } else { throw new StoreException("Did not find PUT index entry for key [" + key + "] and the the original offset in value of the DELETE entry was [" + value.getOriginalMessageOffset() + "]", StoreErrorCodes.ID_Deleted); } return readOptions; }
Source:
public void onViewStateRestored(Bundle savedInstanceState) { super.onViewStateRestored(savedInstanceState); if (savedInstanceState != null) { FormFieldsWrapper formFieldsWrapper = (FormFieldsWrapper) savedInstanceState.getSerializable(ApplicationConstants.BundleKeys.FORM_FIELDS_BUNDLE); inputFields = formFieldsWrapper.getInputFields(); for(InputField field:inputFields){ if(field.getIsRed()==true){ RangeEditText ed = (RangeEditText) getActivity().findViewById(field.getId()); ed.setTextColor(ContextCompat.getColor(OpenMRS.getInstance(), R.color.red)); } } selectOneFields = formFieldsWrapper.getSelectOneFields(); } }

Target:
public void onViewStateRestored(Bundle savedInstanceState) { super.onViewStateRestored(savedInstanceState); if (savedInstanceState != null) { FormFieldsWrapper formFieldsWrapper = (FormFieldsWrapper) savedInstanceState.getSerializable(ApplicationConstants.BundleKeys.FORM_FIELDS_BUNDLE); inputFields = formFieldsWrapper.getInputFields(); for(InputField field:inputFields){ if(field.isRed()){ RangeEditText ed = (RangeEditText) getActivity().findViewById(field.getId()); ed.setTextColor(ContextCompat.getColor(OpenMRS.getInstance(), R.color.red)); } } selectOneFields = formFieldsWrapper.getSelectOneFields(); } }
Source:
public Object parseExpressionNoContext(String input) throws ParseException { InterpreterState state = getLocalThreadInterpreter(); GenContext genContext = Globals.getGenContext(state); try { TypedAST typAST = TestUtil.getNewAST(input.trim() + "\n", "TSL Parse"); if (typAST instanceof Script) { Script script = (Script) typAST; List<ImportDeclaration> importDecls = new ArrayList<>(); importDecls.addAll(script.getImports()); importDecls.addAll(script.getRequires()); List<TypedModuleSpec> dependencies = getDependencies(importDecls, genContext); Expression expr = (Expression) (script.generateIL(genContext, Util.unitType(), dependencies)); expr = state.getResolver().wrap(expr, dependencies); return expr; } else { return parseExpression(input, genContext); } } catch (ParseException e) { System.err.println("Error when running parseExpression on input \"" + input + "\""); throw e; } }

Target:
public IExpr parseExpressionNoContext(String input) throws ParseException { InterpreterState state = getLocalThreadInterpreter(); GenContext genContext = Globals.getGenContext(state); try { TypedAST typAST = TestUtil.getNewAST(input.trim() + "\n", "Parse expressions"); if (typAST instanceof Script) { Script script = (Script) typAST; List<ImportDeclaration> importDecls = new ArrayList<>(); importDecls.addAll(script.getImports()); importDecls.addAll(script.getRequires()); List<TypedModuleSpec> dependencies = getDependencies(importDecls, genContext); Expression expr = (Expression) (script.generateIL(genContext, Util.unitType(), dependencies)); expr = state.getResolver().wrap(expr, dependencies); return expr; } else { return parseExpression(input, genContext); } } catch (ParseException e) { System.err.println("Error when running parseExpression on input \"" + input + "\""); throw e; } }
Source:
public ArrayAggregationState createGroupedState() { if (mode == NEW) { return new GroupArrayAggregationState(type); } if (mode == LEGACY) { return new LegacyArrayAggregationGroupState(type); } throw new PrestoException(FUNCTION_IMPLEMENTATION_ERROR, format("Unexpected group enum type %s", mode)); }

Target:
public ArrayAggregationState createGroupedState() { switch (mode) { case NEW: return new GroupArrayAggregationState(type); case LEGACY: return new LegacyArrayAggregationGroupState(type); default: throw new PrestoException(FUNCTION_IMPLEMENTATION_ERROR, format("Unexpected group enum type %s", mode)); } }
Source:
public String loginPageURL(Context context, HttpServletRequest request, HttpServletResponse response) { boolean lazySession = configurationService.getBooleanProperty("authentication-shibboleth.lazysession", false); if ( lazySession ) { String shibURL = configurationService.getProperty("authentication-shibboleth.lazysession.loginurl"); boolean forceHTTPS = configurationService.getBooleanProperty("authentication-shibboleth.lazysession.secure",true); if (shibURL == null || shibURL.length() == 0) { shibURL = "/Shibboleth.sso/Login"; } shibURL = shibURL.trim(); String host = request.getServerName(); int port = request.getServerPort(); String contextPath = request.getContextPath(); String redirectUrl = null; if (request.getHeader("Referer") != null && StringUtils.isNotBlank(request.getHeader("Referer"))) { redirectUrl = request.getHeader("Referer"); } else if (request.getHeader("X-Requested-With") != null && StringUtils.isNotBlank(request.getHeader("X-Requested-With"))) { redirectUrl = request.getHeader("X-Requested-With"); } String returnURL = ConfigurationManager.getProperty("dspace.baseUrl") + "/api/authn/shibboleth" + ((redirectUrl != null) ? "?redirectUrl=" + redirectUrl : ""); try { shibURL += "?target=" + URLEncoder.encode(returnURL, "UTF-8"); } catch (UnsupportedEncodingException uee) { log.error("Unable to generate lazysession authentication",uee); } log.debug("Redirecting user to Shibboleth initiator: " + shibURL); return response.encodeRedirectURL(shibURL); } else { return response.encodeRedirectURL(request.getContextPath() + "/shibboleth-login"); } }

Target:
public String loginPageURL(Context context, HttpServletRequest request, HttpServletResponse response) { boolean lazySession = configurationService.getBooleanProperty("authentication-shibboleth.lazysession", false); if ( lazySession ) { String shibURL = getShibURL(request); String redirectUrl = null; if (request.getHeader("Referer") != null && StringUtils.isNotBlank(request.getHeader("Referer"))) { redirectUrl = request.getHeader("Referer"); } else if (request.getHeader("X-Requested-With") != null && StringUtils.isNotBlank(request.getHeader("X-Requested-With"))) { redirectUrl = request.getHeader("X-Requested-With"); } String returnURL = configurationService.getProperty("dspace.server.url") + "/api/authn/shibboleth" + ((redirectUrl != null) ? "?redirectUrl=" + redirectUrl : ""); try { shibURL += "?target=" + URLEncoder.encode(returnURL, "UTF-8"); } catch (UnsupportedEncodingException uee) { log.error("Unable to generate lazysession authentication",uee); } log.debug("Redirecting user to Shibboleth initiator: " + shibURL); return response.encodeRedirectURL(shibURL); } else { return response.encodeRedirectURL(request.getContextPath() + "/shibboleth-login"); } }
Source:
public void verifyNoSpotlights() { for (WebElement spotlight: spotlights) { if (spotlight.isDisplayed()) { PageObjectLogging.log("SpotlightVisible", "Spotlight visible, should be hidden", false); throw new NoSuchElementException("Spotlight visible, should be hidden"); } } PageObjectLogging.log("SpotlightsHidden", "Spotlights are hidden", true); }

Target:
public void verifyNoSpotlights() { for (WebElement spotlight: spotlights) { if (spotlight.isDisplayed()) { PageObjectLogging.log("SpotlightVisible", "Spotlight visible, should be hidden", false); throw new WebDriverException("Spotlight visible, should be hidden"); } } PageObjectLogging.log("SpotlightsHidden", "Spotlights are hidden", true); }
Source:
public void setExcludedPaths(Collection<String> paths) { paths.forEach(path -> excludePath(path)); }

Target:
public void setExcludedPaths(Collection<String> paths) { excludedPaths.clear(); paths.forEach(path -> excludePath(path)); }
Source:
private FilterDef interpretFullTextFilterDef(FullTextFilterDef defAnn) { FilterDef filterDef = new FilterDef( defAnn ); if ( filterDef.getImpl().equals( ShardSensitiveOnlyFilter.class ) ) { return filterDef; } try { ClassLoaderHelper.untypedInstanceFromClass( filterDef.getImpl(), "filter definition" ); } catch (Exception e) { throw new SearchException( "Unable to create Filter class: " + filterDef.getImpl().getName(), e ); } for ( Method method : filterDef.getImpl().getMethods() ) { if ( method.isAnnotationPresent( Factory.class ) ) { if ( filterDef.getFactoryMethod() != null ) { throw new SearchException( "Multiple @Factory methods found" + defAnn.name() + ": " + filterDef.getImpl().getName() + "." + method.getName() ); } ReflectionHelper.setAccessible( method ); filterDef.setFactoryMethod( method ); } if ( method.isAnnotationPresent( Key.class ) ) { if ( filterDef.getKeyMethod() != null ) { throw new SearchException( "Multiple @Key methods found" + defAnn.name() + ": " + filterDef.getImpl().getName() + "." + method.getName() ); } ReflectionHelper.setAccessible( method ); filterDef.setKeyMethod( method ); } String name = method.getName(); if ( name.startsWith( "set" ) && method.getParameterTypes().length == 1 ) { filterDef.addSetter( Introspector.decapitalize( name.substring( 3 ) ), method ); } } return filterDef; }

Target:
private FilterDef interpretFullTextFilterDef(FullTextFilterDef defAnn) { FilterDef filterDef = new FilterDef( defAnn ); if ( filterDef.getImpl().equals( ShardSensitiveOnlyFilter.class ) ) { return filterDef; } try { ClassLoaderHelper.untypedInstanceFromClass( filterDef.getImpl(), "filter definition" ); } catch (RuntimeException e) { throw new SearchException( "Unable to create Filter class: " + filterDef.getImpl().getName(), e ); } for ( Method method : filterDef.getImpl().getMethods() ) { if ( method.isAnnotationPresent( Factory.class ) ) { if ( filterDef.getFactoryMethod() != null ) { throw new SearchException( "Multiple @Factory methods found" + defAnn.name() + ": " + filterDef.getImpl().getName() + "." + method.getName() ); } ReflectionHelper.setAccessible( method ); filterDef.setFactoryMethod( method ); } if ( method.isAnnotationPresent( Key.class ) ) { if ( filterDef.getKeyMethod() != null ) { throw new SearchException( "Multiple @Key methods found" + defAnn.name() + ": " + filterDef.getImpl().getName() + "." + method.getName() ); } ReflectionHelper.setAccessible( method ); filterDef.setKeyMethod( method ); } String name = method.getName(); if ( name.startsWith( "set" ) && method.getParameterTypes().length == 1 ) { filterDef.addSetter( Introspector.decapitalize( name.substring( 3 ) ), method ); } } return filterDef; }
Source:
protected void checkOperation(String operationId) { if (StringUtils.isBlank(operationId)) { log.warn("No operationId provided skipping command: " + getCurrentCommand().getId()); return; } if (!service.hasOperation(operationId)) { log.warn("Operation " + operationId + " not found, skipping command: " + getCurrentCommand().getId()); return; } try { OperationType op = service.getOperation(operationId); inputType = op.getInputType(); if (inputType == null || DOC_INPUT_TYPE.equals(inputType)) { inputType = DOC_INPUT_TYPE; } else if (DOCS_INPUT_TYPE.equals(inputType)) { inputType = DOCS_INPUT_TYPE; } else { log.warn(String.format("Unsupported operation input type %s for command: %s", inputType, getCurrentCommand().getId())); return; } } catch (OperationNotFoundException e) { log.warn(String.format("Operation '%s' not found, skipping command: %s", operationId, getCurrentCommand().getId())); return; } this.operationId = operationId; }

Target:
protected void checkOperation(String operationId) { if (StringUtils.isBlank(operationId)) { log.warn("No operationId provided skipping command: " + getCurrentCommand().getId()); return; } try { OperationType op = service.getOperation(operationId); inputType = op.getInputType(); if (inputType == null || DOC_INPUT_TYPE.equals(inputType)) { inputType = DOC_INPUT_TYPE; } else if (DOCS_INPUT_TYPE.equals(inputType)) { inputType = DOCS_INPUT_TYPE; } else { log.warn(String.format("Unsupported operation input type %s for command: %s", inputType, getCurrentCommand().getId())); return; } } catch (OperationNotFoundException e) { log.warn(String.format("Operation '%s' not found, skipping command: %s", operationId, getCurrentCommand().getId())); return; } this.operationId = operationId; }
Source:
public void discard() { synchronized (lock) { if (stateDiscarded) { Preconditions.checkState(discarded, "Checkpoint should be disposed before being discarded"); return; } else { stateDiscarded = true; } } try { StateUtil.bestEffortDiscardAllStateObjects(operatorStates.values()); targetLocation.disposeOnFailure(); } catch (Throwable t) { LOG.warn( "Could not properly dispose the private states in the pending checkpoint of job {}.", checkpointId, jobId, t); } finally { operatorStates.clear(); } }

Target:
public void discard() { synchronized (lock) { if (discarded) { Preconditions.checkState(disposed, "Checkpoint should be disposed before being discarded"); return; } else { discarded = true; } } try { StateUtil.bestEffortDiscardAllStateObjects(operatorStates.values()); targetLocation.disposeOnFailure(); } catch (Throwable t) { LOG.warn( "Could not properly dispose the private states in the pending checkpoint of job {}.", checkpointId, jobId, t); } finally { operatorStates.clear(); } }
Source:
protected void binary(byte[] payload, int offset, int len) { LOGGER.finest(() -> "reading block of length " + len + " from " + agent); try { transport.receive(ByteBuffer.wrap(payload, offset, len)); } catch (IOException e) { error(e); } catch (InterruptedException e) { error(e); } }

Target:
protected void binary(byte[] payload, int offset, int len) { LOGGER.finest(() -> "reading block of length " + len + " from " + agent); try { transport.receive(ByteBuffer.wrap(payload, offset, len)); } catch (IOException | InterruptedException e) { error(e); } }
Source:
public void instrumentForCoverage() { checkState(moduleGraph != null, "No inputs. Did you call init() or initModules()?"); checkState(!hasErrors()); runInCompilerThread( () -> { checkState(options.getInstrumentForCoverageOnly()); checkState(!hasErrors()); if(options.instrumentForCoverageOption != InstrumentOption.NONE) { instrumentForCoverageInternal(options.instrumentForCoverageOption); }else if(options.instrumentForCoverage){ instrumentForCoverageInternal(InstrumentOption.LINE_ONLY); }else if(options.instrumentForCoverage && options.instrumentBranchCoverage){ instrumentForCoverageInternal(InstrumentOption.BRANCH_ONLY); } return null; }); }

Target:
public void instrumentForCoverage() { checkState(moduleGraph != null, "No inputs. Did you call init() or initModules()?"); checkState(!hasErrors()); runInCompilerThread( () -> { checkState(options.getInstrumentForCoverageOnly()); checkState(!hasErrors()); if (options.getInstrumentForCoverageOption() != InstrumentOption.NONE) { instrumentForCoverageInternal(options.getInstrumentForCoverageOption()); } else if (options.instrumentForCoverage) { instrumentForCoverageInternal(InstrumentOption.LINE_ONLY); } else if (options.instrumentForCoverage && options.instrumentBranchCoverage) { instrumentForCoverageInternal(InstrumentOption.BRANCH_ONLY); } return null; }); }
Source:
protected <T> Observable buildUseCaseObservable(Map<String, T> parameters) { if (parameters == null || parameters.get(PARAM_USER) == null) { return Observable.error(new IllegalArgumentException("missing user")); } final User user = (User) parameters.get(PARAM_USER); return userRepository.getSelectedUser() .concatMap(new Function<Long, Observable<Boolean>>() { @Override public Observable<Boolean> apply(Long selectedUserId) { if (selectedUserId == user.getId()) { return userRepository.clearSelectedUser().concatMap( new Function<Boolean, Observable<Boolean>>() { @Override public Observable<Boolean> apply(Boolean aBoolean) { return deleteUser(user); } }); } else { return deleteUser(user); } } }); }

Target:
protected <T> Observable buildUseCaseObservable(Map<String, T> parameters) { if (parameters == null || parameters.get(PARAM_USER) == null) { return Observable.error(new IllegalArgumentException("missing user")); } final User user = (User) parameters.get(PARAM_USER); return userRepository.getSelectedUser() .concatMap(new Function<Long, Observable<Boolean>>() { @Override public Observable<Boolean> apply(Long selectedUserId) { if (selectedUserId.equals(user.getId())) { return userRepository.clearSelectedUser().concatMap( new Function<Boolean, Observable<Boolean>>() { @Override public Observable<Boolean> apply(Boolean aBoolean) { return deleteUser(user); } }); } else { return deleteUser(user); } } }); }