auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private static List<DirectoryUser> queryPrincipals( final ExtensionProxy extension, final String namespace, final ExtMap filter, boolean groupsResolving) { ExtMap inputMap = new ExtMap().mput( Authz.InvokeKeys.QUERY_ENTITY, Authz.QueryEntity.PRINCIPAL ).mput( Authz.InvokeKeys.QUERY_FLAGS, <START> groupsResolving ? Authz.QueryFlags.RESOLVE_GROUPS : Authz.QueryFlags.RESOLVE_GROUPS_NONE <END> ).mput( Authz.InvokeKeys.QUERY_FILTER, filter ).mput( Authz.InvokeKeys.NAMESPACE, namespace ); return populatePrincipals( extension, namespace, inputMap); }</code><technical_language>neat queryFlagValue(groupsResolving, false)</technical_language>

Target:
private static List<DirectoryUser> queryPrincipals( final ExtensionProxy extension, final String namespace, final ExtMap filter, boolean groupsResolving) { ExtMap inputMap = new ExtMap().mput( Authz.InvokeKeys.QUERY_ENTITY, Authz.QueryEntity.PRINCIPAL ).mput( Authz.InvokeKeys.QUERY_FLAGS, queryFlagValue(groupsResolving, false) ).mput( Authz.InvokeKeys.QUERY_FILTER, filter ).mput( Authz.InvokeKeys.NAMESPACE, namespace ); return populatePrincipals( extension, namespace, inputMap); }
Source:
<code>private void collectReadData(final SAMRecord record) { if (record.getSupplementaryAlignmentFlag()) return; metrics.TOTAL_READS++; readLengthHistogram.increment(record.getReadBases().length); if (!record.getReadFailsVendorQualityCheckFlag()) { metrics.PF_READS++; if (isNoiseRead(record)) metrics.PF_NOISE_READS++; if (record.getReadUnmappedFlag() || record.getMappingQuality() == 0) { final byte[] readBases = record.getReadBases(); <START> final boolean revComp = !record.getReadUnmappedFlag() && <END> record.getMappingQuality() == 0 && record.getReadNegativeStrandFlag(); if (!(record instanceof BAMRecord)) { StringUtil.toUpperCase(readBases); } if (adapterUtility.isAdapterSequence(readBases, revComp)) { this.adapterReads++; } } if (!record.getReadUnmappedFlag() && doRefMetrics) { metrics.PF_READS_ALIGNED++; if (record.getReadPairedFlag() && !record.getProperPairFlag()) metrics.PF_READS_IMPROPER_PAIRS++; if (!record.getReadNegativeStrandFlag()) numPositiveStrand++; if (record.getReadPairedFlag() && !record.getMateUnmappedFlag()) { metrics.READS_ALIGNED_IN_PAIRS++; final Integer mateMq = record.getIntegerAttribute(SAMTag.MQ.toString()); if (mateMq == null || mateMq >= MAPPING_QUALITY_THRESHOLD && record.getMappingQuality() >= MAPPING_QUALITY_THRESHOLD) { ++this.chimerasDenominator; if (ChimeraUtil.isChimeric(record, maxInsertSize, expectedOrientations)) { ++this.chimeras; } } } else { if (record.getMappingQuality() >= MAPPING_QUALITY_THRESHOLD) { ++this.chimerasDenominator; if (record.getAttribute(SAMTag.SA.toString()) != null) ++this.chimeras; } } } } }</code><technical_language>This duplicates code in isAdapter() above, side effecting issue. Is a refactor code avoid duplication</technical_language>

Target:
private void collectReadData(final SAMRecord record) { if (record.getSupplementaryAlignmentFlag()) return; metrics.TOTAL_READS++; readLengthHistogram.increment(record.getReadBases().length); if (!record.getReadFailsVendorQualityCheckFlag()) { metrics.PF_READS++; if (isNoiseRead(record)) metrics.PF_NOISE_READS++; if (adapterUtility.isAdapter(record)) { this.adapterReads++; } if (!record.getReadUnmappedFlag() && doRefMetrics) { metrics.PF_READS_ALIGNED++; if (record.getReadPairedFlag() && !record.getProperPairFlag()) metrics.PF_READS_IMPROPER_PAIRS++; if (!record.getReadNegativeStrandFlag()) numPositiveStrand++; if (record.getReadPairedFlag() && !record.getMateUnmappedFlag()) { metrics.READS_ALIGNED_IN_PAIRS++; final Integer mateMq = record.getIntegerAttribute(SAMTag.MQ.toString()); if (mateMq == null || mateMq >= MAPPING_QUALITY_THRESHOLD && record.getMappingQuality() >= MAPPING_QUALITY_THRESHOLD) { ++this.chimerasDenominator; if (ChimeraUtil.isChimeric(record, maxInsertSize, expectedOrientations)) { ++this.chimeras; } } } else { if (record.getMappingQuality() >= MAPPING_QUALITY_THRESHOLD) { ++this.chimerasDenominator; if (record.getAttribute(SAMTag.SA.toString()) != null) ++this.chimeras; } } } } }
Source:
<code>protected RepositoryPath getTrashPath(RepositoryPath path) throws IOException { if (RepositoryFiles.isTrash(path)) { return path; } RepositoryPath trashBasePath = path.getFileSystem().getTrashPath(); RepositoryPath trashPath = rebase(path, trashBasePath); if (!Files.exists(trashPath.getParent().getTarget())) { <START> logger.debug("Creating: dir-[{}]", trashPath.getParent()); <END> Files.createDirectories(trashPath.getParent().getTarget()); } return trashPath; }</code><technical_language>suggestion logger.debug("Creating: [{}]", trashPath.getParent());</technical_language>

Target:
protected RepositoryPath getTrashPath(RepositoryPath path) throws IOException { if (RepositoryFiles.isTrash(path)) { return path; } RepositoryPath trashBasePath = path.getFileSystem().getTrashPath(); RepositoryPath trashPath = rebase(path, trashBasePath); if (!Files.exists(trashPath.getParent().getTarget())) { logger.debug("Creating: [{}]", trashPath.getParent()); Files.createDirectories(trashPath.getParent().getTarget()); } return trashPath; }
Source:
<code>private static void stop() throws Exception { String twillId = verifyTwillId(); TwillController controller = twillRunner.lookup(FLUO_APP_NAME, RunIds.fromString(twillId)); if ((controller != null) && controller.isRunning()) { System.out.print("Stopping Fluo instance " + getAppInfo()+ "..."); controller.stopAndWait(); System.out.println("DONE"); deleteZkData(); } else { <START> System.out.println("WARNING - " + existsButNotRunningMsg()); <END> } }</code><technical_language>user do in this case</technical_language>

