auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private InputPoint createInputPointWithAllSinks( HttpMessage originalMsg, String originalValue, HttpMessage referenceMsg, String referenceValue, String paramName) { InputPoint inputPoint = new InputPoint(); inputPoint.addSinkPoint( new ReflectedSinkPoint(originalMsg, originalValue, referenceMsg, referenceValue)); Set<Integer> sinks = PersistentXSSUtils.getSinksIdsForSource(originalMsg, paramName); if (sinks != null) { for (int sinkMsgId : sinks) { HttpMessage sinkMsg = PersistentXSSUtils.getMessage(sinkMsgId); if (sinkMsg == null) { continue; } inputPoint.addSinkPoint(new StoredSinkPoint(sinkMsg, originalValue)); } } return inputPoint; }

Target:
private InputPoint createInputPointWithAllSinks( HttpMessage originalMsg, String originalValue, HttpMessage referenceMsg, String referenceValue, String paramName) { InputPoint inputPoint = new InputPoint(); inputPoint.addSinkPoint( new ReflectedSinkPoint(originalMsg, originalValue, referenceMsg, referenceValue)); Set<Integer> sinks = PersistentXssUtils.getSinksIdsForSource(originalMsg, paramName); if (sinks != null) { for (int sinkMsgId : sinks) { HttpMessage sinkMsg = PersistentXssUtils.getMessage(sinkMsgId); if (sinkMsg == null) { continue; } inputPoint.addSinkPoint(new StoredSinkPoint(sinkMsg, originalValue)); } } return inputPoint; }
Source:
public Source<byte[], ProgramPrecompile> precompileSource() { StateSource source = stateSource(); return new SourceCodec<byte[], ProgramPrecompile, byte[], byte[]>(source, new Serializer<byte[], byte[]>() { public byte[] serialize(byte[] object) { DataWord ret = new DataWord(object); DataWord addResult = ret.add(new DataWord(1)); return addResult.getLast20Bytes(); } public byte[] deserialize(byte[] stream) { throw new RuntimeException("Shouldn't be called"); } }, new Serializer<ProgramPrecompile, byte[]>() { public byte[] serialize(ProgramPrecompile object) { return object == null ? null : object.serialize(); } public ProgramPrecompile deserialize(byte[] stream) { return stream == null ? null : ProgramPrecompile.deserialize(stream); } }); }

Target:
public Source<byte[], ProgramPrecompile> precompileSource() { StateSource source = stateSource(); return new SourceCodec<byte[], ProgramPrecompile, byte[], byte[]>(source, new Serializer<byte[], byte[]>() { public byte[] serialize(byte[] object) { DataWord ret = DataWord.of(object); DataWord addResult = ret.add(DataWord.ONE); return addResult.getLast20Bytes(); } public byte[] deserialize(byte[] stream) { throw new RuntimeException("Shouldn't be called"); } }, new Serializer<ProgramPrecompile, byte[]>() { public byte[] serialize(ProgramPrecompile object) { return object == null ? null : object.serialize(); } public ProgramPrecompile deserialize(byte[] stream) { return stream == null ? null : ProgramPrecompile.deserialize(stream); } }); }
Source:
protected String getGDBCommandLine() { StringBuffer gdbCommandLine = new StringBuffer(getGDBPath().toOSString()); gdbCommandLine.append(" --interpreter"); gdbCommandLine.append(" mi2"); gdbCommandLine.append(" --nx"); return gdbCommandLine.toString(); }

Target:
protected String getGDBCommandLine() { String cmdArray[] = getGDBCommandLineArray(); return StringUtil.join(cmdArray, " "); }
Source:
protected void initChannel(SocketChannel ch) throws Exception { ch.config() .setSendBufferSize(http2ClientConfig.nettySendBufferSize) .setReceiveBufferSize(http2ClientConfig.nettyReceiveBufferSize) .setWriteBufferWaterMark(new WriteBufferWaterMark(http2ClientConfig.http2InitialWindowSize, 2 * http2ClientConfig.http2InitialWindowSize)); ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast("connectionStatsHandler", connectionStatsHandler); InetSocketAddress peerAddress = ch.remoteAddress(); String peerHost = peerAddress.getHostName(); int peerPort = peerAddress.getPort(); SslHandler sslHandler = new SslHandler(sslFactory.createSSLEngine(peerHost, peerPort, SSLFactory.Mode.SERVER)); pipeline.addLast("SslHandler", sslHandler); pipeline.addLast("securityChecker", this.serverSecurityChecker); pipeline.addLast(Http2FrameCodecBuilder.forServer() .initialSettings(Http2Settings.defaultSettings() .maxFrameSize(http2ClientConfig.http2FrameMaxSize) .initialWindowSize(http2ClientConfig.http2InitialWindowSize)) .frameLogger(new Http2FrameLogger(LogLevel.DEBUG, "server")) .build()) .addLast("Http2MultiplexHandler", new Http2MultiplexHandler( new Http2StreamHandler(nettyMetrics, nettyConfig, performanceConfig, http2ClientConfig, requestHandler))); }

Target:
protected void initChannel(SocketChannel ch) throws Exception { ch.config() .setSendBufferSize(http2ClientConfig.nettySendBufferSize) .setReceiveBufferSize(http2ClientConfig.nettyReceiveBufferSize) .setWriteBufferWaterMark(new WriteBufferWaterMark(http2ClientConfig.http2InitialWindowSize, 2 * http2ClientConfig.http2InitialWindowSize)); ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast("connectionStatsHandler", connectionStatsHandler); InetSocketAddress peerAddress = ch.remoteAddress(); String peerHost = peerAddress.getHostName(); int peerPort = peerAddress.getPort(); SslHandler sslHandler = new SslHandler(sslFactory.createSSLEngine(peerHost, peerPort, SSLFactory.Mode.SERVER)); pipeline.addLast("SslHandler", sslHandler); pipeline.addLast("securityChecker", serverSecurityHandler); pipeline.addLast(Http2FrameCodecBuilder.forServer() .initialSettings(Http2Settings.defaultSettings() .maxFrameSize(http2ClientConfig.http2FrameMaxSize) .initialWindowSize(http2ClientConfig.http2InitialWindowSize)) .frameLogger(new Http2FrameLogger(LogLevel.DEBUG, "server")) .build()) .addLast("Http2MultiplexHandler", new Http2MultiplexHandler( new Http2StreamHandler(nettyMetrics, nettyConfig, performanceConfig, http2ClientConfig, requestHandler))); }
Source:
public StubbingListener getStubbingListener() { if (this.stubbingListener == null) { return new StubbingListener() { public void newStubbing(Invocation stubbing) public void usedStubbing(Invocation stubbing, Invocation actual) }; } return this.stubbingListener; }

