auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private boolean processAllResponses(final Connection connection) throws IOException { boolean isEmpty = false; connection.responseWriteLock.lock(); try { for (int i = 0; i < 20; i++) { Call call = connection.responseQueue.pollFirst(); if (call == null) { return true; } metrics.removeCallFromResponseQueue(call.response.getRemaining()); if (!processResponse(call)) { connection.responseQueue.addFirst(call); metrics.addCallToResponseQueue(call.response.getRemaining()); return false; } } isEmpty = connection.responseQueue.isEmpty(); } finally { connection.responseWriteLock.unlock(); } return isEmpty; }

Target:
private boolean processAllResponses(final Connection connection) throws IOException { boolean isEmpty = false; connection.responseWriteLock.lock(); try { for (int i = 0; i < 20; i++) { Call call = connection.responseQueue.pollFirst(); if (call == null) { return true; } long beforeProcess = call.response.getRemaining(); if (!processResponse(call)) { connection.responseQueue.addFirst(call); long afterProcess = call.response.getRemaining(); metrics.updateResponseQueueSize(afterProcess - beforeProcess); return false; } else { metrics.removeCallFromResponseQueue(); metrics.updateResponseQueueSize(-beforeProcess); } } isEmpty = connection.responseQueue.isEmpty(); } finally { connection.responseWriteLock.unlock(); } return isEmpty; }
Source:
private boolean checkForAssembler() { synchronized(this.executionControl) { if (this.executionControl.incrementAndGet() <= 1) { this.executionControl.set(1); if (logger.isDebugEnabled()) { logger.debug(this.getConnectionId() + " Running an assembler"); } try { this.taskExecutor.execute2(this); } catch (RejectedExecutionException e) { this.executionControl.decrementAndGet(); if (logger.isInfoEnabled()) { logger.info("Insufficient threads in the assembler fixed thread pool; consider increasing " + "this task executor pool size"); } return false; } } else { this.executionControl.decrementAndGet(); } } return true; }

Target:
private boolean checkForAssembler() { synchronized(this.executionControl) { if (this.executionControl.incrementAndGet() <= 1) { this.executionControl.set(1); if (logger.isDebugEnabled()) { logger.debug(this.getConnectionId() + " Running an assembler"); } try { this.taskExecutor.execute2(this); } catch (RejectedExecutionException e) { this.executionControl.decrementAndGet(); if (logger.isInfoEnabled()) { logger.info("Insufficient threads in the assembler fixed thread pool; consider increasing " + "this task executor pool size"); } throw e; } } else { this.executionControl.decrementAndGet(); } } return true; }
Source:
protected String rtrim(String s) { if (s == null || s.length() == 0) { return s; } int pos = s.length(); while (pos > 0 && Character.isWhitespace(s.charAt(pos - 1))) { --pos; } return s.substring(0, pos); }

Target:
public static String rtrim(String s) { if (s == null || s.length() == 0) { return s; } int pos = s.length(); while (pos > 0 && Character.isWhitespace(s.charAt(pos - 1))) { --pos; } return s.substring(0, pos); }
Source:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SomethingWithOption that = (SomethingWithOption) o; if (id != that.id) return false; return name != null ? name.equals(that.name) : that.name == null; }

Target:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SomethingWithOption that = (SomethingWithOption) o; return id == that.id && Objects.equals(name, that.name); }
Source:
public void cmnClearRegion(RegionEventImpl regionEvent, boolean cacheWrite, boolean useRVV) { if (!getBucketAdvisor().isPrimary()) { if (logger.isDebugEnabled()) { logger.debug("Not primary bucket when doing clear, do nothing"); } return; } boolean enableRVV = useRVV && getConcurrencyChecksEnabled(); RegionVersionVector rvv = null; if (enableRVV) { rvv = getVersionVector().getCloneForTransmission(); } Set<InternalDistributedMember> participants = getCacheDistributionAdvisor().adviseInvalidateRegion(); boolean isLockedAlready = this.partitionedRegion.getClearPartitionedRegion() .isLockedForListenerAndClientNotification(); try { if (!isLockedAlready) { obtainWriteLocksForClear(regionEvent, participants); } clearRegionLocal(regionEvent, cacheWrite, null); distributeClearOperation(regionEvent, rvv, participants); } finally { if (!isLockedAlready) { releaseWriteLocksForClear(regionEvent, participants); } } }

Target:
public void cmnClearRegion(RegionEventImpl regionEvent, boolean cacheWrite, boolean useRVV) { if (!getBucketAdvisor().isPrimary()) { if (logger.isDebugEnabled()) { logger.debug("Not primary bucket when doing clear, do nothing"); } return; } boolean enableRVV = useRVV && getConcurrencyChecksEnabled(); RegionVersionVector rvv = null; if (enableRVV) { rvv = getVersionVector().getCloneForTransmission(); } Set<InternalDistributedMember> participants = getCacheDistributionAdvisor().adviseInvalidateRegion(); boolean isLockedAlready = this.partitionedRegion.getPartitionedRegionClear() .isLockedForListenerAndClientNotification(); try { if (!isLockedAlready) { obtainWriteLocksForClear(regionEvent, participants); } clearRegionLocally(regionEvent, cacheWrite, null); distributeClearOperation(regionEvent, rvv, participants); } finally { if (!isLockedAlready) { releaseWriteLocksForClear(regionEvent, participants); } } }
Source:
public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof HostDeviceView)) { return false; } if (!super.equals(o)) return false; HostDeviceView other = (HostDeviceView) o; return super.equals(other) && Objects.equals(configuredVmId, other.configuredVmId) && Objects.equals(attachedVmNames, other.attachedVmNames) && Objects.equals(runningVmName, other.runningVmName) && Objects.equals(iommuPlaceholder, other.iommuPlaceholder); }

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof HostDeviceView)) { return false; } HostDeviceView other = (HostDeviceView) o; return super.equals(other) && Objects.equals(configuredVmId, other.configuredVmId) && Objects.equals(attachedVmNames, other.attachedVmNames) && Objects.equals(runningVmName, other.runningVmName) && Objects.equals(iommuPlaceholder, other.iommuPlaceholder); }
Source:
private static Map<String, ModuleService> loadModules(Class cls) { Map<String, ModuleService> modules = new HashMap<>(); if(cls != null) { Map<String, ExtensionProxy> proxies = new HashMap<>(); ExtMap context = new ExtMap() .mput(ModuleService.EXTENSIONS_MAP, proxies) .mput(ModuleService.PROGRAM_NAME, PROGRAM_NAME); ServiceLoader<ModuleService> loader = ServiceLoader.load(cls); for (ModuleService module : loader) { modules.put(module.getName(), module); module.setContext(context); } } return modules; }