Target:
private static void stop() throws Exception { String twillId = verifyTwillId(); TwillController controller = twillRunner.lookup(FLUO_APP_NAME, RunIds.fromString(twillId)); if (controller != null) { System.out.print("Stopping Fluo instance " + getAppInfo()+ "..."); controller.stopAndWait(); System.out.println("DONE"); } else { logExistsButNotRunning(); } deleteZkData(); }
Source:
<code>public EntryHeader(ByteBuffer buffer) { if (useMagic) { if (buffer.getInt() != MAGIC) throw new IllegalStateException(); } this.keyLength = buffer.getShort(); this.metadataLength = buffer.getShort(); this.valueLength = buffer.getInt(); <START> this.internalMetadataLength = buffer.getInt(); <END> this.seqId = buffer.getLong(); this.expiration = buffer.getLong(); }</code><technical_language>SFS this compatible HEADER_SIZE changed, in this case workaround this MAGIC array exist. I need add a magic field, read depending is/isn't present</technical_language>

Target:
public EntryHeader(ByteBuffer buffer) { this(buffer, false); }
Source:
<code>public MySearchResult(Task t, TaskSearchService searchService, String query, String snippet, String snippetText) { <START> super(t.getTaskID(), "Task", t.getName(), query, snippet, snippetText, "", t, searchService); <END> }</code><technical_language>Admittedly, this i18n'ed changes, while it, i18n "Task", "Resource" "Notes" labels? keys in 18n.properties fpr of them, basically calling GanttLanguage.getInstance().getText()</technical_language>

Target:
MySearchResult(Task t, TaskSearchService searchService, String query, String snippet, String snippetText) { super(t.getTaskID(), GanttLanguage.getInstance().getText("generic.task"), t.getName(), query, snippet, snippetText, t, searchService); }
Source:
<code>private ThrottleJobProperty getThrottleJobProperty(Task task) { if (task instanceof Job) { Job<?,?> p = (Job<?,?>) task; if (task instanceof MatrixConfiguration) { <START> p = (Job<?,?>)((MatrixConfiguration)task).getParent(); <END> } ThrottleJobProperty tjp = p.getProperty(ThrottleJobProperty.class); return tjp; } return null; }</code><technical_language>BTW class cast Job required</technical_language>

Target:
private ThrottleJobProperty getThrottleJobProperty(Task task) { if (task instanceof Job) { Job<?,?> p = (Job<?,?>) task; if (task instanceof MatrixConfiguration) { p = ((MatrixConfiguration)task).getParent(); } ThrottleJobProperty tjp = p.getProperty(ThrottleJobProperty.class); return tjp; } return null; }
Source:
<code>public void testExecuteUpdate() throws Exception { try (Connection connection = createConnection("blackhole", "blackhole")) { try (Statement statement = connection.createStatement()) { statement.execute("CREATE TABLE test_execute_update (" + "c_boolean boolean, " + "c_tinyint tinyint, " + "c_smallint smallint, " + "c_integer integer, " + <START> "c_bigint bigint, " + <END> "c_real real, " + "c_double double, " + "c_decimal decimal, " + "c_varchar varchar, " + "c_varbinary varbinary, " + "c_date date, " + "c_time time, " + "c_timestamp timestamp," + "c_null bigint)"); } try (PreparedStatement statement = connection.prepareStatement( "INSERT INTO test_execute_update VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")) { setTestValues(statement); assertEquals(statement.executeUpdate(), 1); } } }</code><technical_language>test java.sql.PreparedStatement#execute (should return true java.sql.Statement#getResultSet return result)</technical_language>

Target:
public void testExecuteUpdate() throws Exception { try (Connection connection = createConnection("blackhole", "blackhole")) { try (Statement statement = connection.createStatement()) { statement.execute("CREATE TABLE test_execute_update (" + "c_boolean boolean, " + "c_bigint bigint, " + "c_double double, " + "c_decimal decimal, " + "c_varchar varchar, " + "c_varbinary varbinary, " + "c_null bigint)"); } try (PreparedStatement statement = connection.prepareStatement( "INSERT INTO test_execute_update VALUES (?, ?, ?, ?, ?, ?, ?)")) { statement.setBoolean(1, true); statement.setLong(2, 5L); statement.setDouble(3, 7.0d); statement.setBigDecimal(4, BigDecimal.valueOf(8L)); statement.setString(5, "abc'xyz"); statement.setBytes(6, "xyz".getBytes(UTF_8)); statement.setNull(7, Types.BIGINT); assertEquals(statement.executeUpdate(), 1); assertFalse(statement.execute()); assertEquals(statement.getUpdateCount(), 1); assertEquals(statement.getLargeUpdateCount(), 1); } try (Statement statement = connection.createStatement()) { statement.execute("DROP TABLE test_execute_update"); } } }
Source:
<code>public void testDefaultProperty() { Properties p = new Properties(); p.put("p1", "v1"); <START> Interpreter intp = new Interpreter(p) { <END> @Override public void open() { } @Override public void close() { } @Override public InterpreterResult interpret(String st, InterpreterContext context) { return null; } @Override public void cancel(InterpreterContext context) { } @Override public FormType getFormType() { return null; } @Override public int getProgress(InterpreterContext context) { return 0; } }; assertEquals(1, intp.getProperty().size()); assertEquals("v1", intp.getProperty().get("p1")); assertEquals("v1", intp.getProperty("p1")); }</code><technical_language>instead of duplicating this error prone a common interpreter test java file define this</technical_language>

Target:
public void testDefaultProperty() { Properties p = new Properties(); p.put("p1", "v1"); Interpreter intp = new DummyInterpreter(p); assertEquals(1, intp.getProperty().size()); assertEquals("v1", intp.getProperty().get("p1")); assertEquals("v1", intp.getProperty("p1")); }
Source:
<code>public Collection<DataManipulator<?, ?>> getContainers() { <START> return null; <END> }</code><technical_language>this return a non-null value</technical_language>

Target:
public Collection<DataManipulator<?, ?>> getContainers() { return Collections.emptyList(); }
Source:
<code>private String toComparableJson(List<JsonObject> bodyParts) { JsonArray array = new JsonArray( bodyParts.size() ); for ( JsonObject bodyPart : bodyParts ) { array.add( bodyPart ); } <START> return array.toString(); <END> }</code><technical_language>this format JSON in a reliable way</technical_language>

