auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void start(final Environment env) throws IOException { try { parseCommandLine(); final Provider<Command> p = commands.get(commandName); if (p == null) { String msg = (prefix.isEmpty() ? "Gerrit Code Review" : prefix) + ": " + commandName + ": not found"; throw new UnloggedFailure(1, msg); } final Command cmd = p.get(); if (isAdminCommand(cmd) && !currentUser.get().isAdministrator()) { final String msg = "fatal: Not a Gerrit administrator"; throw new UnloggedFailure(BaseCommand.STATUS_NOT_ADMIN, msg); } else if (isStreamCommand(cmd) && !currentUser.get().isAllowedToStream()) { final String msg = "fatal: Not allowed to run streaming commands"; throw new UnloggedFailure(BaseCommand.STATUS_NO_STREAMING, msg); } if (cmd instanceof BaseCommand) { final BaseCommand bc = (BaseCommand) cmd; if (prefix.isEmpty()) bc.setName(commandName); else bc.setName(prefix + " " + commandName); bc.setArguments(args.toArray(new String[args.size()])); } else if (!args.isEmpty()) { throw new UnloggedFailure(1, commandName + " does not take arguments"); } provideStateTo(cmd); synchronized (this) { this.cmd = cmd; } cmd.start(env); } catch (UnloggedFailure e) { String msg = e.getMessage(); if (!msg.endsWith("\n")) { msg += "\n"; } err.write(msg.getBytes(ENC)); err.flush(); onExit(e.exitCode); } }

Target:
public void start(final Environment env) throws IOException { try { parseCommandLine(); final Provider<Command> p = commands.get(commandName); if (p == null) { String msg = (prefix.isEmpty() ? "Gerrit Code Review" : prefix) + ": " + commandName + ": not found"; throw new UnloggedFailure(1, msg); } final Command cmd = p.get(); if (isAdminCommand(cmd) && !currentUser.get().isAdministrator()) { final String msg = "fatal: Not a Gerrit administrator"; throw new UnloggedFailure(BaseCommand.STATUS_NOT_ADMIN, msg); } if (cmd instanceof BaseCommand) { final BaseCommand bc = (BaseCommand) cmd; if (prefix.isEmpty()) bc.setName(commandName); else bc.setName(prefix + " " + commandName); bc.setArguments(args.toArray(new String[args.size()])); } else if (!args.isEmpty()) { throw new UnloggedFailure(1, commandName + " does not take arguments"); } provideStateTo(cmd); synchronized (this) { this.cmd = cmd; } cmd.start(env); } catch (UnloggedFailure e) { String msg = e.getMessage(); if (!msg.endsWith("\n")) { msg += "\n"; } err.write(msg.getBytes(ENC)); err.flush(); onExit(e.exitCode); } }
Source:
private String getColumnText(Object element, int columnIndex) { TaskReview reviewContainer = (TaskReview) element; switch (columnIndex) { case 0: return reviewContainer.getSummary(); case 1: return reviewContainer.getCr(); case 2: return reviewContainer.getV(); case 3: return reviewContainer.getIncomingChanges(); default: return "unrecognized column"; } }

Target:
private String getColumnText(Object element, int columnIndex) { TaskReview reviewContainer = (TaskReview) element; switch (columnIndex) { case 0: return reviewContainer.getSummary(); case 1: return reviewContainer.getCrString(); case 2: return reviewContainer.getVString(); case 3: return reviewContainer.getIncomingChanges(); default: return ""; } }
Source:
protected void setupLocale(Locale locale) { FacesContext ctx = FacesContext.getCurrentInstance(); if (locale == null && ctx != null) { if (log.isDebugEnabled()) { log.debug("Locale not set, falling back to request locale"); } locale = ctx.getExternalContext().getRequestLocale(); } if (locale == null && ctx != null) { if (log.isDebugEnabled()) { log.debug("Locale not set, falling back to default JSF locale"); } locale = ctx.getApplication().getDefaultLocale(); } if (locale == null) { if (log.isDebugEnabled()) { log.debug("Locale not set, falling back to default locale"); } locale = Locale.getDefault(); } LocaleSelector localeSelector = LocaleSelector.instance(); boolean set = false; if (ctx != null) { Locale jsfDefault = ctx.getApplication().getDefaultLocale(); if (jsfDefault != null && jsfDefault.getLanguage().equals(locale)) { set = true; } else { Iterator<Locale> it = ctx.getApplication().getSupportedLocales(); while (it.hasNext()) { Locale current = it.next(); if (current.equals(locale)) { set = true; break; } } } } if (!set) { if (log.isDebugEnabled()) { log.debug( "Locale was not set to '" + locale + "' as it could not be validated as a supported language."); } } else { localeSelector.setLocale(locale); localeSelector.setCookieEnabled(true); localeSelector.select(); } }

Target:
protected void setupLocale(Locale locale) { FacesContext ctx = FacesContext.getCurrentInstance(); if (locale == null && ctx != null) { log.debug("Locale not set, falling back to request locale"); locale = ctx.getExternalContext().getRequestLocale(); } if (locale == null && ctx != null) { log.debug("Locale not set, falling back to default JSF locale"); locale = ctx.getApplication().getDefaultLocale(); } if (locale == null) { log.debug("Locale not set, falling back to default locale"); locale = Locale.getDefault(); } LocaleSelector localeSelector = LocaleSelector.instance(); boolean set = false; if (ctx != null) { Locale jsfDefault = ctx.getApplication().getDefaultLocale(); if (jsfDefault != null && jsfDefault.getLanguage().equals(locale)) { set = true; } else { Iterator<Locale> it = ctx.getApplication().getSupportedLocales(); while (it.hasNext()) { Locale current = it.next(); if (current.equals(locale)) { set = true; break; } } } } if (!set) { if (log.isDebugEnabled()) { log.debug( "Locale was not set to '" + locale + "' as it could not be validated as a supported language."); } } else { localeSelector.setLocale(locale); localeSelector.setCookieEnabled(true); localeSelector.select(); } }
Source:
public String getLabel(Object o) { if (o instanceof ICBreakpointContext) { ICBreakpoint bp = ((ICBreakpointContext) o).getBreakpoint(); return getBreakpointMainLabel(bp, (ICBreakpointContext) o); } return ""; }

Target:
public String getLabel(Object o) { if (o instanceof ICBreakpointContext) { ICBreakpointContext context = (ICBreakpointContext) o; return getBreakpointMainLabel(context.getBreakpoint(), context); } return ""; }
Source:
public MkSocket(final InputStream input) throws IOException { super(); this.address = InetAddress.getLocalHost(); this.output = new ByteArrayOutputStream(); this.input = input; }