Target:
private Map<String, ModuleService> loadModules(Class cls) { Map<String, ModuleService> modules = new HashMap<>(); if(cls != null) { Map<String, ExtensionProxy> proxies = new HashMap<>(); ExtMap context = new ExtMap() .mput(ModuleService.EXTENSIONS_MAP, proxies) .mput(ModuleService.PROGRAM_NAME, PROGRAM_NAME); ServiceLoader<ModuleService> loader = ServiceLoader.load(cls); for (ModuleService module : loader) { modules.put(module.getName(), module); module.setContext(context); } } logger.debug("Loaded modules: {}", StringUtils.join(modules.keySet(), ",")); return modules; }
Source:
protected Optional<TestToolsView> getTestToolsView(PlaceRequest placeRequest) { final Activity activity = placeManager.getActivity(placeRequest); if (activity != null) { final AbstractWorkbenchActivity testToolsActivity = (AbstractWorkbenchActivity) activity; return Optional.of((TestToolsView) testToolsActivity.getWidget()); } else { return Optional.empty(); } }

Target:
protected Optional<TestToolsView> getTestToolsView(PlaceRequest placeRequest) { final Activity activity = placeManager.getActivity(placeRequest); if (activity == null) { return Optional.empty(); } else { final AbstractWorkbenchActivity testToolsActivity = (AbstractWorkbenchActivity) activity; return Optional.of((TestToolsView) testToolsActivity.getWidget()); } }
Source:
public Object getPrincipal() { return this.principal; }

Target:
public OAuth2User getPrincipal() { return this.principal; }
Source:
public synchronized PartitioningSpillResult partitionAndSpill(Page page, IntPredicate spillPartitionMask) { requireNonNull(page, "page is null"); requireNonNull(spillPartitionMask, "spillPartitionMask is null"); checkArgument(page.getChannelCount() == types.size(), "Wrong page channel count, expected %s but got %s", types.size(), page.getChannelCount()); checkState(!readingStarted); IntArrayList unspilledPositions = partitionPage(page, spillPartitionMask); ListenableFuture<?> future = flush(); return new PartitioningSpillResult(future, unspilledPositions); }

Target:
public synchronized PartitioningSpillResult partitionAndSpill(Page page, IntPredicate spillPartitionMask) { requireNonNull(page, "page is null"); requireNonNull(spillPartitionMask, "spillPartitionMask is null"); checkArgument(page.getChannelCount() == types.size(), "Wrong page channel count, expected %s but got %s", types.size(), page.getChannelCount()); checkState(!readingStarted, "reading already started"); IntArrayList unspilledPositions = partitionPage(page, spillPartitionMask); ListenableFuture<?> future = flushFullBuilders(); return new PartitioningSpillResult(future, page.mask(unspilledPositions.toIntArray())); }
Source:
public ConnectionFactory connectionFactory() { return new CachingConnectionFactory("localhost"); }

Target:
public ConnectionFactory connectionFactory() { return new CachingConnectionFactory(brokerRunning.getConnectionFactory()); }
Source:
private void deleteStoreDirectories() { Preconditions.checkNotNull(configs.get(JobConfig.JOB_LOGGED_STORE_BASE_DIR()), configs.get(JobConfig.JOB_NON_LOGGED_STORE_BASE_DIR())); deleteDirectory(configs.get(JobConfig.JOB_NON_LOGGED_STORE_BASE_DIR())); deleteDirectory(configs.get(JobConfig.JOB_LOGGED_STORE_BASE_DIR())); }

Target:
private void deleteStoreDirectories() { Preconditions.checkNotNull(configs.get(JobConfig.JOB_LOGGED_STORE_BASE_DIR())); Preconditions.checkNotNull(configs.get(JobConfig.JOB_NON_LOGGED_STORE_BASE_DIR())); deleteDirectory(configs.get(JobConfig.JOB_NON_LOGGED_STORE_BASE_DIR())); deleteDirectory(configs.get(JobConfig.JOB_LOGGED_STORE_BASE_DIR())); }
Source:
void shouldReturnCorrectStringRepresentationForAnIdWhichIsNullBasedOnTheActualClassname() { ByIdResultSelector byIdResultSelector = new ByIdResultSelector(null); assertThat(byIdResultSelector.toString()).isEqualTo( String.format("%s with ID null", ResultAction.class.getName())); }

Target:
void shouldReturnCorrectStringRepresentationForAnIdWhichIsNullBasedOnTheActualClassname() { ByIdResultSelector byIdResultSelector = new ByIdResultSelector(null); assertThat(byIdResultSelector.toString()).contains("null"); }
Source:
public static WritePropertyFileResponseType writePropertyFile(WritePropertyFileRequestType part1) throws PropertyAccessException { WritePropertyFileResponseType oOutput = new WritePropertyFileResponseType(); if (part1 != null && StringUtils.isNotEmpty(part1.getPropertyFile()) && part1.getProperties() != null && CollectionUtils.isNotEmpty(part1.getProperties().getProperty())) { String sPropertyFile = part1.getPropertyFile(); java.util.Properties oPropsToStore = new java.util.Properties(); for (PropertyType oInputProp : part1.getProperties().getProperty()) { if (oInputProp.getPropertyName() == null || oInputProp.getPropertyName().length() <= 0) { throw new PropertyAccessException( "Found a property without a name. All properties must have a name."); } if (oInputProp.getPropertyValue() == null) { throw new PropertyAccessException( "The property value cannot be null. Property: " + oInputProp.getPropertyName()); } String sPropName = oInputProp.getPropertyName(); String sPropValue = oInputProp.getPropertyValue(); oPropsToStore.setProperty(sPropName, sPropValue); } PropertyFileManager.writePropertyFile(sPropertyFile, oPropsToStore); } else { String sErrorMessage = "Failed to write property file. There must be both a valid " + "file name without the '.properties' extension and at least " + "one property to write."; throw new PropertyAccessException(sErrorMessage); } oOutput.setSuccess(true); return oOutput; }