Target:
private String toComparableJson(List<JsonObject> bodyParts) { JsonArray array = new JsonArray( bodyParts.size() ); for ( JsonObject bodyPart : bodyParts ) { array.add( bodyPart ); } return gson.toJson( array ); }
Source:
<code>public String getUnifiedDiff() { PatchList patchList; try { patchList = getPatchList(); if (patchList.getOldId() == null) { return "[Octopus merge; cannot be formatted as a diff.]\n"; } } catch (PatchListNotAvailableException e) { log.error("Cannot format patch", e); return ""; } TemporaryBuffer.Heap buf = <START> new TemporaryBuffer.Heap(8192, args.settings.maximumDiffSize); <END> try (DiffFormatter fmt = new DiffFormatter(buf)) { Repository git; try { git = args.server.openRepository(change.getProject()); } catch (IOException e) { log.error("Cannot open repository to format patch", e); return ""; } try { fmt.setRepository(git); fmt.setDetectRenames(true); fmt.format(patchList.getOldId(), patchList.getNewId()); return RawParseUtils.decode(buf.toByteArray()); } catch (IOException e) { if (JGitText.get().inMemoryBufferLimitExceeded.equals(e.getMessage())) { return ""; } log.error("Cannot format patch", e); return ""; } finally { git.close(); } } }</code><technical_language>I 8k is small for est. size. force ArrayList grow slowly 1 2 4 entries diff is built. do: Math.min(32*1024, args.settings.maximumDiffSize) estimate</technical_language>