Target:
public MkSocket(final InputStream input) { super(); this.address = InetAddress.getLoopbackAddress(); this.output = new ByteArrayOutputStream(); this.input = input; }
Source:
private void analyseSomeReferencedPackages(PackageVisibilityStatement[] stats, CompilationUnitScope skope) { for (PackageVisibilityStatement export : stats) { PackageBinding pb = export.resolvedPackage; if (pb == null) continue; pb = pb.getIncarnation(this.binding); if (pb != null && pb.hasCompilationUnit(true)) continue; skope.problemReporter().invalidPackageReference(IProblem.PackageDoesNotExistOrIsEmpty, export); } }

Target:
private void analyseSomeReferencedPackages(PackageVisibilityStatement[] stats, CompilationUnitScope skope) { for (PackageVisibilityStatement stat : stats) { PackageBinding pb = stat.resolvedPackage; if (pb == null) continue; pb = pb.getIncarnation(this.binding); if (pb != null && pb.hasCompilationUnit(true)) continue; skope.problemReporter().invalidPackageReference(IProblem.PackageDoesNotExistOrIsEmpty, stat); } }
Source:
public void assertArguments() { ServerConfigurationProvider config = mock(ServerConfigurationProvider.class); when(config.getUrl()).thenReturn("https when(config.getUserName()).thenReturn("snd\\user_cp"); when(config.getUserPassword()).thenReturn("password"); MaskedArgumentListBuilder arguments = new LabelCommand(config, "LABEL", "WORKSPACE", "PATH").getArguments(); assertNotNull("Arguments were null", arguments); assertEquals("label LABEL PATH -version:WWORKSPACE -noprompt -recursive -server:https }

Target:
public void assertArguments() { ServerConfigurationProvider config = mock(ServerConfigurationProvider.class); when(config.getUrl()).thenReturn("<LINK_0>"); when(config.getUserName()).thenReturn("snd\\user_cp"); when(config.getUserPassword()).thenReturn("password"); MaskedArgumentListBuilder arguments = new LabelCommand(config, "int_build.10", "Jenkins-JOB-MASTER", ".").getArguments(); assertNotNull("Arguments were null", arguments); assertEquals("label int_build.10 . -version:WJenkins-JOB-MASTER -comment:Automatically_applied_by_Jenkins_TFS_plugin -noprompt -recursive -server:<LINK_0> -login:snd\\user_cp,password", arguments.toStringWithQuote()); }
Source:
public void toHeapData() { HeapData anotherHeapData = new HeapData(); Data toOnHeap = anotherHeapData.toHeap(); assertInstanceOf(HeapData.class, toOnHeap); }

Target:
public void toHeapData() { Data data = new HeapData(); Data toHeap = data.toHeap(); assertEquals(data, toHeap); }
Source:
private List<File> scanPath(Path path, int pathIndex) { final String[] resources = path.list(); log(pathIndex + ") Scanning path " + path, Project.MSG_VERBOSE); final List<File> allFiles = new ArrayList<>(); final List<File> concreteFiles = new ArrayList<>(); for (String resource : resources) { final File file = new File(resource); if (file.isFile()) { concreteFiles.add(file); } else { final DirectoryScanner scanner = new DirectoryScanner(); scanner.setBasedir(file); scanner.scan(); final List<File> scannedFiles = retrieveAllScannedFiles(scanner, pathIndex); allFiles.addAll(scannedFiles); } } if (!concreteFiles.isEmpty()) { log(String.format(Locale.ROOT, "%d) Adding %d files from path %s", pathIndex, concreteFiles.size(), path), Project.MSG_VERBOSE); allFiles.addAll(concreteFiles); } return allFiles; }

Target:
private List<File> scanPath(Path path, int pathIndex) { final String[] resources = path.list(); log(pathIndex + ") Scanning path " + path, Project.MSG_VERBOSE); final List<File> allFiles = new ArrayList<>(); int concreteFilesCount = 0; for (String resource : resources) { final File file = new File(resource); if (file.isFile()) { concreteFilesCount++; allFiles.add(file); } else { final DirectoryScanner scanner = new DirectoryScanner(); scanner.setBasedir(file); scanner.scan(); final List<File> scannedFiles = retrieveAllScannedFiles(scanner, pathIndex); allFiles.addAll(scannedFiles); } } if (concreteFilesCount > 0) { log(String.format(Locale.ROOT, "%d) Adding %d files from path %s", pathIndex, concreteFilesCount, path), Project.MSG_VERBOSE); } return allFiles; }
Source:
public static int convertMediaTypeToConstant(Media.MediaType mediaType) { if (mediaType.equals(Media.MediaType.PICTURE)){ return Constants.MEDIA_TYPE_IMAGE; } else if (mediaType.equals(Media.MediaType.VIDEO)){ return Constants.MEDIA_TYPE_VIDEO; } return 0; }

Target:
public int convertMediaTypeToConstant(Media.MediaType mediaType) { if (mediaType.equals(Media.MediaType.PICTURE)){ return Constants.MEDIA_TYPE_IMAGE; } else if (mediaType.equals(Media.MediaType.VIDEO)){ return Constants.MEDIA_TYPE_VIDEO; } return 0; }
Source:
private Stream<CompilationMessage> validateInjectedTypes( VariableElement field ) { TypeMirror fieldType = field.asType(); if ( injectsAllowedType( fieldType ) ) { return Stream.empty(); } if ( injectsRestrictedType( fieldType ) ) { if ( ignoresWarnings ) { return Stream.empty(); } return Stream.of( new ContextFieldWarning( field, "@%s usage warning: found restricted type <%s> on %s.\n" + "The procedure will not load unless declared via the configuration option 'dbms.security.procedures.unrestricted'.\n" + "You can ignore this warning by passing the option -A%s to the Java compiler", Context.class.getName(), fieldType.toString(), fieldFullName( field ), ProcedureProcessor.IGNORE_CONTEXT_WARNINGS_OPTION ) ); } return Stream.of( new ContextFieldError( field, "@%s usage error: found unsupported type <%s> on field %s, expected one of: %s", Context.class.getName(), fieldType.toString(), fieldFullName( field ), joinTypes( SUPPORTED_TYPES ) ) ); }

Target:
private Stream<CompilationMessage> validateInjectedTypes( VariableElement field ) { TypeMirror fieldType = field.asType(); if ( injectsAllowedType( fieldType ) ) { return Stream.empty(); } if ( injectsRestrictedType( fieldType ) ) { if ( ignoresWarnings ) { return Stream.empty(); } return Stream.of( new ContextFieldWarning( field, "@%s usage warning: found unsupported restricted type <%s> on %s.\n" + "The procedure will not load unless declared via the configuration option 'dbms.security.procedures.unrestricted'.\n" + "You can ignore this warning by passing the option -A%s to the Java compiler", Context.class.getName(), fieldType.toString(), fieldFullName( field ), IGNORE_CONTEXT_WARNINGS_OPTION ) ); } return Stream.of( new ContextFieldError( field, "@%s usage error: found unknown type <%s> on field %s, expected one of: %s", Context.class.getName(), fieldType.toString(), fieldFullName( field ), joinTypes( SUPPORTED_TYPES ) ) ); }
Source:
public static DescriptionBuilder forClass(Class<?> testClass) { return new DescriptionBuilder(testClass); }

Target:
public static ClassBasedDescriptionBuilder forClass(Class<?> testClass) { return new ClassBasedDescriptionBuilder(testClass); }
Source:
private void check(ProgramState state, BinaryExpressionTree element) { Constraint leftConstraint = state.getConstraint(state.peekStack(1)); Constraint rightConstraint = state.getConstraint(state.peekStack(0)); boolean leftIsUndefined = leftConstraint.isStricterOrEqualTo(Constraint.UNDEFINED); boolean rightIsUndefined = rightConstraint.isStricterOrEqualTo(Constraint.UNDEFINED); final boolean leftIsNan = leftConstraint.isStricterOrEqualTo(Constraint.NAN); final boolean rightIsNan = rightConstraint.isStricterOrEqualTo(Constraint.NAN); if (checkObjectIsComparedNumerically(leftConstraint, rightConstraint)) { raiseIssue(element, true, false, "an Object"); } else if (checkObjectIsComparedNumerically(rightConstraint, leftConstraint)) { raiseIssue(element, false, true, "an Object"); } else if (leftIsUndefined || rightIsUndefined) { raiseIssue(element, leftIsUndefined, rightIsUndefined, "\"undefined\""); } else if (leftIsNan || rightIsNan) { raiseIssue(element, leftIsNan, rightIsNan, "NaN"); } }

Target:
private void check(ProgramState state, BinaryExpressionTree element) { final Constraint leftConstraint = state.getConstraint(state.peekStack(1)); final Constraint rightConstraint = state.getConstraint(state.peekStack(0)); final boolean leftIsUndefined = leftConstraint.isStricterOrEqualTo(Constraint.UNDEFINED); final boolean rightIsUndefined = rightConstraint.isStricterOrEqualTo(Constraint.UNDEFINED); final boolean leftIsNan = leftConstraint.isStricterOrEqualTo(Constraint.NAN); final boolean rightIsNan = rightConstraint.isStricterOrEqualTo(Constraint.NAN); if (checkObjectIsComparedNumerically(leftConstraint, rightConstraint)) { raiseIssue(element, true, false, "an Object"); } else if (checkObjectIsComparedNumerically(rightConstraint, leftConstraint)) { raiseIssue(element, false, true, "an Object"); } else if (leftIsUndefined || rightIsUndefined) { raiseIssue(element, leftIsUndefined, rightIsUndefined, "\"undefined\""); } else if (leftIsNan || rightIsNan) { raiseIssue(element, leftIsNan, rightIsNan, "NaN"); } }
Source:
public void testGetSolverState() throws Exception { KieServerAssert.assertSuccess( solverClient.createSolver( CONTAINER_1_ID, SOLVER_1_ID, SOLVER_1_CONFIG ) ); ServiceResponse<SolverInstance> solverState = solverClient.getSolverState(CONTAINER_1_ID, SOLVER_1_ID); KieServerAssert.assertSuccess(solverState); SolverInstance returnedInstance = solverState.getResult(); assertEquals(CONTAINER_1_ID, returnedInstance.getContainerId()); assertEquals( SOLVER_1_CONFIG, returnedInstance.getSolverConfigFile() ); assertEquals( SOLVER_1_ID, returnedInstance.getSolverId() ); assertEquals( SolverInstance.getSolverInstanceKey( CONTAINER_1_ID, SOLVER_1_ID ), returnedInstance.getSolverInstanceKey()); assertEquals( SolverInstance.SolverStatus.NOT_SOLVING, returnedInstance.getStatus()); assertNull( returnedInstance.getScoreWrapper() ); }

Target:
public void testGetSolverState() throws Exception { KieServerAssert.assertSuccess( solverClient.createSolver( CONTAINER_1_ID, SOLVER_1_ID, SOLVER_1_CONFIG ) ); ServiceResponse<SolverInstance> solverState = solverClient.getSolverState(CONTAINER_1_ID, SOLVER_1_ID); KieServerAssert.assertSuccess(solverState); SolverInstance returnedInstance = solverState.getResult(); assertEquals(CONTAINER_1_ID, returnedInstance.getContainerId()); assertEquals( SOLVER_1_CONFIG, returnedInstance.getSolverConfigFile() ); assertEquals( SOLVER_1_ID, returnedInstance.getSolverId() ); assertEquals( SolverInstance.getSolverInstanceKey( CONTAINER_1_ID, SOLVER_1_ID ), returnedInstance.getSolverInstanceKey()); assertEquals( SolverInstance.SolverStatus.NOT_SOLVING, returnedInstance.getStatus()); assertNotNull( returnedInstance.getScoreWrapper() ); assertNull( returnedInstance.getScoreWrapper().toScore() ); }
Source:
private List<Long> getInstancesToMigrate(Migration migration) throws InvalidKieServerException, PlanNotFoundException { List<Long> instanceIds = migration.getDefinition().getProcessInstanceIds(); Plan plan = planService.get(migration.getDefinition().getPlanId()); if (instanceIds == null || instanceIds.isEmpty()) { boolean allFetched = false; int page = 0; while (!allFetched) { List<ProcessInstance> instances = kieService.getQueryServicesClient(migration.getDefinition().getKieserverId()) .findProcessInstancesByContainerId(plan.getSourceContainerId(), QUERY_PROCESS_INSTANCE_STATUSES, page++, QUERY_PAGE_SIZE); instances.stream().forEach(p -> instanceIds.add(p.getId())); if (instances.size() < QUERY_PAGE_SIZE) { allFetched = true; } } } if (migration.getReports() == null || migration.getReports().isEmpty()) { return instanceIds; } List<Long> migratedInstances = migration.getReports().stream().map(r -> r.getMigrationId()).collect(Collectors.toList()); return instanceIds.stream().filter(id -> !migratedInstances.contains(id)).collect(Collectors.toList()); }

Target:
private List<Long> getInstancesToMigrate(Migration migration) throws InvalidKieServerException, PlanNotFoundException { List<Long> instanceIds = migration.getDefinition().getProcessInstanceIds(); List<Long> migratedInstances = new ArrayList<>(); if (migration.getReports() != null && !migration.getReports().isEmpty()) { migration.getReports().stream().map(r -> r.getProcessInstanceId()).forEach(id -> migratedInstances.add(id)); } Plan plan = planService.get(migration.getDefinition().getPlanId()); if (instanceIds == null || instanceIds.isEmpty()) { boolean allFetched = false; int page = 0; while (!allFetched) { List<ProcessInstance> instances = kieService.getQueryServicesClient(migration.getDefinition().getKieserverId()) .findProcessInstancesByContainerId(plan.getSourceContainerId(), QUERY_PROCESS_INSTANCE_STATUSES, page++, QUERY_PAGE_SIZE); instances.stream().forEach(p -> instanceIds.add(p.getId())); if (instances.size() < QUERY_PAGE_SIZE) { allFetched = true; } } } return instanceIds.stream().filter(id -> !migratedInstances.contains(id)).collect(Collectors.toList()); }
Source:
public IgniteInternalFuture<Void> purgePartitionsExclusively(CacheGroupContext grp, List<GridDhtLocalPartition> parts) throws IgniteCheckedException { validateCacheGroupForExclusivePurge(grp); if (F.isEmpty(parts)) return new GridFinishedFuture<>(); GroupEvictionContext grpEvictionCtx = evictionGroupsMap.computeIfAbsent( grp.groupId(), (k) -> new GroupEvictionContext(grp)); ExclusivePurgeFuture fut = new ExclusivePurgeFuture(grpEvictionCtx, parts); synchronized (mux) { if (grpEvictionCtx.exclPurgeFut != null) throw new IgniteCheckedException("Only one exclusive purge can be scheduled for the same cache group." + " [grpId=" + grp.groupId() + "]"); Set<Integer> res = new HashSet<>(); for (TaskId taskId : grpEvictionCtx.taskIds) res.add(taskId.part); res.retainAll(fut.partIds); if (!res.isEmpty()) throw new IgniteCheckedException("Can't schedule exclusive purge for a partition " + "due to scheduled regular clear for the same partition. [grpId=" + grp.groupId() + ", partIds=" + Arrays.toString(U.toIntArray(res)) + "]"); grpEvictionCtx.exclPurgeFut = fut; fut.listen(f -> { synchronized (mux) { grpEvictionCtx.exclPurgeFut = null; } }); } for (GridDhtLocalPartition part : parts) { if (part.exclusivePurgeAsync(fut.resFut)) fut.onInit(part); } return fut; }

Target:
public IgniteInternalFuture<Void> purgePartitionsExclusively(CacheGroupContext grp, List<GridDhtLocalPartition> parts) throws IgniteCheckedException { validateCacheGroupForExclusivePurge(grp); if (F.isEmpty(parts)) return new GridFinishedFuture<>(); GroupEvictionContext grpEvictionCtx = evictionGroupsMap.computeIfAbsent( grp.groupId(), (k) -> new GroupEvictionContext(grp)); ExclusivePurgeFuture fut = new ExclusivePurgeFuture(grpEvictionCtx, parts); synchronized (mux) { if (grpEvictionCtx.exclPurgeFut != null) { throw new IgniteCheckedException("Only one exclusive purge can be scheduled for the same cache group." + " [grpId=" + grp.groupId() + "]"); } Set<Integer> res = new HashSet<>(); for (TaskId taskId : grpEvictionCtx.taskIds) res.add(taskId.part); res.retainAll(fut.partIds); if (!res.isEmpty()) { throw new IgniteCheckedException("Can't schedule exclusive purge for a partition " + "due to scheduled regular clear for the same partition. [grpId=" + grp.groupId() + ", partIds=" + Arrays.toString(U.toIntArray(res)) + "]"); } grpEvictionCtx.exclPurgeFut = fut; fut.listen(f -> { synchronized (mux) { grpEvictionCtx.exclPurgeFut = null; } }); } for (GridDhtLocalPartition part : parts) { if (part.exclusivePurgeAsync(fut.resFut)) fut.onInit(part); } return fut; }
Source:
public void test1() throws Exception { final File fileToProcess = new File(getNonCompilablePath("SuppressionXpathRegression1.java")); final DefaultConfiguration moduleConfig = createModuleConfig(PackageDeclarationCheck.class); final String[] expectedViolation = { "1:1: " + getCheckMessage(PackageDeclarationCheck.class, PackageDeclarationCheck.MSG_KEY_MISMATCH), }; final List<String> expectedXpathQueries = Collections.singletonList( "/PACKAGE_DEF" ); runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); }