Target:
public static WritePropertyFileResponseType writePropertyFile(WritePropertyFileRequestType part1) throws PropertyAccessException { WritePropertyFileResponseType oOutput = new WritePropertyFileResponseType(); if (part1 != null && StringUtils.isNotEmpty(part1.getPropertyFile()) && part1.getProperties() != null && CollectionUtils.isNotEmpty(part1.getProperties().getProperty())) { String sPropertyFile = part1.getPropertyFile(); java.util.Properties oPropsToStore = new java.util.Properties(); for (PropertyType oInputProp : part1.getProperties().getProperty()) { if (StringUtils.isEmpty(oInputProp.getPropertyName())) { throw new PropertyAccessException( "Found a property without a name. All properties must have a name."); } if (oInputProp.getPropertyValue() == null) { throw new PropertyAccessException( "The property value cannot be null. Property: " + oInputProp.getPropertyName()); } String sPropName = oInputProp.getPropertyName(); String sPropValue = oInputProp.getPropertyValue(); oPropsToStore.setProperty(sPropName, sPropValue); } PropertyFileManager.writePropertyFile(sPropertyFile, oPropsToStore); } else { String sErrorMessage = "Failed to write property file. There must be both a valid " + "file name without the '.properties' extension and at least " + "one property to write."; throw new PropertyAccessException(sErrorMessage); } oOutput.setSuccess(true); return oOutput; }
Source:
public OrderBook getOrderBook(CurrencyPair currencyPair, Object... args) throws IOException { LgoOrderbook orderBook = super.getLgoOrderBook(currencyPair); return convertOrderBook(orderBook, currencyPair); }

Target:
public OrderBook getOrderBook(CurrencyPair currencyPair, Object... args) throws IOException { try { LgoOrderbook orderBook = super.getLgoOrderBook(currencyPair); return LgoAdapters.adaptOrderBook(orderBook, currencyPair); } catch (LgoException e) { throw LgoErrorAdapter.adapt(e); } }
Source:
public static void activateIfWanted() { if (isPreventSystemExit()) { SecurityManager currentSecMgr = System.getSecurityManager(); if (currentSecMgr != null) { SystemExitSecurityManager systemExitSecurityManager = new SystemExitSecurityManager( currentSecMgr); tryUpdateSecurityManager(systemExitSecurityManager); } } }

Target:
public static void activateIfWanted() { if (isPreventSystemExit() && !isAndroid()) { SecurityManager currentSecMgr = System.getSecurityManager(); tryUpdateSecurityManager(new SystemExitSecurityManager(currentSecMgr)); } }
Source:
void testUserFormExistingUserInvalidPasswordLength() { UserForm userForm = new UserForm(); userForm.setUsername(VALID_USERNAME); userForm.setPassword(INVALID_PASSWORD); Set<ConstraintViolation<UserForm>> violations = validator.validate(userForm, UserForm.ExistingUser.class); assertThat(violations.isEmpty()).as("Violations are empty!").isFalse(); assertThat(violations.size()).isEqualTo(1); assertThat(violations).extracting("message").containsAnyOf("Password has to be more than 8 characters!"); }

Target:
void testUserFormExistingUserInvalidPasswordLength() { UserForm userForm = new UserForm(); userForm.setUsername(VALID_USERNAME); userForm.setPassword(INVALID_PASSWORD); Set<ConstraintViolation<UserForm>> violations = validator.validate(userForm, UserForm.ExistingUser.class); assertThat(violations).as("Violations are empty!").hasSize(1); assertThat(violations).extracting("message").containsAnyOf("Password has to be more than 8 characters!"); }
Source:
public void action(AuthenticationFlowContext context) { if (DisplayUtils.isConsole(context)) { ConsoleOTPFormAuthenticator.SINGLETON.action(context); return; } validateOTP(context); }

Target:
public void action(AuthenticationFlowContext context) { validateOTP(context); }
Source:
public static void serverShutdown(int portOffset, AutomationContext automationContext) throws XPathExpressionException, RemoteException, InterruptedException { long time = System.currentTimeMillis() + DEFAULT_START_STOP_WAIT_MS; log.info("Shutting down server.."); boolean logOutSuccess = false; if (ClientConnectionUtil.isPortOpen(Integer.parseInt(ExtensionConstants. SERVER_DEFAULT_HTTPS_PORT))) { int httpsPort = Integer.parseInt(FrameworkConstants.SERVER_DEFAULT_HTTPS_PORT) + portOffset; String url = automationContext.getContextUrls().getBackEndUrl(); String backendURL = url.replaceAll("(:\\d+)", ":" + httpsPort); ServerAdminClient serverAdminServiceClient = new ServerAdminClient(backendURL, automationContext.getContextTenant().getTenantAdmin().getUserName(), automationContext.getContextTenant().getTenantAdmin().getPassword()); serverAdminServiceClient.shutdown(); while (System.currentTimeMillis() < time && !logOutSuccess) { logOutSuccess = isServerDown(automationContext, portOffset); } log.info("Server stopped successfully..."); } }

Target:
public static void serverShutdown(int portOffset, AutomationContext automationContext) throws CarbonToolsIntegrationTestException { long time = System.currentTimeMillis() + DEFAULT_START_STOP_WAIT_MS; log.info("Shutting down server.."); try { boolean logOutSuccess = false; if (ClientConnectionUtil.isPortOpen( Integer.parseInt(ExtensionConstants.SERVER_DEFAULT_HTTPS_PORT))) { int httpsPort = Integer.parseInt(FrameworkConstants.SERVER_DEFAULT_HTTPS_PORT) + portOffset; String url = automationContext.getContextUrls().getBackEndUrl(); String backendURL = url.replaceAll("(:\\d+)", ":" + httpsPort); ServerAdminClient serverAdminServiceClient; serverAdminServiceClient = new ServerAdminClient(backendURL, automationContext.getContextTenant().getTenantAdmin().getUserName(), automationContext.getContextTenant().getTenantAdmin().getPassword()); serverAdminServiceClient.shutdown(); while (System.currentTimeMillis() < time && !logOutSuccess) { logOutSuccess = isServerDown(portOffset); } log.info("Server stopped successfully..."); } } catch (XPathExpressionException ex) { log.error("Error when reading automation.xml ", ex); throw new CarbonToolsIntegrationTestException("Error when reading automation.xml ", ex); } catch (RemoteException ex) { log.error("Error while shutdown the server ", ex); throw new CarbonToolsIntegrationTestException("Error while shutdown the server ", ex); } }
Source:
private Pod decoratePod(Pod pod) { Volume[] volumes = kubernetesComponentConf.getSecretNamesToMountPaths() .keySet() .stream() .map(secretName -> new VolumeBuilder() .withName(secretVolumeName(secretName)) .withNewSecret() .withSecretName(secretName) .endSecret() .build() ).toArray(Volume[]::new); return new PodBuilder(pod) .editOrNewSpec() .addToVolumes(volumes) .endSpec() .build(); }