Target:
public String getUnifiedDiff() { PatchList patchList; try { patchList = getPatchList(); if (patchList.getOldId() == null) { return "[Octopus merge; cannot be formatted as a diff.]\n"; } } catch (PatchListNotAvailableException e) { log.error("Cannot format patch", e); return ""; } TemporaryBuffer.Heap buf = new TemporaryBuffer.Heap(HEAP_EST_SIZE, args.settings.maximumDiffSize); try (DiffFormatter fmt = new DiffFormatter(buf)) { Repository git; try { git = args.server.openRepository(change.getProject()); } catch (IOException e) { log.error("Cannot open repository to format patch", e); return ""; } try { fmt.setRepository(git); fmt.setDetectRenames(true); fmt.format(patchList.getOldId(), patchList.getNewId()); return RawParseUtils.decode(buf.toByteArray()); } catch (IOException e) { if (JGitText.get().inMemoryBufferLimitExceeded.equals(e.getMessage())) { return ""; } log.error("Cannot format patch", e); return ""; } finally { git.close(); } } }
Source:
<code><START> protected ApplicationInfo getAppInfo() { <END> try { return context.getPackageManager().getApplicationInfo(context.getPackageName(), 0); } catch (final PackageManager.NameNotFoundException e) { return null; } }</code><technical_language>suggestion /* package */ ApplicationInfo getAppInfo() {</technical_language>

Target:
private ApplicationInfo getAppInfo() { try { return mContext.getPackageManager().getApplicationInfo(mContext.getPackageName(), 0); } catch (final PackageManager.NameNotFoundException e) { return null; } }
Source:
<code>public boolean removeJobs(String sessionId, List<String> jobsId) throws RestException { try { checkAccess(sessionId, "DELETE jobs/"); <START> Scheduler s = checkAccess(sessionId, "DELETE jobs/" + jobsId.get(0)); <END> return s.removeJobs(jobsId.stream().map(JobIdImpl::makeJobId).collect(Collectors.toList())); } catch (SchedulerException e) { throw RestException.wrapExceptionToRest(e); } }</code><technical_language>check if jobsId is empty not</technical_language>

Target:
public boolean removeJobs(String sessionId, List<String> jobsId) throws RestException { try { checkAccess(sessionId, "DELETE jobs/"); Scheduler s = checkAccess(sessionId, "DELETE jobs/" + (jobsId.isEmpty() ? "" : jobsId.get(0))); return s.removeJobs(jobsId.stream().map(JobIdImpl::makeJobId).collect(Collectors.toList())); } catch (SchedulerException e) { throw RestException.wrapExceptionToRest(e); } }
Source:
<code>private Map<Node, Map<TopicPartition, ListOffsetRequest.PartitionData>> groupListOffsetRequests( Map<TopicPartition, Long> timestampsToSearch, Set<TopicPartition> partitionsToRetry) { final Map<TopicPartition, ListOffsetRequest.PartitionData> partitionDataMap = new HashMap<>(); for (Map.Entry<TopicPartition, Long> entry: timestampsToSearch.entrySet()) { TopicPartition tp = entry.getKey(); Long offset = entry.getValue(); Optional<Metadata.LeaderAndEpoch> leaderAndEpochOpt = metadata.currentLeader(tp); if (!leaderAndEpochOpt.isPresent()) { log.debug("Leader for partition is unknown for fetching offset {}", tp, offset); metadata.requestUpdate(); partitionsToRetry.add(tp); } else { Metadata.LeaderAndEpoch leaderAndEpoch = leaderAndEpochOpt.get(); Node leader = leaderAndEpoch.leader; <START> <END> if (client.isUnavailable(leader)) { client.maybeThrowAuthFailure(leader); log.debug("Leader for partition is unavailable for fetching offset until reconnect backoff expires", leader, tp); partitionsToRetry.add(tp); } else { partitionDataMap.put(tp, new ListOffsetRequest.PartitionData(offset, leaderAndEpoch.epoch)); } } } return regroupPartitionMapByNode(partitionDataMap); }</code><technical_language>This condition exist anymore</technical_language>

Target:
private Map<Node, Map<TopicPartition, ListOffsetRequest.PartitionData>> groupListOffsetRequests( Map<TopicPartition, Long> timestampsToSearch, Set<TopicPartition> partitionsToRetry) { final Map<TopicPartition, ListOffsetRequest.PartitionData> partitionDataMap = new HashMap<>(); for (Map.Entry<TopicPartition, Long> entry: timestampsToSearch.entrySet()) { TopicPartition tp = entry.getKey(); Long offset = entry.getValue(); Metadata.LeaderAndEpoch leaderAndEpoch = metadata.currentLeader(tp); if (!leaderAndEpoch.leader.isPresent()) { log.debug("Leader for partition is unknown for fetching offset {}", tp, offset); metadata.requestUpdate(); partitionsToRetry.add(tp); } else { Node leader = leaderAndEpoch.leader.get(); if (client.isUnavailable(leader)) { client.maybeThrowAuthFailure(leader); log.debug("Leader for partition is unavailable for fetching offset until reconnect backoff expires", leader, tp); partitionsToRetry.add(tp); } else { partitionDataMap.put(tp, new ListOffsetRequest.PartitionData(offset, leaderAndEpoch.epoch)); } } } return regroupPartitionMapByNode(partitionDataMap); }
Source:
<code>public void testNonExistentVersion() throws Exception { HttpResponse localVersionNegotiationResponse = HttpResponse.builder().statusCode(300).message("HTTP/1.1 300 Multiple Choices").payload( payloadFromResourceWithContentType("/glanceVersionResponseVersionUnavailable.json", "application/json")).build(); GlanceApi apiWhenExist = requestsSendResponses(keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, versionNegotiationRequest, localVersionNegotiationResponse); try { apiWhenExist.getImageApiForZone("az-1.region-a.geo-1").list(); } catch (UncheckedExecutionException e) { if (e.getCause().getClass() == HttpException.class) return; } <START> fail("Did not throw expected HttpException"); <END> }</code><technical_language>Instead of try...catch...fail, @Test(expected = HttpException) here</technical_language>

Target:
public void testNonExistentVersion() throws Exception { HttpResponse localVersionNegotiationResponse = HttpResponse.builder().statusCode(300).message("HTTP/1.1 300 Multiple Choices").payload( payloadFromResourceWithContentType("/glanceVersionResponseVersionUnavailable.json", "application/json")).build(); GlanceApi apiWhenExist = requestsSendResponses(keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, versionNegotiationRequest, localVersionNegotiationResponse); apiWhenExist.getImageApiForZone("az-1.region-a.geo-1").list(); }
Source:
<code>private static String buildExceptionMessage(final Error error, final ImmutableList<Integer> expectedStatusCodes, final int statusCode) { <START> final Joiner joiner = Joiner.on(','); <END> return error == null ? String.format( "Expected a status code of %s but got %d. Could not parse the response for additional information.", joiner.join(expectedStatusCodes), statusCode ) : String.format( "Expected a status code of %s but got %d. Error message: \"%s\"", joiner.join(expectedStatusCodes), statusCode, error.getMessage() ); }</code><technical_language>For readability, join ", " (with a space comma)</technical_language>

Target:
private static String buildExceptionMessage(final Error error, final ImmutableList<Integer> expectedStatusCodes, final int statusCode) { final Joiner joiner = Joiner.on(", "); return error == null ? String.format( "Expected a status code of %s but got %d. Could not parse the response for additional information.", joiner.join(expectedStatusCodes), statusCode ) : String.format( "Expected a status code of %s but got %d. Error message: \"%s\"", joiner.join(expectedStatusCodes), statusCode, error.getMessage() ); }
Source:
<code>public void shouldGetReports() { when(commcareHttpClient.reportsListMetadataRequest(configService.getByName(null).getAccountConfig())).thenReturn(getResponseForReportsList()); ReportsMetadataInfo reportsMetadataInfo = reportService.getReportsList(); assertThat(reportsMetadataInfo.getMetadataInfo().getTotalCount(), equalTo(2)); assertThat(reportsMetadataInfo.getReportMetadataInfoList().size(), equalTo(2)); assertThat(reportsMetadataInfo.getReportMetadataInfoList().get(0).getColumns().size(), equalTo(3)); assertThat(reportsMetadataInfo.getReportMetadataInfoList().get(0).getFilters().size(), equalTo(2)); <START> } <END></code><technical_language>please check more values, list size</technical_language>

Target:
public void shouldGetReports() { ReportsMetadataInfo reportsMetadataInfo = prepareReportsMetadataInfo(); when(commcareHttpClient.reportsListMetadataRequest(configService.getByName(null).getAccountConfig())).thenReturn(getResponseForReportsListMetadata()); ReportsMetadataInfo fetched = reportService.getReportsList(); assertEquals(reportsMetadataInfo, fetched); }
Source:
<code>public static String pathToRemoteSystem(IHost host, String path, String append) { boolean hostIsWindows = hostIsWindows(host); char sep = hostIsWindows ? WINDOWS_SEPARATOR : UNIX_SEPARATOR; <START> boolean endsWithSep = path.endsWith(Character.toString(WINDOWS_SEPARATOR)) || path.endsWith(Character.toString(UNIX_SEPARATOR)); <END> String path2 = append == null ? path : (endsWithSep ? path : path + sep) + append; String path3 = hostIsWindows ? separatorsToWindows(path2) : separatorsToUnix(path2); return path3; }</code><technical_language>do need check for separators ? 'sep'</technical_language>

Target:
public static String pathToRemoteSystem(IHost host, String path, String append) { boolean hostIsWindows = isHostWindows(host); char sep = hostIsWindows ? WINDOWS_SEPARATOR : UNIX_SEPARATOR; boolean endsWithSep = path.endsWith(Character.toString(WINDOWS_SEPARATOR)) || path.endsWith(Character.toString(UNIX_SEPARATOR)); String path2 = append == null ? path : (endsWithSep ? path : path + sep) + append; String path3 = hostIsWindows ? separatorsToWindows(path2) : separatorsToUnix(path2); return path3; }
Source:
<code>public Response getPMMLAvailability(@PathParam("algorithmName") String algorithmName, @QueryParam("format") String format) { if (algorithmName == null) { return Response.status(Response.Status.BAD_REQUEST).entity("Cannot find the algorithm name from the URI.") .build(); } <START> if (format == null || format.equals("pmml")) { <END> List<MLAlgorithm> mlAlgorithms = MLCoreServiceValueHolder.getInstance().getAlgorithms(); for (MLAlgorithm mlAlgorithm : mlAlgorithms) { if (algorithmName.equals(mlAlgorithm.getName()) && mlAlgorithm.getPmmlExportable()) { return Response.ok().build(); } } return Response.status(Response.Status.NOT_FOUND) .entity("PMML downoald not supported for : " + algorithmName).build(); } else { return Response.status(Response.Status.BAD_REQUEST).entity("unidentified value for query parameter") .build(); } }</code><technical_language>enum for pmml right</technical_language>

Target:
public Response getPMMLAvailability(@PathParam("algorithmName") String algorithmName, @QueryParam("format") String format) { if (algorithmName == null) { return Response.status(Response.Status.BAD_REQUEST).entity("Cannot find the algorithm name from the URI.") .build(); } if (format == null || format.equals(MLConstants.ML_MODEL_FORMAT_PMML)) { List<MLAlgorithm> mlAlgorithms = MLCoreServiceValueHolder.getInstance().getAlgorithms(); for (MLAlgorithm mlAlgorithm : mlAlgorithms) { if (algorithmName.equals(mlAlgorithm.getName()) && mlAlgorithm.getPmmlExportable()) { return Response.ok().build(); } } return Response.status(Response.Status.NOT_FOUND) .entity("PMML download not supported for : " + algorithmName).build(); } else { return Response.status(Response.Status.BAD_REQUEST).entity("unidentified value for query parameter") .build(); } }
Source:
<code>private MPMetrics(Context context, String token) { mContext = context; mToken = token; mCarrier = getCarrier(); mModel = getModel(); mVersion = getVersion(); mDeviceId = getDeviceId(); mSuperProperties = new JSONObject(); mDbAdapter = new MPDbAdapter(mContext, mToken); mDbAdapter.cleanupEvents(System.currentTimeMillis() - MPConfig.DATA_EXPIRATION, MPDbAdapter.EVENTS_TABLE); mDbAdapter.cleanupEvents(System.currentTimeMillis() - MPConfig.DATA_EXPIRATION, MPDbAdapter.PEOPLE_TABLE); sExecutor.setKeepAliveTime(MPConfig.SUBMIT_THREAD_TTL, TimeUnit.MILLISECONDS); mTimerHandler = new UniqueHandler(); <START> mPushPref = context.getSharedPreferences("mpPushPref", 0); <END> }</code><technical_language>Prefer predefined constants i.e. MODE_PRIVATE preferable fully qualified package name, i.e. 'com.mixpanel.android.mpmetrics.MPMetrics'</technical_language>

Target:
private MPMetrics(Context context, String token) { mContext = context; mToken = token; mCarrier = getCarrier(); mModel = getModel(); mVersion = getVersion(); mDeviceId = getDeviceId(); mSuperProperties = new JSONObject(); mDbAdapter = new MPDbAdapter(mContext, mToken); mDbAdapter.cleanupEvents(System.currentTimeMillis() - MPConfig.DATA_EXPIRATION, MPDbAdapter.EVENTS_TABLE); mDbAdapter.cleanupEvents(System.currentTimeMillis() - MPConfig.DATA_EXPIRATION, MPDbAdapter.PEOPLE_TABLE); sExecutor.setKeepAliveTime(MPConfig.SUBMIT_THREAD_TTL, TimeUnit.MILLISECONDS); mTimerHandler = new UniqueHandler(); mPushPref = context.getSharedPreferences("com.mixpanel.android.mpmetrics.MPMetrics", Context.MODE_PRIVATE); }
Source:
<code>private void addMediaToPostCompletedMediaListMap(MediaModel media) { List<MediaModel> mediaListForPost = mCompletedUploads.get(media.getLocalPostId()); if (mediaListForPost == null) { mediaListForPost = new ArrayList<>(); } mediaListForPost.add(media); <START> mCompletedUploads.put(new Integer(media.getLocalPostId()), mediaListForPost); <END> }</code><technical_language>necessary box media.getLocalPostId() in a new Integer instance here</technical_language>

Target:
private void addMediaToPostCompletedMediaListMap(MediaModel media) { List<MediaModel> mediaListForPost = mCompletedUploadsByPost.get(media.getLocalPostId()); if (mediaListForPost == null) { mediaListForPost = new ArrayList<>(); } mediaListForPost.add(media); mCompletedUploadsByPost.put(media.getLocalPostId(), mediaListForPost); }
Source:
<code>public Collection<String> getEntitiesClassNames() { <START> if (idMapping != null) { <END> return idMapping.values(); } return null; }</code><technical_language>idMapping possibly null</technical_language>

Target:
public Collection<String> getEntitiesClassNames() { return idMapping.values(); }
Source:
<code>public static int mapApiToArtVersion(int api) { if (api < 19) { return NO_VERSION; } switch (api) { case 19: case 20: return 7; case 21: return 39; case 22: return 45; case 23: return 64; case 24: case 25: return 79; case 26: return 124; case 27: return 131; case 28: return 144; } <START> return 143; <END> }</code><technical_language>change 28 case a default case, remove this</technical_language>

Target:
public static int mapApiToArtVersion(int api) { if (api < 19) { return NO_VERSION; } switch (api) { case 19: case 20: return 7; case 21: return 39; case 22: return 45; case 23: return 64; case 24: case 25: return 79; case 26: return 124; case 27: return 131; default: return 144; } }
Source:
<code>public String getLocalSite() { <START> SiteConfiguration sites = configurationManager.getGlobalConfiguration().sites(); <END> return sites == null ? null : sites.localSite(); }</code><technical_language>IMO, get site name RELAY2. site-name in global configuration mandatory set different</technical_language>

Target:
public String getLocalSite() { if (cacheManager.getTransport() == null) return null; return cacheManager.getTransport().localSiteName(); }
Source:
<code>public static synchronized void decreaseClientNum() throws InterruptedException { <START> if (--m_activeClientCount == 0) { <END> VoltLogger.shutdownAsynchronousLogging(); EstTimeUpdater.stop(); ReverseDNSCache.stop(); } }</code><technical_language>Do need protect 0</technical_language>

Target:
public static synchronized void decreaseClientNum() throws InterruptedException { if (!m_preserveResources && m_activeClientCount <= 1) { m_activeClientCount = 0; VoltLogger.shutdownAsynchronousLogging(); EstTimeUpdater.stop(); ReverseDNSCache.stop(); } else { m_activeClientCount--; } }
Source:
<code>public void given__multibranch_with_primary__when__reporting_health__then__primary_health() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); c.createBranch("foo", "stable"); c.setPrimaryBranch("foo", "master"); HealthReportingMultiBranchProject prj = r.jenkins.createProject(HealthReportingMultiBranchProject.class, "foo"); prj.setCriteria(null); prj.getSourcesList().add(new BranchSource(new MockSCMSource(c, "foo", new MockSCMDiscoverBranches()))); prj.scheduleBuild2(0).getFuture().get(); r.waitUntilNoActivity(); prj.getHealthMetrics().replaceBy(Collections.singletonList(new PrimaryBranchHealthMetric())); prj.invalidateBuildHealthReports(); FreeStyleProject master = prj.getItem("master"); assertThat("We now have the master branch", master, notNullValue()); <START> assertThat(prj.getBuildHealthReports(), containsInAnyOrder( master.getBuildHealthReports().stream().map(Matchers::is).collect(Collectors.toList()) )); <END> } }</code><technical_language>A reason in this assertThat explain condition tested for</technical_language>