Target:
public void test1() throws Exception { final File fileToProcess = new File(getNonCompilablePath("SuppressionXpathRegression1.java")); final DefaultConfiguration moduleConfig = createModuleConfig(PackageDeclarationCheck.class); final String[] expectedViolation = { "2:1: " + getCheckMessage(PackageDeclarationCheck.class, PackageDeclarationCheck.MSG_KEY_MISMATCH), }; final List<String> expectedXpathQueries = Collections.singletonList( "/PACKAGE_DEF" ); runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); }
Source:
private RegisteredUserDTO convertUserDOToUserDTO(final RegisteredUser user) { if (null == user) { return null; } RegisteredUserDTO userDTO = this.dtoMapper.map(user, RegisteredUserDTO.class); try { userDTO.setLinkedAccounts(this.database.getAuthenticationProvidersByUser(user)); userDTO.setHasSegueAccount(this.userAuthenticationManager.hasLocalCredentials(user)); } catch (SegueDatabaseException e) { log.error("Unable to set linked accounts or local account property for user due to a database error."); } return userDTO; }

Target:
private RegisteredUserDTO convertUserDOToUserDTO(final RegisteredUser user) { if (null == user) { return null; } return this.convertUserDOsToUserDTOs(Collections.singletonList(user)).get(0); }
Source:
public HTableDescriptor getTableDescriptor(TableName tableName) throws TableNotFoundException, IOException { if (tableName == null) { return null; } String bigtableTableName = TableMetadataSetter.getBigtableName(tableName, options); GetTableRequest request = GetTableRequest.newBuilder().setName(bigtableTableName).build(); Table response; try { response = bigtableAdminClient.getTable(request); } catch (Throwable throwable) { throw new IOException("Failed to listTables", throwable); } if (response == null) { return null; } else { return tableAdapter.adapt(response); } }