Target:
private Pod decoratePod(Pod pod) { final Volume[] volumes = kubernetesComponentConf.getSecretNamesToMountPaths().keySet().stream() .map(secretName -> new VolumeBuilder() .withName(secretVolumeName(secretName)) .withNewSecret() .withSecretName(secretName) .endSecret() .build() ) .toArray(Volume[]::new); return new PodBuilder(pod) .editOrNewSpec() .addToVolumes(volumes) .endSpec() .build(); }
Source:
public void attachWindowConfig(BaseWindowedBolt bolt) { if (windowType == WindowType.COUNT) { bolt.withWindow(BaseWindowedBolt.Count.of(windowSize), BaseWindowedBolt.Count.of(slideInterval)); } else { bolt.withWindow(windowDuration, slidingIntervalDuration); } }

Target:
public void attachWindowConfig(BaseWindowedBolt bolt) { switch(windowType) { case COUNT: bolt.withWindow(BaseWindowedBolt.Count.of(windowSize), BaseWindowedBolt.Count.of(slideInterval)); break; case TIME: bolt.withWindow(windowDuration, slidingIntervalDuration); break; default: throw new RuntimeException("Unknown windowType " + String.valueOf(windowType)); } }
Source:
public String toString() { return String.format(ID.toString()+"=>"+entry.toString()); }

Target:
public String toString() { return String.format("%s=>%s", recordId, entry); }
Source:
public boolean isDeleteByTermEnforced() { if ( deleteByTermEnforced ) { return true; } if ( indexMetadataIsComplete ) { Set<Class<?>> entitiesInvolved = getEntitiesInIndexManager(); if ( entitiesInvolved.size() == 1 ) { return true; } for ( EntityIndexBinding entityIndexBinding : searchIntegrator.getIndexBindings().values() ) { if ( entityIndexBinding.getDocumentBuilder().getMappedSubclasses().containsAll( entitiesInvolved ) ) { return true; } } Set<String> idFieldNames = new HashSet<String>( entitiesInvolved.size() ); for ( Class<?> entity : entitiesInvolved ) { idFieldNames.add( indexManager.getIndexBinding( entity ).getDocumentBuilder().getIdKeywordName() ); } return entitiesInvolved.size() == idFieldNames.size(); } else { return false; } }

Target:
public boolean isDeleteByTermEnforced() { if ( deleteByTermEnforced ) { return true; } if ( indexMetadataIsComplete ) { Set<Class<?>> entitiesInvolved = getEntitiesInIndexManager(); if ( entitiesInvolved.size() == 1 ) { return true; } IdUniquenessResolver idUniquenessResolver = this.serviceManager.requestService( IdUniquenessResolver.class ); try { for ( Class<?> firstEntity : entitiesInvolved ) { boolean firstEntityIsUsingJPAId = indexManager.getIndexBinding( firstEntity ) .getDocumentBuilder() .getTypeMetadata() .isJpaIdUsedAsDocumentId(); boolean followingEntities = false; for ( Class<?> secondEntity : entitiesInvolved ) { if ( firstEntity == secondEntity ) { followingEntities = true; } else if ( followingEntities ) { boolean secondEntityIsUsingJPAId = indexManager.getIndexBinding( secondEntity ) .getDocumentBuilder() .getTypeMetadata() .isJpaIdUsedAsDocumentId(); boolean uniqueIdEqualityMeansEntityEquality = firstEntityIsUsingJPAId && secondEntityIsUsingJPAId && idUniquenessResolver.areIdsUniqueForClasses( firstEntity, secondEntity ); if ( !uniqueIdEqualityMeansEntityEquality ) { return false; } } } } } finally { this.serviceManager.releaseService( IdUniquenessResolver.class ); } return true; } else { return false; } }
Source:
public <T> T get(String claimName, Class<T> requiredType) { Object value = get(claimName); if (value == null) { return null; } if (requiredType == Date.class && value instanceof Long) { value = new Date((Long)value); } if (!requiredType.isInstance(value)) { throw new RequiredTypeException("Expected value to be of type: " + requiredType + ", but was " + value.getClass()); } return requiredType.cast(value); }

Target:
public <T> T get(String claimName, Class<T> requiredType) { Object value = get(claimName); if (value == null) { return null; } if (Claims.EXPIRATION.equals(claimName) || Claims.ISSUED_AT.equals(claimName) || Claims.NOT_BEFORE.equals(claimName) ) { value = getDate(claimName); } if (requiredType == Date.class && value instanceof Long) { value = new Date((Long)value); } if (!requiredType.isInstance(value)) { throw new RequiredTypeException("Expected value to be of type: " + requiredType + ", but was " + value.getClass()); } return requiredType.cast(value); }
Source:
public Collection<IProjectAdapter> getProjectsFor(final IOpenShiftConnection conn) { Set<IProjectAdapter> adapters = getCacheFor(conn); if(adapters == null) { Collection<IProject> projects = conn.<IProject>getResources(ResourceKind.PROJECT); adapters = createEntry(conn); synchronized (adapters) { for (IProject p : projects) { addNewProjectAdapter(adapters, conn, p); } } adapters.forEach(a->notifyAdd(a)); } return new ArrayList<>(adapters); }

Target:
public Collection<IProjectAdapter> getProjectsFor(final IOpenShiftConnection conn) { Set<IProjectAdapter> adapters = null; boolean initialize = false; synchronized (cache) { if(initialize = !hasCacheFor(conn)) { adapters = createEntry(conn); } } if(initialize) { Collection<IProject> projects = conn.<IProject>getResources(ResourceKind.PROJECT); synchronized (adapters) { for (IProject p : projects) { addNewProjectAdapter(adapters, conn, p); } } adapters.forEach(a->notifyAdd(a)); } return new ArrayList<>(getCacheFor(conn)); }
Source:
public MSSQLQuarterDiffFunction() { super("(select sign(i1) * floor(abs(i1)) from (values (datediff(mm, ?1, ?2)/3)) as temp(i1))"); }