Target:
public void given__multibranch_with_primary__when__reporting_health__then__primary_health() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); c.createBranch("foo", "stable"); c.setPrimaryBranch("foo", "master"); HealthReportingMultiBranchProject prj = r.jenkins.createProject(HealthReportingMultiBranchProject.class, "foo"); prj.setCriteria(null); prj.getSourcesList().add(new BranchSource(new MockSCMSource(c, "foo", new MockSCMDiscoverBranches()))); prj.scheduleBuild2(0).getFuture().get(); r.waitUntilNoActivity(); prj.getHealthMetrics().replaceBy(Collections.singletonList(new PrimaryBranchHealthMetric())); prj.invalidateBuildHealthReports(); FreeStyleProject master = prj.getItem("master"); assertThat("We now have the master branch", master, notNullValue()); assertThat("'master' branch's reports should be exactly the reports as it is the primary branch", prj.getBuildHealthReports(), containsInAnyOrder(master.getBuildHealthReports().toArray()) ); } }
Source:
<code>private void edit() { VM vm = (VM) getSelectedItem(); if (vm == null) { return; } if (getWindow() != null) { return; } UnitVmModel model = new UnitVmModel(new ExistingVmModelBehavior(vm)); model.getVmType().setSelectedItem(vm.getVmType()); model.setVmAttachedToPool(vm.getVmPoolId() != null); setWindow(model); model.setTitle(ConstantsManager.getInstance() .getMessages() <START> .editVmTitle(ConstantsManager.getInstance().getConstants().vm())); <END> model.setHashName("edit_vm"); model.setCustomPropertiesKeysList(getCustomPropertiesKeysList()); model.initialize(this.getSystemTreeSelectedItem()); VmBasedWidgetSwitchModeCommand switchModeCommand = new VmBasedWidgetSwitchModeCommand(); switchModeCommand.init(model); model.getCommands().add(switchModeCommand); UICommand tempVar = new UICommand("OnSave", this); tempVar.setTitle(ConstantsManager.getInstance().getConstants().ok()); tempVar.setIsDefault(true); model.getCommands().add(tempVar); UICommand tempVar2 = new UICommand("Cancel", this); tempVar2.setTitle(ConstantsManager.getInstance().getConstants().cancel()); tempVar2.setIsCancel(true); model.getCommands().add(tempVar2); }</code><technical_language>message simply converted a constant: s/Edit {0} Virtual Machine/Edit Virtual Machine</technical_language>