Target:
public HTableDescriptor getTableDescriptor(TableName tableName) throws TableNotFoundException, IOException { if (tableName == null) { return null; } String bigtableTableName = TableMetadataSetter.getBigtableName(tableName, options); GetTableRequest request = GetTableRequest.newBuilder().setName(bigtableTableName).build(); try { return tableAdapter.adapt(bigtableAdminClient.getTable(request)); } catch (UncheckedExecutionException e) { if (e.getCause() != null && e.getCause() instanceof OperationRuntimeException) { Status status = ((OperationRuntimeException) e.getCause()).getStatus(); if (status.getCode() == Status.NOT_FOUND.getCode()) { throw new TableNotFoundException(tableName); } } throw new IOException("Failed to getTableDescriptor() on " + tableName, e); } catch (Throwable throwable) { throw new IOException("Failed to getTableDescriptor() on " + tableName, throwable); } }
Source:
public Project fetchProjectByName(final String name) throws ProjectManagerException { Project project = null; final ProjectResultHandler handler = new ProjectResultHandler(); try { final List<Project> projects = this.dbOperator .query(ProjectResultHandler.SELECT_ACTIVE_PROJECT_BY_NAME, handler, name); if (projects.isEmpty()) { throw new ProjectManagerException("No active project with name " + name + " exists in db."); } project = projects.get(0); for (final Triple<String, Boolean, Permission> perm : fetchPermissionsForProject(project)) { if (perm.getThird().toFlags() != 0) { setProjectPermission(project, perm); } } } catch (final SQLException ex) { logger.error(ProjectResultHandler.SELECT_ACTIVE_PROJECT_BY_NAME + " failed.", ex); throw new ProjectManagerException( ProjectResultHandler.SELECT_ACTIVE_PROJECT_BY_NAME + " failed.", ex); } return project; }