Target:
public StubbingListener getStubbingListener() { if (this.stubbingListener == null) { return NoOpStubbingListener.INSTANCE; } return this.stubbingListener; }
Source:
public boolean enableApplicationToken(String applicationToken, String sessionToken) { try { String response = transport.execute( SimpleRequestBuilder.buildNewRequest(InterfaceKeys.JSON).addRequestClass(ClassKeys.SYSTEM) .addFunction(FunctionKeys.ENABLE_APPLICATION_TOKEN) .addParameter(ParameterKeys.TOKEN, sessionToken) .addParameter(ParameterKeys.APPLICATION_TOKEN, applicationToken).buildRequestString(), 60000, 60000); return JSONResponseHandler.checkResponse(JSONResponseHandler.toJsonObject(response)); } catch (Exception e) { logger.debug("An exception occurred", e); } return false; }

Target:
public boolean enableApplicationToken(String applicationToken, String sessionToken) { String response = transport.execute(SimpleRequestBuilder.buildNewJsonRequest(ClassKeys.SYSTEM) .addFunction(FunctionKeys.ENABLE_APPLICATION_TOKEN).addParameter(ParameterKeys.TOKEN, sessionToken) .addParameter(ParameterKeys.APPLICATION_TOKEN, applicationToken).buildRequestString(), Config.HIGH_CONNECTION_TIMEOUT, Config.HIGH_READ_TIMEOUT); return JSONResponseHandler.checkResponse(JSONResponseHandler.toJsonObject(response)); }
Source:
public void accept(Event<T> structuredEvent) { try { T data = structuredEvent.getData(); OperationDetails operation = data.getOperation(); var extractor = eventDataExtractorMap.get(operation.getEventType().name().toLowerCase() + "EventDataExtractor"); AuditEvent event = AuditEvent.builder() .withAccountId(operation.getTenant()) .withActor(ActorCrn.builder().withActorCrn(operation.getUserCrn()).build()) .withEventData(extractor.eventData(data)) .withEventName(extractor.eventName(data)) .withEventSource(extractor.eventSource(data)) .withSourceIp(extractor.sourceIp(data)) .build(); auditClient.createAuditEvent(event); } catch (UnsupportedOperationException e) { LOGGER.debug("Audit log is unnecessary: {}", e.getMessage()); } catch (Exception e) { LOGGER.error("Cannot perform auditing: {}", e.getMessage(), e); } }

Target:
public void accept(Event<T> structuredEvent) { try { T data = structuredEvent.getData(); OperationDetails operation = data.getOperation(); EventDataExtractor<T> extractor = eventDataExtractorMap.get(operation.getEventType().name().toLowerCase() + "EventDataExtractor"); LOGGER.info("Extract audit event as {}", extractor); AuditEvent event = AuditEvent.builder() .withAccountId(operation.getTenant()) .withActor(ActorCrn.builder().withActorCrn(operation.getUserCrn()).build()) .withEventData(extractor.eventData(data)) .withEventName(extractor.eventName(data)) .withEventSource(extractor.eventSource(data)) .withSourceIp(extractor.sourceIp(data)) .build(); auditClient.createAuditEvent(event); } catch (UnsupportedOperationException e) { LOGGER.debug("Audit log is unnecessary: {}", e.getMessage()); } catch (Exception e) { LOGGER.error("Cannot perform auditing: {}", e.getMessage(), e); } }
Source:
private static byte[] toBytes(UUID uuid) { byte[] out = new byte[16]; long msb = uuid.getMostSignificantBits(); for (int i = 0; i < 8; i++) { out[i] = (byte) ((msb >> ((7 - i) * 8)) & 0xff); } long lsb = uuid.getLeastSignificantBits(); for (int i = 8; i < 16; i++) { out[i] = (byte) ((lsb >> ((15 - i) * 8)) & 0xff); } return out; }

Target:
private static byte[] toBytes(UUID uuid) { byte[] out = new byte[16]; long msb = uuid.getMostSignificantBits(); for (int i = 0; i < 8; i++) { out[i] = (byte) (msb >> (7 - i) * 8); } long lsb = uuid.getLeastSignificantBits(); for (int i = 8; i < 16; i++) { out[i] = (byte) (lsb >> (15 - i) * 8); } return out; }
Source:
void handleRevocation(final Collection<TopicPartition> revokedPartitions) { if (activeTaskIds().isEmpty()) { log.debug("Consumer revoked partitions with no active tasks currently owned, will need to rejoin the group."); return; } final Set<TaskId> revokedTasks = new HashSet<>(); final Set<TopicPartition> remainingPartitions = new HashSet<>(revokedPartitions); for (final Task task : tasks.values()) { if (remainingPartitions.containsAll(task.inputPartitions())) { revokedTasks.add(task.id()); } remainingPartitions.removeAll(task.inputPartitions()); } if (!remainingPartitions.isEmpty()) { throw new IllegalStateException("Some revoked partitions that do not belong " + "to any tasks remain: " + remainingPartitions); } for (final TaskId taskId : revokedTasks) { final Task task = tasks.get(taskId); task.suspend(); } }

Target:
void handleRevocation(final Collection<TopicPartition> revokedPartitions) { final Set<TopicPartition> remainingPartitions = new HashSet<>(revokedPartitions); for (final Task task : tasks.values()) { if (remainingPartitions.containsAll(task.inputPartitions())) { task.suspend(); } remainingPartitions.removeAll(task.inputPartitions()); } if (!remainingPartitions.isEmpty()) { log.warn("The following partitions are missing from the task partitions. It could potentially " + "due to race condition of consumer detecting the heartbeat failure, or the tasks " + "have been cleaned up by the handleAssignment callback.", remainingPartitions); } }
Source:
public static SrlBankProblem mongoGetBankProblem(final Authenticator authenticator, final DB dbs, final String authId, final String problemBankId) throws AuthenticationException, DatabaseAccessException { final DBCollection collection = dbs.getCollection(getCollectionFromType(School.ItemType.BANK_PROBLEM)); final DBObject mongoBankProblem = collection.findOne(convertStringToObjectId(problemBankId)); if (mongoBankProblem == null) { throw new DatabaseAccessException("bank problem can not be found with id: " + problemBankId); } final Authentication.AuthType authType = Authentication.AuthType.newBuilder() .setCheckAccess(true) .setCheckingAdmin(true) .build(); final AuthenticationResponder responder = authenticator .checkAuthentication(School.ItemType.BANK_PROBLEM, problemBankId, authId, 0, authType); if (!responder.hasStudentPermission() && responder.isRegistrationRequired()) { throw new AuthenticationException(AuthenticationException.INVALID_PERMISSION); } return extractBankProblem(mongoBankProblem, problemBankId, responder.hasTeacherPermission()); }