Target:
private void edit() { VM vm = (VM) getSelectedItem(); if (vm == null) { return; } if (getWindow() != null) { return; } UnitVmModel model = new UnitVmModel(new ExistingVmModelBehavior(vm)); model.getVmType().setSelectedItem(vm.getVmType()); model.setVmAttachedToPool(vm.getVmPoolId() != null); setWindow(model); model.setTitle(ConstantsManager.getInstance() .getConstants().editVmTitle()); model.setHashName("edit_vm"); model.setCustomPropertiesKeysList(getCustomPropertiesKeysList()); model.initialize(this.getSystemTreeSelectedItem()); VmBasedWidgetSwitchModeCommand switchModeCommand = new VmBasedWidgetSwitchModeCommand(); switchModeCommand.init(model); model.getCommands().add(switchModeCommand); UICommand tempVar = new UICommand("OnSave", this); tempVar.setTitle(ConstantsManager.getInstance().getConstants().ok()); tempVar.setIsDefault(true); model.getCommands().add(tempVar); UICommand tempVar2 = new UICommand("Cancel", this); tempVar2.setTitle(ConstantsManager.getInstance().getConstants().cancel()); tempVar2.setIsCancel(true); model.getCommands().add(tempVar2); }
Source:
<code>public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Usage usage = (Usage) o; if (!amount.equals(usage.amount)) return false; if (merchantTag != null ? !merchantTag.equals(usage.merchantTag) : usage.merchantTag != null) return false; <START> if (recordingAt != null ? !recordingAt.equals(usage.recordingAt) : usage.recordingAt != null) return false; <END> if (!usageAt.equals(usage.usageAt)) return false; if (createdAt != null ? !createdAt.equals(usage.createdAt) : usage.createdAt != null) return false; if (updatedAt != null ? !updatedAt.equals(usage.updatedAt) : usage.updatedAt != null) return false; if (billedAt != null ? !billedAt.equals(usage.billedAt) : usage.billedAt != null) return false; if (usageType != null ? !usageType.equals(usage.usageType) : usage.usageType != null) return false; if (unitAmountInCents != null ? !unitAmountInCents.equals(usage.unitAmountInCents) : usage.unitAmountInCents != null) return false; return usagePercentage != null ? usagePercentage.equals(usage.usagePercentage) : usage.usagePercentage == null; }</code><technical_language>@vivyzer missed recordingAt I</technical_language>

Target:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Usage usage = (Usage) o; if (!amount.equals(usage.amount)) return false; if (merchantTag != null ? !merchantTag.equals(usage.merchantTag) : usage.merchantTag != null) return false; if (recordingAt != null ? recordingAt.compareTo(usage.recordingAt) != 0 : usage.recordingAt != null) return false; if (!usageAt.equals(usage.usageAt)) return false; if (createdAt != null ? createdAt.compareTo(usage.createdAt) != 0 : usage.createdAt != null) return false; if (updatedAt != null ? updatedAt.compareTo(usage.updatedAt) != 0 : usage.updatedAt != null) return false; if (billedAt != null ? billedAt.compareTo(usage.billedAt) != 0 : usage.billedAt != null) return false; if (usageType != null ? !usageType.equals(usage.usageType) : usage.usageType != null) return false; if (unitAmountInCents != null ? !unitAmountInCents.equals(usage.unitAmountInCents) : usage.unitAmountInCents != null) return false; return usagePercentage != null ? usagePercentage.equals(usage.usagePercentage) : usage.usagePercentage == null; }
Source:
<code>private AdapterDeclaration parseAdapterDeclaration() throws TypeImportException, XMLStreamException { AdapterDeclaration a = LibraryElementFactory.eINSTANCE.createAdapterDeclaration(); readNameCommentAttributes(a); String typeName = getAttributeValue(LibraryElementTags.TYPE_ATTRIBUTE); if (null != typeName) { AdapterTypePaletteEntry entry = getAdapterPaletEntry(typeName, palette); a.setPaletteEntry(entry); AdapterType dataType = null; if <START> (entry != null) { <END> dataType = entry.getType(); } a.setTypeName(typeName); if (dataType != null) { a.setType(dataType); } } else { throw new TypeImportException(Messages.FBTImporter_ADAPTER_DECLARATION_TYPE_EXCEPTION); } PositionableElement pos = LibraryElementFactory.eINSTANCE.createPositionableElement(); getXandY(pos); adapterPositions.put(a.getName(), pos); proceedToEndElementNamed(LibraryElementTags.ADAPTER_DECLARATION_ELEMENT); return a; }</code><technical_language>order of operands</technical_language>