Target:
public Project fetchProjectByName(final String name) throws ProjectManagerException { Project project = null; final ProjectResultHandler handler = new ProjectResultHandler(); try { final List<Project> projects = this.dbOperator .query(ProjectResultHandler.SELECT_ACTIVE_PROJECT_BY_NAME, handler, name); if (projects.isEmpty()) { return null; } project = projects.get(0); for (final Triple<String, Boolean, Permission> perm : fetchPermissionsForProject(project)) { if (perm.getThird().toFlags() != 0) { setProjectPermission(project, perm); } } } catch (final SQLException ex) { logger.error(ProjectResultHandler.SELECT_ACTIVE_PROJECT_BY_NAME + " failed.", ex); throw new ProjectManagerException( ProjectResultHandler.SELECT_ACTIVE_PROJECT_BY_NAME + " failed.", ex); } return project; }
Source:
public Builder(String code, String name) { if (code == null) { throw new IllegalArgumentException("Code of the authorization module must be specified as non null " + "value"); } if (name == null) { throw new IllegalArgumentException("Name of the authorization module must be specified as non null " + "value"); } if (code.isEmpty()) { throw new IllegalArgumentException("Code of the authorization module must not be empty value"); } if (name.isEmpty()) { throw new IllegalArgumentException("Name of the authorization module must not be empty value"); } this.code = code; this.name = name; }

Target:
public Builder(String code, String name) { if (code == null) { throw new IllegalArgumentException("Code of the authorization module must be specified as non null value"); } if (name == null) { throw new IllegalArgumentException("Name of the authorization module must be specified as non null value"); } if (code.isEmpty()) { throw new IllegalArgumentException("Code of the authorization module must not be empty value"); } if (name.isEmpty()) { throw new IllegalArgumentException("Name of the authorization module must not be empty value"); } this.code = code; this.name = name; }
Source:
public String getPid() { if(this.pid == null) { return null; } return this.pid; }

Target:
public String getPid() { return this.pid; }
Source:
private Property findPropertyById(String id) { return variableScope.lookup(id) .map(VariableScope.Variable::getTypedIdentifier) .orElse(null); }

Target:
private Optional<Property> findPropertyById(String id) { return variableScope.lookup(id) .map(VariableScope.Variable::getTypedIdentifier); }
Source:
public int toIntRange(BoltProtocolVersion minVersion) { if(majorVersion != minVersion.majorVersion) { throw new IllegalArgumentException( "Versions should be from the same version" ); } else if (minorVersion < minVersion.minorVersion) { throw new IllegalArgumentException("Max version should be newest than min version"); } int range = minorVersion - minVersion.minorVersion; int shiftedRange = range << 16; return shiftedRange | toInt(); }

Target:
public int toIntRange( BoltProtocolVersion minVersion ) { if ( majorVersion != minVersion.majorVersion ) { throw new IllegalArgumentException( "Versions should be from the same major version" ); } else if ( minorVersion < minVersion.minorVersion ) { throw new IllegalArgumentException( "Max version should be newer than min version" ); } int range = minorVersion - minVersion.minorVersion; int shiftedRange = range << 16; return shiftedRange | toInt(); }
Source:
public static Status ofCode(int code) { return Arrays.stream(Status.values()) .filter(s -> s.getStatusCode() == code) .findFirst() .orElseThrow(() -> new IllegalArgumentException("There is no known status for this code (" + code + ").")); }

Target:
public static Status ofCode(int code) { return Arrays.stream(Status.values()) .filter(status -> status.getStatusCode() == code) .findFirst() .orElseThrow(() -> new IllegalArgumentException("There is no known status for this code (" + code + ").")); }
Source:
@Nonnull private Set<SourceExpression> parseSourceList() throws DirectiveParseException { Set<SourceExpression> sourceExpressions = new LinkedHashSet<>(); if (this.hasNext(DirectiveValueToken.class)) { boolean parseException = false; Token dv = this.advance(); if (trimRHSWS(dv.value).equalsIgnoreCase("'none'")) { sourceExpressions.add(None.INSTANCE); return sourceExpressions; } for (SubDirectiveValueToken subdv : splitByWSP(dv)) { try { sourceExpressions.add(this.parseSourceExpression(subdv)); } catch (DirectiveValueParseException e) { parseException = true; } } if (parseException) { throw INVALID_SOURCE_LIST; } } return sourceExpressions; }