Target:
public static SrlBankProblem mongoGetBankProblem(final Authenticator authenticator, final DB dbs, final String authId, final String problemBankId) throws AuthenticationException, DatabaseAccessException { final DBCollection bankProblemCollection = dbs.getCollection(getCollectionFromType(School.ItemType.BANK_PROBLEM)); final DBObject mongoBankProblem = bankProblemCollection.findOne(convertStringToObjectId(problemBankId)); if (mongoBankProblem == null) { throw new DatabaseAccessException("bank problem can not be found with id: " + problemBankId); } final Authentication.AuthType authType = Authentication.AuthType.newBuilder() .setCheckAccess(true) .setCheckingAdmin(true) .build(); final AuthenticationResponder responder = authenticator .checkAuthentication(School.ItemType.BANK_PROBLEM, problemBankId, authId, 0, authType); if (!responder.hasStudentPermission() && responder.isRegistrationRequired()) { throw new AuthenticationException(AuthenticationException.INVALID_PERMISSION); } return extractBankProblem(mongoBankProblem, problemBankId, responder.hasTeacherPermission()); }
Source:
protected void handleTabKey() { AbstractPane[] panes = fRendering.getRenderingPanes(); AbstractPane nextPane = null; if (this instanceof AddressPane) { nextPane = panes[1]; tabAddress = this.fCaretAddress; } else if (this instanceof DataPane) { nextPane = panes[2]; tabAddress = this.fCaretAddress; } else { nextPane = panes[0]; tabAddress = this.fCaretAddress; } nextPane.setCaretAddress(tabAddress); nextPane.fOldSubCellCaretPosition = 0; nextPane.fSubCellCaretPosition = 0; nextPane.updateCaret(); nextPane.ensureCaretWithinViewport(); nextPane.setFocus(); }

Target:
protected void handleTabKey() { AbstractPane nextPane = fRendering.nextPane(this); switchTo(nextPane); }
Source:
public void removePostShouldSetModificationDateToLastPostInTheTopic(){ Post post1 = new Post(); post1.setCreationDate(new DateTime()); Post post2 = new Post(); post2.setCreationDate(new DateTime()); Topic topic = new Topic(new JCUser(), "title"); topic.addPost(post1); topic.addPost(post2); Post post3 = new Post(); post3.setCreationDate(new DateTime()); topic.addPost(post3); assertEquals(topic.getModificationDate(), post3.getCreationDate()); topic.removePost(post3); assertEquals(topic.getModificationDate(), post2.getCreationDate()); }

Target:
public void removePostShouldSetModificationDateToLastPostInTheTopic(){ Post post1 = new Post(); post1.setCreationDate(new DateTime()); Post post2 = new Post(); post2.setCreationDate(new DateTime()); Topic topic = new Topic(new JCUser(), "title"); topic.addPost(post1); topic.addPost(post2); Post post3 = new Post(); post3.setCreationDate(new DateTime()); topic.addPost(post3); topic.removePost(post3); assertEquals(topic.getModificationDate(), post2.getCreationDate()); }
Source:
private void runAsync() { CompletableFuture<Response> beforeFuture = beforeInvoke(); if (beforeFuture == null) { invoke(); } else { beforeFuture.whenComplete((rsp, throwable) -> { if (rsp != null) { response = rsp; reply.reply(rsp); onFinally(); } else if (throwable != null) { afterCommandException(unwrap(throwable)); } else { invoke(); } }); } }

Target:
private void runAsync() { CompletableFuture<Response> beforeFuture = beforeInvoke(); if (beforeFuture == null) { invoke(); } else { beforeFuture.whenComplete((rsp, throwable) -> { if (rsp != null) { response = rsp; reply.reply(rsp); onFinally(); } else if (throwable != null) { afterCommandException(unwrap(throwable)); reply.reply(response); onFinally(); } else { invoke(); } }); } }
Source:
public CommandExecutor lookupKieSession(String kieSessionId, KieContainerInstance containerInstance, KieServerRegistry registry) { CommandExecutor ks = null; if( kieSessionId != null ) { KieSessionModel ksm = containerInstance.getKieContainer().getKieSessionModel(kieSessionId); if( ksm != null ) { switch (ksm.getType() ) { case STATEFUL: ks = ((KieContainerImpl)containerInstance.getKieContainer()).getKieSession(kieSessionId); break; case STATELESS: ks = ((KieContainerImpl)containerInstance.getKieContainer()).getStatelessKieSession(kieSessionId); break; } } PrometheusKieServerExtension extension = (PrometheusKieServerExtension)registry.getServerExtension(PrometheusKieServerExtension.EXTENSION_NAME); if (extension != null && ks != null) { RuleRuntimeEventManager eventManager = (RuleRuntimeEventManager)ks; extension.getDroolsListeners(kieSessionId, containerInstance).forEach(l -> eventManager.addEventListener(l)); } return ks; } return null; }

Target:
public CommandExecutor lookupKieSession(String kieSessionId, KieContainerInstance containerInstance, KieServerRegistry registry) { CommandExecutor ks = null; if( kieSessionId != null ) { KieSessionModel ksm = containerInstance.getKieContainer().getKieSessionModel(kieSessionId); if( ksm != null ) { switch (ksm.getType() ) { case STATEFUL: ks = ((KieContainerImpl)containerInstance.getKieContainer()).getKieSession(kieSessionId); break; case STATELESS: ks = ((KieContainerImpl)containerInstance.getKieContainer()).getStatelessKieSession(kieSessionId); break; } } PrometheusKieServerExtension extension = (PrometheusKieServerExtension)registry.getServerExtension(PrometheusKieServerExtension.EXTENSION_NAME); if (extension != null && ks != null) { RuleRuntimeEventManager eventManager = (RuleRuntimeEventManager) ks; PrometheusMetricsDroolsListener listener = new PrometheusMetricsDroolsListener(PrometheusKieServerExtension.getMetrics(), kieSessionId, containerInstance); eventManager.addEventListener(listener); List<AgendaEventListener> droolsListeners = extension.getDroolsListeners(kieSessionId, containerInstance); droolsListeners.forEach(l -> { if (!eventManager.getAgendaEventListeners().contains(l)) { eventManager.addEventListener(l); } }); } return ks; } return null; }
Source:
private static TaskEditor getMockEditor() { TaskEditor editor = mock(TaskEditor.class); TaskEditorInput input = mock(TaskEditorInput.class); when(editor.getTaskEditorInput()).thenReturn(input); when(input.getTask()).thenReturn(linkedTask); return editor; }