Target:
private AdapterDeclaration parseAdapterDeclaration() throws TypeImportException, XMLStreamException { AdapterDeclaration a = LibraryElementFactory.eINSTANCE.createAdapterDeclaration(); readNameCommentAttributes(a); String typeName = getAttributeValue(LibraryElementTags.TYPE_ATTRIBUTE); if (null != typeName) { AdapterTypePaletteEntry entry = getAdapterPaletEntry(typeName, palette); a.setPaletteEntry(entry); AdapterType dataType = null; if (null != entry) { dataType = entry.getType(); } a.setTypeName(typeName); if (null != dataType) { a.setType(dataType); } } else { throw new TypeImportException(Messages.FBTImporter_ADAPTER_DECLARATION_TYPE_EXCEPTION); } PositionableElement pos = LibraryElementFactory.eINSTANCE.createPositionableElement(); getXandY(pos); adapterPositions.put(a.getName(), pos); proceedToEndElementNamed(LibraryElementTags.ADAPTER_DECLARATION_ELEMENT); return a; }
Source:
<code>public void run() { try { boolean caughtUp = true; while (running) { if (!hardDelete()) { caughtUp = true; try { Thread.sleep(hardDeleterSleepTimeWhenCaughtUpMs); } catch (InterruptedException e) { logger.info("Caught interrupted exception"); } <START> } else if (caughtUp) { <END> caughtUp = false; logger.info("Resumed hard deletes for after having caught up", dataDir); } } } finally { close(); } }</code><technical_language>discussed, a metric useful</technical_language>

Target:
public void run() { try { while (running) { if (!hardDelete()) { isCaughtUp = true; try { Thread.sleep(hardDeleterSleepTimeWhenCaughtUpMs); } catch (InterruptedException e) { logger.info("Caught interrupted exception"); } } else if (isCaughtUp) { isCaughtUp = false; logger.info("Resumed hard deletes for after having caught up", dataDir); } } } finally { close(); } }
Source:
<code>private boolean hasDependentType(AnnotatedTypeMirror atm) { if (atm == null) { return false; } boolean b = new SimpleAnnotatedTypeScanner<>( (type, p) -> { <START> for (AnnotationMirror am : type.getAnnotations()) { <END> if (isExpressionAnno(am)) { return true; } } return false; }, Boolean::logicalOr, false) .visit(atm); return b; }</code><technical_language>this rewritten type.getAnnotations().stream().anyMatch(am -> isExpressionAnno(am))</technical_language>

Target:
private boolean hasDependentType(AnnotatedTypeMirror atm) { if (atm == null) { return false; } boolean b = new SimpleAnnotatedTypeScanner<>( (type, p) -> type.getAnnotations().stream() .anyMatch(this::isExpressionAnno), Boolean::logicalOr, false) .visit(atm); return b; }
Source:
<code>private AbstractTaskReference adaptFromRevCommit(RevCommit commit) { Repository[] repositories = Activator.getDefault().getRepositoryCache().getAllRepositories(); for (Repository r : repositories) { RevWalk revWalk = new RevWalk(r); String repoUrl = null; String message = null; try { RevCommit revCommit = revWalk.parseCommit(commit); if (revCommit != null) { repoUrl = getRepoUrl(r); message = revCommit.getFullMessage(); } <START> } catch (IOException e) { <END> continue; } if (message == null || message.trim().length() == 0) continue; String taskRepositoryUrl = null; if (repoUrl != null) { TaskRepository repository = getTaskRepositoryByGitRepoURL(repoUrl); if (repository != null) taskRepositoryUrl = repository.getRepositoryUrl(); } return new LinkedTaskInfo(taskRepositoryUrl, null, null, message); } return null; }</code><technical_language>a cases of IllegalArguementException's thrown malformed encoding headers</technical_language>

Target:
private AbstractTaskReference adaptFromRevCommit(RevCommit commit) { Repository[] repositories = Activator.getDefault().getRepositoryCache().getAllRepositories(); for (Repository r : repositories) { RevWalk revWalk = new RevWalk(r); String repoUrl = null; String message = null; long timestamp = 0; try { RevCommit revCommit = revWalk.parseCommit(commit); if (revCommit != null) { repoUrl = getRepoUrl(r); message = revCommit.getFullMessage(); timestamp = (long)revCommit.getCommitTime() * 1000; } } catch (IOException e) { continue; } catch (IllegalArgumentException e) { continue; } if (message == null || message.trim().length() == 0) continue; String taskRepositoryUrl = null; if (repoUrl != null) { TaskRepository repository = getTaskRepositoryByGitRepoURL(repoUrl); if (repository != null) taskRepositoryUrl = repository.getRepositoryUrl(); } return new LinkedTaskInfo(taskRepositoryUrl, null, null, message, timestamp); } return null; }
Source:
<code>public EurekaHttpResponse<Void> register(InstanceInfo info) { String urlPath = "apps/" + info.getAppName(); Response response = null; try { Builder resourceBuilder = jerseyClient.target(serviceUrl).path(urlPath).request(); addExtraProperties(resourceBuilder); addExtraHeaders(resourceBuilder); response = resourceBuilder .accept(MediaType.APPLICATION_JSON) .acceptEncoding("gzip") <START> .post(Entity.entity(info, MediaType.APPLICATION_JSON_TYPE)); <END> return anEurekaHttpResponse(response.getStatus()).headers(headersOf(response)).build(); } finally { if (logger.isDebugEnabled()) { logger.debug("Jersey2 HTTP POST {}/{} with instance {}; statusCode={}", serviceUrl, urlPath, info.getId(), response == null ? "N/A" : response.getStatus()); } if (response != null) { response.close(); } } }</code><technical_language>is this .post(Entity.json(info))</technical_language>