Target:
public MSSQLQuarterDiffFunction() { super("round(datediff(mm, ?1, ?2)/3,0,1)"); }
Source:
private SymbolReference<ResolvedReferenceTypeDeclaration> tryToSolveTypeUncached(String name) { String[] nameElements = name.split("\\."); for (int i = nameElements.length; i > 0; i--) { StringBuilder filePath = new StringBuilder(srcDir.getAbsolutePath()); for (int j = 0; j < i; j++) { filePath.append("/") .append(nameElements[j]); } filePath.append(".java"); StringBuilder typeName = new StringBuilder(); for (int j = i - 1; j < nameElements.length; j++) { if (j != i - 1) { typeName.append("."); } typeName.append(nameElements[j]); } File srcFile = new File(filePath.toString()); { Optional<CompilationUnit> compilationUnit = parse(srcFile); if (compilationUnit.isPresent()) { Optional<com.github.javaparser.ast.body.TypeDeclaration<?>> astTypeDeclaration = Navigator.findType(compilationUnit.get(), typeName.toString()); if (astTypeDeclaration.isPresent()) { return SymbolReference.solved(JavaParserFacade.get(this).getTypeDeclaration(astTypeDeclaration.get())); } } } { List<CompilationUnit> compilationUnits = parseDirectory(srcFile.getParentFile()); for (CompilationUnit compilationUnit : compilationUnits) { Optional<com.github.javaparser.ast.body.TypeDeclaration<?>> astTypeDeclaration = Navigator.findType(compilationUnit, typeName.toString()); if (astTypeDeclaration.isPresent()) { return SymbolReference.solved(JavaParserFacade.get(this).getTypeDeclaration(astTypeDeclaration.get())); } } } } return SymbolReference.unsolved(ResolvedReferenceTypeDeclaration.class); }

Target:
private SymbolReference<ResolvedReferenceTypeDeclaration> tryToSolveTypeUncached(String name) { String[] nameElements = name.split("\\."); for (int i = nameElements.length; i > 0; i--) { StringBuilder filePath = new StringBuilder(srcDir.toAbsolutePath().toString()); for (int j = 0; j < i; j++) { filePath.append("/") .append(nameElements[j]); } filePath.append(".java"); StringBuilder typeName = new StringBuilder(); for (int j = i - 1; j < nameElements.length; j++) { if (j != i - 1) { typeName.append("."); } typeName.append(nameElements[j]); } Path srcFile = Paths.get(filePath.toString()); { Optional<CompilationUnit> compilationUnit = parse(srcFile); if (compilationUnit.isPresent()) { Optional<com.github.javaparser.ast.body.TypeDeclaration<?>> astTypeDeclaration = Navigator.findType(compilationUnit.get(), typeName.toString()); if (astTypeDeclaration.isPresent()) { return SymbolReference.solved(JavaParserFacade.get(this).getTypeDeclaration(astTypeDeclaration.get())); } } } { List<CompilationUnit> compilationUnits = parseDirectory(srcFile.getParent()); for (CompilationUnit compilationUnit : compilationUnits) { Optional<com.github.javaparser.ast.body.TypeDeclaration<?>> astTypeDeclaration = Navigator.findType(compilationUnit, typeName.toString()); if (astTypeDeclaration.isPresent()) { return SymbolReference.solved(JavaParserFacade.get(this).getTypeDeclaration(astTypeDeclaration.get())); } } } } return SymbolReference.unsolved(ResolvedReferenceTypeDeclaration.class); }
Source:
private Map<CDOID, CDOObject> updateCDOViewObjectsCache(List<CDORevision> loadedRevisions) { Map<CDOID, CDOObject> cdoIDs = new HashMap<CDOID, CDOObject>(); for (CDORevision cdoRevision : loadedRevisions) { CDOID cdoID = cdoRevision.getID(); if (cdoID != null && !cdoRevision.isResourceNode()) { InternalCDOObject object = getObject(cdoID, true); cdoIDs.put(cdoID, object); } } return cdoIDs; }

Target:
private Map<CDOID, CDOObject> updateCDOViewObjectsCache(List<CDORevision> loadedRevisions) { Map<CDOID, CDOObject> cdoIDs = new HashMap<CDOID, CDOObject>(); CDOLockStateLoadingPolicy lockStateLoadingPolicy = options().getCDOLockStateLoadingPolicy(); for (CDORevision cdoRevision : loadedRevisions) { CDOID cdoID = cdoRevision.getID(); if (cdoID != null && lockStateLoadingPolicy.loadLockState(cdoID)) { boolean isResourceNode = cdoRevision.isResourceNode(); InternalCDOObject object = getObject(cdoID, !isResourceNode); if (object != null) { cdoIDs.put(cdoID, object); } } } return cdoIDs; }
Source:
public static Method findGetter(String propertyName, Class beanClass) { Method result = findMethod(beanClass, "get" + propertyName.substring(0, 1).toUpperCase(Locale.ENGLISH) + propertyName.substring(1)); if (result != null) { return result; } result = findMethod(beanClass, "is" + propertyName.substring(0, 1).toUpperCase(Locale.ENGLISH) + propertyName.substring(1)); if (result != null) { return result; } return null; }

Target:
public static Method findGetter(String propertyName, Class beanClass) { Method result = findMethod(beanClass, "get" + propertyName.substring(0, 1).toUpperCase(Locale.ENGLISH) + propertyName.substring(1)); if (result != null) { result.setAccessible(true); return result; } result = findMethod(beanClass, "is" + propertyName.substring(0, 1).toUpperCase(Locale.ENGLISH) + propertyName.substring(1)); if (result != null) { result.setAccessible(true); return result; } return null; }
Source:
public void testOperators() throws Exception { final String str = "package org.drools.test;\n" + "import " + Person.class.getCanonicalName() + ";\n" + "rule R1 when \n" + " Person(20 < age, 30 > age)\n" + " Person(30 <= age, 40 >= age)\n" + "then\n" + "end"; final KieSession ksession = getKieSession(str); if (testRunType == RUN_TYPE.FLOW_DSL || testRunType == RUN_TYPE.PATTERN_DSL) { String exprId1 = new DRLIdGenerator().getExprId(Person.class, "org.drools.modelcompiler.util.EvaluationUtil." + "greaterThanNumbers(_this.getAge(), 20)"); assertThat(getConstraintString(ksession, 0, 0), containsString(exprId1)); String exprId2 = new DRLIdGenerator().getExprId(Person.class, "org.drools.modelcompiler.util.EvaluationUtil." + "lessThanNumbers(_this.getAge(), 30)"); assertThat(getConstraintString(ksession, 0, 1), containsString(exprId2)); String exprId3 = new DRLIdGenerator().getExprId(Person.class, "org.drools.modelcompiler.util.EvaluationUtil." + "greaterOrEqualNumbers(_this.getAge(), 30)"); assertThat(getConstraintString(ksession, 1, 0), containsString(exprId3)); String exprId4 = new DRLIdGenerator().getExprId(Person.class, "org.drools.modelcompiler.util.EvaluationUtil." + "lessOrEqualNumbers(_this.getAge(), 40)"); assertThat(getConstraintString(ksession, 1, 1), containsString(exprId4)); } final Person p1 = new Person("John", 21); final Person p2 = new Person("Paul", 40); ksession.insert(p1); ksession.insert(p2); assertEquals(1, ksession.fireAllRules()); }