Target:
private static TaskEditor getMockEditor() { TaskEditor editor = mock(TaskEditor.class); when(editor.getTaskEditorInput()).thenReturn(taskEditorInput); return editor; }
Source:
public void testSerDeser() throws IOException { ObjectMapper mapper = new DefaultObjectMapper(); Assert.assertEquals(loadingCache, mapper.readerFor(LoadingCache.class).readValue(mapper.writeValueAsString(loadingCache))); Assert.assertTrue(loadingCache.hashCode() == mapper.readerFor(LoadingCache.class).readValue(mapper.writeValueAsString(loadingCache)).hashCode()); }

Target:
public void testSerDeser() throws IOException { ObjectMapper mapper = new DefaultObjectMapper(); Assert.assertEquals(loadingCache, mapper.readerFor(LoadingCache.class).readValue(mapper.writeValueAsString(loadingCache))); Assert.assertEquals(loadingCache.hashCode(), mapper.readerFor(LoadingCache.class).readValue(mapper.writeValueAsString(loadingCache)).hashCode()); }
Source:
public XYTimeQueryFilter(long start, long end, int n, Collection<Long> entryIds) { super(start, end, n); fEntryIds = Collections.unmodifiableCollection(entryIds); }

Target:
public XYTimeQueryFilter(long start, long end, int n, Collection<Long> entryIds) { super(start, end, n); fEntryIds = ImmutableList.copyOf(entryIds); }
Source:
String getSuiteUid(ITestContext iTestContext) { String uid; String suite = getCurrentSuiteName(iTestContext); if (suiteUid.containsKey(suite)){ uid=suiteUid.get(suite); } else { uid=UUID.randomUUID().toString(); suiteUid.put(suite, uid); } return uid; }

Target:
String getSuiteUid(ITestContext iTestContext) { String uid; String suite = getCurrentSuiteTitle(iTestContext); if (suiteUid.containsKey(suite)){ uid = suiteUid.get(suite); } else { uid = UUID.randomUUID().toString(); suiteUid.put(suite, uid); } return uid; }
Source:
public SpongeDyeableData(DyeColor dyeColor) { super(DyeableData.class, dyeColor, Keys.DYE_COLOR, ImmutableDyeableData.class); }

Target:
public SpongeDyeableData(DyeColor dyeColor) { super(DyeableData.class, checkNotNull(dyeColor), Keys.DYE_COLOR, ImmutableDyeableData.class); }
Source:
void flushStoredSessions() { if (flushingRequest.tryAcquire(1)) { try { List<File> storedFiles; storedFiles = sessionStore.findStoredFiles(); if (!storedFiles.isEmpty()) { SessionTrackingPayload payload = new SessionTrackingPayload(storedFiles, client.appData); try { configuration.getDelivery().deliver(payload, configuration); sessionStore.deleteStoredFiles(storedFiles); } catch (NetworkException exception) { sessionStore.cancelQueuedFiles(storedFiles); Logger.info("Failed to post stored session payload"); } catch (BadResponseException exception) { Logger.warn("Invalid session tracking payload", exception); sessionStore.deleteStoredFiles(storedFiles); } } } finally { flushingRequest.release(1); } } }

Target:
void flushStoredSessions() { if (flushingRequest.tryAcquire(1)) { try { List<File> storedFiles; storedFiles = sessionStore.findStoredFiles(); if (!storedFiles.isEmpty()) { SessionTrackingPayload payload = new SessionTrackingPayload(storedFiles, client.appData); try { configuration.getDelivery().deliver(payload, configuration); sessionStore.deleteStoredFiles(storedFiles); } catch (DeliveryFailureException exception) { sessionStore.cancelQueuedFiles(storedFiles); Logger.warn("Leaving session payload for future delivery", exception); } catch (Exception exception) { Logger.warn("Deleting invalid session tracking payload", exception); sessionStore.deleteStoredFiles(storedFiles); } } } finally { flushingRequest.release(1); } } }
Source:
public SubordinateAtomicAction (int timeout) { super(); dynamic1PC = false; start(); if (timeout > AtomicAction.NO_TIMEOUT) TransactionReaper.transactionReaper().insert(this, timeout); }

Target:
public SubordinateAtomicAction (int timeout) { super(); subordinate = true; start(); if (timeout > AtomicAction.NO_TIMEOUT) TransactionReaper.transactionReaper().insert(this, timeout); }
Source:
public static void closeSecondaryShells(SWTWorkbenchBot bot) { SWTBotShell[] shells = bot.shells(); SWTBotShell mainShell = getMainShell(shells); if (mainShell == null) { return; } for (SWTBotShell shell : shells) { boolean visible = shell.isVisible(); if (shell != mainShell && visible) { shell.close(); } } }

Target:
public static void closeSecondaryShells(SWTWorkbenchBot bot) { SWTBotShell[] shells = bot.shells(); SWTBotShell mainShell = getMainShell(shells); if (mainShell == null) { return; } Arrays.stream(shells) .filter(shell -> shell != mainShell) .filter(SWTBotShell::isVisible) .forEach(SWTBotShell::close); }
Source:
private IndexMetaData getIndexMetaData(String indexAlias) throws DotDataException { String indexName = null; boolean defaultIndex = false; long recordCount = 0; if (UtilMethods.isSet(indexAlias)) { indexAlias = indexAlias.split("\\s+")[0]; final List<String> indices = siteSearchAPI.listIndices(); final Map<String, String> aliasMap = esIndexAPI.getAliasToIndexMap(indices); indexName = aliasMap.get(indexAlias); if (UtilMethods.isSet(indexName)) { if (siteSearchAPI.isDefaultIndex(indexAlias)) { Logger.info(this, "Index is current Site-Search DEFAULT."); defaultIndex = true; } } else { if(indices.contains(indexAlias)){ indexName = indexAlias; indexAlias = null; } } if(UtilMethods.isSet(indexName)){ final SiteSearchResults search = siteSearchAPI.search(indexName, "*",0, 10); recordCount = search.getTotalResults(); } } return new IndexMetaData(indexName, defaultIndex, indexAlias, recordCount == 0); }