Target:
@Nonnull private Set<SourceExpression> parseSourceList() throws DirectiveParseException { Set<SourceExpression> sourceExpressions = new LinkedHashSet<>(); if (this.hasNext(DirectiveValueToken.class)) { boolean parseException = false; boolean seenNone = false; Token dv = this.advance(); for (SubDirectiveValueToken subdv : splitByWSP(dv)) { try { SourceExpression se = this.parseSourceExpression(subdv); if (seenNone || se == None.INSTANCE && !sourceExpressions.isEmpty()) { this.error(subdv, "'none' must not be combined with any other source-expression"); throw INVALID_SOURCE_EXPR; } if (se == None.INSTANCE) { seenNone = true; } sourceExpressions.add(se); } catch (DirectiveValueParseException e) { parseException = true; } } if (parseException) { throw INVALID_SOURCE_LIST; } } return sourceExpressions; }
Source:
public static List<ITmfStateInterval> queryHistoryRange(ITmfStateSystem ss, int attributeQuark, long t1, long t2, long resolution, @Nullable IProgressMonitor monitor) throws AttributeNotFoundException, StateSystemDisposedException { List<ITmfStateInterval> intervals = new LinkedList<>(); ITmfStateInterval currentInterval = null; long ts, tEnd; if (t2 < t1 || resolution <= 0) { throw new TimeRangeException("Start:" + t1 + ", End:" + t2 + ", Resolution:" + resolution); } if (t2 > ss.getCurrentEndTime()) { tEnd = ss.getCurrentEndTime(); } else { tEnd = t2; } IProgressMonitor mon = monitor; if (mon == null) { mon = new NullProgressMonitor(); } for (ts = t1; ts <= tEnd; ts += ((currentInterval.getEndTime() - ts) / resolution + 1) * resolution) { if (mon.isCanceled()) { return intervals; } currentInterval = ss.querySingleState(ts, attributeQuark); intervals.add(currentInterval); } if (currentInterval != null && currentInterval.getEndTime() < tEnd) { currentInterval = ss.querySingleState(tEnd, attributeQuark); intervals.add(currentInterval); } return intervals; }

Target:
public static List<ITmfStateInterval> queryHistoryRange(ITmfStateSystem ss, int attributeQuark, long t1, long t2, long resolution, @Nullable IProgressMonitor monitor) throws AttributeNotFoundException, StateSystemDisposedException { List<ITmfStateInterval> intervals = new LinkedList<>(); ITmfStateInterval currentInterval = null; long ts, tEnd; if (t2 < t1 || resolution <= 0) { throw new TimeRangeException(ss.getSSID() + " Start:" + t1 + ", End:" + t2 + ", Resolution:" + resolution); } if (t2 > ss.getCurrentEndTime()) { tEnd = ss.getCurrentEndTime(); } else { tEnd = t2; } IProgressMonitor mon = monitor; if (mon == null) { mon = new NullProgressMonitor(); } for (ts = t1; ts <= tEnd; ts += ((currentInterval.getEndTime() - ts) / resolution + 1) * resolution) { if (mon.isCanceled()) { return intervals; } currentInterval = ss.querySingleState(ts, attributeQuark); intervals.add(currentInterval); } if (currentInterval != null && currentInterval.getEndTime() < tEnd) { currentInterval = ss.querySingleState(tEnd, attributeQuark); intervals.add(currentInterval); } return intervals; }
Source:
public void killedWorker(int port) { LOG.info("killedWorker: removing port " + port + " from the 'assigned port state'"); String taskId = _state.get(Integer.toString(port)); _state.remove(Integer.toString(port)); TaskStatus status = TaskStatus.newBuilder() .setState(TaskState.TASK_FINISHED) .setTaskId(TaskID.newBuilder().setValue(taskId)) .build(); _driver.sendStatusUpdate(status); }

Target:
public void killedWorker(int port) { LOG.info("killedWorker: executor removing port assignment and sending " + "TASK_FINISHED update to Mesos", _executorId, port); TaskID taskId = _taskAssignments.deregister(port); if (taskId == null) { LOG.error("killedWorker: Executor failed to find TaskID for port {}, so not " + "issuing TaskStatus update to Mesos for this dead task.", _executorId, port); return; } TaskStatus status = TaskStatus.newBuilder() .setState(TaskState.TASK_FINISHED) .setTaskId(taskId) .build(); _driver.sendStatusUpdate(status); }
Source:
private void setupPlaybackScreen() { final Activity activity = getActivity(); findPreference(PREF_PLAYBACK_SPEED_LAUNCHER) .setOnPreferenceClickListener(preference -> { VariableSpeedDialog.showDialog(activity); return true; }); findPreference(PREF_PLAYBACK_REWIND_DELTA_LAUNCHER) .setOnPreferenceClickListener(preference -> { MediaplayerActivity.showSkipPreference(activity, MediaplayerActivity.SkipDirection.SKIP_REWIND); return true; }); findPreference(PREF_PLAYBACK_FAST_FORWARD_DELTA_LAUNCHER) .setOnPreferenceClickListener(preference -> { MediaplayerActivity.showSkipPreference(activity, MediaplayerActivity.SkipDirection.SKIP_FORWARD); return true; }); if (!PictureInPictureUtil.supportsPictureInPicture(activity)) { ListPreference behaviour = (ListPreference) findPreference(UserPreferences.PREF_VIDEO_BEHAVIOR); behaviour.setEntries(R.array.video_background_behavior_options_without_pip); behaviour.setEntryValues(R.array.video_background_behavior_values_without_pip); } findPreference(UserPreferences.PREF_QUEUE_ADD_TO_FRONT).setOnPreferenceChangeListener( (preference, newValue) -> { if (newValue instanceof Boolean) { boolean enableKeepInProgressAtFront = ((Boolean) newValue); checkKeepInProgressAtFrontItemVisibility(enableKeepInProgressAtFront); } return true; }); checkKeepInProgressAtFrontItemVisibility(UserPreferences.enqueueAtFront()); }