Target:
public void testOperators() throws Exception { final String str = "package org.drools.test;\n" + "import " + Person.class.getCanonicalName() + ";\n" + "rule R1 when \n" + " Person(20 < age, 30 > age)\n" + " Person(30 <= age, 40 >= age)\n" + "then\n" + "end\n" + "rule R2 when \n" + " Person(age > 20, age < 30)\n" + " Person(age >= 30, age <= 40)\n" + "then\n" + "end"; final KieSession ksession = getKieSession(str); assertEquals(4, ReteDumper.collectNodes(ksession).stream().filter(AlphaNode.class::isInstance).count()); final Person p1 = new Person("John", 21); final Person p2 = new Person("Paul", 40); ksession.insert(p1); ksession.insert(p2); assertEquals(2, ksession.fireAllRules()); }
Source:
private boolean validateExternalVnicProfileMapping() { final Set<EngineMessage> externalVnicProfileMappingValidationResult = externalVnicProfileMappingValidator.validateExternalVnicProfileMapping( getParameters().getExternalVnicProfileMappings(), getParameters().getClusterId()); if (externalVnicProfileMappingValidationResult.isEmpty()) { return true; } else { return failValidation(new ArrayList<>(externalVnicProfileMappingValidationResult)); } }

Target:
private boolean validateExternalVnicProfileMapping() { Collection<ExternalVnicProfileMapping> externalVnicProfileMappings = getParameters().getExternalVnicProfileMappings(); Guid clusterId = getParameters().getClusterId(); ValidationResult validationResult = externalVnicProfileMappingValidator .validateExternalVnicProfileMapping(externalVnicProfileMappings, clusterId); return validate(validationResult); }
Source:
public SignupBottomSheetDialog(@NonNull final Context context, @NonNull final SignupSheetListener signupSheetListener) { super(context); final View layout = LayoutInflater.from(context).inflate(R.layout.signup_bottom_sheet_dialog, null); Button termsOfServiceText = layout.findViewById(R.id.signup_tos); termsOfServiceText.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { signupSheetListener.onSignupSheetTermsOfServiceClicked(); } }); termsOfServiceText.setText(Html.fromHtml(String.format( context.getResources().getString(R.string.signup_terms_of_service_text), "<u>", "</u>"))); Button signupWithEmailButton = layout.findViewById(R.id.signup_email); signupWithEmailButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { signupSheetListener.onSignupSheetEmailClicked(); } }); Button signupWithGoogleButton = layout.findViewById(R.id.signup_google); signupWithGoogleButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { signupSheetListener.onSignupSheetGoogleClicked(); } }); setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { signupSheetListener.onSignupSheetCanceled(); } }); setContentView(layout); setTitle(R.string.signup_title); final BottomSheetBehavior behavior = BottomSheetBehavior.from((View) layout.getParent()); setOnShowListener(new OnShowListener() { @Override public void onShow(DialogInterface dialog) { behavior.setPeekHeight(layout.getHeight()); } }); }

Target:
public SignupBottomSheetDialog(@NonNull final Context context, @NonNull final SignupSheetListener signupSheetListener) { super(context); final View layout = LayoutInflater.from(context).inflate(R.layout.signup_bottom_sheet_dialog, null); Button termsOfServiceText = layout.findViewById(R.id.signup_tos); termsOfServiceText.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { signupSheetListener.onSignupSheetTermsOfServiceClicked(); } }); termsOfServiceText.setText(Html.fromHtml(String.format( context.getResources().getString(R.string.signup_terms_of_service_text), "<u>", "</u>"))); Button signupWithEmailButton = layout.findViewById(R.id.signup_email); signupWithEmailButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { signupSheetListener.onSignupSheetEmailClicked(); } }); Button signupWithGoogleButton = layout.findViewById(R.id.signup_google); signupWithGoogleButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { signupSheetListener.onSignupSheetGoogleClicked(); } }); setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { signupSheetListener.onSignupSheetCanceled(); } }); setContentView(layout); setTitle(R.string.sign_up); final BottomSheetBehavior behavior = BottomSheetBehavior.from((View) layout.getParent()); setOnShowListener(new OnShowListener() { @Override public void onShow(DialogInterface dialog) { behavior.setPeekHeight(layout.getHeight()); } }); }
Source:
private void reactAndPost(EventEnvelope event) { EventReactorMethod method = thisClass.reactorOf(event.messageClass(), event.originClass()); DispatchOutcomeHandler .from(method.invoke(this, event)) .onEvents(eventBus::post) .onError(error -> { HandlerFailedUnexpectedly systemEvent = HandlerFailedUnexpectedly .newBuilder() .setEntity(eventAnchor) .setHandledSignal(event.messageId()) .setError(error) .vBuild(); system.postEvent(systemEvent, event.asMessageOrigin()); }) .handle(); }