Target:
private IndexMetaData getIndexMetaData(String indexAlias) throws DotDataException { String indexName = null; boolean defaultIndex = false; long recordCount = 0; if (UtilMethods.isSet(indexAlias)) { indexAlias = indexAlias.split("\\s+")[0]; final List<String> indices = siteSearchAPI.listIndices(); final Map<String, String> aliasMap = esIndexAPI.getAliasToIndexMap(indices); indexName = aliasMap.get(indexAlias); if (UtilMethods.isSet(indexName)) { if (siteSearchAPI.isDefaultIndex(indexAlias)) { Logger.info(SiteSearchJobImpl.class, String.format("Index `%s` is currently Site-Search DEFAULT.",indexAlias)); defaultIndex = true; } } else { if(indices.contains(indexAlias)){ indexName = indexAlias; indexAlias = null; } } if(UtilMethods.isSet(indexName)){ final SiteSearchResults search = siteSearchAPI.search(indexName, "*",0, 10); recordCount = search.getTotalResults(); } } return new IndexMetaData(indexName, defaultIndex, indexAlias, recordCount == 0); }
Source:
public ArgumentListBuilder toWindowsCommand(boolean escapeVars) { ArgumentListBuilder windowsCommand = new ArgumentListBuilder().add("cmd.exe", "/C"); boolean quoted, percent; for (int i = 0; i < args.size(); i++) { StringBuilder quotedArgs = new StringBuilder(); String arg = args.get(i); quoted = percent = false; for (int j = 0; j < arg.length(); j++) { char c = arg.charAt(j); if (!quoted && (c == ' ' || c == '*' || c == '?' || c == ',' || c == ';')) { quoted = startQuoting(quotedArgs, arg, j); } else if (c == '^' || c == '&' || c == '<' || c == '>' || c == '|') { if (!quoted) quoted = startQuoting(quotedArgs, arg, j); } else if (c == '"') { if (!quoted) quoted = startQuoting(quotedArgs, arg, j); quotedArgs.append('"'); } else if (percent && escapeVars && ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'))) { if (!quoted) quoted = startQuoting(quotedArgs, arg, j); quotedArgs.append('"').append(c); c = '"'; } percent = (c == '%'); if (quoted) quotedArgs.append(c); } if(i == 0) quotedArgs.append('"'); if (quoted) quotedArgs.append('"'); else quotedArgs.append(arg); windowsCommand.add(quotedArgs, mask.get(i)); } windowsCommand.add("&&").add("exit").add("%%ERRORLEVEL%%\""); return windowsCommand; }

Target:
public ArgumentListBuilder toWindowsCommand(boolean escapeVars) { ArgumentListBuilder windowsCommand = new ArgumentListBuilder().add("cmd.exe", "/C"); boolean quoted, percent; for (int i = 0; i < args.size(); i++) { StringBuilder quotedArgs = new StringBuilder(); String arg = args.get(i); quoted = percent = false; for (int j = 0; j < arg.length(); j++) { char c = arg.charAt(j); if (!quoted && (c == ' ' || c == '*' || c == '?' || c == ',' || c == ';')) { quoted = startQuoting(quotedArgs, arg, j); } else if (c == '^' || c == '&' || c == '<' || c == '>' || c == '|') { if (!quoted) quoted = startQuoting(quotedArgs, arg, j); } else if (c == '"') { if (!quoted) quoted = startQuoting(quotedArgs, arg, j); quotedArgs.append('"'); } else if (percent && escapeVars && ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'))) { if (!quoted) quoted = startQuoting(quotedArgs, arg, j); quotedArgs.append('"').append(c); c = '"'; } percent = (c == '%'); if (quoted) quotedArgs.append(c); } if(i == 0 && quoted) quotedArgs.insert(0, '"'); else if (i == 0 && !quoted) quotedArgs.append('"'); if (quoted) quotedArgs.append('"'); else quotedArgs.append(arg); windowsCommand.add(quotedArgs, mask.get(i)); } windowsCommand.add("&&").add("exit").add("%%ERRORLEVEL%%\""); return windowsCommand; }
Source:
private String getGlobalProperty(String globalPropertyName, boolean required) { String globalProperty = administrationService.getGlobalProperty(globalPropertyName); if (required && StringUtils.isEmpty(globalProperty)) { throw new IllegalStateException("Configuration required: " + globalPropertyName); } return globalProperty; }

Target:
private String getGlobalProperty(String globalPropertyName, boolean required) { final String result = administrationService.getGlobalProperty(globalPropertyName); if (required && StringUtils.isBlank(result)) { throw new IllegalStateException("Configuration required: " + globalPropertyName); } return result; }
Source:
public void beforeEach(ExtensionContext extensionContext) throws Exception { Optional<ExtensionContext> currentContext = Optional.of(extensionContext); while (currentContext.isPresent()) { ExtensionContext context = currentContext.get(); Object testInstance = context.getStore(ASSERTJ_CORE).remove(TEST_INSTANCE); if (testInstance != null) { List<Field> softlyFields = AnnotationSupport.findAnnotatedFields(testInstance.getClass(), Softly.class); if (!softlyFields.isEmpty()) { if (softlyFields.size() > 1) { throw failures.failure("Only one field of type " + SoftAssertions.class.getName() + " can have the annotation @Softly"); } Field softlyField = softlyFields.get(0); if (softlyField.getType() != SoftAssertions.class) { throw failures.failure("@Softly field must be of the type " + SoftAssertions.class.getName()); } softlyField.setAccessible(true); softlyField.set(testInstance, new SoftAssertions()); this.softlies.add((SoftAssertions) softlyField.get(testInstance)); } } currentContext = context.getParent(); } if (this.softlies.isEmpty()) { LOGGER.log(Level.WARNING, "\n======================================" + "\nNo instance of soft assertions detected" + "\n======================================"); } }

Target:
public void beforeEach(ExtensionContext extensionContext) throws Exception { Optional<ExtensionContext> currentContext = Optional.of(extensionContext); while (currentContext.isPresent()) { ExtensionContext context = currentContext.get(); Object testInstance = context.getStore(ASSERTJ_CORE).remove(TEST_INSTANCE); if (testInstance != null) { List<Field> softlyFields = AnnotationSupport.findAnnotatedFields(testInstance.getClass(), Softly.class); if (!softlyFields.isEmpty()) { if (softlyFields.size() > 1) { throw failures.failure("Only one field of type " + SoftAssertions.class.getName() + " can have the annotation @Softly"); } if (context.getTestInstanceLifecycle().isPresent() && context.getTestInstanceLifecycle().get() == PER_CLASS) { throw failures.failure("@Softly annotation not permitted in test class with life cycle PER_CLASS"); } Field softlyField = softlyFields.get(0); if (softlyField.getType() != SoftAssertions.class) { throw failures.failure("@Softly field must be of the type " + SoftAssertions.class.getName()); } softlyField.setAccessible(true); softlyField.set(testInstance, new SoftAssertions()); this.softlies.add((SoftAssertions) softlyField.get(testInstance)); } } currentContext = context.getParent(); } if (this.softlies.isEmpty()) { LOGGER.log(Level.WARNING, "\n======================================" + "\nNo instance of soft assertions detected" + "\n======================================"); } }
Source:
public void setup() throws InterruptedException, KeeperException.NoNodeException { System.setProperty(authProvider, superDigest); QuorumPeerConfig.setReconfigEnabled(false); qu = new QuorumUtil(1); qu.disableJMXTest = true; try { qu.startAll(); } catch (IOException e) { Assert.fail("Fail to start quorum servers."); } resetZKAdmin(); }

Target:
public void setup() throws InterruptedException { System.setProperty(authProvider, superDigest); QuorumPeerConfig.setReconfigEnabled(false); qu = new QuorumUtil(1); qu.disableJMXTest = true; try { qu.startAll(); } catch (IOException e) { Assert.fail("Fail to start quorum servers."); } resetZKAdmin(); }
Source:
protected int getSideFromRectangle(Point pt) { while (includedRect.contains(pt)) { includedRect.shrink(1, 1); } int side = includedRect.getPosition(pt); return side; }

Target:
protected int getSideFromRectangle(Point pt) { while (getIncludedRect().contains(pt)) { getIncludedRect().shrink(1, 1); } int side = getIncludedRect().getPosition(pt); return side; }
Source:
public <T, P extends PartitionLocation<T>> File fetchSegmentFile( File partitionDir, String supervisorTaskId, P location ) throws IOException { final byte[] buffer = new byte[BUFFER_SIZE]; final File zippedFile = new File(partitionDir, StringUtils.format("temp_%s", location.getSubTaskId())); final URI uri = location.toIntermediaryDataServerURI(supervisorTaskId); FileUtils.copyLarge( uri, u -> { try { return httpClient.go(new Request(HttpMethod.GET, u.toURL()), new InputStreamResponseHandler()) .get(); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } }, zippedFile, buffer, t -> t instanceof IOException, NUM_FETCH_RETRIES, StringUtils.format("Failed to fetch file[%s]", uri) ); return zippedFile; }

Target:
public <T, P extends PartitionLocation<T>> File fetchSegmentFile( File partitionDir, String supervisorTaskId, P location ) throws IOException { final byte[] buffer = new byte[BUFFER_SIZE]; final File zippedFile = new File(partitionDir, StringUtils.format("temp_%s", location.getSubTaskId())); final URI uri = location.toIntermediaryDataServerURI(supervisorTaskId); FileUtils.copyLarge( uri, u -> { try { return httpClient.go(new Request(HttpMethod.GET, u.toURL()), new InputStreamResponseHandler()) .get(); } catch (InterruptedException | ExecutionException e) { throw new IOException(e); } }, zippedFile, buffer, t -> t instanceof IOException, NUM_FETCH_RETRIES, StringUtils.format("Failed to fetch file[%s]", uri) ); return zippedFile; }
Source:
private PieData getData() { PieDataSet dataSet = new PieDataSet(null, ""); List<String> labels = new ArrayList<>(); List<Integer> colors = new ArrayList<>(); for (Account account : mAccountsDbAdapter.getSimpleAccountList()) { if (account.getAccountType() == mAccountType && !account.isPlaceholderAccount() && account.getCommodity() == mCommodity) { double balance = mAccountsDbAdapter.getAccountsBalance(Collections.singletonList(account.getUID()), mReportPeriodStart, mReportPeriodEnd).asDouble(); if (balance > 0) { dataSet.addEntry(new Entry((float) balance, dataSet.getEntryCount())); int color; if (mUseAccountColor) { color = (account.getColor() != Account.DEFAULT_COLOR) ? account.getColor() : ReportsActivity.COLORS[(dataSet.getEntryCount() - 1) % ReportsActivity.COLORS.length]; } else { color = ReportsActivity.COLORS[(dataSet.getEntryCount() - 1) % ReportsActivity.COLORS.length]; } colors.add(color); labels.add(account.getName()); } } } dataSet.setColors(colors); dataSet.setSliceSpace(SPACE_BETWEEN_SLICES); return new PieData(labels, dataSet); }

Target:
private PieData getData() { PieDataSet dataSet = new PieDataSet(null, ""); List<String> labels = new ArrayList<>(); List<Integer> colors = new ArrayList<>(); for (Account account : mAccountsDbAdapter.getSimpleAccountList()) { if (account.getAccountType() == mAccountType && !account.isPlaceholderAccount() && account.getCommodity().equals(mCommodity)) { double balance = mAccountsDbAdapter.getAccountsBalance(Collections.singletonList(account.getUID()), mReportPeriodStart, mReportPeriodEnd).asDouble(); if (balance > 0) { dataSet.addEntry(new Entry((float) balance, dataSet.getEntryCount())); int color; if (mUseAccountColor) { color = (account.getColor() != Account.DEFAULT_COLOR) ? account.getColor() : ReportsActivity.COLORS[(dataSet.getEntryCount() - 1) % ReportsActivity.COLORS.length]; } else { color = ReportsActivity.COLORS[(dataSet.getEntryCount() - 1) % ReportsActivity.COLORS.length]; } colors.add(color); labels.add(account.getName()); } } } dataSet.setColors(colors); dataSet.setSliceSpace(SPACE_BETWEEN_SLICES); return new PieData(labels, dataSet); }
Source:
protected void handleElementContentChanged(IFileEditorInput fileEditorInput) { FileInfo info= (FileInfo) getElementInfo(fileEditorInput); if (info == null) return; IDocument document= createEmptyDocument(); IStatus status= null; try { try { refreshFile(fileEditorInput.getFile(), getProgressMonitor()); } catch (CoreException x) { handleCoreException(x, "FileDocumentProvider.handleElementContentChanged"); } cacheEncodingState(fileEditorInput); setDocumentContent(document, fileEditorInput, info.fEncoding); } catch (CoreException x) { status= x.getStatus(); } String newContent= document.get(); if ( !newContent.equals(info.fDocument.get())) { fireElementContentAboutToBeReplaced(fileEditorInput); removeUnchangedElementListeners(fileEditorInput, info); info.fDocument.removeDocumentListener(info); info.fDocument.set(newContent); info.fCanBeSaved= false; info.fModificationStamp= computeModificationStamp(fileEditorInput.getFile()); info.fStatus= status; addUnchangedElementListeners(fileEditorInput, info); fireElementContentReplaced(fileEditorInput); } else { removeUnchangedElementListeners(fileEditorInput, info); info.fCanBeSaved= false; info.fModificationStamp= computeModificationStamp(fileEditorInput.getFile()); info.fStatus= status; addUnchangedElementListeners(fileEditorInput, info); fireElementDirtyStateChanged(fileEditorInput, false); } }

Target:
protected void handleElementContentChanged(IFileEditorInput fileEditorInput) { FileInfo info= (FileInfo) getElementInfo(fileEditorInput); if (info == null) return; IDocument document= createEmptyDocument(); IStatus status= null; try { try { refreshFile(fileEditorInput.getFile()); } catch (CoreException x) { handleCoreException(x, "FileDocumentProvider.handleElementContentChanged"); } cacheEncodingState(fileEditorInput); setDocumentContent(document, fileEditorInput, info.fEncoding); } catch (CoreException x) { status= x.getStatus(); } String newContent= document.get(); if ( !newContent.equals(info.fDocument.get())) { fireElementContentAboutToBeReplaced(fileEditorInput); removeUnchangedElementListeners(fileEditorInput, info); info.fDocument.removeDocumentListener(info); info.fDocument.set(newContent); info.fCanBeSaved= false; info.fModificationStamp= computeModificationStamp(fileEditorInput.getFile()); info.fStatus= status; addUnchangedElementListeners(fileEditorInput, info); fireElementContentReplaced(fileEditorInput); } else { removeUnchangedElementListeners(fileEditorInput, info); info.fCanBeSaved= false; info.fModificationStamp= computeModificationStamp(fileEditorInput.getFile()); info.fStatus= status; addUnchangedElementListeners(fileEditorInput, info); fireElementDirtyStateChanged(fileEditorInput, false); } }
Source:
public void run() { client.events().inAnyNamespace().watch(this); }

Target:
public void run() { LOG.info("Master URL: {}", client.getMasterUrl()); LOG.info("Namespaces: {}", client.namespaces().list().getItems().stream().map(x -> x.getMetadata().getName()).collect(Collectors.toList())); client.endpoints().inNamespace("paas-run-playground").watch(this); }
Source:
public void onRevealLogFolder() { Path mapPath = preferencesService.getFafLogDirectory(); try { FileUtils.openFolder(mapPath); } catch (IOException e) { e.printStackTrace(); } }

Target:
public void onRevealLogFolder() { Path logPath = preferencesService.getFafLogDirectory(); this.platformService.reveal(logPath); }
Source:
public Builder<PersistenceConfiguration> configure(OperationContext context, ModelNode model) throws OperationFailedException { this.remoteCacheName = CACHE.resolveModelAttribute(context, model).asString(); this.socketTimeout = SOCKET_TIMEOUT.resolveModelAttribute(context, model).asLong(); this.tcpNoDelay = TCP_NO_DELAY.resolveModelAttribute(context, model).asBoolean(); List<ValueDependency<OutboundSocketBinding>> list = new ArrayList<>(); for (String binding : StringListAttributeDefinition.unwrapValue(context, SOCKET_BINDINGS.resolveModelAttribute(context, model))) { InjectedValueDependency<OutboundSocketBinding> outboundSocketBindingInjectedValueDependency = new InjectedValueDependency<>(CommonUnaryRequirement.OUTBOUND_SOCKET_BINDING.getServiceName(context, binding), OutboundSocketBinding.class); list.add(outboundSocketBindingInjectedValueDependency); } this.bindings = list; return super.configure(context, model); }

Target:
public Builder<PersistenceConfiguration> configure(OperationContext context, ModelNode model) throws OperationFailedException { this.remoteCacheName = CACHE.resolveModelAttribute(context, model).asString(); this.socketTimeout = SOCKET_TIMEOUT.resolveModelAttribute(context, model).asLong(); this.tcpNoDelay = TCP_NO_DELAY.resolveModelAttribute(context, model).asBoolean(); final List<String> unwrappedList = StringListAttributeDefinition.unwrapValue(context, SOCKET_BINDINGS.resolveModelAttribute(context, model)); final List<ValueDependency<OutboundSocketBinding>> list = new ArrayList<>(unwrappedList.size()); for (String binding : unwrappedList) { list.add(new InjectedValueDependency<>(CommonUnaryRequirement.OUTBOUND_SOCKET_BINDING.getServiceName(context, binding), OutboundSocketBinding.class)); } this.bindings = list; return super.configure(context, model); }
Source:
private static void checkFirstFailed(Object input) { ChannelOutboundHandlerAdapter noOpWrites = new ChannelOutboundHandlerAdapter() { @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { promise.tryFailure(new RuntimeException()); } }; EmbeddedChannel ch = new EmbeddedChannel(noOpWrites, new ChunkedWriteHandler()); ChannelFuture r = ch.writeAndFlush(input).awaitUninterruptibly(); ch.close(); assertTrue(r.cause() instanceof RuntimeException); }

Target:
private static void checkFirstFailed(Object input) { ChannelOutboundHandlerAdapter noOpWrites = new ChannelOutboundHandlerAdapter() { @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { ReferenceCountUtil.release(msg); promise.tryFailure(new RuntimeException()); } }; EmbeddedChannel ch = new EmbeddedChannel(noOpWrites, new ChunkedWriteHandler()); ChannelFuture r = ch.writeAndFlush(input); assertFalse(ch.finish()); assertTrue(r.cause() instanceof RuntimeException); }
Source:
public static String getCheckpointTopic(String jobName, String jobId, Config config) { String checkpointTopic = String.format("__samza_checkpoint_ver_%d_for_%s_%s", CHECKPOINT_LOG_VERSION_NUMBER, jobName.replaceAll("_", "-"), jobId.replaceAll("_", "-")); return StreamManager.createUniqueNameForBatch(checkpointTopic, config); }

Target:
public static String getCheckpointTopic(String jobName, String jobId, Config config) { String checkpointTopic = String.format(CHECKPOINT_TOPIC_FORMAT, CHECKPOINT_LOG_VERSION_NUMBER, jobName.replaceAll("_", "-"), jobId.replaceAll("_", "-")); return StreamManager.createUniqueNameForBatch(checkpointTopic, config); }
Source:
protected boolean createTopics(Collection<NewTopic> newTopics) { boolean createStatus = true; try { CreateTopicsResult resultFuture = adminClient.createTopics(newTopics); resultFuture.all().get(10000, TimeUnit.MILLISECONDS); } catch (Exception e) { createStatus = false; } return createStatus; }

Target:
protected boolean createTopics(Collection<NewTopic> newTopics) { boolean createStatus = true; try { CreateTopicsResult resultFuture = adminClient.createTopics(newTopics); resultFuture.all().get(ADMIN_OPERATION_WAIT_DURATION_MS, TimeUnit.MILLISECONDS); } catch (Exception e) { createStatus = false; } return createStatus; }
Source:
public void testMultiplePerTargetAspectsWithOrderAnnotation() throws SecurityException, NoSuchMethodException { TestBean target = new TestBean(); int realAge = 65; target.setAge(realAge); List<Advisor> advisors = new LinkedList<>(); PerTargetAspectWithOrderAnnotation10 aspect1 = new PerTargetAspectWithOrderAnnotation10(); aspect1.count = 100; advisors.addAll( getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(aspect1, "someBean1"))); PerTargetAspectWithOrderAnnotation5 aspect2 = new PerTargetAspectWithOrderAnnotation5(); advisors.addAll( getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(aspect2, "someBean2"))); sort(advisors, new OrderComparator()); TestBean itb = (TestBean) createProxy(target, advisors, TestBean.class); assertThat(itb.getAge()).as("Around advice must NOT apply").isEqualTo(realAge); itb.getSpouse(); assertThat(itb.getAge()).as("Around advice must apply").isEqualTo(0); assertThat(itb.getAge()).as("Around advice must apply").isEqualTo(1); }

Target:
public void testMultiplePerTargetAspectsWithOrderAnnotation() throws SecurityException, NoSuchMethodException { TestBean target = new TestBean(); int realAge = 65; target.setAge(realAge); List<Advisor> advisors = new LinkedList<>(); PerTargetAspectWithOrderAnnotation10 aspect1 = new PerTargetAspectWithOrderAnnotation10(); aspect1.count = 100; advisors.addAll( getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(aspect1, "someBean1"))); PerTargetAspectWithOrderAnnotation5 aspect2 = new PerTargetAspectWithOrderAnnotation5(); advisors.addAll( getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(aspect2, "someBean2"))); OrderComparator.sort(advisors); TestBean itb = (TestBean) createProxy(target, advisors, TestBean.class); assertThat(itb.getAge()).as("Around advice must NOT apply").isEqualTo(realAge); itb.getSpouse(); assertThat(itb.getAge()).as("Around advice must apply").isEqualTo(0); assertThat(itb.getAge()).as("Around advice must apply").isEqualTo(1); }
Source:
public int decompress(byte[] input, int inputOffset, int inputLength, byte[] output, int outputOffset, int maxOutputLength) throws MalformedInputException { Inflater inflater = new Inflater(true); inflater.setInput(input, inputOffset, inputLength); int uncompressedLength = 0; try { uncompressedLength = inflater.inflate(output, outputOffset, maxOutputLength); if (!inflater.finished()) { throw new IllegalStateException("maxCompressedLength formula is incorrect, because deflate produced more data"); } } catch (DataFormatException e) { throw new MalformedInputException(inputOffset, e.getMessage()); } finally { inflater.end(); } return uncompressedLength; }

Target:
public int decompress(byte[] input, int inputOffset, int inputLength, byte[] output, int outputOffset, int maxOutputLength) throws MalformedInputException { Inflater inflater = new Inflater(true); inflater.setInput(input, inputOffset, inputLength); int uncompressedLength = 0; try { uncompressedLength = inflater.inflate(output, outputOffset, maxOutputLength); if (!inflater.finished()) { throw new IllegalArgumentException("maxOutputLength is incorrect, there is more data to be decompressed"); } } catch (DataFormatException e) { throw new MalformedInputException(inputOffset, e.getMessage()); } finally { inflater.end(); } return uncompressedLength; }
Source:
private void initViewModel() { dashPayViewModel = new ViewModelProvider(this).get(DashPayViewModel.class); dashPayViewModel.isPlatformAvailableLiveData().observe(this, new Observer<Resource<Boolean>>() { @Override public void onChanged(Resource<Boolean> status) { if(status.getStatus() == Status.SUCCESS) isPlatformAvailable = status.getData(); else isPlatformAvailable = false; showHideJoinDashPayAction(); } }); AppDatabase.getAppDatabase().blockchainIdentityDataDao().load().observe(this, new Observer<BlockchainIdentityData>() { @Override public void onChanged(BlockchainIdentityData blockchainIdentityData) { if (blockchainIdentityData != null) { BlockchainIdentity.RegistrationStatus status = blockchainIdentityData.getRegistrationStatus(); hasIdentity = (status == BlockchainIdentity.RegistrationStatus.REGISTERED); showHideJoinDashPayAction(); } } }); }

Target:
private void initViewModel() { dashPayViewModel = new ViewModelProvider(this).get(DashPayViewModel.class); dashPayViewModel.isPlatformAvailableLiveData().observe(this, new Observer<Resource<Boolean>>() { @Override public void onChanged(Resource<Boolean> status) { if (status.getStatus() == Status.SUCCESS) isPlatformAvailable = status.getData(); else isPlatformAvailable = false; showHideJoinDashPayAction(); } }); AppDatabase.getAppDatabase().blockchainIdentityDataDao().loadBase().observe(this, new Observer<BlockchainIdentityBaseData>() { @Override public void onChanged(BlockchainIdentityBaseData blockchainIdentityData) { if (blockchainIdentityData != null) { hasIdentity = (blockchainIdentityData.getCreationState() == BlockchainIdentityData.CreationState.DONE); showHideJoinDashPayAction(); if (retryCreationIfInProgress && blockchainIdentityData.getCreationInProgress()) { retryCreationIfInProgress = false; startService(CreateIdentityService.createIntentForRetry(WalletActivity.this, false)); } } } }); }