Target:
private void setupPlaybackScreen() { final Activity activity = getActivity(); findPreference(PREF_PLAYBACK_SPEED_LAUNCHER) .setOnPreferenceClickListener(preference -> { VariableSpeedDialog.showDialog(activity); return true; }); findPreference(PREF_PLAYBACK_REWIND_DELTA_LAUNCHER) .setOnPreferenceClickListener(preference -> { MediaplayerActivity.showSkipPreference(activity, MediaplayerActivity.SkipDirection.SKIP_REWIND); return true; }); findPreference(PREF_PLAYBACK_FAST_FORWARD_DELTA_LAUNCHER) .setOnPreferenceClickListener(preference -> { MediaplayerActivity.showSkipPreference(activity, MediaplayerActivity.SkipDirection.SKIP_FORWARD); return true; }); if (!PictureInPictureUtil.supportsPictureInPicture(activity)) { ListPreference behaviour = (ListPreference) findPreference(UserPreferences.PREF_VIDEO_BEHAVIOR); behaviour.setEntries(R.array.video_background_behavior_options_without_pip); behaviour.setEntryValues(R.array.video_background_behavior_values_without_pip); } buildEnqueueLocationPreference(); }
Source:
protected boolean isExitState(EObject model) { if (currentModel == null) { return false; } if (model == null) { return true; } if (model != currentModel) { } return false; }

Target:
protected boolean isExitState(EObject model) { return currentModel != null && model == null; }
Source:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Path path = (new File(request.getRequestURI())).toPath().normalize(); String requestedUri = path.toString(); if (StringUtils.isNotBlank(getServletContext().getContextPath())) { requestedUri = requestedUri.substring(getServletContext().getContextPath().length()); } String requestedResource = "/index.html"; response.setStatus(HttpStatus.SERVICE_UNAVAILABLE.value()); if (requestedUri.startsWith(assetsPath)) { response.setStatus(HttpStatus.OK.value()); requestedResource = requestedUri; } readResource(requestedResource, response); }

Target:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String requestedUri = request.getRequestURI(); if (StringUtils.isNotBlank(getServletContext().getContextPath())) { requestedUri = requestedUri.substring(getServletContext().getContextPath().length()); } String requestedResource = "/index.html"; response.setStatus(HttpStatus.SERVICE_UNAVAILABLE.value()); if (requestedUri.startsWith(assetsPath)) { response.setStatus(HttpStatus.OK.value()); requestedResource = requestedUri; } readResource(requestedResource, response); } catch (Exception e) { e.printStackTrace(); response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value()); } }
Source:
public List<InputSplit> getSplits( List<InputSplit> splits, Configuration cfg) throws IOException { final List<InputSplit> origSplits = removeIndexFiles(splits); Collections.sort(origSplits, new Comparator<InputSplit>() { public int compare(InputSplit a, InputSplit b) { FileSplit fa = (FileSplit)a, fb = (FileSplit)b; return fa.getPath().compareTo(fb.getPath()); } }); final List<InputSplit> newSplits = new ArrayList<InputSplit>(origSplits.size()); for (int i = 0; i < origSplits.size();) { try { if (cfg.getBoolean(ENABLE_BAI_SPLIT_CALCULATOR, false)) { i = addBAISplits (origSplits, i, newSplits, cfg); } else { i = addIndexedSplits(origSplits, i, newSplits, cfg); } } catch (IOException e) { i = addProbabilisticSplits (origSplits, i, newSplits, cfg); } } return filterByInterval(newSplits, cfg); }

Target:
public List<InputSplit> getSplits( List<InputSplit> splits, Configuration cfg) throws IOException { final List<InputSplit> origSplits = removeIndexFiles(splits); Collections.sort(origSplits, new Comparator<InputSplit>() { public int compare(InputSplit a, InputSplit b) { FileSplit fa = (FileSplit)a, fb = (FileSplit)b; return fa.getPath().compareTo(fb.getPath()); } }); final List<InputSplit> newSplits = new ArrayList<InputSplit>(origSplits.size()); for (int i = 0; i < origSplits.size();) { try { i = addIndexedSplits (origSplits, i, newSplits, cfg); } catch (IOException | ProviderNotFoundException e) { if (cfg.getBoolean(ENABLE_BAI_SPLIT_CALCULATOR, false)) { try { i = addBAISplits (origSplits, i, newSplits, cfg); } catch (IOException | ProviderNotFoundException e2) { i = addProbabilisticSplits (origSplits, i, newSplits, cfg); } } else { i = addProbabilisticSplits (origSplits, i, newSplits, cfg); } } } return filterByInterval(newSplits, cfg); }
Source:
private static void checkFile(final ModelRepository modelRepo, final File file, final Kind kind) { if (modelRepo != null && file != null) { try { synchronized (FolderObserver.class) { if ((kind == ENTRY_CREATE || kind == ENTRY_MODIFY)) { if (parsers.contains(getExtension(file.getName())) && !file.getName().startsWith(".")) { try (FileInputStream inputStream = FileUtils.openInputStream(file)) { modelRepo.addOrRefreshModel(file.getName(), inputStream); } catch (IOException e) { LoggerFactory.getLogger(FolderObserver.class) .warn("Error while opening file during update: {}", file.getAbsolutePath()); } } else { ignoredFiles.add(file); } } else if (kind == ENTRY_DELETE) { modelRepo.removeModel(file.getName()); } } } catch (Exception e) { LoggerFactory.getLogger(FolderObserver.class).error("Error handling update of file '{}': {}.", file.getAbsolutePath(), e.getMessage(), e); } } }

Target:
private static void checkFile(final ModelRepository modelRepo, final File file, final Kind kind) { if (modelRepo != null && file != null) { try { synchronized (FolderObserver.class) { if ((kind == ENTRY_CREATE || kind == ENTRY_MODIFY)) { if (parsers.contains(getExtension(file.getName()))) { try (FileInputStream inputStream = FileUtils.openInputStream(file)) { modelRepo.addOrRefreshModel(file.getName(), inputStream); } catch (IOException e) { LoggerFactory.getLogger(FolderObserver.class) .warn("Error while opening file during update: {}", file.getAbsolutePath()); } } else { ignoredFiles.add(file); } } else if (kind == ENTRY_DELETE) { modelRepo.removeModel(file.getName()); } } } catch (Exception e) { LoggerFactory.getLogger(FolderObserver.class).error("Error handling update of file '{}': {}.", file.getAbsolutePath(), e.getMessage(), e); } } }
Source:
private void upgradeProtocol(ChannelPipeline p, String scheme) throws IOException, GeneralSecurityException { if (p.get(HTTP_HANDLER) != null) { p.remove(HTTP_HANDLER); } if (isSecure(scheme)) { if (p.get(SSL_HANDLER) == null) { p.addFirst(HTTP_HANDLER, createHttpClientCodec); p.addFirst(SSL_HANDLER, new SslHandler(createSSLEngine())); } else { p.addAfter(SSL_HANDLER, HTTP_HANDLER, createHttpClientCodec); } } else { p.addFirst(HTTP_HANDLER, createHttpClientCodec); } }