Target:
private void reactAndPost(EventEnvelope event) { EventReactorMethod method = thisClass.reactorOf(event.messageClass(), event.originClass()); DispatchOutcomeHandler .from(method.invoke(this, event)) .onEvents(eventBus::post) .onError(error -> postFailure(error, event)) .handle(); }
Source:
private static void loadExtensions(ModuleService moduleService, Map<String, Object> argMap) { ExtensionsManager extensionsManager = new ExtensionsManager(); Map<String, ExtensionProxy> proxies = moduleService.getContext().get(ModuleService.EXTENSIONS_MAP); List<File> files = (List<File>)argMap.get("extension-file"); if(files == null) { files = listFiles( ((String) argMap.get("extensions-dir")).replace( "@ENGINE_ETC@", System.getProperty("org.ovirt.engine.exttool.core.engineEtc") ), "properties" ); } for(File f : files) { proxies.put(extensionsManager.load(f), null); } for(Map.Entry<String, ExtensionProxy> entry : proxies.entrySet()) { extensionsManager.initialize(entry.getKey()); entry.setValue(extensionsManager.getExtensionByName(entry.getKey())); } }

Target:
private static void loadExtensions(ModuleService moduleService, Map<String, Object> argMap) { ExtensionsManager extensionsManager = new ExtensionsManager(); Map<String, ExtensionProxy> proxies = moduleService.getContext().get(ModuleService.EXTENSIONS_MAP); List<File> files = (List<File>)argMap.get("extension-file"); if(files == null) { files = listFiles( ((String) argMap.get("extensions-dir")).replace("@ENGINE_ETC@", ENGINE_ETC), "properties" ); } for(File f : files) { proxies.put(extensionsManager.load(f), null); } for(Map.Entry<String, ExtensionProxy> entry : proxies.entrySet()) { extensionsManager.initialize(entry.getKey()); entry.setValue(extensionsManager.getExtensionByName(entry.getKey())); } }
Source:
public void add( Collection<? extends IndexEntryUpdate<?>> updates ) throws IndexEntryConflictException, IOException { Map<CoordinateReferenceSystem,Collection<IndexEntryUpdate<?>>> batchMap = new HashMap<>(); for ( Map.Entry<CoordinateReferenceSystem,SpatialKnownIndex> index : indexMap.entrySet() ) { batchMap.put( index.getKey(), new ArrayList<>() ); } for ( IndexEntryUpdate<?> update : updates ) { selectUpdates( batchMap, update.values() ).add( update ); } for ( CoordinateReferenceSystem crs : batchMap.keySet() ) { indexFactory.selectAndCreate( indexMap, indexId, crs ).getPopulator( descriptor, samplingConfig ).add( batchMap.get( crs ) ); } }

Target:
public void add( Collection<? extends IndexEntryUpdate<?>> updates ) throws IndexEntryConflictException, IOException { Map<CoordinateReferenceSystem,Collection<IndexEntryUpdate<?>>> batchMap = new HashMap<>(); for ( IndexEntryUpdate<?> update : updates ) { selectUpdates( batchMap, update.values() ).add( update ); } for ( CoordinateReferenceSystem crs : batchMap.keySet() ) { SpatialKnownIndex index = indexFactory.selectAndCreate( indexMap, indexId, crs ); index.startPopulation( descriptor, samplingConfig ); index.add( batchMap.get( crs ) ); } }
Source:
public Mono<Integer> forceCloseAllHandles(boolean recursive) { return fluxContext(context -> forceCloseAllHandlesWithTimeout(recursive, null, context)) .reduce(0, Integer::sum); }

Target:
public Mono<Integer> forceCloseAllHandles(boolean recursive) { try { return withContext(context -> forceCloseAllHandlesWithTimeout(recursive, null, context) .reduce(0, Integer::sum)); } catch (RuntimeException ex) { return monoError(logger, ex); } }
Source:
public Collection<Product> getProducts() { return products.values(); }

Target:
public Map<String, Product> getProducts() { return products; }
Source:
protected void executeCommand() { UserProfile profile = getParameters().getUserProfile(); profile.setId(Guid.newGuid()); profile.setUserId(getUserId()); if (!profile.getSshPublicKey().isEmpty() && ( profile.getSshPublicKeyId() == null || profile.getSshPublicKeyId().equals(Guid.Empty))) { profile.setSshPublicKeyId(Guid.newGuid()); } userProfileDao.save(profile); setSucceeded(true); }

Target:
protected void executeCommand() { UserProfile profile = getParameters().getUserProfile(); profile.setId(Guid.newGuid()); profile.setUserId(getUserId()); if (!profile.getSshPublicKey().isEmpty() && Guid.isNullOrEmpty(profile.getSshPublicKeyId())) { profile.setSshPublicKeyId(Guid.newGuid()); } userProfileDao.save(profile); setSucceeded(true); }
Source:
public SetSpecialDaysResponse getSetSpecialDaysResponse( @OrganisationIdentification final String organisationIdentification, @RequestPayload final SetSpecialDaysAsyncRequest request) throws OsgpException { final MeterResponseData meterResponseData = this.configurationService.dequeueSetSpecialDaysResponse(request .getCorrelationUid()); final SetSpecialDaysResponse response = new SetSpecialDaysResponse(); if (meterResponseData != null) { response.setResult(OsgpResultType.fromValue(meterResponseData.getResultType().getValue())); if (meterResponseData.getMessageData() instanceof String) { response.setDescription((String) meterResponseData.getMessageData()); } } else { response.setResult(OsgpResultType.NOT_FOUND); } return response; }

Target:
public SetSpecialDaysResponse getSetSpecialDaysResponse( @OrganisationIdentification final String organisationIdentification, @RequestPayload final SetSpecialDaysAsyncRequest request) { final SetSpecialDaysResponse response = new SetSpecialDaysResponse(); try { final MeterResponseData meterResponseData = this.configurationService.dequeueSetSpecialDaysResponse(request .getCorrelationUid()); response.setResult(OsgpResultType.fromValue(meterResponseData.getResultType().getValue())); if (meterResponseData.getMessageData() instanceof String) { response.setDescription((String) meterResponseData.getMessageData()); } } catch (final FunctionalException e) { if (e.getExceptionType() == FunctionalExceptionType.UNKNOWN_CORRELATION_UID) { response.setResult(OsgpResultType.NOT_FOUND); } else { response.setResult(OsgpResultType.NOT_OK); } } return response; }
Source:
private void highlightDTD( int startOffset) { int closingBracketStartOffset; closingBracketStartOffset = getTagClosingBracketStartOffset(startOffset); highlighting.add(new HighlightingData(startOffset, startOffset + 9, "j")); highlighting.add(new HighlightingData(closingBracketStartOffset, closingBracketStartOffset + 1, "j")); }