Target:
public EurekaHttpResponse<Void> register(InstanceInfo info) { String urlPath = "apps/" + info.getAppName(); Response response = null; try { Builder resourceBuilder = jerseyClient.target(serviceUrl).path(urlPath).request(); addExtraProperties(resourceBuilder); addExtraHeaders(resourceBuilder); response = resourceBuilder .accept(MediaType.APPLICATION_JSON) .acceptEncoding("gzip") .post(Entity.json(info)); return anEurekaHttpResponse(response.getStatus()).headers(headersOf(response)).build(); } finally { if (logger.isDebugEnabled()) { logger.debug("Jersey2 HTTP POST {}/{} with instance {}; statusCode={}", serviceUrl, urlPath, info.getId(), response == null ? "N/A" : response.getStatus()); } if (response != null) { response.close(); } } }
Source:
<code>public Configuration clone() { try { super.clone(); } catch (CloneNotSupportedException ex) { <START> } <END> for (String config : BaseConfigurations.DEFAULT_CONFIGURATIONS) { if (!configurations.containsKey(config)) { load(config); } } return new Configuration(configurations); }</code><technical_language>this code exist? suppressed warning added this</technical_language>

Target:
public Configuration clone() { for (String config : BaseConfigurations.DEFAULT_CONFIGURATIONS) { if (!configurations.containsKey(config)) { load(config); } } return new Configuration(configurations); }
Source:
<code>public void waitForOperation(Operation operation, long timeout, TimeUnit timeUnit) throws TimeoutException, InterruptedException { GetOperationRequest request = GetOperationRequest.newBuilder() .setName(operation.getName()) .build(); ExponentialBackOff backOff = new ExponentialBackOff.Builder() .setInitialIntervalMillis(100) .setMultiplier(1.3) .setMaxIntervalMillis(Ints.checkedCast(TimeUnit.SECONDS.toMillis(60))) .setMaxElapsedTimeMillis(Ints.checkedCast(timeUnit.toMillis(timeout))) .build(); Operation currentOperationState = operation; while (true) { if (currentOperationState.getDone()) { switch (currentOperationState.getResultCase()) { case RESPONSE: return; case ERROR: throw StatusProto.toStatusRuntimeException(currentOperationState.getError()); case RESULT_NOT_SET: throw new IllegalStateException( "System returned invalid response for Operation check: " + currentOperationState); } } final long backOffMillis; try { backOffMillis = backOff.nextBackOffMillis(); } catch (IOException e) { throw new RuntimeException(e); } if (backOffMillis == BackOff.STOP) { throw new TimeoutException("Operation did not complete in time"); } else { <START> Thread.sleep(backOffMillis); <END> } currentOperationState = getOperation(request); } }</code><technical_language>Catch InterruptedException? Do expect caller handle InterruptedException</technical_language>

Target:
public void waitForOperation(Operation operation, long timeout, TimeUnit timeUnit) throws TimeoutException, IOException { GetOperationRequest request = GetOperationRequest.newBuilder() .setName(operation.getName()) .build(); ExponentialBackOff backOff = new ExponentialBackOff.Builder() .setInitialIntervalMillis(100) .setMultiplier(1.3) .setMaxIntervalMillis(Ints.checkedCast(TimeUnit.SECONDS.toMillis(60))) .setMaxElapsedTimeMillis(Ints.checkedCast(timeUnit.toMillis(timeout))) .build(); Operation currentOperationState = operation; while (true) { if (currentOperationState.getDone()) { switch (currentOperationState.getResultCase()) { case RESPONSE: return; case ERROR: throw StatusProto.toStatusRuntimeException(currentOperationState.getError()); case RESULT_NOT_SET: throw new IllegalStateException( "System returned invalid response for Operation check: " + currentOperationState); } } final long backOffMillis; try { backOffMillis = backOff.nextBackOffMillis(); } catch (IOException e) { throw new RuntimeException(e); } if (backOffMillis == BackOff.STOP) { throw new TimeoutException("Operation did not complete in time"); } else { try { Thread.sleep(backOffMillis); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException("Interrupted while waiting for operation to finish"); } } currentOperationState = getOperation(request); } }
Source:
<code>void execute() { <START> File[] cacheKeyDirs = rootCacheDir.listFiles(new FilenameFilter() { <END> @Override public boolean accept(File current, String name) { return new File(current, name).isDirectory(); } }); if (cacheKeyDirs == null || cacheKeyDirs.length == 0) { LOGGER.log(Level.FINE, "cacheKeys directory '{0]' is empty, nothing to clean up", rootCacheDir); } else { ExecutorService executor = Executors.newSingleThreadExecutor(); try { executor.execute(new Runnable() { @Override public void run() { for (File dir: cacheKeyDirs) { if (dir.isDirectory() && dir.exists() && cacheKeys.contains(dir.getName())) { LOGGER.log(Level.FINE, "cacheKey belongs to agent, keeping the directory '{0}'", dir.getName()); } else { try { FileUtils.deleteDirectory(dir); LOGGER.log(Level.INFO, "The agent is no longer available, cache entry {0} was deleted", dir.getName()); } catch (IOException e) { LOGGER.log(Level.WARNING, "Couldn't remove the cache directory " + dir.getName(), e); } } } } }); } catch (RuntimeException e) { LOGGER.log(Level.WARNING, "The clean up task has ended with errors", e); } finally { executor.shutdown(); } } }</code><technical_language>I a FileFilter code simpler</technical_language>

Target:
void execute() { File[] cacheKeyDirs = rootCacheDir.listFiles(new FileFilter() { @Override public boolean accept(File file) { return file.isDirectory(); } }); if (cacheKeyDirs == null || cacheKeyDirs.length == 0) { LOGGER.log(Level.FINE, "cacheKeys directory '{0]' is empty, nothing to clean up", rootCacheDir); } else { ExecutorService executor = Executors.newSingleThreadExecutor(); try { executor.execute(new Runnable() { @Override public void run() { for (File dir: cacheKeyDirs) { if (cacheKeys.contains(dir.getName())) { LOGGER.log(Level.FINE, "cacheKey belongs to agent, keeping the directory '{0}'", dir.getName()); } else { try { FileUtils.deleteDirectory(dir); LOGGER.log(Level.INFO, "The agent is no longer available, cache entry {0} was deleted", dir.getAbsolutePath() ); } catch (IOException e) { LOGGER.log(Level.WARNING, "Couldn't remove the cache directory " + dir.getName(), e); } } } } }); } catch (RuntimeException e) { LOGGER.log(Level.WARNING, "The clean up task has ended with errors", e); } finally { executor.shutdown(); } } }