Target:
private void upgradeProtocol(ChannelPipeline p, String scheme) throws IOException, GeneralSecurityException { if (p.get(HTTP_HANDLER) != null) { p.remove(HTTP_HANDLER); } if (isSecure(scheme)) { if (p.get(SSL_HANDLER) == null) { p.addFirst(HTTP_HANDLER, createHttpClientCodec()); p.addFirst(SSL_HANDLER, new SslHandler(createSSLEngine())); } else { p.addAfter(SSL_HANDLER, HTTP_HANDLER, createHttpClientCodec()); } } else { p.addFirst(HTTP_HANDLER, createHttpClientCodec()); } }
Source:
public CompositeLineConsumer(LineConsumer... lineConsumers) { this.lineConsumers = new ArrayList<>(lineConsumers.length); Arrays.stream(lineConsumers).forEach(this.lineConsumers::add); this.isClosed = false; }

Target:
public CompositeLineConsumer(LineConsumer... lineConsumers) { this.lineConsumers = new CopyOnWriteArrayList<>(lineConsumers); this.isOpen = true; }
Source:
public void testFinishLocalSetup() throws Exception { final XpathFileGeneratorAuditListener logger = new XpathFileGeneratorAuditListener(System.out); logger.finishLocalSetup(); logger.auditStarted(null); logger.auditFinished(null); assertNotNull("instance should not be null", logger); }

Target:
public void testFinishLocalSetup() { final OutputStream out = new ByteArrayOutputStream(); final XpathFileGeneratorAuditListener listener = new XpathFileGeneratorAuditListener(out, AutomaticBean.OutputStreamOptions.CLOSE); listener.finishLocalSetup(); listener.auditStarted(null); listener.auditFinished(null); final String actual = out.toString(); assertTrue("Output should be empty", actual.isEmpty()); }
Source:
public void findAll() throws Exception { List<Capability> capabilities = newArrayList(newCapability().build(), newCapability().build()); driver.addExpectation(onRequestTo("/r/capabilities").withMethod(GET), returnResponse(capabilities)); List<Capability> got = client.findAll(); assertThat(got, deepEquals(capabilities)); }

Target:
public void findAll() throws Exception { List<Capability> capabilities = Lists.newArrayList(newCapability().build(), newCapability().build()); driver.addExpectation(onRequestTo("/r/capabilities").withMethod(GET), returnResponse(capabilities)); List<Capability> got = client.findAll(); assertThat(got, deepEquals(capabilities)); }
Source:
public void onNext(T t) { if (fusionMode != ASYNC) { if (!queue.offer(t)) { onError(new IllegalStateException("Queue is full?!")); return; } } drain(); }

Target:
public void onNext(T t) { if (fusionMode != ASYNC && !queue.offer(t)) { onError(new IllegalStateException("Queue is full?!")); return; } drain(); }
Source:
private void API$hideItem(final ItemStack stack) { try { if (this.hideItem == null) this.getHideItemMethod(); this.hideItem.invoke(null, stack); } catch (final Throwable thr) { Throwables.propagate(thr); } }

Target:
private void API$hideItem(final ItemStack stack) { try { if (this.hideItem == null) this.hideItem = Class.forName(API).getMethod(HIDE_ITEM, ItemStack.class); this.hideItem.invoke(null, stack); } catch (final Throwable thr) { Throwables.propagate(thr); } }
Source:
public Filter toFilter() { if (extractionFn == null) { return new SelectorFilter(dimension, value); } else { final String valueOrNull = Strings.emptyToNull(value); final DruidCompositePredicate predicate = new DruidCompositePredicate() { @Override public boolean applyLong(long value) { return Objects.equals(valueOrNull, String.valueOf(value)); } @Override public boolean apply(Object input) { return Objects.equals(valueOrNull, input); } @Override public String toString() { return value; } }; return new DimensionPredicateFilter(dimension, predicate, extractionFn); } }

Target:
public Filter toFilter() { if (extractionFn == null) { return new SelectorFilter(dimension, value); } else { final String valueOrNull = Strings.emptyToNull(value); final DruidPredicateFactory predicateFactory = new DruidPredicateFactory() { @Override public Predicate<String> makeStringPredicate() { return new Predicate<String>() { @Override public boolean apply(String input) { return Objects.equals(valueOrNull, input); } }; } @Override public DruidLongPredicate makeLongPredicate() { initLongValue(); if (valueAsLong == null) { return new DruidLongPredicate() { @Override public boolean applyLong(long input) { return false; } }; } else { final long unboxedLong = valueAsLong.longValue(); return new DruidLongPredicate() { @Override public boolean applyLong(long input) { return input == unboxedLong; } }; } } }; return new DimensionPredicateFilter(dimension, predicateFactory, extractionFn); } }
Source:
public void clearApplicationData(Context context, LogoutListener logoutListener) { File cacheDirectory = context.getCacheDir(); File applicationDirectory = new File(cacheDirectory.getParent()); if (applicationDirectory.exists()) { String[] fileNames = applicationDirectory.list(); for (String fileName : fileNames) { if (!fileName.equals("lib")) { FileUtils.deleteFile(new File(applicationDirectory, fileName)); } } } sessionManager.logout() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(() -> { Timber.d("All accounts have been removed"); clearImageCache(); defaultPrefs.clearAll(); defaultPrefs.putBoolean("firstrun", false); new Thread(this::updateAllDatabases).start(); logoutListener.onLogoutComplete(); }); }

Target:
public void clearApplicationData(Context context, LogoutListener logoutListener) { File cacheDirectory = context.getCacheDir(); File applicationDirectory = new File(cacheDirectory.getParent()); if (applicationDirectory.exists()) { String[] fileNames = applicationDirectory.list(); for (String fileName : fileNames) { if (!fileName.equals("lib")) { FileUtils.deleteFile(new File(applicationDirectory, fileName)); } } } sessionManager.logout() .andThen(Completable.fromAction(() ->{ Timber.d("All accounts have been removed"); clearImageCache(); defaultPrefs.clearAll(); defaultPrefs.putBoolean("firstrun", false); updateAllDatabases(); } )) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(logoutListener::onLogoutComplete, Timber::e); }