Target:
private void highlightDTD( int startOffset) { int closingBracketStartOffset; closingBracketStartOffset = getTagClosingBracketStartOffset(startOffset); addHighlighting(startOffset, startOffset + 9, "j"); addHighlighting(closingBracketStartOffset, closingBracketStartOffset + 1, "j"); }
Source:
private void endTurn(GameBean game) throws GameException { boolean shouldUpdateNextMove = true; if (game.getStage().equals(GameStage.PREPARATION)) { Integer previousPreparationCycle = game.getPreparationCycle(); preparationStageUtil.updateGameStageToMain(game); preparationStageUtil.updateCurrentCycleInitialBuildingNumber(game); preparationStageUtil.updatePreparationCycle(game); Integer newPreparationCycle = game.getPreparationCycle(); boolean preparationFinished = newPreparationCycle == null && !game.getCurrentMove().equals(1); shouldUpdateNextMove = (preparationFinished || previousPreparationCycle.equals(newPreparationCycle)); } else { game.setDiceThrown(false); game.setDiceFirstValue(null); game.setDiceSecondValue(null); } if (shouldUpdateNextMove) { playUtil.updateNextMove(game); } }

Target:
private void endTurn(GameBean game) throws GameException { switch (game.getStage()) { case PREPARATION: Integer previousPreparationCycle = game.getPreparationCycle(); preparationStageUtil.updateGameStageToMain(game); preparationStageUtil.updateCurrentCycleInitialBuildingNumber(game); preparationStageUtil.updatePreparationCycle(game); if (game.getPreparationCycle() == null || previousPreparationCycle.equals(game.getPreparationCycle())) { preparationStageUtil.updateNextMove(game); } break; case MAIN: mainStageUtil.resetDices(game); mainStageUtil.updateNextMove(game); break; } }
Source:
public void select(final int... indices) { log.debug(MessageFormat.format("Set selection {0} to indices {1}]", this, StringUtils.join(indices, ", "))); waitForEnabled(); if (indices.length > 1) assertMultiSelect("multiple selections"); for (int i = 0; i < indices.length; i++) { assertIsLegalIndex(indices[i]); } asyncExec(new VoidResult() { public void run() { widget.setSelection(indices); } }); notifySelect(indices.length); }

Target:
public void select(final int... indices) { log.debug(MessageFormat.format("Set selection {0} to indices {1}]", this, StringUtils.join(indices, ", "))); waitForEnabled(); if (indices.length > 1) assertMultiSelect("multiple selections"); for (int i = 0; i < indices.length; i++) { assertIsLegalIndex(indices[i]); } asyncExec(new VoidResult() { public void run() { for (int i = 0; i < indices.length; i++) { if (i == 0) { widget.setSelection(indices[0]); notifySelect(true); } else { widget.select(indices[i]); notifySelect(false); } } } }); }
Source:
public String createApplication( @NotNull(message = "No application entered to create.") @Valid final Application app ) throws GenieException { log.debug("Called with application: {}", app); final Optional<String> appId = app.getId(); if (appId.isPresent() && this.applicationRepository.existsByUniqueId(appId.get())) { throw new GenieConflictException("An application with id " + appId.get() + " already exists"); } final ApplicationEntity applicationEntity = new ApplicationEntity(); applicationEntity.setUniqueId(app.getId().orElse(UUID.randomUUID().toString())); this.updateEntityWithDtoContents(applicationEntity, app); this.applicationRepository.save(applicationEntity); return applicationEntity.getUniqueId(); }

Target:
public String createApplication( @NotNull(message = "No application entered to create.") @Valid final Application app ) throws GenieException { log.debug("Called with application: {}", app); final ApplicationEntity applicationEntity = new ApplicationEntity(); applicationEntity.setUniqueId(app.getId().orElse(UUID.randomUUID().toString())); this.updateEntityWithDtoContents(applicationEntity, app); try { this.applicationRepository.save(applicationEntity); } catch (final DataIntegrityViolationException e) { throw new GenieConflictException( "An application with id " + applicationEntity.getUniqueId() + " already exists", e ); } return applicationEntity.getUniqueId(); }
Source:
public void monthNameFormat(String pattern) { monthNameFormat = new SimpleDateFormat(pattern, locale); monthNameFormat.setTimeZone(timeZone); for (MonthDescriptor month : months) { month.setLabel(monthNameFormat.format(month.getDate())); } validateAndUpdate(); }

Target:
private void monthNameFormat(String pattern) { monthNameFormat = new SimpleDateFormat(pattern, locale); monthNameFormat.setTimeZone(timeZone); for (MonthDescriptor month : months) { month.setLabel(monthNameFormat.format(month.getDate())); } }
Source:
public void updateLocalPatientsList() { new PatientDAO().getAllPatients().observeOn(AndroidSchedulers.mainThread()).subscribe(patientList -> { final int NO_STRING_ID = R.string.last_vitals_none_label; boolean isFiltering = StringUtils.notNull(mQuery) && !mQuery.isEmpty(); if (isFiltering) { patientList = FilterUtil.getPatientsFilteredByQuery(patientList, mQuery); if (patientList.isEmpty()) { syncedPatientsView.updateListVisibility(false, R.string.search_patient_no_result_for_query, mQuery); } else { syncedPatientsView.updateListVisibility(true, NO_STRING_ID, null); } } else { if (patientList.isEmpty()) { syncedPatientsView.updateListVisibility(false, R.string.search_patient_no_results, null); } else { syncedPatientsView.updateListVisibility(true, NO_STRING_ID, null); } } syncedPatientsView.updateAdapter(patientList); }); }

Target:
public void updateLocalPatientsList() { addSubscription(new PatientDAO().getAllPatients().observeOn(AndroidSchedulers.mainThread()).subscribe(patientList -> { final int NO_STRING_ID = R.string.last_vitals_none_label; boolean isFiltering = StringUtils.notNull(mQuery) && !mQuery.isEmpty(); if (isFiltering) { patientList = FilterUtil.getPatientsFilteredByQuery(patientList, mQuery); if (patientList.isEmpty()) { syncedPatientsView.updateListVisibility(false, R.string.search_patient_no_result_for_query, mQuery); } else { syncedPatientsView.updateListVisibility(true, NO_STRING_ID, null); } } else { if (patientList.isEmpty()) { syncedPatientsView.updateListVisibility(false, R.string.search_patient_no_results, null); } else { syncedPatientsView.updateListVisibility(true, NO_STRING_ID, null); } } syncedPatientsView.updateAdapter(patientList); })); }